| 1 | use v5.40; | ||
| 2 | no warnings 'experimental::class', 'recursion'; | ||
| 3 | use feature 'class'; | ||
| 4 | |||
| 5 | # An actor is a named or anonymous mailbox behind a single private fiber, with a handler that | ||
| 6 | # runs at most one message at a time. spawn() builds and starts it (a class-level factory, since | ||
| 7 | # perlclass instances cannot be assembled by hand); the mailbox is created in ADJUST, the fiber | ||
| 8 | # and its weak self-capture in _start, so spawn() does the checks and plumbing a factory must. | ||
| 9 | class Acme::Parataxis::Actor v0.1.6 { | ||
| 10 | use Acme::Parataxis qw[fiber]; | ||
| 11 | use Acme::Parataxis::Channel; | ||
| 12 | use Acme::Parataxis::Future; | ||
| 13 | use Carp qw[croak]; | ||
| 14 | our $STOP = \do { my $x = 1 }; # envelope value that tells the loop to shut down gracefully | ||
| 15 | field $cap : param; # mailbox capacity | ||
| 16 | field $code : param; # the handler: ($self, $value) => result, run for each message | ||
| 17 | field $done = 0; # set once at teardown | ||
| 18 | field $error; # what killed the actor, or undef for a graceful stop | ||
| 19 | field $fiber; # the private fiber the message loop runs on | ||
| 20 | field $mailbox; # the Channel the messages queue through | ||
| 21 | field $name : param = undef; # the registered name, or undef for an unnamed actor | ||
| 22 | field $on_death = []; # death hooks, fired exactly once at teardown | ||
| 23 | field $opts : param; # the original spawn %opts, so respawn() can reproduce them | ||
| 24 | field $stopping = 0; # set by stop(), refuses new send()s/ask()s | ||
| 25 | field $supervised : param; # a supervised handler crash stops this actor and reports it | ||
| 26 | ADJUST { | ||
| 27 | $mailbox = Acme::Parataxis::Channel->new( capacity => $cap ); | ||
| 28 | } | ||
| 29 | |||
| 30 | sub spawn : prototype($\&;$\%) ( $class, $code, $capacity = 16, %opts ) { | ||
| 31 | croak 'Actor->spawn() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 32 | croak "Actor->spawn() mailbox capacity must be >= 1 (got $capacity)" unless $capacity >= 1; | ||
| 33 | # | ||
| 34 | my %unknown = %opts; | ||
| 35 | # | ||
| 36 | delete @unknown{qw[supervised name]}; | ||
| 37 | croak 'Actor->spawn(): unknown options: ' . join ', ', sort keys %unknown if %unknown; | ||
| 38 | my $name = $opts{name}; | ||
| 39 | if ( defined $name ) { | ||
| 40 | croak 'Actor->spawn(): the name must be a non-empty string' unless !ref $name && length $name; | ||
| 41 | my $existing = $Acme::Parataxis::ACTOR_REGISTRY{$name}; | ||
| 42 | croak "Actor->spawn(): an actor named '$name' is already registered" if $existing && $existing->is_alive; | ||
| 43 | } | ||
| 44 | my $self = $class->new( code => $code, cap => $capacity, name => $name, supervised => !!$opts{supervised}, opts => \%opts ); | ||
| 45 | $self->_start; | ||
| 46 | return $self; | ||
| 47 | } | ||
| 48 | |||
| 49 | # Lives in its own method so the fiber closure only ever reaches the actor through field | ||
| 50 | # values captured as lexicals (a perlclass closure cannot touch fields directly). The fiber | ||
| 51 | # body captures a weak copy of $self, so a done actor is collectable. | ||
| 52 | method _start () { | ||
| 53 | my $weak = $self; # the fiber body captures this weak copy, so a done actor is collectable | ||
| 54 | builtin::weaken($weak); | ||
| 55 | my $mb = $mailbox; | ||
| 56 | my $srv = $supervised; | ||
| 57 | $fiber = fiber { | ||
| 58 | my $crash; | ||
| 59 | |||
| 60 | # The loop is guarded so teardown is reached on *every* exit path: an interrupt (a | ||
| 61 | # cancellation token or a with_timeout deadline landing on this fiber) thrown from a | ||
| 62 | # parked wait inside a handler escapes the loop and must not skip the drain below. | ||
| 63 | my $ok = 1; | ||
| 64 | my $interrupt; | ||
| 65 | try { | ||
| 66 | while (1) { | ||
| 67 | my $env = $mb->get; # Park it here without holding $self | ||
| 68 | my ( $reply, $value ) = @$env; | ||
| 69 | last if defined $value && ref $value && $value == $STOP; | ||
| 70 | # | ||
| 71 | my $actor = $weak; | ||
| 72 | last unless defined $actor; # Handle was dropped by user | ||
| 73 | my $err = $actor->_dispatch( $reply, $value ); | ||
| 74 | if ( defined $err && $srv ) { $crash = $err; last } | ||
| 75 | } | ||
| 76 | } | ||
| 77 | catch ($e) { $ok = 0; $interrupt = $e } | ||
| 78 | $crash = $interrupt unless $ok; | ||
| 79 | if ( my $actor = $weak ) { $actor->_finish($crash) } | ||
| 80 | }; | ||
| 81 | $Acme::Parataxis::ACTOR_REGISTRY{$name} = $self if defined $name; # only a spawned actor is registered | ||
| 82 | return; | ||
| 83 | } | ||
| 84 | |||
| 85 | method _finish ($crash) { | ||
| 86 | return if $done; | ||
| 87 | $done = 1; | ||
| 88 | $error = $crash if defined $crash; | ||
| 89 | |||
| 90 | # Release any registered name so a dead actor never answers a lookup. The guard (entry still == $self) | ||
| 91 | # keeps an older actor's teardown from clobbering a same-named replacement that registered since. | ||
| 92 | delete $Acme::Parataxis::ACTOR_REGISTRY{$name} if defined $name && ( $Acme::Parataxis::ACTOR_REGISTRY{$name} // 0 ) == $self; | ||
| 93 | |||
| 94 | # The drain is best effort: a watcher must learn about this death even if an interrupt lands | ||
| 95 | # on this fiber mid-teardown, or whoever is waiting for the report waits forever. | ||
| 96 | my $msg = defined $crash ? "$crash" : 'actor stopped before this message was handled!'; | ||
| 97 | try { $self->_fail_queued($msg) } catch ($e) { | ||
| 98 | warn "Acme::Parataxis::Actor: drain failed: $e" | ||
| 99 | } | ||
| 100 | for my $cb ( @{ $on_death // [] } ) { | ||
| 101 | try { $cb->( $self, $error ) } | ||
| 102 | catch ($e) { warn "Acme::Parataxis::Actor: death hook died: $e" } | ||
| 103 | } | ||
| 104 | return; | ||
| 105 | } | ||
| 106 | |||
| 107 | # Fail every ask still outstanding: whatever sits in the mailbox, plus any sender parked in | ||
| 108 | # put() that an earlier take released. Each take frees one mailbox slot, which is what releases | ||
| 109 | # a parked sender, so one yield per idle stretch lets a released sender land its envelope before | ||
| 110 | # the mailbox is declared empty. Nothing new can arrive meanwhile: done is already set, so | ||
| 111 | # _check_alive refuses it, and a sender between that check and the push never yields. | ||
| 112 | method _fail_queued ($msg) { | ||
| 113 | my $mb = $mailbox; | ||
| 114 | my $idle = 0; | ||
| 115 | while ( $idle < 3 ) { | ||
| 116 | my ( $ok, $env ) = $mb->try_get; | ||
| 117 | if ($ok) { | ||
| 118 | $idle = 0; | ||
| 119 | my ($reply) = @$env; | ||
| 120 | next unless defined $reply; | ||
| 121 | next if $reply->is_ready; | ||
| 122 | try { $reply->set_error($msg) } | ||
| 123 | catch ($e) { warn 'Acme::Parataxis::Actor: failed to fail a queued ask: ' . $e } | ||
| 124 | next; | ||
| 125 | } | ||
| 126 | $idle++; | ||
| 127 | Acme::Parataxis->yield if $idle == 1; | ||
| 128 | } | ||
| 129 | return; | ||
| 130 | } | ||
| 131 | |||
| 132 | # Fires exactly once when this actor is gone: $err is what killed it, or undef for a graceful stop. An actor that | ||
| 133 | # is already done calls back immediately, so a watcher never has to check. | ||
| 134 | method on_death : prototype($&) ($cb) { | ||
| 135 | if ($done) { $cb->( $self, $error ); return $self } | ||
| 136 | push $on_death->@*, $cb; | ||
| 137 | return $self; | ||
| 138 | } | ||
| 139 | method error () {$error} # why it died, or undef if it stopped gracefully | ||
| 140 | |||
| 141 | # A fresh, already-running actor with the same handler, mailbox size and options: what a supervisor starts in | ||
| 142 | # place of this one. The new actor owns a new mailbox, so asks still outstanding here are failed here rather than | ||
| 143 | # answered there. | ||
| 144 | method respawn () { | ||
| 145 | return ref($self)->spawn( $code, $cap, $opts->%* ); | ||
| 146 | } | ||
| 147 | |||
| 148 | method _dispatch ( $reply, $value ) { | ||
| 149 | my $err; | ||
| 150 | my $ok = 1; | ||
| 151 | try { | ||
| 152 | my $rv = $code->( $self, $value ); | ||
| 153 | $reply->set_result($rv) if defined $reply; | ||
| 154 | } | ||
| 155 | catch ($e) { | ||
| 156 | $ok = 0; | ||
| 157 | $err = $e; | ||
| 158 | } | ||
| 159 | if ( !$ok ) { | ||
| 160 | if ( defined $reply ) { | ||
| 161 | try { | ||
| 162 | $reply->set_error($err); | ||
| 163 | } | ||
| 164 | catch ($e) { | ||
| 165 | } | ||
| 166 | } | ||
| 167 | elsif ( !$supervised ) { # a supervised actor reports this death to its supervisor instead | ||
| 168 | warn "Acme::Parataxis::Actor: handler died: $err"; | ||
| 169 | } | ||
| 170 | } | ||
| 171 | return $err; # undef when the handler returned normally; the caller turns it into a crash if supervised | ||
| 172 | } | ||
| 173 | |||
| 174 | method send ($value) { | ||
| 175 | $self->_check_alive; | ||
| 176 | $mailbox->put( [ undef, $value ] ); | ||
| 177 | return 1; | ||
| 178 | } | ||
| 179 | |||
| 180 | method ask ($value) { | ||
| 181 | $self->_check_alive; | ||
| 182 | my $reply = Acme::Parataxis::Future->new; | ||
| 183 | $mailbox->put( [ $reply, $value ] ); | ||
| 184 | return $reply; | ||
| 185 | } | ||
| 186 | |||
| 187 | method stop () { | ||
| 188 | return $self if $done || $stopping; | ||
| 189 | $stopping = 1; | ||
| 190 | |||
| 191 | # Non-blocking enqueue so DESTROY never yields or parks: | ||
| 192 | $mailbox->put_priority( [ undef, $STOP ] ); | ||
| 193 | return $self; | ||
| 194 | } | ||
| 195 | method is_alive () { return !$done } | ||
| 196 | method fid () { return $fiber->fid } | ||
| 197 | method name () { return $name } # the registered name, or undef for an unnamed actor | ||
| 198 | |||
| 199 | # Hot code swap: atomically replace the handler for *subsequent* messages. | ||
| 200 | method swap : prototype($\&) ($new) { | ||
| 201 | croak 'requires a CODE ref' unless builtin::reftype($new) // '' eq 'CODE'; | ||
| 202 | croak 'swap(): this actor is no longer running' if $done; | ||
| 203 | $code = $new; | ||
| 204 | return $self; | ||
| 205 | } | ||
| 206 | |||
| 207 | method _check_alive () { | ||
| 208 | croak 'send()/ask(): this actor is no longer running' if $done; | ||
| 209 | croak 'send()/ask(): this actor is shutting down' if $stopping; | ||
| 210 | return; | ||
| 211 | } | ||
| 212 | |||
| 213 | method DESTROY () { | ||
| 214 | return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; | ||
| 215 | delete $Acme::Parataxis::ACTOR_REGISTRY{$name} if defined $name && ( $Acme::Parataxis::ACTOR_REGISTRY{$name} // 0 ) == $self; | ||
| 216 | $self->stop unless $done; | ||
| 217 | return; | ||
| 218 | } | ||
| 219 | }; | ||
| 220 | # | ||
| 221 | 1; |