| 1 | use v5.40; | ||
| 2 | no warnings qw[experimental::class recursion]; | ||
| 3 | use feature 'class'; | ||
| 4 | # | ||
| 5 | class Acme::Parataxis::Ticker v0.1.6 { | ||
| 6 | use Carp qw[croak]; | ||
| 7 | use Time::HiRes qw[time]; | ||
| 8 | use Acme::Parataxis qw[await_sleep]; | ||
| 9 | use Acme::Parataxis::CancellationToken; | ||
| 10 | use Acme::Parataxis::Channel; | ||
| 11 | |||
| 12 | # A drift-free interval timer. `while (1) { do_work(); await_sleep($ms) }` runs every $ms *plus* however long | ||
| 13 | # do_work took, so the loop drifts later and later. A Ticker instead sleeps only the *remainder* of each | ||
| 14 | # interval, measured against absolute tick boundaries, so ticks land on the boundary regardless of how long the | ||
| 15 | # consumer took to ask for the last one. | ||
| 16 | # | ||
| 17 | # A background fiber walks those boundaries and try_put's each tick time into a capacity-1 channel. Before each | ||
| 18 | # put it drains whatever the consumer has not collected yet, so exactly one tick can ever be outstanding and it | ||
| 19 | # is always the newest: a slow consumer silently loses ticks instead of accumulating a stale backlog it would | ||
| 20 | # then have to work through. | ||
| 21 | field $interval : reader : param; # milliseconds between ticks | ||
| 22 | field $channel; # capacity 1 - the single un-collected tick, if any | ||
| 23 | field $stop_token; # interrupts the ticker fiber's await_sleep when stop() is called | ||
| 24 | field $running : reader = false; | ||
| 25 | field $fired : reader = 0; # ticks produced | ||
| 26 | field $dropped : reader = 0; # ticks discarded: superseded uncollected ones (boundaries missed while the | ||
| 27 | |||
| 28 | # host slept past the schedule are counted as skipped, never as fired) | ||
| 29 | field $skipped : reader = 0; # tick boundaries leapfrogged after a late wakeup: never fired, never delivered | ||
| 30 | |||
| 31 | # after waking far behind schedule | ||
| 32 | field $next_at; # absolute time of the next tick boundary | ||
| 33 | ADJUST { | ||
| 34 | croak 'Ticker->new( interval => $ms ) requires a positive interval' unless defined $interval && $interval > 0; | ||
| 35 | $channel = Acme::Parataxis::Channel->new( capacity => 1 ); | ||
| 36 | $stop_token = Acme::Parataxis::CancellationToken->new( kind => 'cancel' ); | ||
| 37 | $running = true; | ||
| 38 | my $interval_s = $interval / 1000; | ||
| 39 | |||
| 40 | # The boundary math rides Acme::Parataxis::mock_time, so inside run( virtual => 1 ) a Ticker created during | ||
| 41 | # the run ticks on *virtual* boundaries and can be driven with Parataxis->advance; outside one it is the wall | ||
| 42 | # clock, exactly as before. | ||
| 43 | $next_at = Acme::Parataxis::mock_time() + $interval_s; | ||
| 44 | Acme::Parataxis::fiber { | ||
| 45 | |||
| 46 | # stop() interrupts the sleep below (which also recalls the armed pool job, so a stopped ticker never | ||
| 47 | # keeps the run alive); the interrupt surfaces as an exception out of await_sleep and unwinds here. | ||
| 48 | # The catch is deliberately empty: that throw is how stop() gets in, and a real fault in the loop has | ||
| 49 | # always been swallowed rather than escalated to the fiber's owner. | ||
| 50 | try { | ||
| 51 | $stop_token->register; | ||
| 52 | while ($running) { | ||
| 53 | my $remain = $next_at - Acme::Parataxis::mock_time(); | ||
| 54 | await_sleep( $remain * 1000 ) if $remain > 0; | ||
| 55 | last unless $running; | ||
| 56 | |||
| 57 | # Newest wins: drop the tick the consumer never collected before publishing this one. | ||
| 58 | while ( $channel->size ) { | ||
| 59 | my ( $got, $stale ) = $channel->try_get; | ||
| 60 | last unless $got; | ||
| 61 | $dropped++; | ||
| 62 | } | ||
| 63 | $channel->try_put($next_at); | ||
| 64 | $fired++; | ||
| 65 | $next_at += $interval_s; | ||
| 66 | |||
| 67 | # Wound far behind schedule: leapfrog the boundaries already missed rather than burst-firing | ||
| 68 | # them all at once on the next pass. Never fired, so they cannot count as dropped: the invariant | ||
| 69 | # fired == dropped + pending + consumed (Ticker.pod) stays exact on hosts that wake timers late. | ||
| 70 | while ( $next_at <= Acme::Parataxis::mock_time() ) { $next_at += $interval_s; $skipped++ } | ||
| 71 | } | ||
| 72 | } | ||
| 73 | catch ($e) { } | ||
| 74 | |||
| 75 | # A finished fiber must not stay registered on the token, or a later stop() would interrupt an id that | ||
| 76 | # no longer names a live waiter. | ||
| 77 | try { $stop_token->unregister } catch ($e) { | ||
| 78 | } | ||
| 79 | (); | ||
| 80 | }; | ||
| 81 | } | ||
| 82 | |||
| 83 | # Block until the next tick. Returns the tick's scheduled time, or undef once the ticker has been stopped, so | ||
| 84 | # `while (my $t = $tick->wait_next) { ... }` terminates on stop(). Must run inside a scheduled fiber. | ||
| 85 | method wait_next () { | ||
| 86 | my $fid = Acme::Parataxis->current_fid; | ||
| 87 | croak 'wait_next() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 88 | return undef unless $running; | ||
| 89 | my ( $got, $tick ) = $channel->try_get; | ||
| 90 | return $tick if $got; | ||
| 91 | |||
| 92 | # Park on the channel. stop() shuts the channel down, which releases this wait with undef, so a consumer | ||
| 93 | # can never hang on a ticker that was stopped underneath it. The semaphore's re-check makes a tick that | ||
| 94 | # lands between try_get and here arrive without an extra park. | ||
| 95 | my $v = $channel->get; | ||
| 96 | return undef unless $running; | ||
| 97 | return $v; | ||
| 98 | } | ||
| 99 | |||
| 100 | # Halt the ticker: stop publishing, release any consumer parked in wait_next, and interrupt the ticker fiber's | ||
| 101 | # sleep so it unwinds and its armed pool job is recalled. Idempotent, and safe before the fiber ever runs. | ||
| 102 | method stop () { | ||
| 103 | return 0 unless $running; | ||
| 104 | $running = false; | ||
| 105 | $channel->shutdown; | ||
| 106 | $stop_token->cancel; | ||
| 107 | return 1; | ||
| 108 | } | ||
| 109 | |||
| 110 | # Ticks still waiting to be collected (0 or 1; never a backlog). | ||
| 111 | method pending () { $channel->size } | ||
| 112 | }; | ||
| 113 | # | ||
| 114 | 1; |