Skip to content

Core\RateLimit\Decision::isAllowed

$decision->isAllowed(): bool

Tells you whether a rate-limited call was inside its limit.

Core\RateLimit::consumeLocally and Core\RateLimit::consume both return a Core\RateLimit\Decision. Its isAllowed method returns true when the call was inside the limit. The units of the call are then used. It returns false when the call was over the limit. A call that is not allowed uses no units, so a later call with a smaller cost can still be allowed.

Good to know: a rate limit does not stop anything by itself. Your program reads isAllowed and then does the work, or skips it and tells the user to try again later.

Return value

Returns bool. true when the units were charged. false when the call was over the limit and nothing was charged.

Changelog

VersionChange
0.0.6Core\RateLimit::consumeLocally counts a request in the memory of this server process. Core\RateLimit\Decision->isAllowed() checks the result. The old names were shed and allowed.

Examples

Inside the limit or not

<?nvs
// Shows how `isAllowed` tells you whether a call was inside the limit.
// The limit is 1 call per hour, so the first call is inside it
// and the second is not. This prints `true` and then `false`.
var $first = Core\RateLimit::consumeLocally('newsletter:signup', 1, 1h);
var $second = Core\RateLimit::consumeLocally('newsletter:signup', 1, 1h);
echo $first->isAllowed() ? 'true' : 'false', "\n";
echo $second->isAllowed() ? 'true' : 'false', "\n";
Output
true
false

A refused call uses nothing

<?nvs
// Shows that a refused call uses no units. A smaller call can still be allowed after it.
class Upload
{
public static function send(uint $megabytes): void
{
// Each user may upload 5 megabytes per hour.
var $decision = Core\RateLimit::consumeLocally('upload:user:9', 5, 1h, { cost: $megabytes });
if ($decision->isAllowed()) {
echo $megabytes, " MB: allowed\n";
} else {
echo $megabytes, " MB: refused\n";
}
}
}
// 4 MB is allowed and leaves 1 MB. 3 MB is refused and uses nothing,
// so the last 1 MB is still allowed.
Upload::send(4);
Upload::send(3);
Upload::send(1);
Output
4 MB: allowed
3 MB: refused
1 MB: allowed

Send some emails now

<?nvs
// Shows a job that sends emails, at most 3 per second. The emails that
// are not allowed stay in the queue for the next run.
array<string> $queue = ['ana@example.com', 'ben@example.com', 'chen@example.com', 'dev@example.com', 'eli@example.com'];
array<string> $later = [];
foreach ($queue as string $address) {
var $decision = Core\RateLimit::consumeLocally('mail:outgoing', 3, 1s);
if ($decision->isAllowed()) {
echo 'sent to ', $address, "\n";
} else {
$later[] = $address;
}
}
// The first 3 are sent, so this prints 2.
echo Core\Arr::count($later), " emails wait for the next run\n";
Output
sent to ana@example.com
sent to ben@example.com
sent to chen@example.com
2 emails wait for the next run