clock = \Closure::fromCallable( $clock ?? static fn (): int => time() ); $this->sleeper = \Closure::fromCallable( $sleeper ?? static function (int $microseconds): void { usleep($microseconds); } ); } public function acquire( AdministratorTelegramDestination $destination ): void { $now = ($this->clock)(); if (!is_int($now) || $now < 1) { throw new AdministratorTelegramLocalUnavailable( 'Administrator Telegram rate clock is unavailable' ); } try { $connection = (new Configurations())->getConnection(); $reservation = $connection->transaction(function () use ( $connection, $now ): array { $gate = $connection->table( 'administrator_telegram_delivery_gate' )->where('id', 1)->lockForUpdate()->first(); if ($gate === null) { throw new \RuntimeException( 'Administrator Telegram rate gate is missing' ); } $oldNext = (int) $gate->next_send_at; $oldUpdated = (int) $gate->updated_at; if ($oldUpdated > $now + self::MAX_BACKLOG_SECONDS || $oldNext > $now + self::MAX_BACKLOG_SECONDS + self::RATE_LIMIT_SECONDS) { $updated = $connection->table( 'administrator_telegram_delivery_gate' )->where('id', 1)->where('next_send_at', $oldNext) ->update([ // Quarantine one full normal collision window. // The current call does not receive a permit. 'next_send_at' => $now + self::MAX_BACKLOG_SECONDS + self::RATE_LIMIT_SECONDS, 'updated_at' => $now, ]); if ((int) $updated !== 1) { throw new \RuntimeException( 'Administrator Telegram rate gate recovery failed' ); } return ['slot' => null, 'recovered' => true]; } $slot = max($now, $oldNext); if ($slot - $now > self::MAX_BACKLOG_SECONDS) { throw new AdministratorTelegramRateBacklog( 'Administrator Telegram delivery backlog is full' ); } $updated = $connection->table( 'administrator_telegram_delivery_gate' )->where('id', 1) ->where('next_send_at', $oldNext) ->update([ 'next_send_at' => $slot + self::RATE_LIMIT_SECONDS, 'updated_at' => $now, ]); if ((int) $updated !== 1) { throw new \RuntimeException( 'Administrator Telegram rate gate update failed' ); } return ['slot' => $slot, 'recovered' => false]; }, 3); if ($reservation['recovered']) { throw new AdministratorTelegramLocalUnavailable( 'Administrator Telegram rate clock recovered' ); } $slot = (int) $reservation['slot']; $wait = $slot - $now; if ($wait > 0) { ($this->sleeper)($wait * 1000000); } } catch (AdministratorTelegramRateBacklog $exception) { throw $exception; } catch (AdministratorTelegramLocalUnavailable $exception) { throw $exception; } catch (\Throwable $exception) { throw new AdministratorTelegramLocalUnavailable( 'Administrator Telegram rate gate is temporarily unavailable' ); } } }