Store request without waiting and get estimate
alex88 opened this issue · comments
Is it possible using this library to actually just return the time the user has to wait before doing another request instead of actually wait for such time in php?
Sure, you can use the getEstimate
for that purpose.
The problem with that is that it never stores the last request, if you try this code:
<?php
$loader = require_once __DIR__.'/app/bootstrap.php.cache';
$throttle = new Stiphle\Throttle\LeakyBucket;
$identifier = 'dave';
while(true) {
// the throttle method returns the amount of milliseconds it slept for
echo $throttle->throttle($identifier, 5, 10000);
echo "\n";
}
it correctly throttles, this one instead:
<?php
$loader = require_once __DIR__.'/app/bootstrap.php.cache';
$throttle = new Stiphle\Throttle\LeakyBucket;
$identifier = 'dave';
while(true) {
// the throttle method returns the amount of milliseconds it slept for
echo $throttle->getEstimate($identifier, 5, 10000);
echo "\n";
}
always returns 0 since it doesn't store the last ratio and last request informations. So you can't actually just say to the user, "you've to wait for x seconds" without actually waiting for such time.
So I think my initial intention for this was to have something along the lines of:
if ($throttle->getEstimate($identifier, 5, 10000) > 1000) {
return new Response('Too many requests', 429);
}
$throttle->throttle($identifier, 5, 10000);
return $resource;
That is, if you don't want to actually throttle in process, tell the client to wait, but don't give them the resource. Getting denied doesn't count towards the quota.
If that doesn't suit your needs, we could probably have a look at injecting or making configurable the sleep part?
Oh I haven't thought about that, in that case it could work, since when getEstimate
is 0 throttle
won't wait. Sorry for the question then 👍
No problem, hope it works out! I haven't used this lib or given it any love for a while, but it certainly served it's purpose when I did :)