| 1 | use v5.40; | ||
| 2 | no warnings 'experimental::class', 'recursion'; | ||
| 3 | use feature 'class'; | ||
| 4 | # | ||
| 5 | class Acme::Parataxis::RateLimiter v0.1.6 { | ||
| 6 | use Carp qw[croak]; | ||
| 7 | use Time::HiRes qw[time]; | ||
| 8 | use Acme::Parataxis qw[fiber]; | ||
| 9 | use Acme::Parataxis::Semaphore; | ||
| 10 | use Acme::Parataxis::Ticker; | ||
| 11 | |||
| 12 | # A token bucket. The bucket is an ordinary Semaphore holding `burst` permits: acquire() is a `down`, so a fiber | ||
| 13 | # with nothing left to spend parks through the usual _park path and inherits cancellation, with_timeout and | ||
| 14 | # unregister-on-interrupt for free. The Ticker wakes the refill fiber `rate` times a second, and each wake | ||
| 15 | # credits every whole token accrued since the previous one on the wall clock (the fraction carries over), so the | ||
| 16 | # delivered rate tracks real time however coarsely the platform wakes the ticker: a late wake credits the tokens | ||
| 17 | # missed since the last one instead of falling behind. Tokens are credited only while the bucket sits below its | ||
| 18 | # ceiling, so an idle limiter tops itself up to `burst` and then stops, and a busy one hands out tokens at a | ||
| 19 | # steady `rate` per second forever. | ||
| 20 | # | ||
| 21 | # The Semaphore count therefore never needs a separate counter, and `Semaphore::adjust` already sizes its wake | ||
| 22 | # budget to min(tokens added, waiters), so one refill wakes exactly one waiter and an empty bucket wakes nobody | ||
| 23 | # until there is actually something to spend. | ||
| 24 | field $rate : reader : param; | ||
| 25 | field $burst : reader : param; | ||
| 26 | field $bucket; # Semaphore: count is the tokens currently available, always 0 .. $burst | ||
| 27 | field $ticker; # Ticker firing `rate` times a second | ||
| 28 | field $running = false; | ||
| 29 | ADJUST { | ||
| 30 | croak 'RateLimiter->new( rate => $per_second ) requires a positive rate' unless defined $rate && $rate > 0; | ||
| 31 | croak 'RateLimiter->new( burst => $n ) requires a positive burst' unless defined $burst && $burst >= 1; | ||
| 32 | $bucket = Acme::Parataxis::Semaphore->new( count => $burst ); | ||
| 33 | $ticker = Acme::Parataxis::Ticker->new( interval => 1000 / $rate ); | ||
| 34 | $running = true; | ||
| 35 | |||
| 36 | # token credit rides mock_time (the wall clock inside a virtual run's constructor/during it, the virtual | ||
| 37 | # clock otherwise is untouched): RateLimiter refills on the *same clock* the Ticker ticks on. | ||
| 38 | my $last = Acme::Parataxis::mock_time(); | ||
| 39 | my $first = true; | ||
| 40 | Acme::Parataxis::fiber { | ||
| 41 | while ($running) { | ||
| 42 | last unless $ticker->wait_next; | ||
| 43 | my $now = Acme::Parataxis::mock_time(); | ||
| 44 | my $won = ( $now - $last ) * $rate; | ||
| 45 | my $due = int( $won + $won * 1e-9 ); # relative margin for NV noise: int() truncates, so an exactly-due | ||
| 46 | |||
| 47 | # tick would round to 0 and be skipped when the stored (now-last) | ||
| 48 | # lands just below a whole tick on wide-NV perls (long-double and | ||
| 49 | # quadmath builds); 1e-9 sits far above representational error and | ||
| 50 | # far below any meaningful credit, so it never over-drops a token | ||
| 51 | $last += $due / $rate; # advance over exactly the window these whole tokens cover | ||
| 52 | |||
| 53 | # (any fraction carries to the next wake; a backwards clock resyncs) | ||
| 54 | # The first wake can be arbitrarily late when the limiter was built before run() started. That | ||
| 55 | # window was spent idle at the ceiling, so it must not be credited as backfill. | ||
| 56 | $due = 1 if $first && $due > 1; | ||
| 57 | $first = 0; | ||
| 58 | next if $due < 1; | ||
| 59 | my $room = $burst - $bucket->count; | ||
| 60 | $bucket->adjust( $due < $room ? $due : $room ) if $room > 0; | ||
| 61 | } | ||
| 62 | (); | ||
| 63 | }; | ||
| 64 | } | ||
| 65 | |||
| 66 | # Take $n tokens, parking while the bucket cannot cover them and resuming as refills arrive. Must run inside a | ||
| 67 | # scheduled fiber. An interrupted (timed-out or cancelled) acquire unregisters itself from the bucket through the | ||
| 68 | # semaphore's own park dereg, so it is never woken later by a refill it no longer cares about. | ||
| 69 | method acquire ( $n = 1 ) { | ||
| 70 | my $fid = Acme::Parataxis->current_fid; | ||
| 71 | croak 'acquire() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 72 | croak 'acquire($n) requires a positive integer' unless defined $n && $n =~ /\A[1-9][0-9]*\z/; | ||
| 73 | croak 'RateLimiter has been stopped' unless $running; | ||
| 74 | $bucket->down('RateLimiter acquire') for 1 .. $n; | ||
| 75 | 1; | ||
| 76 | } | ||
| 77 | |||
| 78 | # Halt refills. Anyone already parked in acquire is let through rather than stranded (a stopped limiter must never | ||
| 79 | # wedge the run), but a later acquire croaks instead of parking forever with nobody left to refill. Idempotent and | ||
| 80 | # safe from inside or outside a fiber. | ||
| 81 | method stop () { | ||
| 82 | return 0 unless $running; | ||
| 83 | $running = false; | ||
| 84 | $ticker->stop; | ||
| 85 | my $waiting = scalar $bucket->waiters; | ||
| 86 | $bucket->adjust($waiting) if $waiting > 0; | ||
| 87 | return 1; | ||
| 88 | } | ||
| 89 | method running () {$running} | ||
| 90 | |||
| 91 | # Tokens currently available to spend (0 .. burst). | ||
| 92 | method tokens () { $bucket->count } | ||
| 93 | |||
| 94 | # Fibers currently parked waiting for a token. | ||
| 95 | method waiters () { scalar $bucket->waiters } | ||
| 96 | } | ||
| 97 | # | ||
| 98 | 1; |