43 lines
1.1 KiB
PHP
43 lines
1.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
function throttle_webhook_channel(string $channel, int $minIntervalSeconds): void
|
|
{
|
|
if ($channel === '' || $minIntervalSeconds <= 0) {
|
|
return;
|
|
}
|
|
|
|
$sanitizedChannel = preg_replace('/[^a-z0-9_-]+/i', '_', $channel) ?? 'default';
|
|
$lockPath = sys_get_temp_dir() . '/erp_naurua_webhook_throttle_' . $sanitizedChannel . '.lock';
|
|
|
|
$handle = fopen($lockPath, 'c+');
|
|
if ($handle === false) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
if (!flock($handle, LOCK_EX)) {
|
|
return;
|
|
}
|
|
|
|
rewind($handle);
|
|
$raw = stream_get_contents($handle);
|
|
$lastSentAt = is_string($raw) ? (float) trim($raw) : 0.0;
|
|
$now = microtime(true);
|
|
$waitSeconds = ($lastSentAt + $minIntervalSeconds) - $now;
|
|
|
|
if ($waitSeconds > 0) {
|
|
usleep((int) ceil($waitSeconds * 1000000));
|
|
}
|
|
|
|
$sentAt = microtime(true);
|
|
rewind($handle);
|
|
ftruncate($handle, 0);
|
|
fwrite($handle, sprintf('%.6f', $sentAt));
|
|
fflush($handle);
|
|
} finally {
|
|
flock($handle, LOCK_UN);
|
|
fclose($handle);
|
|
}
|
|
}
|