Compare commits

..

No commits in common. "8684a6e19b6da3009595d7301c0a5fe8efa16208" and "863f3fffc5eb55d4367fc0b0d623cfaccd6a12f4" have entirely different histories.

12 changed files with 74 additions and 435 deletions

View File

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

View File

@ -1,48 +1,59 @@
# Start <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>
```bash
git clone ...
docker compose up -d
```
# Доступность <p align="center">
```bash <a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
curl -s "http://localhost:8080/api/slots/availability" <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>
# Создать hold ## About Laravel
```bash 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:
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).
```bash - [Powerful dependency injection container](https://laravel.com/docs/container).
curl -s -X POST "http://localhost:8080/api/holds/1/confirm" - 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).
# Отменить Laravel is accessible, powerful, and provides tools required for large, robust applications.
```bash
curl -s -X DELETE "http://localhost:8080/api/holds/1"
```
# Oversell ## Learning Laravel
```bash
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \ 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.
-H "X-Idempotency-Key: 20ff64a3-43d6-4ddb-874e-441d0a87570e"
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.
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: d7db5b73-1ea5-4156-99b6-dbace1b483a9" ## Laravel Sponsors
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \ 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).
-H "X-Idempotency-Key: ddd6174c-0fda-4765-8413-12dd3cda9692"
### Premium Partners
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \
-H "X-Idempotency-Key: 7af943b4-dfcf-4d5e-99c0-fa06fc9b2a6a" - **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \ - **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
-H "X-Idempotency-Key: fcb4b745-e928-4af3-bb35-c307cc5a574e" - **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
curl -s -X POST "http://localhost:8080/api/slots/2/hold" \ - **[DevSquad](https://devsquad.com/hire-laravel-developers)**
-H "X-Idempotency-Key: 38ae0adb-7f23-40c0-9ac1-069a15d89a98" - **[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).

View File

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

View File

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

View File

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

View File

@ -2,63 +2,9 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Exceptions\HoldNotAvailableException; use Illuminate\Http\Request;
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 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

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

View File

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

View File

@ -1,13 +0,0 @@
<?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']);