|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Workflow\Support; |
| 6 | + |
| 7 | +use Illuminate\Cache\DatabaseStore; |
| 8 | +use Illuminate\Database\SqlServerConnection; |
| 9 | +use Illuminate\Support\Carbon; |
| 10 | +use Illuminate\Support\Facades\Cache; |
| 11 | + |
| 12 | +final class CacheThrottle |
| 13 | +{ |
| 14 | + public static function acquire(string $key, string|bool $value, int $seconds, ?string $activeMarker = null): bool |
| 15 | + { |
| 16 | + $cache = Cache::store(); |
| 17 | + $store = $cache->getStore(); |
| 18 | + if (! $store instanceof DatabaseStore || $store->getConnection() instanceof SqlServerConnection) { |
| 19 | + return ($activeMarker === null || ! $cache->has($activeMarker)) |
| 20 | + && $cache->add($key, $value, $seconds); |
| 21 | + } |
| 22 | + |
| 23 | + // DatabaseStore::add deletes expired rows before inserting. Renew this |
| 24 | + // throttle in place so competing queue polls do not delete the same row. |
| 25 | + $table = config('cache.stores.' . Cache::getDefaultDriver() . '.table', 'cache'); |
| 26 | + $prefixedKey = $store->getPrefix() . $key; |
| 27 | + $query = $store->getConnection() |
| 28 | + ->table($table) |
| 29 | + ->useWritePdo() |
| 30 | + ->where('key', $prefixedKey); |
| 31 | + $now = Carbon::now()->getTimestamp(); |
| 32 | + if ($activeMarker !== null) { |
| 33 | + $markerExpiration = $store->getConnection() |
| 34 | + ->table($table) |
| 35 | + ->useWritePdo() |
| 36 | + ->where('key', $store->getPrefix() . $activeMarker)->value('expiration'); |
| 37 | + if ($markerExpiration !== null && $markerExpiration >= $now) { |
| 38 | + // A wake just before chain expiry must not delay its replacement. |
| 39 | + $seconds = min($seconds, max(1, (int) $markerExpiration - $now)); |
| 40 | + } |
| 41 | + } |
| 42 | + $expiration = $query->value('expiration'); |
| 43 | + $values = [ |
| 44 | + 'value' => serialize($value), |
| 45 | + 'expiration' => $now + $seconds, |
| 46 | + ]; |
| 47 | + if ($expiration === null) { |
| 48 | + return $store->getConnection() |
| 49 | + ->table($table) |
| 50 | + ->insertOrIgnore([ |
| 51 | + 'key' => $prefixedKey, |
| 52 | + ...$values, |
| 53 | + ]) === 1; |
| 54 | + } |
| 55 | + if ($expiration > $now) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | + return $query->where('expiration', '<=', $now) |
| 60 | + ->update($values) === 1; |
| 61 | + } |
| 62 | +} |
0 commit comments