blib/lib/Acme/Parataxis/Supervisor.pm untested

filter: Statementstmt 0.0% 0 / 202 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 59 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 9 Podpod n/a totaltotal 0.0% 0 / 383 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 use v5.40;
2 no warnings qw[experimental::class recursion];
3 use feature 'class';
4 #
5 # OTP-style supervisor trees: children are supervised actors (or nested supervisors) that are
6 # restarted whenever they die, according to a restart strategy, until a restart budget runs out -
7 # at which point the tree is torn down and run() fails with an aggregate
8 # Acme::Parataxis::Error::Supervisor. This is the "heal-fast" half of supervision's "supervision is
9 # deliberately out of scope" guardrail, and it is pure Perl on top of the existing park/wake
10 # machinery: one supervision fiber owns the tree and learns a child died through that child's own
11 # teardown (an actor's on_death hook, or a wrapper fiber around a nested supervisor's run).
12 class Acme::Parataxis::Supervisor v0.1.6 {
13 use Acme::Parataxis qw[fiber];
14 use Acme::Parataxis::Channel;
15 use Acme::Parataxis::Error;
16 use builtin qw[blessed];
17 use Time::HiRes qw[time];
18 use Carp qw[croak];
19  
20 # Restart strategy. OneForOne restarts only the child that died; OneForAll restarts every child
21 # (they share state the death may have broken); RestForOne restarts the dead child and
22 # everything started after it. max_restarts deaths within `within` seconds exhaust the budget:
23 # the (max_restarts+1)-th death inside the window fails the supervisor instead of restarting.
24 field $strategy : reader : param = 'OneForOne';
25 field $max_restarts : reader : param = 5;
26 field $within : reader : param = 60;
27  
28 # Supervised children in start order. Each is a spec ({name, factory, initial}) plus the live
29 # bookkeeping for the instance currently running: `instance`, the `token` identifying that
30 # attempt, `pending` (an event for it is still expected), `restarts`, and `index`.
31 field @children;
32  
33 # The original supervise() arguments, so a restarted supervisor can rebuild its own subtree
34 # from scratch instead of inheriting the dead one's instances.
35 field @specs;
36  
37 # Restart budget: [ when, child name, reason ] for every restart still inside the window.
38 field @budget;
39  
40 # Where dying instances report [ $child, $token, $err ]. Oversized so a report can never park a
41 # fiber that is in the middle of tearing itself down.
42 field $deaths;
43 field $running : reader = false;
44 field $stopping : reader = false;
45 field $started : reader = false;
46 ADJUST {
47 croak "Supervisor->new: strategy must be OneForOne, OneForAll or RestForOne (got '$strategy')"
48 unless defined $strategy && ( $strategy eq 'OneForOne' || $strategy eq 'OneForAll' || $strategy eq 'RestForOne' );
49 croak 'Supervisor->new: max_restarts must be a non-negative integer' unless defined $max_restarts && $max_restarts =~ /\A\d+\z/;
50 croak 'Supervisor->new: within must be a non-negative number of seconds' unless defined $within && $within =~ /\A[0-9]+(?:\.[0-9]+)?\z/;
51 $deaths = Acme::Parataxis::Channel->new( capacity => 4096 );
52 }
53  
54 # Register a child. $thing is an Actor (adopted as-is for the first run, restarted with a fresh
55 # mailbox), a Supervisor (the same, for a subtree), or a CODE ref factory returning either -
56 # which is what you want when the child should not exist until the tree starts. The optional
57 # name defaults to child_1, child_2, ... in registration order and must be unique.
58 method supervise ( $thing, %opts ) {
59 croak 'Supervisor->supervise() may not add children once run() has started' if $started;
60 croak 'Supervisor->supervise() requires an Acme::Parataxis::Actor, an Acme::Parataxis::Supervisor, or a CODE ref factory'
61 unless ref $thing eq 'CODE' ||
62 ( blessed($thing) && ( $thing->isa('Acme::Parataxis::Actor') || $thing->isa('Acme::Parataxis::Supervisor') ) );
63 my $unknown = join ', ', grep { $_ ne 'name' } sort keys %opts;
64 croak "Supervisor->supervise(): unknown options: $unknown" if length $unknown;
65 my $name = defined $opts{name} ? $opts{name} : 'child_' . ( scalar(@children) + 1 );
66 croak 'Supervisor->supervise(): name must be a non-empty string' if ref $name || !defined $name || $name eq '';
67 croak "Supervisor->supervise(): a child named '$name' is already supervised" if grep { $_->{name} eq $name } @children;
68 my ( $factory, $initial );
69  
70 if ( ref $thing eq 'CODE' ) {
71 $factory = $thing;
72 }
73 elsif ( $thing->isa('Acme::Parataxis::Supervisor') ) {
74 $factory = sub { $thing->_duplicate };
75 $initial = $thing;
76 }
77 else {
78 $factory = sub { $thing->respawn };
79 $initial = $thing;
80 }
81 push @specs, [ $thing, %opts ];
82 push @children,
83 {
84 name => $name,
85 factory => $factory,
86 initial => $initial,
87 instance => undef,
88 token => undef,
89 pending => 0,
90 restarts => 0,
91 index => scalar @children
92 };
93 return $self;
94 }
95  
96 # A fresh supervisor with the same configuration and the same children, every one of them
97 # rebuilt from its factory: restarting a nested supervisor starts a whole new subtree, it does
98 # not resume the dead one.
99 method _duplicate () {
100 my $copy = ref($self)->new( strategy => $strategy, max_restarts => $max_restarts, within => $within );
101 for my $spec (@specs) {
102 my ( $thing, %opts ) = @$spec;
103 if ( ref $thing ne 'CODE' ) {
104 my $inst = $thing;
105 $thing = $inst->isa('Acme::Parataxis::Supervisor') ? sub { $inst->_duplicate } : sub { $inst->respawn };
106 }
107 $copy->supervise( $thing, %opts );
108 }
109 return $copy;
110 }
111  
112 # Start the tree and supervise it until stop() is called or the restart budget runs out.
113 # Returns normally after a stop(); dies with Acme::Parataxis::Error::Supervisor when the budget
114 # is exhausted. Either way every child is stopped and drained before this returns, so no fiber
115 # of the tree outlives it.
116 method run () {
117 croak 'Supervisor->run() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
118 croak 'Supervisor->run() requires at least one supervised child' unless @children;
119 croak 'Supervisor->run() may only be called once' if $started;
120 $started = $running = true;
121 my $ok = 1;
122 my $err;
123 try { $self->_supervise_loop } catch ($e) {
124 $ok = 0;
125 $err = $e
126 }
127 $self->_shutdown;
128 $running = false;
129 die $err unless $ok;
130 return $self;
131 }
132  
133 # Ask the tree to shut down. Safe to call from any fiber, including from inside a child: it
134 # never parks, so it cannot re-enter the scheduler halfway through tearing the tree down. The
135 # supervision loop wakes on the marker below and stops restarting anything.
136 method stop () {
137 return $self if $stopping;
138 $stopping = true;
139 $deaths->put( ['WAKE'] );
140 $self->_stop_children;
141 return $self;
142 }
143  
144 # Bring the whole tree down: ask every child that is still running to stop, then wait for each
145 # of them to report its death. Waiting matters - it is what makes "the live fiber count returns
146 # to baseline once run() returns" true instead of a race.
147 method _shutdown () {
148 $stopping = true;
149 $self->_stop_children;
150 while ( grep { $_->{pending} } @children ) {
151 my $ev = $deaths->get;
152 next if @$ev == 1; # wake marker
153 my ( $child, $token ) = @$ev;
154 next unless ref $child eq 'HASH' && defined $child->{token} && $child->{token} == $token;
155 $child->{pending} = 0;
156 }
157 return;
158 }
159  
160 method _stop_children () {
161 for my $child (@children) {
162 next unless $child->{pending}; # not running: never started, already reported, or failed to start
163 my $inst = $child->{instance} or next;
164 try { $inst->stop } catch ($e) {
165 warn "Acme::Parataxis::Supervisor: stopping child '$child->{name}' failed: $e"
166 }
167 }
168 return;
169 }
170  
171 method _supervise_loop () {
172 $self->_spawn($_) for @children;
173 while ( !$stopping ) {
174 my $ev = $deaths->get;
175 last if $stopping;
176 next if @$ev == 1; # wake marker from a stop() already seen above
177 my ( $child, $token, $err ) = @$ev;
178 next unless ref $child eq 'HASH' && defined $child->{token} && $child->{token} == $token;
179  
180 # The current instance really died. An expected stop cannot land here: stop() sets the
181 # flag first, and a sibling replaced during a OneForAll/RestForOne restart reports under
182 # the token it was started with, which no longer matches.
183 $child->{pending} = 0;
184 my $reason = defined $err ? $err : "child '$child->{name}' exited cleanly";
185 my $now = time;
186 @budget = grep { $now - $_->[0] < $within } @budget; # within => 0 keeps nothing: the budget never trips
187 if ( @budget >= $max_restarts ) {
188 my @failures = ( ( map { $_->[2] } @budget ), $reason );
189 die Acme::Parataxis::Error::Supervisor->new(
190 failures => \@failures,
191 primary => $reason,
192 child => $child->{name},
193 strategy => $strategy,
194 restarts => $max_restarts
195 );
196 }
197 push @budget, [ $now, $child->{name}, $reason ];
198 $self->_apply_strategy($child);
199 }
200 return;
201 }
202  
203 # Which children a death of $dead drags down with it, in start order. Restarting in start
204 # order keeps RestForOne's suffix (and OneForAll's set) coming back up the way it went down.
205 method _apply_strategy ($dead) {
206 my @set = grep { $strategy eq 'OneForOne' ? $_ == $dead : $strategy eq 'OneForAll' ? 1 : $_->{index} >= $dead->{index} }
207 sort { $a->{index} <=> $b->{index} } @children;
208 $self->_restart_child($_) for @set;
209 return;
210 }
211  
212 # Replace one child's instance: ask the old one to stop if it has not already gone, then start
213 # a fresh one. The old instance's death report still arrives, but under the token it was
214 # started with, so it is dropped instead of being mistaken for a new crash.
215 method _restart_child ($child) {
216 if ( $child->{pending} && defined $child->{instance} ) {
217 try { $child->{instance}->stop }
218 catch ($e) {
219 warn "Acme::Parataxis::Supervisor: restarting '$child->{name}' but stopping the old instance failed: $e"
220 }
221 }
222 $self->_spawn($child);
223 $child->{restarts}++; # every child this strategy replaced counts, not only the one that died
224 return;
225 }
226  
227 # Start one child's next instance and arrange for exactly one death report for it, whatever
228 # goes wrong: a factory that dies, a factory returning the wrong thing (a programming error,
229 # so it propagates out of run()), a hook that cannot be installed, or the instance dying later.
230 method _spawn ($child) {
231 my ( $inst, $err, $ok );
232  
233 # The first start adopts the instance supervise() was handed (an actor already running, or
234 # a nested supervisor already built); every start after that goes through the factory, which
235 # is what makes a restart a fresh instance instead of a second run of a dead one.
236 if ( defined $child->{initial} ) { ( $inst, $ok ) = ( delete $child->{initial}, 1 ) }
237 else {
238 $ok = 1;
239 try { $inst = $child->{factory}->() } catch ($e) {
240 $ok = 0;
241 $err = $e
242 }
243 }
244 croak "Supervisor child '$child->{name}' factory must return an Acme::Parataxis::Actor or an Acme::Parataxis::Supervisor"
245 if $ok && ( !blessed($inst) || ( !$inst->isa('Acme::Parataxis::Actor') && !$inst->isa('Acme::Parataxis::Supervisor') ) );
246 my $token = [];
247 $child->{token} = $token;
248 $child->{instance} = $inst;
249 $child->{pending} = 1;
250 if ( !defined $inst ) { # the factory itself died: that is the child's death
251 $deaths->put( [ $child, $token, $err ] );
252 return;
253 }
254 my $hooked = 1;
255 my $hook_err;
256 try {
257 if ( $inst->isa('Acme::Parataxis::Supervisor') ) {
258 fiber {
259 my $ok2 = 1;
260 my $run_err;
261 try { $inst->run } catch ($e) {
262 $ok2 = 0;
263 $run_err = $e
264 }
265 $self->_report( $child, $token, $ok2 ? undef : $run_err );
266 };
267 }
268 else {
269 $inst->on_death( sub ( $actor, $e ) { $self->_report( $child, $token, $e ) } );
270 }
271 }
272 catch ($e) { $hooked = 0; $hook_err = $e }
273 unless ($hooked) { # could not watch it (e.g. no fiber slot left): report and give up on it
274 $child->{instance} = undef;
275 $deaths->put( [ $child, $token, $hook_err ] );
276 }
277 return;
278 }
279  
280 method _report ( $child, $token, $err ) {
281 $deaths->put( [ $child, $token, $err ] );
282 return;
283 }
284  
285 # introspection
286 method children () {
287 map { $_->{name} } @children;
288 }
289  
290 method child ($name) {
291 croak 'Supervisor->child() requires a child name' unless defined $name && !ref $name;
292 my ($child) = grep { $_->{name} eq $name } @children;
293 croak "Supervisor->child(): no supervised child named '$name'" unless $child;
294 return $child->{instance};
295 }
296  
297 # Restarts of one child, or of the whole tree when called without a name.
298 method restarts ( $name = undef ) {
299 unless ( defined $name ) {
300 my $total = 0;
301 $total += $_->{restarts} for @children;
302 return $total;
303 }
304 my ($child) = grep { $_->{name} eq $name } @children;
305 croak "Supervisor->restarts(): no supervised child named '$name'" unless $child;
306 return $child->{restarts};
307 }
308 };
309 #
310 1;