Move app into module structure
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user