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>
70 lines
1.7 KiB
PHP
70 lines
1.7 KiB
PHP
<?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();
|
|
}
|
|
}
|