Compare commits

..

10 Commits

Author SHA1 Message Date
8684a6e19b feat: fix idempotency cache 2026-05-18 08:50:13 +07:00
42433a8cbf feat: add invalidation 2026-05-17 21:53:04 +07:00
4c018d0bf7 feat: add readme 2026-05-17 21:48:44 +07:00
0179410ce9 fix: bugs 2026-05-17 21:48:34 +07:00
8dfe50e7a3 feat: fix env and start 2026-05-17 21:29:05 +07:00
a0d59a87d0 feat: add seeder 2026-05-17 21:22:53 +07:00
93ba9de599 feat: add routes and bootstrap 2026-05-17 21:16:32 +07:00
f7a19b72ad feat: add controller logic 2026-05-17 21:10:10 +07:00
8d21cfb983 feat: add service logic 2026-05-17 20:58:40 +07:00
dfaec2d948 feat: add middleware 2026-05-17 19:50:49 +07:00
12 changed files with 435 additions and 74 deletions

View File

@ -1,6 +1,6 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_KEY=base64:MR10CFjbrEDkYi2FLwW0tNNHGHleWthQlxD5LLKdFnQ=
APP_DEBUG=true
APP_URL=http://localhost
@ -20,12 +20,12 @@ LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=slots
DB_USERNAME=slots
DB_PASSWORD=slots
SESSION_DRIVER=database
SESSION_LIFETIME=120
@ -37,13 +37,13 @@ BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
CACHE_STORE=redis
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

View File

@ -1,59 +1,48 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
# Start
```bash
git clone ...
docker compose up -d
```
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
# Доступность
```bash
curl -s "http://localhost:8080/api/slots/availability"
```
## About Laravel
# Создать hold
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
```bash
curl -s -X POST "http://localhost:8080/api/slots/1/hold" \
-H "X-Idempotency-Key: 3f36b498-4144-43d3-9853-b22379b520ff"
```
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
# Подтвердить
```bash
curl -s -X POST "http://localhost:8080/api/holds/1/confirm"
```
Laravel is accessible, powerful, and provides tools required for large, robust applications.
# Отменить
```bash
curl -s -X DELETE "http://localhost:8080/api/holds/1"
```
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
# Oversell
```bash
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: 20ff64a3-43d6-4ddb-874e-441d0a87570e"
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: d7db5b73-1ea5-4156-99b6-dbace1b483a9"
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: ddd6174c-0fda-4765-8413-12dd3cda9692"
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: 7af943b4-dfcf-4d5e-99c0-fa06fc9b2a6a"
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: fcb4b745-e928-4af3-bb35-c307cc5a574e"
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: 38ae0adb-7f23-40c0-9ac1-069a15d89a98"
```

View File

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use RuntimeException;
class HoldNotAvailableException extends RuntimeException
{
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use RuntimeException;
class SlotCapacityExceededException extends RuntimeException
{
}

View File

@ -2,9 +2,18 @@
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\SlotService;
use Illuminate\Http\JsonResponse;
class AvailabilityController extends Controller
{
//
public function __construct(
private readonly SlotService $slotService,
) {
}
public function index(): JsonResponse
{
return response()->json($this->slotService->getAvailability());
}
}

View File

@ -2,9 +2,63 @@
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exceptions\HoldNotAvailableException;
use App\Exceptions\SlotCapacityExceededException;
use App\Models\Hold;
use App\Models\Slot;
use App\Services\SlotService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class HoldController extends Controller
{
//
public function __construct(
private readonly SlotService $slotService,
) {
}
public function store(Slot $slot): JsonResponse
{
$idempotencyKey = request()->header('X-Idempotency-Key');
try {
$hold = $this->slotService->createHold($slot, $idempotencyKey);
} catch (SlotCapacityExceededException $exception) {
return response()->json([
'message' => $exception->getMessage()
], Response::HTTP_CONFLICT);
}
return response()->json($this->holdPayload($hold), Response::HTTP_CREATED);
}
public function confirm(Hold $hold): JsonResponse
{
try {
$hold = $this->slotService->confirmHold($hold);
} catch (HoldNotAvailableException $exception) {
return response()->json([
'message' => $exception->getMessage()
], Response::HTTP_CONFLICT);
}
return response()->json($this->holdPayload($hold));
}
public function destroy(Hold $hold): JsonResponse
{
$hold = $this->slotService->cancelHold($hold);
return response()->json($this->holdPayload($hold));
}
private function holdPayload(Hold $hold): array
{
return [
'id' => $hold->id,
'slot_id' => $hold->slot_id,
'status' => $hold->status,
'expires_at' => $hold->expires_at->toIso8601String(),
];
}
}

View File

@ -0,0 +1,110 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
class IdempotencyMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$idempotencyKey = $request->header('X-Idempotency-Key');
if (! is_string($idempotencyKey) || ! Str::isUuid($idempotencyKey)) {
return response()->json([
'message' => 'X-Idempotency-Key MUST be a valid UUID.',
], Response::HTTP_BAD_REQUEST);
}
$cacheKey = $this->cacheKey($request, $idempotencyKey);
$lockKey = $this->lockKey($request, $idempotencyKey);
// Проверяем чтобы не выполнять код
$cached = Cache::get($cacheKey);
if (is_array($cached)) {
return $this->replayResponse($cached);
}
$lock = Cache::lock($lockKey, config('slots.idempotency_lock_seconds'));
if (! $lock->get()) {
return $this->waitForCachedResponse($cacheKey) ?? $this->inProgressResponse();
}
$response = $next($request);
try {
$cached = Cache::get($cacheKey);
if (is_array($cached)) {
return $this->replayResponse($cached);
}
if ($response instanceof JsonResponse) {
Cache::put($cacheKey, [
'status' => $response->getStatusCode(),
'body' => $response->getData(true),
], config('slots.idempotency_cache_ttl_seconds'));
}
return $response;
} finally {
$lock->release();
}
}
private function waitForCachedResponse(string $cacheKey): ?JsonResponse
{
$deadline = microtime(true) + config('slots.idempotency_wait_seconds');
while (microtime(true) < $deadline) {
$cached = Cache::get($cacheKey);
if (is_array($cached) && isset($cached['body'], $cached['status'])) {
return $this->replayResponse($cached);
}
usleep(100_000);
}
return null;
}
private function inProgressResponse(): ?JsonResponse
{
return response()->json([
'message' => 'Conflict. Retry with same idempotency key',
], Response::HTTP_CONFLICT)
->header('X-Retry-After', 1);
}
/**
* @param array{status: int, body: string} $data
*/
private function replayResponse(array $data): JsonResponse
{
return response()->json($data['body'], (int) $data['status']);
}
private function cacheKey(Request $request, string $idempotencyKey): string
{
return sprintf(
'idempotency:response:%s:%s:%s',
strtoupper($request->method()),
$request->path(),
$idempotencyKey
);
}
private function lockKey(Request $request, string $idempotencyKey): string
{
return sprintf(
'idempotency:lock:%s:%s:%s',
strtoupper($request->method()),
$request->path(),
$idempotencyKey
);
}
}

View File

@ -2,7 +2,153 @@
namespace App\Services;
use App\Enums\HoldStatus;
use App\Exceptions\HoldNotAvailableException;
use App\Exceptions\SlotCapacityExceededException;
use App\Models\Hold;
use App\Models\Slot;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class SlotService
{
private const string AVAILABILITY_CACHE_KEY = 'slots:availability';
/**
* @return list<array{slot_id: int, capacity: int, remaining: int}>
*/
public function getAvailability(): array
{
$fresh = config('slots.availability_cache_fresh_seconds');
$ttl = config('slots.availability_cache_ttl_seconds');
return Cache::flexible(self::AVAILABILITY_CACHE_KEY, [$fresh, $ttl], function (): array {
return $this->buildAvailabilityPayload();
});
}
private function buildAvailabilityPayload(): array
{
return Slot::query()
->orderBy('id')
->get()
->map(fn (Slot $slot): array => [
'slot_id' => $slot->id,
'capacity' => $slot->capacity,
'remaining' => $this->availableRemaining($slot),
])
->all();
}
public function createHold(Slot $slot, string $idempotencyKey): Hold
{
$existing = $this->findHoldByIdempotencyKey($idempotencyKey);
if ($existing !== null) {
return $existing->load('slot');
}
try {
return DB::transaction(function () use ($slot, $idempotencyKey): Hold {
$lockedSlot = Slot::query()->lockForUpdate()->findOrFail($slot->id);
if ($this->availableRemaining($lockedSlot) <= 0) {
throw new SlotCapacityExceededException('Slot capacity is exhausted.');
}
return Hold::query()->create([
'slot_id' => $lockedSlot->id,
'idempotency_key' => $idempotencyKey,
'status' => HoldStatus::Held,
'expires_at' => now()->addMinutes(config('slots.hold_ttl_minutes')),
])->load('slot');
});
} catch (UniqueConstraintViolationException) {
$existing = $this->findHoldByIdempotencyKey($idempotencyKey);
if ($existing === null) {
throw new SlotCapacityExceededException('Slot capacity is exhausted.');
}
return $existing->load('slot');
}
}
public function confirmHold(Hold $hold): Hold
{
return DB::transaction(function () use ($hold) {
$lockedHold = Hold::query()->lockForUpdate()->findOrFail($hold->id);
if ($lockedHold->status === HoldStatus::Confirmed) {
return $lockedHold->load('slot');
}
if ($lockedHold->status !== HoldStatus::Held || $lockedHold->isExpired()) {
throw new HoldNotAvailableException('Hold cannot be confirmed');
}
$slot = Slot::query()->lockForUpdate()->findOrFail($lockedHold->slot_id);
if ($slot->remaining < 1) {
throw new SlotCapacityExceededException('Slot capacity is exhausted.');
}
$slot->remaining--;
$slot->save();
$lockedHold->status = HoldStatus::Confirmed;
$lockedHold->save();
$this->invalidateAvailabilityCache();
return $lockedHold->load('slot');
});
}
public function cancelHold(Hold $hold): Hold
{
return DB::transaction(function () use ($hold) {
$lockedHold = Hold::query()->lockForUpdate()->findOrFail($hold->id);
if ($lockedHold->status === HoldStatus::Cancelled) {
return $lockedHold->load('slot');
}
if ($lockedHold->status === HoldStatus::Confirmed) {
$slot = Slot::query()->lockForUpdate()->findOrFail($lockedHold->slot_id);
$slot->remaining = min($slot->capacity, $slot->remaining + 1);
$slot->save();
}
$lockedHold->status = HoldStatus::Cancelled;
$lockedHold->save();
$this->invalidateAvailabilityCache();
return $lockedHold->load('slot');
});
}
private function availableRemaining(Slot $slot): int
{
$activeHolds = Hold::query()
->where('slot_id', $slot->id)
->where('status', HoldStatus::Held)
->where('expires_at', '>', now())
->count();
return max(0, $slot->remaining - $activeHolds);
}
private function findHoldByIdempotencyKey(string $idempotencyKey): ?Hold
{
return Hold::query()
->where('idempotency_key', $idempotencyKey)
->first();
}
private function invalidateAvailabilityCache(): void
{
Cache::forget(self::AVAILABILITY_CACHE_KEY);
}
}

View File

@ -1,5 +1,6 @@
<?php
use App\Http\Middleware\IdempotencyMiddleware;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
@ -7,11 +8,14 @@ use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->alias([
'idempotency' => IdempotencyMiddleware::class
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//

View File

@ -0,0 +1,17 @@
<?php
namespace Database\Seeders;
use App\Models\Slot;
use Illuminate\Database\Seeder;
class SlotSeeder extends Seeder
{
public function run(): void
{
Slot::query()->upsert([
['id' => 1, 'capacity' => 10, 'remaining' => 10],
['id' => 2, 'capacity' => 5, 'remaining' => 5],
], ['id'], ['capacity', 'remaining']);
}
}

View File

@ -27,13 +27,14 @@ services:
condition: service_healthy
redis:
condition: service_started
# command: >
# sh -c "
# composer install --no-interaction &&
# php artisan migrate --force &&
# php artisan db:seed --class=SlotSeeder --force &&
# php artisan serve --host=0.0.0.0 --port=8000
# "
command: >
sh -c "
composer install --no-interaction &&
cp .env.example .env
php artisan migrate --force &&
php artisan db:seed --class=SlotSeeder --force &&
php artisan serve --host=0.0.0.0 --port=8000
"
mysql:
image: mysql:8.4

13
routes/api.php Normal file
View File

@ -0,0 +1,13 @@
<?php
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'])
->middleware('idempotency');
Route::post('/holds/{hold}/confirm', [HoldController::class, 'confirm']);
Route::delete('/holds/{hold}', [HoldController::class, 'destroy']);