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

filter: Statementstmt 0.0% 0 / 46 Branchbran 0.0% 0 / 16 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod n/a totaltotal 0.0% 0 / 68 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 'experimental::class', 'recursion';
3 use feature 'class';
4 #
5 class Acme::Parataxis::CancellationToken v0.1.6 {
6 use Acme::Parataxis;
7 use Carp qw[croak];
8 use Time::HiRes qw[time];
9  
10 # $kind selects which error an interrupted waiter throws. Public tokens use 'cancel'; with_timeout's internal
11 # deadline token uses 'timeout' so the same mechanism raises Timeout instead of Cancelled.
12 field $cancelled : reader : param = false;
13 field $kind : reader : param = 'cancel';
14 field $t0 : reader = time; # token birth, for elapsed-time tracing
15  
16 # Fiber ids currently parked under this token, in registration order. cancel() wakes them; unregister()/the
17 # on_wake( { ... } ) cleanup removes them when their wait finishes normally.
18 field @registered;
19  
20 method register () {
21 my $fid = Acme::Parataxis->current_fid;
22 croak 'register() must be called from inside a scheduled fiber' if $fid < 0;
23 if ($cancelled) { # too late to wait in vain: the next parked wait throws immediately on its wake
24 Acme::Parataxis::_interrupt( $fid, $kind );
25 return $fid;
26 }
27 push @registered, $fid if !grep { $_ == $fid } @registered;
28 return $fid;
29 }
30  
31 method unregister () { # Remove the current fiber from the token. Safe to call any number of times.
32 my $fid = Acme::Parataxis->current_fid;
33 @registered = grep { $_ != $fid } @registered;
34 return $fid;
35 }
36  
37 method cancel () { # Idempotent: flips the flag, wakes every registered (parked) fiber with an interrupt.
38 return if $cancelled;
39 my @fids = @registered;
40 $cancelled = true;
41 @registered = ();
42 warn sprintf "PARATAXIS_TRACE t=%.0fms(age=%.0fms) token cancel kind=%s fids=%s states=%s\n", ( time - $^T ) * 1000, ( time - $t0 ) * 1000,
43 $kind, join( ',', @fids ), join(
44 ',',
45 map {
46 my $fb = Acme::Parataxis->by_id($_);
47 $fb ? ( $fb->is_done ? "f$_:done" : 'f' . $_ . ':' . ( $fb->wait_reason ? $fb->wait_reason->[0] : 'run' ) ) : "f$_:gone"
48 } @fids
49 ) if $ENV{PARATAXIS_TRACE};
50 Acme::Parataxis::_interrupt( $_, $kind ) for @fids;
51 return true;
52 }
53 method waiters () { return scalar @registered }
54 };
55 #
56 1;