feat: slot booking API with hot cache and oversell protection

GET /slots/availability, POST /slots/{id}/hold, POST /holds/{id}/confirm
and DELETE /holds/{id} on Laravel 12 and MySQL 8.

- availability cached for 10s behind a single-flight lock with a stale
  copy, invalidated after commit on confirm and cancel
- oversell prevented by a conditional decrement, verified by the number
  of affected rows rather than a preceding select
- idempotency enforced by a unique index on holds.idempotency_key
- active holds counted with an expires_at filter, so no background
  cleanup is required for correctness
- 27 feature tests against MySQL, service documentation, Postman collection

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Dmitriy 2026-07-31 14:47:18 +03:00
commit 16f3f851b1
75 changed files with 13035 additions and 0 deletions

18
.editorconfig Normal file
View file

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[compose.yaml]
indent_size = 4

70
.env.example Normal file
View file

@ -0,0 +1,70 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=slots
DB_USERNAME=root
DB_PASSWORD=secret
# TTL кеша доступности, секунды (5-15)
SLOT_AVAILABILITY_CACHE_TTL=10
# Время жизни холда, секунды
SLOT_HOLD_TTL=300
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

11
.gitattributes vendored Normal file
View file

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

185
README.md Normal file
View file

@ -0,0 +1,185 @@
# Slot Booking API
API бронирования слотов: горячий кеш доступности, временные холды с идемпотентностью, защита от оверсела.
**Стек:** Laravel 12 (PHP 8.2+), MySQL 8+. Внешних сервисов не требуется — кеш и блокировки хранятся в той же базе.
Описание устройства сервиса — [docs/README.md](docs/README.md). Коллекция Postman — [docs/postman](docs/postman/slot-booking-api.postman_collection.json).
## Быстрый старт
```bash
docker run -d --name stl-mysql \
-e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=slots \
-p 3307:3306 mysql:8
```
```bash
cp .env.example .env && composer install && php artisan key:generate
```
```bash
php artisan migrate --seed
```
```bash
php artisan serve --port=8001
```
Сидер создаёт три слота с вместимостью 10, 5 и 1. Слот с одним местом позволяет воспроизвести конфликт оверсела двумя запросами.
## Тесты
Тесты выполняются против MySQL (см. `phpunit.xml`), поэтому нужна отдельная база:
```bash
docker exec stl-mysql mysql -uroot -psecret -e "CREATE DATABASE IF NOT EXISTS slots_test"
```
```bash
php artisan test
```
27 тестов, 90 проверок: кеш и его инвалидация, поведение при потере гонки за пересчёт, идемпотентность, истечение холдов, защита от оверсела при конкурентном подтверждении.
## Эндпоинты
| Метод | Путь | Ответ |
|---|---|---|
| `GET` | `/slots/availability` | `200` — массив слотов |
| `POST` | `/slots/{id}/hold` | `201` создан / `200` повтор по тому же ключу / `409` мест нет / `422` некорректный `Idempotency-Key` / `404` |
| `POST` | `/holds/{id}/confirm` | `200` / `409` мест нет либо холд неактивен / `404` |
| `DELETE` | `/holds/{id}` | `200` / `404` |
Ошибки приходят в виде `{"message": "...", "reason": "<код>"}`. Коды: `capacity_exhausted`, `hold_cancelled`, `hold_expired`, `idempotency_key_reuse`, `not_found`.
## Примеры запросов
Прогон против запущенного сервера. Слот `3` имеет `capacity = 1`.
### Доступность
```bash
curl -s http://127.0.0.1:8001/slots/availability
```
```json
[{"slot_id":1,"capacity":10,"remaining":10},{"slot_id":2,"capacity":5,"remaining":5},{"slot_id":3,"capacity":1,"remaining":1}]
```
### Создание холда
```bash
curl -si -X POST http://127.0.0.1:8001/slots/3/hold -H 'Idempotency-Key: 6e517e8e-1470-4a78-bdbd-e2b50776a6a0'
```
```
HTTP/1.1 201 Created
{"hold_id":1,"slot_id":3,"status":"held","expires_at":"2026-07-29T18:19:56+00:00","confirmed_at":null,"cancelled_at":null}
```
### Повтор с тем же ключом — тот же холд, `200` вместо `201`
```bash
curl -si -X POST http://127.0.0.1:8001/slots/3/hold -H 'Idempotency-Key: 6e517e8e-1470-4a78-bdbd-e2b50776a6a0'
```
```
HTTP/1.1 200 OK
{"hold_id":1,"slot_id":3,"status":"held","expires_at":"2026-07-29T18:19:56+00:00","confirmed_at":null,"cancelled_at":null}
```
Второй строки в `holds` не появляется.
### Конфликт при оверселе
```bash
curl -si -X POST http://127.0.0.1:8001/slots/3/hold -H 'Idempotency-Key: bab7c4be-3184-40d6-ab90-b4118c40bcb3'
```
```
HTTP/1.1 409 Conflict
{"message":"Slot 3 has no remaining capacity.","reason":"capacity_exhausted"}
```
### Переиспользование ключа для другого слота
```bash
curl -si -X POST http://127.0.0.1:8001/slots/1/hold -H 'Idempotency-Key: 6e517e8e-1470-4a78-bdbd-e2b50776a6a0'
```
```
HTTP/1.1 422 Unprocessable Content
{"message":"Idempotency-Key 6e517e8e-... was already used for a different slot than 1.","reason":"idempotency_key_reuse"}
```
### Подтверждение
```bash
curl -si -X POST http://127.0.0.1:8001/holds/1/confirm
```
```
HTTP/1.1 200 OK
{"hold_id":1,"slot_id":3,"status":"confirmed","expires_at":"2026-07-29T18:19:56+00:00","confirmed_at":"2026-07-29T18:14:57+00:00","cancelled_at":null}
```
Кеш инвалидирован, остаток слота `3` обновился сразу:
```bash
curl -s http://127.0.0.1:8001/slots/availability
```
```json
[{"slot_id":1,"capacity":10,"remaining":10},{"slot_id":2,"capacity":5,"remaining":5},{"slot_id":3,"capacity":1,"remaining":0}]
```
Повторный `confirm` того же холда возвращает `200` и тот же результат — место списывается один раз.
### Отмена
```bash
curl -si -X DELETE http://127.0.0.1:8001/holds/1
```
```
HTTP/1.1 200 OK
{"hold_id":1,"slot_id":3,"status":"cancelled","expires_at":"2026-07-29T18:19:56+00:00","confirmed_at":"2026-07-29T18:14:57+00:00","cancelled_at":"2026-07-29T18:14:57+00:00"}
```
```bash
curl -s http://127.0.0.1:8001/slots/availability
```
```json
[{"slot_id":1,"capacity":10,"remaining":10},{"slot_id":2,"capacity":5,"remaining":5},{"slot_id":3,"capacity":1,"remaining":1}]
```
Подтвердить отменённый холд уже нельзя:
```bash
curl -si -X POST http://127.0.0.1:8001/holds/1/confirm
```
```
HTTP/1.1 409 Conflict
{"message":"Hold 1 is no longer active and cannot be confirmed.","reason":"hold_cancelled"}
```
## Структура
```
app/Enums/HoldStatus.php held | confirmed | cancelled
app/Exceptions/SlotBookingException.php доменные отказы и их HTTP-статус
app/Http/Controllers/AvailabilityController.php
app/Http/Controllers/HoldController.php
app/Http/Requests/StoreHoldRequest.php валидация заголовка Idempotency-Key
app/Http/Resources/HoldResource.php
app/Models/Slot.php
app/Models/Hold.php scopeActive() — определение активного холда
app/Services/SlotService.php транзакции, кеш, идемпотентность
config/slots.php TTL кеша и TTL холда
routes/api.php
docs/README.md устройство сервиса
docs/postman/ коллекция Postman
```

12
app/Enums/HoldStatus.php Normal file
View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum HoldStatus: string
{
case Held = 'held';
case Confirmed = 'confirmed';
case Cancelled = 'cancelled';
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Exceptions;
use App\Enums\HoldStatus;
use App\Models\Hold;
use RuntimeException;
/**
* Доменные отказы бронирования. Сопоставление с ответами HTTP в bootstrap/app.php.
*/
final class SlotBookingException extends RuntimeException
{
private function __construct(
public readonly string $reason,
public readonly int $status,
string $message,
) {
parent::__construct($message);
}
public static function capacityExhausted(int $slotId): self
{
return new self(
'capacity_exhausted',
409,
"Slot {$slotId} has no remaining capacity.",
);
}
public static function holdNotActive(Hold $hold): self
{
$reason = $hold->status === HoldStatus::Cancelled ? 'hold_cancelled' : 'hold_expired';
return new self(
$reason,
409,
"Hold {$hold->id} is no longer active and cannot be confirmed.",
);
}
public static function idempotencyKeyReuse(string $key, int $slotId): self
{
return new self(
'idempotency_key_reuse',
422,
"Idempotency-Key {$key} was already used for a different slot than {$slotId}.",
);
}
}

View file

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Services\SlotService;
use Illuminate\Http\JsonResponse;
final class AvailabilityController extends Controller
{
public function __construct(private readonly SlotService $slots) {}
/**
* GET /slots/availability
*/
public function index(): JsonResponse
{
return response()->json($this->slots->availability());
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Requests\StoreHoldRequest;
use App\Http\Resources\HoldResource;
use App\Services\SlotService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
final class HoldController extends Controller
{
public function __construct(private readonly SlotService $slots) {}
/**
* POST /slots/{slot}/hold
*
* Без привязки модели: строку слота читает сервис, внутри транзакции и с локом.
*/
public function store(StoreHoldRequest $request, int $slot): JsonResponse
{
$hold = $this->slots->hold($slot, $request->idempotencyKey());
// Повтор по ключу ничего не создал — отвечаем 200 вместо 201.
$status = $hold->wasRecentlyCreated ? Response::HTTP_CREATED : Response::HTTP_OK;
return HoldResource::make($hold)->response()->setStatusCode($status);
}
/**
* POST /holds/{hold}/confirm
*/
public function confirm(int $hold): JsonResponse
{
return HoldResource::make($this->slots->confirm($hold))->response();
}
/**
* DELETE /holds/{hold}
*/
public function destroy(int $hold): JsonResponse
{
return HoldResource::make($this->slots->cancel($hold))->response();
}
}

View file

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* Валидация заголовка Idempotency-Key у POST /slots/{slot}/hold.
*/
final class StoreHoldRequest extends FormRequest
{
/**
* Ключ приходит заголовком переносим во входные данные, чтобы проверять правилами.
*/
protected function prepareForValidation(): void
{
$this->merge([
'idempotency_key' => $this->header('Idempotency-Key'),
]);
}
/**
* @return array<string, list<string>>
*/
public function rules(): array
{
return [
'idempotency_key' => ['required', 'uuid'],
];
}
/**
* @return array<string, string>
*/
public function messages(): array
{
return [
'idempotency_key.required' => 'The Idempotency-Key header is required.',
'idempotency_key.uuid' => 'The Idempotency-Key header must be a valid UUID.',
];
}
public function idempotencyKey(): string
{
return $this->validated()['idempotency_key'];
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources;
use App\Models\Hold;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin Hold
*/
final class HoldResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'hold_id' => $this->id,
'slot_id' => $this->slot_id,
'status' => $this->status->value,
'expires_at' => $this->expires_at->toIso8601String(),
'confirmed_at' => $this->confirmed_at?->toIso8601String(),
'cancelled_at' => $this->cancelled_at?->toIso8601String(),
];
}
}

70
app/Models/Hold.php Normal file
View file

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\HoldStatus;
use Database\Factories\HoldFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property int $slot_id
* @property string $idempotency_key
* @property HoldStatus $status
* @property Carbon $expires_at
* @property Carbon|null $confirmed_at
* @property Carbon|null $cancelled_at
*/
class Hold extends Model
{
/** @use HasFactory<HoldFactory> */
use HasFactory;
protected $fillable = [
'slot_id',
'idempotency_key',
'status',
'expires_at',
'confirmed_at',
'cancelled_at',
];
protected function casts(): array
{
return [
'status' => HoldStatus::class,
'expires_at' => 'datetime',
'confirmed_at' => 'datetime',
'cancelled_at' => 'datetime',
];
}
/** @return BelongsTo<Slot, $this> */
public function slot(): BelongsTo
{
return $this->belongsTo(Slot::class);
}
/**
* Холды, занимающие место. Определение одно для проверки вместимости и
* проекции доступности.
*
* @param Builder<Hold> $query
*/
public function scopeActive(Builder $query): void
{
$query->where('status', HoldStatus::Held)
->where('expires_at', '>', now());
}
public function isExpired(): bool
{
return $this->expires_at->isPast();
}
}

47
app/Models/Slot.php Normal file
View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Database\Factories\SlotFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property Carbon $starts_at
* @property Carbon $ends_at
* @property int $capacity
* @property int $remaining
*/
class Slot extends Model
{
/** @use HasFactory<SlotFactory> */
use HasFactory;
protected $fillable = [
'starts_at',
'ends_at',
'capacity',
'remaining',
];
protected function casts(): array
{
return [
'starts_at' => 'datetime',
'ends_at' => 'datetime',
'capacity' => 'integer',
'remaining' => 'integer',
];
}
/** @return HasMany<Hold, $this> */
public function holds(): HasMany
{
return $this->hasMany(Hold::class);
}
}

49
app/Models/User.php Normal file
View file

@ -0,0 +1,49 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace App\Providers;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Регистрация сервисов приложения.
*/
public function register(): void
{
//
}
/**
* Инициализация сервисов приложения.
*/
public function boot(): void
{
// Формат доступности задан массивом, остальные эндпоинты приведены
// к той же конвенции.
JsonResource::withoutWrapping();
}
}

View file

@ -0,0 +1,262 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Enums\HoldStatus;
use App\Exceptions\SlotBookingException;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Бронирование слотов: кеш доступности, транзакционные холды, подтверждение без оверсела.
*/
final class SlotService
{
private const CACHE_KEY = 'slots:availability';
private const STALE_KEY = 'slots:availability:stale';
private const LOCK_KEY = 'slots:availability:lock';
/** Секунды удержания лока пересчёта. */
private const LOCK_TTL = 10;
/** Секунды ожидания лока на холодном кеше. */
private const LOCK_WAIT = 3;
/**
* Проекция доступности из кеша.
*
* От stampede защищают лок на пересчёт, stale-копия для остальных и
* ограниченное ожидание с прямым запросом в базу как последним средством.
*
* @return list<array{slot_id: int, capacity: int, remaining: int}>
*/
public function availability(): array
{
$fresh = Cache::get(self::CACHE_KEY);
if ($fresh !== null) {
return $fresh;
}
$lock = Cache::lock(self::LOCK_KEY, self::LOCK_TTL);
if ($lock->get()) {
try {
return $this->refreshAvailability();
} finally {
$lock->release();
}
}
// Пересчёт уже идёт: отдать данные, устаревшие на пару секунд, дешевле,
// чем послать в базу всех сразу.
$stale = Cache::get(self::STALE_KEY);
if ($stale !== null) {
return $stale;
}
// Нет ни свежих, ни stale: первый запрос либо момент сразу после
// инвалидации. Ждём владельца лока — перепроверка вернёт его результат.
try {
return $lock->block(self::LOCK_WAIT, fn (): array => $this->refreshAvailability());
} catch (LockTimeoutException) {
return $this->computeAvailability();
}
}
/**
* Создать холд либо вернуть созданный ранее по этому ключу.
*/
public function hold(int $slotId, string $idempotencyKey): Hold
{
$existing = Hold::query()->where('idempotency_key', $idempotencyKey)->first();
if ($existing !== null) {
return $this->assertBelongsToSlot($existing, $slotId, $idempotencyKey);
}
try {
return DB::transaction(function () use ($slotId, $idempotencyKey): Hold {
// Лок на строке слота сериализует холды по нему, иначе подсчёт
// мест ниже недостоверен.
$slot = Slot::query()->lockForUpdate()->findOrFail($slotId);
if ($this->bookableSeats($slot) < 1) {
throw SlotBookingException::capacityExhausted($slot->id);
}
return $slot->holds()->create([
'idempotency_key' => $idempotencyKey,
'status' => HoldStatus::Held,
'expires_at' => now()->addSeconds((int) config('slots.hold_ttl')),
]);
});
} catch (UniqueConstraintViolationException) {
// Гонка двух запросов с одним ключом: победитель уже вставил строку,
// его холд и есть ответ для этого ключа.
$hold = Hold::query()->where('idempotency_key', $idempotencyKey)->firstOrFail();
return $this->assertBelongsToSlot($hold, $slotId, $idempotencyKey);
}
}
/**
* Подтвердить холд, списав одно место.
*/
public function confirm(int $holdId): Hold
{
$hold = DB::transaction(function () use ($holdId): Hold {
$hold = Hold::query()->lockForUpdate()->findOrFail($holdId);
if ($hold->status === HoldStatus::Confirmed) {
return $hold;
}
if ($hold->status === HoldStatus::Cancelled || $hold->isExpired()) {
throw SlotBookingException::holdNotActive($hold);
}
// Условие в UPDATE, а не в отдельном SELECT: между проверкой и
// списанием нет промежутка для конкурента. Ноль строк — мест не было.
$consumed = Slot::query()
->whereKey($hold->slot_id)
->where('remaining', '>', 0)
->decrement('remaining');
if ($consumed === 0) {
throw SlotBookingException::capacityExhausted($hold->slot_id);
}
$hold->update([
'status' => HoldStatus::Confirmed,
'confirmed_at' => now(),
]);
return $hold;
});
// Только после коммита: иначе читатель закеширует незафиксированные данные.
$this->invalidateAvailability();
return $hold;
}
/**
* Отменить холд, вернув место, если оно было списано.
*/
public function cancel(int $holdId): Hold
{
$hold = DB::transaction(function () use ($holdId): Hold {
$hold = Hold::query()->lockForUpdate()->findOrFail($holdId);
if ($hold->status === HoldStatus::Cancelled) {
return $hold;
}
// Место списывало только подтверждение, поэтому возвращает только оно.
// Холд в статусе held просто перестаёт попадать в активные.
if ($hold->status === HoldStatus::Confirmed) {
Slot::query()
->whereKey($hold->slot_id)
->whereColumn('remaining', '<', 'capacity')
->increment('remaining');
}
$hold->update([
'status' => HoldStatus::Cancelled,
'cancelled_at' => now(),
]);
return $hold;
});
$this->invalidateAvailability();
return $hold;
}
public function invalidateAvailability(): void
{
Cache::forget(self::CACHE_KEY);
Cache::forget(self::STALE_KEY);
}
/**
* Пересчитать и закешировать проекцию. Вызывается под локом.
*
* @return list<array{slot_id: int, capacity: int, remaining: int}>
*/
private function refreshAvailability(): array
{
// Владелец лока до нас мог уже всё посчитать.
$fresh = Cache::get(self::CACHE_KEY);
if ($fresh !== null) {
return $fresh;
}
$ttl = (int) config('slots.availability_cache_ttl');
$data = $this->computeAvailability();
Cache::put(self::CACHE_KEY, $data, $ttl);
Cache::put(self::STALE_KEY, $data, $ttl * 6);
return $data;
}
/**
* Места, доступные к бронированию: подтверждённые брони уже вычтены из
* remaining, активные холды вычитаются дополнительно.
*
* @return list<array{slot_id: int, capacity: int, remaining: int}>
*/
private function computeAvailability(): array
{
$activeHolds = Hold::query()
->active()
->selectRaw('slot_id, COUNT(*) AS held_count')
->groupBy('slot_id');
return Slot::query()
->leftJoinSub($activeHolds, 'active_holds', 'active_holds.slot_id', '=', 'slots.id')
->orderBy('slots.id')
->get([
'slots.id',
'slots.capacity',
'slots.remaining',
DB::raw('COALESCE(active_holds.held_count, 0) AS held_count'),
])
->map(fn (Slot $slot): array => [
'slot_id' => $slot->id,
'capacity' => $slot->capacity,
'remaining' => max(0, $slot->remaining - (int) $slot->getAttribute('held_count')),
])
->all();
}
/**
* Свободные места слота, строка которого заблокирована вызывающим.
*/
private function bookableSeats(Slot $slot): int
{
return $slot->remaining - $slot->holds()->active()->count();
}
private function assertBelongsToSlot(Hold $hold, int $slotId, string $idempotencyKey): Hold
{
if ($hold->slot_id !== $slotId) {
throw SlotBookingException::idempotencyKeyReuse($idempotencyKey, $slotId);
}
return $hold;
}
}

18
artisan Executable file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

39
bootstrap/app.php Normal file
View file

@ -0,0 +1,39 @@
<?php
use App\Exceptions\SlotBookingException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
// Пути в задании заданы без префикса. Маршруты при этом остаются
// в routes/api.php со stateless-мидлварами группы api.
api: __DIR__.'/../routes/api.php',
apiPrefix: '',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
// Доменные отказы несут свой статус и код причины.
$exceptions->render(fn (SlotBookingException $e) => response()->json([
'message' => $e->getMessage(),
'reason' => $e->reason,
], $e->status));
// 404 без имени класса модели в ответе. ModelNotFoundException ловить
// бесполезно: Laravel подменяет её на NotFoundHttpException до колбэков.
$exceptions->render(fn (NotFoundHttpException $e) => response()->json([
'message' => 'Resource not found.',
'reason' => 'not_found',
], 404));
// Только API: JSON даже клиенту без Accept: application/json.
$exceptions->shouldRenderJsonWhen(fn (Request $request, Throwable $e) => true);
})->create();

2
bootstrap/cache/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

7
bootstrap/providers.php Normal file
View file

@ -0,0 +1,7 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];

86
composer.json Normal file
View file

@ -0,0 +1,86 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.50"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8389
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

126
config/app.php Normal file
View file

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

117
config/auth.php Normal file
View file

@ -0,0 +1,117 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

117
config/cache.php Normal file
View file

@ -0,0 +1,117 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

184
config/database.php Normal file
View file

@ -0,0 +1,184 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

80
config/filesystems.php Normal file
View file

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

132
config/logging.php Normal file
View file

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
config/mail.php Normal file
View file

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];

129
config/queue.php Normal file
View file

@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

38
config/services.php Normal file
View file

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
config/session.php Normal file
View file

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

15
config/slots.php Normal file
View file

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
return [
// Сколько секунд GET /slots/availability отдаётся из кеша.
// Stale-копия живёт в шесть раз дольше и гасит stampede во время пересчёта.
'availability_cache_ttl' => (int) env('SLOT_AVAILABILITY_CACHE_TTL', 10),
// Время жизни холда. Истёкшие перестают занимать место за счёт фильтра
// по expires_at, поэтому фоновая очистка не нужна.
'hold_ttl' => (int) env('SLOT_HOLD_TTL', 300),
];

1
database/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.sqlite*

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\HoldStatus;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends Factory<Hold>
*/
final class HoldFactory extends Factory
{
protected $model = Hold::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'slot_id' => Slot::factory(),
'idempotency_key' => (string) Str::uuid(),
'status' => HoldStatus::Held,
'expires_at' => now()->addSeconds((int) config('slots.hold_ttl')),
];
}
public function expired(): self
{
return $this->state(fn (): array => [
'status' => HoldStatus::Held,
'expires_at' => now()->subMinute(),
]);
}
public function confirmed(): self
{
return $this->state(fn (): array => [
'status' => HoldStatus::Confirmed,
'confirmed_at' => now(),
]);
}
public function cancelled(): self
{
return $this->state(fn (): array => [
'status' => HoldStatus::Cancelled,
'cancelled_at' => now(),
]);
}
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Models\Slot;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Slot>
*/
final class SlotFactory extends Factory
{
protected $model = Slot::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
$capacity = 5;
$startsAt = now()->startOfHour()->addHour();
return [
'starts_at' => $startsAt,
'ends_at' => $startsAt->copy()->addHour(),
'capacity' => $capacity,
'remaining' => $capacity,
];
}
/**
* Слот с заданной вместимостью, без броней.
*/
public function withCapacity(int $capacity): self
{
return $this->state(fn (): array => [
'capacity' => $capacity,
'remaining' => $capacity,
]);
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View file

@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View file

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View file

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('slots', function (Blueprint $table): void {
$table->id();
$table->dateTime('starts_at');
$table->dateTime('ends_at');
// remaining — вместимость минус подтверждённые брони.
// unsigned, чтобы база отвергла уход в минус.
$table->unsignedInteger('capacity');
$table->unsignedInteger('remaining');
$table->timestamps();
$table->index('starts_at');
});
}
public function down(): void
{
Schema::dropIfExists('slots');
}
};

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('holds', function (Blueprint $table): void {
$table->id();
$table->foreignId('slot_id')->constrained()->cascadeOnDelete();
// Уникальный индекс и обеспечивает идемпотентность: две
// одновременные вставки с одним ключом невозможны.
$table->uuid('idempotency_key')->unique();
$table->enum('status', ['held', 'confirmed', 'cancelled'])->default('held');
$table->dateTime('expires_at');
$table->dateTime('confirmed_at')->nullable();
$table->dateTime('cancelled_at')->nullable();
$table->timestamps();
// Под подсчёт активных холдов слота.
$table->index(['slot_id', 'status', 'expires_at']);
});
}
public function down(): void
{
Schema::dropIfExists('holds');
}
};

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Database\Seeders;
use App\Models\Slot;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Три слота для ручной проверки. На слоте с одним местом конфликт оверсела
* воспроизводится двумя запросами.
*/
public function run(): void
{
$start = now()->startOfHour()->addHour();
foreach ([10, 5, 1] as $index => $capacity) {
Slot::query()->create([
'starts_at' => $start->copy()->addHours($index),
'ends_at' => $start->copy()->addHours($index + 1),
'capacity' => $capacity,
'remaining' => $capacity,
]);
}
}
}

268
docs/README.md Normal file
View file

@ -0,0 +1,268 @@
# Как работает сервис
Документ описывает устройство API бронирования слотов: модель данных, поведение каждого эндпоинта и механизмы, обеспечивающие корректность под нагрузкой. Инструкции по запуску и примеры запросов — в [README](../README.md) в корне.
## Предметная область
**Слот** — окно с ограниченной вместимостью: складское окно, интервал доставки, время приёма. Имеет неизменную `capacity` и расходуемый остаток `remaining`.
**Холд** — временная заявка на одно место, живёт 5 минут. Место придержано, но ещё не продано.
**Подтверждение** — превращение холда в бронь. Только здесь место списывается окончательно.
Состояния холда:
```
┌──────────────► confirmed место списано
│ │
создан → held │ │ DELETE /holds/{id}
│ ▼
├──────────────► cancelled место возвращено
└── прошло 5 минут ► истёк статус в базе остаётся held,
но место больше не занимает
```
Истечение холда не меняет его статус в базе. Холд перестаёт занимать место в тот момент, когда `expires_at` уходит в прошлое, — это следует из условий запросов, а не из отдельной операции. Поэтому фоновая задача очистки не требуется для корректности.
## Инварианты
Свойства, которые сервис поддерживает при любой последовательности и конкурентности запросов:
```
capacity неизменна
remaining = capacity количество подтверждённых броней
0 ≤ remaining ≤ capacity
доступно к бронированию = remaining количество активных холдов
```
Оверсел — нарушение третьего условия. Механизмы, описанные ниже, существуют именно для его предотвращения.
## Схема данных
**`slots`**
| Колонка | Назначение |
|---|---|
| `starts_at`, `ends_at` | границы окна |
| `capacity` | вместимость, не меняется |
| `remaining` | остаток: вместимость минус подтверждённые брони |
Оба счётчика объявлены `unsignedInteger`: база не позволит записать отрицательное значение, даже если приложение ошибётся.
**`holds`**
| Колонка | Назначение |
|---|---|
| `slot_id` | внешний ключ на слот, каскадное удаление |
| `idempotency_key` | UUID с уникальным индексом |
| `status` | `held`, `confirmed`, `cancelled` |
| `expires_at` | момент истечения |
| `confirmed_at`, `cancelled_at` | отметки времени переходов |
Уникальный индекс на `idempotency_key` — не ограничение целостности «на всякий случай», а механизм идемпотентности: две одновременные вставки с одним ключом невозможны физически.
Составной индекс `(slot_id, status, expires_at)` покрывает единственный горячий запрос — подсчёт активных холдов слота.
Понятие «холд занимает место» определено один раз, в `Hold::scopeActive()`:
```php
$query->where('status', HoldStatus::Held)->where('expires_at', '>', now());
```
Это определение используют и проверка вместимости, и проекция доступности, поэтому разойтись они не могут.
## `GET /slots/availability`
Возвращает список слотов с числом мест, доступных к бронированию.
```json
[{"slot_id":1,"capacity":10,"remaining":10},{"slot_id":2,"capacity":5,"remaining":5}]
```
`remaining` в ответе — это остаток за вычетом активных холдов, то есть то, что клиент действительно может забронировать. Без вычета клиент видел бы свободные места и получал отказ при попытке их занять.
Проекция считается одним запросом:
```sql
select slots.id, slots.capacity, slots.remaining,
coalesce(active_holds.held_count, 0) as held_count
from slots
left join (
select slot_id, count(*) as held_count from holds
where status = 'held' and expires_at > ?
group by slot_id
) as active_holds on active_holds.slot_id = slots.id
order by slots.id
```
### Кеширование
Ответ кешируется на 10 секунд (`SLOT_AVAILABILITY_CACHE_TTL`, допустимый по требованиям диапазон 515).
Наивное кеширование через `Cache::remember` уязвимо к cache stampede: в момент истечения TTL все параллельные запросы одновременно обнаруживают промах и все идут в базу — пик нагрузки приходится на момент высокого трафика. Защита построена в три слоя:
**Single-flight.** Пересчитывает только процесс, захвативший `Cache::lock`. Внутри блокировки кеш перечитывается повторно: предыдущий владелец мог его уже заполнить.
**Stale-копия.** Хранится в шесть раз дольше основной записи. Процессы, не получившие блокировку, отдают её немедленно, не обращаясь к базе. Данные при этом устаревают на единицы секунд — для справочного списка это допустимо.
**Ограниченное ожидание.** На холодном кеше stale-копии нет: это первый запрос после старта либо момент сразу после инвалидации. Такой запрос ждёт владельца блокировки до трёх секунд и читает записанный им результат. Если не дождался — обращается к базе напрямую: чтение не должно завершаться ошибкой.
Инвалидация удаляет оба ключа — основной и stale, иначе после подтверждения брони клиенты продолжали бы получать устаревшие остатки.
## `POST /slots/{id}/hold`
Создаёт холд. Требует заголовок `Idempotency-Key` с корректным UUID, иначе `422`.
Последовательность:
```sql
select * from holds where idempotency_key = ? limit 1
select * from slots where slots.id = ? limit 1 for update
select count(*) from holds
where holds.slot_id = ? and status = 'held' and expires_at > ?
insert into holds (idempotency_key, status, expires_at, slot_id, ...) values (...)
```
Шаги 24 выполняются в транзакции.
### Идемпотентность
Повторный запрос с тем же ключом возвращает исходный холд и код `200` вместо `201`. Новая строка не создаётся.
Поиск по ключу перед вставкой — оптимизация для обычного повтора, не гарантия. Два одновременных запроса с одним ключом оба не найдут ничего и оба пойдут вставлять; второй получит нарушение уникального индекса. Исключение перехватывается, холд перечитывается и возвращается как результат. Гарантию даёт база, а не порядок операций в приложении.
Ключ, уже использованный для другого слота, приводит к `422`: молча вернуть найденный холд означало бы отдать клиенту бронь на слот, которого он не запрашивал.
### Проверка вместимости
Число доступных мест — это `remaining` минус количество активных холдов, то есть значение из двух таблиц. Одной атомарной операцией это не выражается, поэтому строка слота блокируется `SELECT ... FOR UPDATE`: конкурентные запросы по одному слоту выстраиваются в очередь, и посчитанное значение остаётся достоверным до конца транзакции. Блокировка затрагивает одну строку — бронирования разных слотов друг друга не задерживают.
Порядок обращений к базе внутри транзакции существен. MySQL на уровне изоляции REPEATABLE READ создаёт снимок данных при первом *неблокирующем* чтении; `SELECT ... FOR UPDATE` таким не является. Блокировка выполняется первой, поэтому снимок создаётся уже после её получения и подсчёт видит холды, вставленные конкурентом. Любое обычное чтение, добавленное перед блокировкой, зафиксировало бы снимок раньше и открыло бы окно для оверсела.
Создание холда не уменьшает `remaining` — место списывается только при подтверждении.
## `POST /holds/{id}/confirm`
Переводит холд в `confirmed` и списывает одно место.
```sql
select * from holds where holds.id = ? limit 1 for update
update slots set remaining = remaining - 1, updated_at = ?
where slots.id = ? and remaining > 0
update holds set status = ?, confirmed_at = ?, updated_at = ? where id = ?
```
Блокируется строка **холда**, а не слота: решение зависит от состояния самого холда, и блокировка нужна, чтобы два одновременных подтверждения одного холда не прошли проверки одновременно.
### Защита от оверсела
Предварительной проверки остатка нет. Условие находится в самом `UPDATE`, и результат определяется числом затронутых строк:
```php
$consumed = Slot::query()
->whereKey($hold->slot_id)
->where('remaining', '>', 0)
->decrement('remaining');
if ($consumed === 0) {
throw SlotBookingException::capacityExhausted($hold->slot_id);
}
```
Новое значение вычисляет база (`remaining = remaining - 1`), а не приложение, поэтому чужое списание невозможно затереть. Проверка и списание — одна операция, промежутка, в который мог бы вклиниться конкурент, не существует. Ноль затронутых строк означает, что мест не было, и приводит к `409`.
Этот приём предпочтительнее блокировки, когда условие выражается в том же запросе, который меняет данные: ожидания не возникает, конкуренты не выстраиваются в очередь.
Гарантия дублируется на уровне схемы: `remaining` объявлен без знака, поэтому даже при ошибке в приложении база отвергнет уход в минус.
### Идемпотентность и проверки состояния
Повторное подтверждение возвращает `200` и тот же результат; место списывается один раз.
Порядок проверок: сначала «уже подтверждён», затем «отменён или истёк». Подтверждённый холд с истёкшим `expires_at` — нормальная ситуация: бронь действительна, срок относился к периоду ожидания подтверждения. Проверка истечения, поставленная первой, ломала бы идемпотентность спустя пять минут после подтверждения.
### Инвалидация кеша
Кеш сбрасывается после фиксации транзакции, а не внутри неё. Сброс внутри оставлял бы окно, в котором читатель обращается к базе, видит ещё не зафиксированные значения и записывает в кеш устаревшие данные на весь TTL.
Создание холда кеш намеренно не инвалидирует: требования предписывают инвалидацию после подтверждения и отмены. Это согласуется и с назначением кеша — поток холдов сбрасывал бы его непрерывно, обнуляя смысл кеширования. Доступность носит справочный характер, авторитетная проверка выполняется при создании холда.
## `DELETE /holds/{id}`
Переводит холд в `cancelled`.
Место возвращается только при отмене подтверждённого холда, поскольку только подтверждение его списывало. Холд в статусе `held` при отмене перестаёт учитываться в активных, и слот становится доступен без изменения `remaining`. Инкремент дополнительно ограничен условием `remaining < capacity`, поэтому никакая последовательность отмен не увеличит остаток выше вместимости.
Повторная отмена возвращает `200`; место возвращается один раз.
## Конкурентность: два механизма
| Операция | Механизм | Причина выбора |
|---|---|---|
| `hold` | `SELECT ... FOR UPDATE` по строке слота | решение зависит от подсчёта в другой таблице, одним запросом не выражается |
| `confirm` | условие в `UPDATE`, проверка по числу затронутых строк | условие выражается в том же запросе, который меняет данные |
| идемпотентность | уникальный индекс | зазор между проверкой и вставкой средствами приложения не закрывается |
Проверено под реальной конкуренцией (20 параллельных запросов, сервер в 8 воркеров):
| Сценарий | Результат |
|---|---|
| 20 холдов на слот с одним местом | один `201`, девятнадцать `409`, одна строка в базе |
| 20 подтверждений за одно место | один `200`, девятнадцать `409`, `remaining` = 0 |
| 20 холдов с одинаковым ключом | один `201`, девятнадцать `200`, одна строка в базе |
## Формат ошибок
```json
{"message": "Slot 3 has no remaining capacity.", "reason": "capacity_exhausted"}
```
| `reason` | Код | Когда |
|---|---|---|
| `capacity_exhausted` | 409 | мест нет при создании или подтверждении |
| `hold_cancelled` | 409 | подтверждение отменённого холда |
| `hold_expired` | 409 | подтверждение истёкшего холда |
| `idempotency_key_reuse` | 422 | ключ уже использован для другого слота |
| `not_found` | 404 | слот или холд не существует |
Ошибки валидации отдаются в стандартном для Laravel формате с объектом `errors`.
Сервисный слой не работает с HTTP: он бросает `SlotBookingException` с машиночитаемым кодом, а сопоставление с кодами ответа описано в `bootstrap/app.php`. Тот же сервис можно вызвать из консольной команды или обработчика очереди без изменений.
## Реализационные решения
**Активные холды считаются запросом, а не хранятся счётчиком.** Фоновая очистка по условиям задачи не требуется, а счётчик без неё разошёлся бы с реальностью в момент, когда первый холд истекает молча. Фильтр по `expires_at` освобождает место автоматически и точно в срок.
**Кеш и блокировки хранятся в MySQL** (`CACHE_STORE=database`), поэтому проект поднимается без дополнительных сервисов. Код обращается только к фасаду `Cache`, так что переход на Redis — изменение одной переменной окружения.
**Префикс `api` у маршрутов отключён**, чтобы пути совпадали с указанными в задании. Маршруты при этом объявлены в `routes/api.php` и получают stateless-мидлвары группы `api`.
**Привязка моделей к маршрутам не используется**: сервису нужно читать строку внутри собственной транзакции с блокировкой, а мидлвар сделал бы это раньше и без неё.
**Ответы не заворачиваются в `data`**: формат доступности задан в требованиях как массив, остальные эндпоинты приведены к той же конвенции.
## Тесты
27 функциональных тестов, 90 проверок. Выполняются против MySQL, а не SQLite: под проверкой находятся `SELECT ... FOR UPDATE` и условный декремент, которые SQLite не воспроизводит.
Покрыто, помимо основных сценариев:
- невозможность оверсела при конкурентном подтверждении последнего места;
- отсутствие обращений к базе у запроса, проигравшего гонку за пересчёт кеша;
- истечение TTL кеша и его инвалидация после подтверждения;
- отсутствие инвалидации при создании холда;
- освобождение мест истёкшими и отменёнными холдами;
- идемпотентность создания, подтверждения и отмены;
- отказ при переиспользовании ключа для другого слота.
## Границы
Не реализовано, так как выходит за рамки задания:
- фоновая очистка истёкших холдов (для корректности не нужна, в продакшене — чтобы таблица не росла);
- аутентификация и привязка холда к пользователю;
- пагинация и фильтры доступности;
- ограничение частоты запросов, уведомления о смене статуса холда.
При высокой конкуренции на один популярный слот блокировка строки станет узким местом: запросы к нему выстроятся в очередь. В этом случае имеет смысл перейти к счётчику, уменьшающемуся уже при создании холда, и добавить возврат мест по истечении. Такая схема сложнее и требует фоновой очистки, поэтому при текущих требованиях выбрана простая.

View file

@ -0,0 +1,682 @@
{
"info": {
"name": "Slot Booking API",
"description": "Бронирование слотов: горячий кеш, идемпотентные холды, защита от оверсела.\n\nПеред прогоном сценария нужна свежая база:\n\n php artisan migrate:fresh --seed\n php artisan serve --host=0.0.0.0 --port=8001\n\nПапка «Сценарий по порядку» рассчитана на запуск через Collection Runner: запросы связаны переменными hold_id и idem_key, которые заполняются автоматически.\n\nПеременные коллекции:\n- base_url — адрес сервера\n- slot_id — слот с одним местом (3), на нём воспроизводится конфликт\n- other_slot_id — слот с десятью местами (1)\n- hold_id, idem_key — заполняются скриптами, руками трогать не нужно",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"variable": [
{
"key": "base_url",
"value": "http://localhost:8001",
"type": "string"
},
{
"key": "slot_id",
"value": "3",
"type": "string"
},
{
"key": "other_slot_id",
"value": "1",
"type": "string"
},
{
"key": "hold_id",
"value": "",
"type": "string"
},
{
"key": "idem_key",
"value": "",
"type": "string"
}
],
"item": [
{
"name": "Сценарий по порядку",
"description": "Полный жизненный цикл холда. Запускать сверху вниз или целиком через Runner.",
"item": [
{
"name": "1. Доступность — исходное состояние",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK', () => pm.response.to.have.status(200));",
"",
"const slots = pm.response.json();",
"const target = Number(pm.collectionVariables.get('slot_id'));",
"const slot = slots.find((s) => s.slot_id === target);",
"",
"pm.test('слот ' + target + ' есть в ответе', () => pm.expect(slot).to.not.be.undefined);",
"",
"pm.test('на слоте есть свободное место (иначе нужен свежий seed)', function () {",
" pm.expect(slot.remaining, 'запусти: php artisan migrate:fresh --seed').to.be.above(0);",
"});",
"",
"console.log('Доступность:', JSON.stringify(slots));"
]
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/slots/availability",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"availability"
]
},
"description": "capacity — вместимость слота, remaining — сколько реально можно забронировать: подтверждённые брони и активные холды уже вычтены.\n\nОтвет кешируется на 10 секунд."
}
},
{
"name": "2. Создать холд → 201",
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"// Генерируем UUID и запоминаем его в переменной коллекции,",
"// чтобы следующий запрос смог повторить вызов с тем же ключом.",
"pm.collectionVariables.set('idem_key', pm.variables.replaceIn('{{$guid}}'));"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('201 Created', () => pm.response.to.have.status(201));",
"",
"const hold = pm.response.json();",
"",
"pm.test('статус held', () => pm.expect(hold.status).to.eql('held'));",
"pm.test('слот тот, который просили', () => {",
" pm.expect(hold.slot_id).to.eql(Number(pm.collectionVariables.get('slot_id')));",
"});",
"pm.test('срок жизни холда задан', () => pm.expect(hold.expires_at).to.be.a('string'));",
"",
"pm.collectionVariables.set('hold_id', hold.hold_id);",
"console.log('hold_id =', hold.hold_id, '| ключ =', pm.collectionVariables.get('idem_key'));"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "{{idem_key}}"
}
],
"url": {
"raw": "{{base_url}}/slots/{{slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{slot_id}}",
"hold"
]
},
"description": "Тела нет — всё нужное в URL и заголовке Idempotency-Key.\n\nХолд придерживает место на 5 минут, но remaining слота пока не уменьшает: место списывается только при подтверждении.\n\nПолученный hold_id автоматически сохраняется в переменную коллекции."
}
},
{
"name": "3. Повтор с тем же ключом → 200",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK, а не 201 — ничего не создано', () => pm.response.to.have.status(200));",
"",
"pm.test('вернулся тот же холд', () => {",
" pm.expect(pm.response.json().hold_id).to.eql(Number(pm.collectionVariables.get('hold_id')));",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "{{idem_key}}"
}
],
"url": {
"raw": "{{base_url}}/slots/{{slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{slot_id}}",
"hold"
]
},
"description": "Тот же ключ, что и в предыдущем запросе. Это имитация ретрая клиента после таймаута.\n\nВторого холда не появится, второе место не съедено. Статус 200 вместо 201 — потому что ресурс создан не этим запросом."
}
},
{
"name": "4. Новый ключ, мест нет → 409",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('409 Conflict', () => pm.response.to.have.status(409));",
"pm.test('reason = capacity_exhausted', () => {",
" pm.expect(pm.response.json().reason).to.eql('capacity_exhausted');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "{{$guid}}"
}
],
"url": {
"raw": "{{base_url}}/slots/{{slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{slot_id}}",
"hold"
]
},
"description": "Ключ новый ({{$guid}} подставляет свежий UUID при каждой отправке), значит это уже другой запрос, а не повтор.\n\nЕдинственное место слота придержано холдом из шага 2, поэтому — конфликт. Именно это и есть защита от оверсела на этапе создания холда."
}
},
{
"name": "5. Тот же ключ, другой слот → 422",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('422 Unprocessable Content', () => pm.response.to.have.status(422));",
"pm.test('reason = idempotency_key_reuse', () => {",
" pm.expect(pm.response.json().reason).to.eql('idempotency_key_reuse');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "{{idem_key}}"
}
],
"url": {
"raw": "{{base_url}}/slots/{{other_slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{other_slot_id}}",
"hold"
]
},
"description": "Ключ из шага 2, но слот другой. Молча вернуть найденный холд нельзя — клиент получил бы бронь на слот, которого не просил.\n\nЭто ошибка клиента, поэтому 422, а не 409."
}
},
{
"name": "6. Подтвердить холд → 200",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK', () => pm.response.to.have.status(200));",
"",
"const hold = pm.response.json();",
"",
"pm.test('статус confirmed', () => pm.expect(hold.status).to.eql('confirmed'));",
"pm.test('confirmed_at заполнен', () => pm.expect(hold.confirmed_at).to.not.be.null);"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/holds/{{hold_id}}/confirm",
"host": [
"{{base_url}}"
],
"path": [
"holds",
"{{hold_id}}",
"confirm"
]
},
"description": "Здесь место списывается окончательно, одним атомарным UPDATE с условием remaining > 0.\n\nПосле коммита сбрасывается кеш доступности — проверяем это следующим запросом."
}
},
{
"name": "7. Доступность — кеш сброшен",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK', () => pm.response.to.have.status(200));",
"",
"const target = Number(pm.collectionVariables.get('slot_id'));",
"const slot = pm.response.json().find((s) => s.slot_id === target);",
"",
"pm.test('remaining = 0 сразу, не дожидаясь истечения TTL', () => {",
" pm.expect(slot.remaining).to.eql(0);",
"});"
]
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/slots/availability",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"availability"
]
},
"description": "remaining стал нулём немедленно, хотя TTL кеша 10 секунд. Это и есть инвалидация после подтверждения.\n\nСравни с шагом 2: создание холда кеш намеренно не сбрасывает."
}
},
{
"name": "8. Подтвердить повторно → 200",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK — операция идемпотентна', () => pm.response.to.have.status(200));",
"pm.test('статус остался confirmed', () => {",
" pm.expect(pm.response.json().status).to.eql('confirmed');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/holds/{{hold_id}}/confirm",
"host": [
"{{base_url}}"
],
"path": [
"holds",
"{{hold_id}}",
"confirm"
]
},
"description": "Второе подтверждение того же холда не списывает второе место. Проверить можно шагом 7: remaining так и остался нулём, а не ушёл в минус."
}
},
{
"name": "9. Отменить холд → 200",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK', () => pm.response.to.have.status(200));",
"",
"const hold = pm.response.json();",
"",
"pm.test('статус cancelled', () => pm.expect(hold.status).to.eql('cancelled'));",
"pm.test('cancelled_at заполнен', () => pm.expect(hold.cancelled_at).to.not.be.null);"
]
}
}
],
"request": {
"method": "DELETE",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/holds/{{hold_id}}",
"host": [
"{{base_url}}"
],
"path": [
"holds",
"{{hold_id}}"
]
},
"description": "Тела у запроса нет.\n\nХолд был подтверждён, значит место списывалось — и отмена его возвращает. Если бы отменялся неподтверждённый холд, remaining не изменился бы: списания не было."
}
},
{
"name": "10. Подтвердить отменённый → 409",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('409 Conflict', () => pm.response.to.have.status(409));",
"pm.test('reason = hold_cancelled', () => {",
" pm.expect(pm.response.json().reason).to.eql('hold_cancelled');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/holds/{{hold_id}}/confirm",
"host": [
"{{base_url}}"
],
"path": [
"holds",
"{{hold_id}}",
"confirm"
]
},
"description": "Отменённый холд подтвердить нельзя. Запрос корректен, но конфликтует с текущим состоянием ресурса — это семантика 409."
}
},
{
"name": "11. Доступность — место вернулось",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('200 OK', () => pm.response.to.have.status(200));",
"",
"const target = Number(pm.collectionVariables.get('slot_id'));",
"const slot = pm.response.json().find((s) => s.slot_id === target);",
"",
"pm.test('remaining вернулся к 1', () => pm.expect(slot.remaining).to.eql(1));",
"pm.test('remaining не превысил capacity', () => {",
" pm.expect(slot.remaining).to.be.at.most(slot.capacity);",
"});"
]
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/slots/availability",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"availability"
]
},
"description": "Место снова доступно, и remaining не превысил capacity — сколько бы раз ни повторить отмену."
}
}
]
},
{
"name": "Ошибки и валидация",
"description": "Отдельные запросы, порядок не важен.",
"item": [
{
"name": "Без Idempotency-Key → 422",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('422 Unprocessable Content', () => pm.response.to.have.status(422));",
"pm.test('ошибка про idempotency_key', () => {",
" pm.expect(pm.response.json().errors).to.have.property('idempotency_key');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/slots/{{other_slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{other_slot_id}}",
"hold"
]
},
"description": "Заголовок обязателен. Валидация отрабатывает до контроллера, поэтому в базу запрос вообще не идёт."
}
},
{
"name": "Idempotency-Key не UUID → 422",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('422 Unprocessable Content', () => pm.response.to.have.status(422));",
"pm.test('ошибка про idempotency_key', () => {",
" pm.expect(pm.response.json().errors).to.have.property('idempotency_key');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "not-a-uuid"
}
],
"url": {
"raw": "{{base_url}}/slots/{{other_slot_id}}/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"{{other_slot_id}}",
"hold"
]
},
"description": "Формат ключа проверяется правилом uuid. Случайная строка вместо UUID — ошибка клиента."
}
},
{
"name": "Несуществующий слот → 404",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('404 Not Found', () => pm.response.to.have.status(404));",
"pm.test('reason = not_found', () => {",
" pm.expect(pm.response.json().reason).to.eql('not_found');",
"});",
"pm.test('имя класса модели в ответ не утекает', () => {",
" pm.expect(pm.response.text()).to.not.include('App\\\\Models');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Idempotency-Key",
"value": "{{$guid}}"
}
],
"url": {
"raw": "{{base_url}}/slots/999/hold",
"host": [
"{{base_url}}"
],
"path": [
"slots",
"999",
"hold"
]
},
"description": "Аккуратный JSON без стектрейса и без имени класса модели."
}
},
{
"name": "Несуществующий холд → 404",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('404 Not Found', () => pm.response.to.have.status(404));",
"pm.test('reason = not_found', () => {",
" pm.expect(pm.response.json().reason).to.eql('not_found');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/holds/999999/confirm",
"host": [
"{{base_url}}"
],
"path": [
"holds",
"999999",
"confirm"
]
}
}
}
]
}
]
}

17
package.json Normal file
View file

@ -0,0 +1,17 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.7"
}
}

35
phpunit.xml Normal file
View file

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<!-- Против MySQL: SQLite не воспроизводит SELECT ... FOR UPDATE
и условный декремент, то есть ровно то, что проверяется. -->
<env name="DB_CONNECTION" value="mysql"/>
<env name="DB_DATABASE" value="slots_test"/>
<env name="DB_URL" value=""/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

25
public/.htaccess Normal file
View file

@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

0
public/favicon.ico Normal file
View file

20
public/index.php Normal file
View file

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

2
public/robots.txt Normal file
View file

@ -0,0 +1,2 @@
User-agent: *
Disallow:

11
resources/css/app.css Normal file
View file

@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

1
resources/js/app.js Normal file
View file

@ -0,0 +1 @@
import './bootstrap';

4
resources/js/bootstrap.js vendored Normal file
View file

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

File diff suppressed because one or more lines are too long

18
routes/api.php Normal file
View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
use App\Http\Controllers\AvailabilityController;
use App\Http\Controllers\HoldController;
use Illuminate\Support\Facades\Route;
Route::get('/slots/availability', [AvailabilityController::class, 'index']);
Route::post('/slots/{slot}/hold', [HoldController::class, 'store'])
->whereNumber('slot');
Route::post('/holds/{hold}/confirm', [HoldController::class, 'confirm'])
->whereNumber('hold');
Route::delete('/holds/{hold}', [HoldController::class, 'destroy'])
->whereNumber('hold');

8
routes/console.php Normal file
View file

@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

7
routes/web.php Normal file
View file

@ -0,0 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

4
storage/app/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

2
storage/app/private/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/app/public/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

9
storage/framework/.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

3
storage/framework/cache/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View file

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/sessions/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/testing/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/views/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/logs/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

View file

@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
final class AvailabilityTest extends TestCase
{
use RefreshDatabase;
public function test_it_lists_every_slot_with_capacity_and_remaining(): void
{
$first = Slot::factory()->withCapacity(10)->create();
$second = Slot::factory()->withCapacity(5)->create();
$this->getJson('/slots/availability')
->assertOk()
->assertExactJson([
['slot_id' => $first->id, 'capacity' => 10, 'remaining' => 10],
['slot_id' => $second->id, 'capacity' => 5, 'remaining' => 5],
]);
}
public function test_active_holds_are_subtracted_from_remaining(): void
{
$slot = Slot::factory()->withCapacity(5)->create();
Hold::factory()->count(2)->for($slot)->create();
$this->getJson('/slots/availability')
->assertOk()
->assertJsonPath('0.remaining', 3);
}
public function test_expired_holds_stop_reserving_capacity(): void
{
$slot = Slot::factory()->withCapacity(2)->create();
Hold::factory()->expired()->for($slot)->create();
$this->getJson('/slots/availability')
->assertOk()
->assertJsonPath('0.remaining', 2);
}
public function test_cancelled_holds_stop_reserving_capacity(): void
{
$slot = Slot::factory()->withCapacity(2)->create();
Hold::factory()->cancelled()->for($slot)->create();
$this->getJson('/slots/availability')
->assertOk()
->assertJsonPath('0.remaining', 2);
}
public function test_the_response_is_served_from_cache_within_the_ttl(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
// Меняем источник истины за спиной кеша.
$slot->update(['remaining' => 1]);
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
}
public function test_the_cache_expires_after_the_configured_ttl(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
$slot->update(['remaining' => 1]);
$this->travel(config('slots.availability_cache_ttl') + 1)->seconds();
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 1);
}
public function test_a_caller_that_loses_the_recompute_race_is_served_stale_data(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
// Прогревает и основную запись, и stale-копию.
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
$this->travel(config('slots.availability_cache_ttl') + 1)->seconds();
$slot->update(['remaining' => 0]);
// Имитируем воркер, который пересчитывает прямо сейчас.
$lock = Cache::lock('slots:availability:lock', 10);
$this->assertTrue($lock->get());
DB::enableQueryLog();
$response = $this->getJson('/slots/availability');
$queries = DB::getQueryLog();
DB::disableQueryLog();
$lock->release();
$response->assertOk()->assertJsonPath('0.remaining', 3);
$this->assertSame([], $queries, 'Проигравший гонку за пересчёт не должен обращаться к базе.');
}
}

View file

@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Enums\HoldStatus;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
final class CancelHoldTest extends TestCase
{
use RefreshDatabase;
public function test_cancelling_a_held_hold_releases_it_without_touching_remaining(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
$hold = Hold::factory()->for($slot)->create();
$this->deleteJson("/holds/{$hold->id}")
->assertOk()
->assertJsonPath('status', HoldStatus::Cancelled->value)
->assertJsonPath('cancelled_at', fn (?string $value): bool => $value !== null);
// Место не списывалось, remaining меняться не должен.
$this->assertSame(1, $slot->refresh()->remaining);
// Освободившееся место снова можно забронировать.
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 1);
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated();
}
public function test_cancelling_a_confirmed_hold_gives_the_seat_back(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
$holdId = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated()
->json('hold_id');
$this->postJson("/holds/{$holdId}/confirm")->assertOk();
$this->assertSame(0, $slot->refresh()->remaining);
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 0);
$this->deleteJson("/holds/{$holdId}")->assertOk();
$this->assertSame(1, $slot->refresh()->remaining);
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 1);
}
public function test_cancelling_twice_is_idempotent(): void
{
$slot = Slot::factory()->withCapacity(2)->create();
$holdId = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated()
->json('hold_id');
$this->postJson("/holds/{$holdId}/confirm")->assertOk();
$this->assertSame(1, $slot->refresh()->remaining);
$this->deleteJson("/holds/{$holdId}")->assertOk();
$this->deleteJson("/holds/{$holdId}")->assertOk();
// Место возвращается ровно один раз.
$this->assertSame(2, $slot->refresh()->remaining);
}
public function test_it_returns_404_for_an_unknown_hold(): void
{
$this->deleteJson('/holds/999')->assertNotFound();
}
}

View file

@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Enums\HoldStatus;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
final class ConfirmHoldTest extends TestCase
{
use RefreshDatabase;
public function test_it_confirms_a_hold_and_consumes_one_seat(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
$hold = Hold::factory()->for($slot)->create();
$this->postJson("/holds/{$hold->id}/confirm")
->assertOk()
->assertJsonPath('status', HoldStatus::Confirmed->value)
->assertJsonPath('confirmed_at', fn (?string $value): bool => $value !== null);
$this->assertSame(2, $slot->refresh()->remaining);
$this->assertSame(HoldStatus::Confirmed, $hold->refresh()->status);
}
public function test_confirming_twice_consumes_only_one_seat(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
$hold = Hold::factory()->for($slot)->create();
$this->postJson("/holds/{$hold->id}/confirm")->assertOk();
$this->postJson("/holds/{$hold->id}/confirm")->assertOk();
$this->assertSame(2, $slot->refresh()->remaining);
}
public function test_two_holds_racing_for_the_last_seat_cannot_oversell(): void
{
// Состояние после проигранной гонки: два холда на одно место.
// Созданы напрямую, минуя проверку вместимости.
$slot = Slot::factory()->withCapacity(1)->create();
$winner = Hold::factory()->for($slot)->create();
$loser = Hold::factory()->for($slot)->create();
$this->postJson("/holds/{$winner->id}/confirm")->assertOk();
$this->postJson("/holds/{$loser->id}/confirm")
->assertConflict()
->assertJsonPath('reason', 'capacity_exhausted');
$this->assertSame(0, $slot->refresh()->remaining);
$this->assertSame(HoldStatus::Held, $loser->refresh()->status);
}
public function test_it_refuses_to_confirm_an_expired_hold(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
$hold = Hold::factory()->expired()->for($slot)->create();
$this->postJson("/holds/{$hold->id}/confirm")
->assertConflict()
->assertJsonPath('reason', 'hold_expired');
$this->assertSame(1, $slot->refresh()->remaining);
}
public function test_it_refuses_to_confirm_a_cancelled_hold(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
$hold = Hold::factory()->cancelled()->for($slot)->create();
$this->postJson("/holds/{$hold->id}/confirm")
->assertConflict()
->assertJsonPath('reason', 'hold_cancelled');
$this->assertSame(1, $slot->refresh()->remaining);
}
public function test_it_invalidates_the_availability_cache(): void
{
$slot = Slot::factory()->withCapacity(3)->create();
$key = (string) Str::uuid();
// Кеш прогрет до всех изменений.
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
$holdId = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => $key])
->assertCreated()
->json('hold_id');
// Создание холда кеш не сбрасывает: доступность справочная,
// авторитетная проверка — POST /slots/{id}/hold.
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 3);
$this->postJson("/holds/{$holdId}/confirm")->assertOk();
$this->getJson('/slots/availability')->assertJsonPath('0.remaining', 2);
}
public function test_it_returns_404_for_an_unknown_hold(): void
{
$this->postJson('/holds/999/confirm')->assertNotFound();
}
}

View file

@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Enums\HoldStatus;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
final class CreateHoldTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_a_hold(): void
{
$slot = Slot::factory()->withCapacity(2)->create();
$key = (string) Str::uuid();
$response = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => $key])
->assertCreated()
->assertJsonPath('slot_id', $slot->id)
->assertJsonPath('status', HoldStatus::Held->value);
$hold = Hold::query()->sole();
$this->assertSame($key, $hold->idempotency_key);
$this->assertSame($hold->id, $response->json('hold_id'));
// Холды живут заданный TTL, по умолчанию пять минут.
$this->assertEqualsWithDelta(
now()->addSeconds((int) config('slots.hold_ttl'))->timestamp,
$hold->expires_at->timestamp,
2,
);
}
public function test_a_hold_does_not_consume_a_seat_until_it_is_confirmed(): void
{
$slot = Slot::factory()->withCapacity(2)->create();
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated();
$this->assertSame(2, $slot->refresh()->remaining);
}
public function test_replaying_the_same_idempotency_key_returns_the_original_hold(): void
{
$slot = Slot::factory()->withCapacity(5)->create();
$key = (string) Str::uuid();
$first = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => $key])
->assertCreated();
$second = $this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => $key])
->assertOk();
$this->assertSame($first->json('hold_id'), $second->json('hold_id'));
$this->assertSame(1, Hold::query()->count());
}
public function test_it_returns_409_when_capacity_is_exhausted(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated();
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertConflict()
->assertJsonPath('reason', 'capacity_exhausted');
$this->assertSame(1, Hold::query()->count());
}
public function test_capacity_freed_by_an_expired_hold_can_be_taken_again(): void
{
$slot = Slot::factory()->withCapacity(1)->create();
Hold::factory()->expired()->for($slot)->create();
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => (string) Str::uuid()])
->assertCreated();
}
public function test_it_rejects_a_missing_idempotency_key(): void
{
$slot = Slot::factory()->create();
$this->postJson("/slots/{$slot->id}/hold")
->assertUnprocessable()
->assertJsonValidationErrors('idempotency_key');
}
public function test_it_rejects_an_idempotency_key_that_is_not_a_uuid(): void
{
$slot = Slot::factory()->create();
$this->postJson("/slots/{$slot->id}/hold", [], ['Idempotency-Key' => 'not-a-uuid'])
->assertUnprocessable()
->assertJsonValidationErrors('idempotency_key');
}
public function test_it_rejects_reusing_an_idempotency_key_for_another_slot(): void
{
$first = Slot::factory()->create();
$second = Slot::factory()->create();
$key = (string) Str::uuid();
$this->postJson("/slots/{$first->id}/hold", [], ['Idempotency-Key' => $key])
->assertCreated();
$this->postJson("/slots/{$second->id}/hold", [], ['Idempotency-Key' => $key])
->assertUnprocessable()
->assertJsonPath('reason', 'idempotency_key_reuse');
}
public function test_it_returns_404_for_an_unknown_slot(): void
{
$this->postJson('/slots/999/hold', [], ['Idempotency-Key' => (string) Str::uuid()])
->assertNotFound()
->assertExactJson(['message' => 'Resource not found.', 'reason' => 'not_found']);
}
}

10
tests/TestCase.php Normal file
View file

@ -0,0 +1,10 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

18
vite.config.js Normal file
View file

@ -0,0 +1,18 @@
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
tailwindcss(),
],
server: {
watch: {
ignored: ['**/storage/framework/views/**'],
},
},
});