TenantAtlas/app/Services/Inventory/InventoryConcurrencyLimiter.php
2026-01-07 15:51:47 +01:00

41 lines
1.0 KiB
PHP

<?php
namespace App\Services\Inventory;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Cache;
class InventoryConcurrencyLimiter
{
public function __construct(private readonly int $lockTtlSeconds = 900) {}
public function acquireGlobalSlot(): ?Lock
{
$max = (int) config('tenantpilot.inventory_sync.concurrency.global_max', 2);
$max = max(0, $max);
return $this->acquireSlot('inventory_sync:global:slot:', $max);
}
public function acquireTenantSlot(int $tenantId): ?Lock
{
$max = (int) config('tenantpilot.inventory_sync.concurrency.per_tenant_max', 1);
$max = max(0, $max);
return $this->acquireSlot("inventory_sync:tenant:{$tenantId}:slot:", $max);
}
private function acquireSlot(string $prefix, int $max): ?Lock
{
for ($slot = 0; $slot < $max; $slot++) {
$lock = Cache::lock($prefix.$slot, $this->lockTtlSeconds);
if ($lock->get()) {
return $lock;
}
}
return null;
}
}