verbose/lib/ckratelimit.php
2024-09-28 06:06:22 +02:00

47 lines
1.9 KiB
PHP

<?php
function ckratelimit($headers) {
$aaheaders=[];
array_shift($headers);
foreach ($headers as $header)
if (preg_match('#^([^:]+): (.*)$#',$header,$matches)===1)
$aaheaders[strtolower($matches[1])]=$matches[2];
//$aaheaders['x-ratelimit-remaining']=0;
//print_r($aaheaders);
if (!isset($aaheaders['date'])) return ['ok'=>false,'error'=>'no «date» header'];
if (!isset($aaheaders['x-ratelimit-reset'])) return ['ok'=>false,'error'=>'no «x-ratelimit-reset» header'];
if (!isset($aaheaders['x-ratelimit-remaining'])) return ['ok'=>false,'error'=>'no «x-ratelimit-remaining» header'];
if (preg_match('#^\d+$#',$aaheaders['x-ratelimit-remaining'])!==1) return ['ok'=>false,'error'=>'«x-ratelimit-remaining» header is not an integer'];
$remaining=$aaheaders['x-ratelimit-remaining']+0;
$date=@strtotime($aaheaders['date']);
if (!is_int($date)) return ['ok'=>false,'error'=>'«date» header could not be converted to a unix timestamp'];
$reset=@strtotime($aaheaders['x-ratelimit-reset']);
if (!is_int($reset)) return ['ok'=>false,'error'=>'«x-ratelimit-reset» header could not be converted to a unix timestamp'];
// don't do the one on the line below, since it happens lots of times
//if ($reset<$date) return ['ok'=>false,'error'=>'the unix timestamp parsed from «x-ratelimit-reset» header is less than the unix timestamp parsed from «date» header'];
return ['ok'=>true,'sleep'=>$reset-$date+1,'remaining'=>$remaining];
}
/*
// test
$context=[
'http'=>[
'header'=>"Accept: application/json\r\n";
]
];
$context=stream_context_create($context);
while (true) {
$res=@file_get_contents('https://livellosegreto.it/api/v2/instance',false,$context);
echo "{$res}\n";
print_r($http_response_header);
$rl=ckratelimit($http_response_header);
print_r($rl);
if ($rl['sleep']>0) {
echo 'Reached rate limit, sleeping for '.ght($rl['sleep']).' (until '.date('c',time()+$rl['sleep']).') ...';
sleep($rl['sleep']);
echo "\n";
}
}
exit(0);*/
?>