Rate limits
@rate_limit(key, limit:, per:) counts attempts under a key and refuses them past the limit, in any script, not just routes. It counts in the app's memory cache, or the store: you give:
<import package="KScript.Cache" />
<let name="limit" value="@rate_limit('login:ann@example.com', limit: 5, per: 1m)" />
<if $limit->is_limited()>
<echo>Try again in { $limit->available_in() }</echo>
</if>
<do>$limit->hit()</do>
<echo>{ $limit->remaining() } tries left</echo>
<do>$limit->clear()</do>import KScript.Cache
$limit = @rate_limit('login:ann@example.com', limit: 5, per: 1m)
if $limit->is_limited() => echo "Try again in { $limit->available_in() }"
$limit->hit()
echo "{ $limit->remaining() } tries left"
$limit->clear()| Method | What it does |
|---|---|
->attempt(work) |
Counts an attempt and runs work, returning its value. Past the limit it throws TooManyRequests with retry_after, which a route answers with 429. |
->hit() |
Counts an attempt, such as a failed sign-in, and returns how many are left. |
->is_limited() |
True when the attempts are used up for now. |
->remaining() |
How many attempts are left in this window. |
->available_in() |
How long until attempts are allowed again: 0s when some are left. |
->clear() |
Forgets the attempts, such as after a successful sign-in. |
The window starts with the first attempt and lasts per. To count across several servers, give a shared store: @rate_limit('login:' + $email, limit: 5, per: 1m, store: @cache(database)).
Groups
A group is a small cache of its own inside a store, with the same methods. Its keys are kept apart from the store's own and from other groups', and ->clear_group() removes all of them at once:
<import package="KScript.Cache" />
<let name="rates" value="$cache->group('rates')" />
<do>$rates->set('GBP', 1.0)</do>
<do>$rates->set('EUR', 1.17)</do>
<echo>Removed { $cache->clear_group('rates') } rates</echo>import KScript.Cache
$rates = $cache->group('rates')
$rates->set('GBP', 1.0)
$rates->set('EUR', 1.17)
echo "Removed { $cache->clear_group('rates') } rates"