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

filter: Statementstmt 0.0% 0 / 186 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 50 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 7 Podpod n/a totaltotal 0.0% 0 / 337 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 use feature 'class';
3 no warnings 'experimental::class', 'experimental::try', 'recursion';
4 #
5 class Acme::Parataxis::Channel v0.1.6 {
6 use Acme::Parataxis qw[fiber await_sleep];
7 use Acme::Parataxis::CancellationToken;
8 use Acme::Parataxis::Semaphore;
9 use Carp qw[croak];
10 #
11 field $capacity : reader : param //= 2_000_000_000;
12 field $timeout : reader : param //= 0; # per-channel default wait bound in ms; 0 (and undef) means none
13 field $sem_get = Acme::Parataxis::Semaphore->new( count => 0 );
14 field $sem_put = Acme::Parataxis::Semaphore->new( count => $capacity );
15 field @data : reader;
16 field @select_waiters; # [fid, op] pairs parked here by select(); op is 'get' or 'put'
17 ADJUST {
18 $capacity >= 1 or die "Channel capacity must be >= 1 (got $capacity)\n";
19 defined $timeout && $timeout >= 0 or die "Channel timeout must be a non-negative number of milliseconds (got $timeout)\n";
20 }
21  
22 # Runs $op (a get/put body that parks through the channel semaphores) under the channel's default
23 # wait bound. The deadline is armed only when the op may actually park ($may_park): a ready channel
24 # never pays for a timer. Exactly like Channel::select's deadline - one token registered before the
25 # park (register-then-arm closes the lost-wakeup window) and one timer, re-used across the
26 # semaphore's internal re-parks; Error::Timeout on expiry, the waiter unregistered from the
27 # semaphore when interrupted. Teardown unregisters the caller and cancels the token on every exit,
28 # which recalls the timer's armed sleep job instead of leaving a worker sleeping out the bound.
29 method _with_deadline ( $may_park, $op ) {
30 return $op->() if !defined $timeout || $timeout <= 0 || !$may_park;
31 my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );
32 $deadline->register;
33 my $ms = $timeout;
34 fiber {
35 $deadline->register;
36 try { await_sleep($ms); $deadline->cancel } catch ($e) {
37 } # swallows its own interrupt
38 };
39 my ( $ok, $err, @rv );
40 $ok = 1;
41 if (wantarray) {
42 try { @rv = $op->() } catch ($e) {
43 $ok = 0;
44 $err = $e
45 }
46 }
47 else {
48 try { $rv[0] = $op->() } catch ($e) {
49 $ok = 0;
50 $err = $e
51 }
52 }
53 $deadline->unregister;
54 $deadline->cancel;
55 die $err if !$ok;
56 return wantarray ? @rv : $rv[0];
57 }
58  
59 method put ($value) {
60 return $self->_with_deadline(
61 @data >= $capacity,
62 sub {
63 $sem_put->down( 'Channel put', 5 );
64 push @data, $value;
65 $sem_get->up;
66 $self->_wake_select_waiters('get');
67 1;
68 }
69 );
70 }
71  
72 method put_priority ($value) {
73 push @data, $value;
74 $sem_get->up;
75 $self->_wake_select_waiters('get');
76 1;
77 }
78  
79 method try_put ($value) {
80 return 0 unless $sem_put->try;
81 push @data, $value;
82 $sem_get->up;
83 $self->_wake_select_waiters('get');
84 return 1;
85 }
86  
87 method get () {
88 return $self->_with_deadline(
89 @data == 0,
90 sub {
91 $sem_get->down( 'Channel get', 5 );
92 $sem_put->up;
93 my $v = shift @data;
94 $self->_wake_select_waiters('put');
95 return $v;
96 }
97 );
98 }
99  
100 method try_get () {
101 return ( 0, undef ) unless $sem_get->try;
102 $sem_put->up;
103 my $v = shift @data;
104 $self->_wake_select_waiters('put');
105 return ( 1, $v );
106 }
107 method size () { scalar @data }
108  
109 method shutdown () {
110 $sem_get->adjust(1_000_000_000);
111 $self->_wake_select_waiters('get');
112 1;
113 }
114  
115 method adjust ($diff) {
116 $sem_put->adjust($diff);
117 $self->_wake_select_waiters('put');
118 1;
119 }
120 method select_waiters () { scalar @select_waiters } # introspection: how many fibers are parked in select() here
121  
122 method remove_waiter ($fid) { # Unregisters the fiber from any internal wait queue; returns the number of entries removed.
123 $sem_get->remove_waiter($fid) + $sem_put->remove_waiter($fid) + $self->_unregister_select_waiter($fid);
124 }
125 method _register_select_waiter ( $fid, $op ) { push @select_waiters, [ $fid, $op ]; return $fid; }
126  
127 method _unregister_select_waiter ($fid) {
128 my $before = @select_waiters;
129 @select_waiters = grep { $_->[0] != $fid } @select_waiters;
130 return $before - @select_waiters;
131 }
132  
133 method _wake_select_waiters ($op) { # Wakes the select waiters waiting for $op, dropping stale fids
134 return unless @select_waiters;
135 my @still;
136 for my $ent (@select_waiters) {
137 my ( $fid, $want ) = @$ent;
138 next if !defined Acme::Parataxis->by_id($fid); # stale: dropped, not retained for the next wake
139 if ( $want eq $op ) { Acme::Parataxis::_scheduler_enqueue_by_id($fid) }
140 else { push @still, $ent }
141 }
142 @select_waiters = @still;
143 return;
144 }
145  
146 # CSP select: wait on the first ready case and return its (channel, value). A plain package sub rather than a
147 # method, since it has no channel of its own to dispatch on, so it takes the class as $class and is called as
148 # Acme::Parataxis::Channel->select(...). Two probe/register phases -- probe without yielding first, fall back to
149 # registering on every case in the channel's private @select_waiters, arming the shared deadline *after*
150 # registration, then parking.
151 sub select ( $class, @args ) {
152 my ( $timeout, $default );
153 my @cases;
154 while (@args) {
155 my $arg = shift @args;
156 if ( ref $arg eq 'ARRAY' && @$arg >= 2 ) {
157 my ( $ch, $op, @rest ) = @$arg;
158 Carp::croak 'select() case channel must be an Acme::Parataxis::Channel' unless ref($ch) && $ch->isa('Acme::Parataxis::Channel');
159 Carp::croak 'select() case op must be "get" or "put"' unless $op eq 'get' || $op eq 'put';
160 Carp::croak 'select() "put" case requires a value' if $op eq 'put' && @$arg < 3;
161 push @cases, [ $ch, $op, $rest[0] ];
162 }
163 elsif ( $arg eq 'timeout' ) {
164 $timeout = shift @args;
165 Carp::croak 'select() timeout must be a non-negative number of milliseconds' unless defined $timeout && $timeout >= 0;
166 }
167 elsif ( $arg eq 'default' ) {
168 $default = shift @args;
169 Carp::croak 'select() default must be a CODE ref' unless ref $default eq 'CODE';
170 }
171 else {
172 Carp::croak 'select() arguments must be [ $channel, "get" | "put", $value? ] cases, with timeout/default options';
173 }
174 }
175 Carp::croak 'select() needs at least one case' unless @cases;
176 my $fid = Acme::Parataxis->current_fid;
177 Carp::croak 'select() must be called from inside a scheduled fiber' if $fid < 0;
178  
179 # No explicit timeout: each case's channel-level default (Channel->new( timeout => $ms )) applies
180 # and select parks until the earliest fires - so the shared deadline is the smallest positive
181 # default among the cases. An explicit timeout option (including timeout => 0) always wins.
182 if ( !defined $timeout ) {
183 my @bounds = sort { $a <=> $b } grep { defined && $_ > 0 } map { $_->[0]->timeout } @cases;
184 $timeout = @bounds ? $bounds[0] : undef;
185 }
186  
187 # The timeout deadline is armed once on the first park and reused across re-parks, so a spurious wake can
188 # never stack timers. "Register, then arm" (token.register before the sleep job) closes the lost-wakeup
189 # window an await_sleep-only timeout would leave between the probe step and registration.
190 my $deadline;
191 my $timer_armed;
192 my ( $out_ch, $out_val, $out_die ) = ( undef, undef, undef );
193 OUTER: while (1) {
194  
195 # Phase 1 -- probe, no yield: shuffle so no ordering starves a case, commit the first match, and let
196 # default run only when nothing is ready (it never parks).
197 my @order = 0 .. $#cases;
198 for ( my $i = $#order; $i > 0; $i-- ) {
199 my $j = int rand( $i + 1 );
200 @order[ $i, $j ] = @order[ $j, $i ];
201 }
202 for my $i (@order) {
203 my ( $ch, $op, $v ) = @{ $cases[$i] };
204 if ( $op eq 'get' ) {
205 my ( $ok, $got ) = $ch->try_get;
206 if ($ok) { ( $out_ch, $out_val ) = ( $ch, $got ); last OUTER; }
207 }
208 else {
209 if ( $ch->try_put($v) ) { ( $out_ch, $out_val ) = ( $ch, $v ); last OUTER; }
210 }
211 }
212 if ( defined $default ) { ( $out_ch, $out_val ) = ( undef, $default->() ); last OUTER; }
213  
214 # Phase 2 -- register on every involved channel, arm the shared deadline, then park. On wake the
215 # park's deregistrations were already dropped (_resume_hooks) or the per-channel wake skipped the
216 # fiber, so re-probe exactly once and fall back to re-registering; the one-shot re-poll per wake is
217 # natural here because registering happens before the next park.
218 for my $case (@cases) { $case->[0]->_register_select_waiter( $fid, $case->[1] ); }
219 if ( defined $timeout && $timeout > 0 ) {
220 $deadline //= Acme::Parataxis::CancellationToken->new( kind => 'timeout' );
221 $deadline->register;
222 unless ($timer_armed) {
223 my $ms = $timeout;
224  
225 # The timer registers on the shared deadline and swallows its own interrupt, so teardown can
226 # recall it when a case commits first instead of leaving a worker parked for the full $ms.
227 Acme::Parataxis::fiber {
228 $deadline->register;
229 try { Acme::Parataxis::await_sleep($ms); $deadline->cancel } catch ($e) {
230 }
231 };
232 $timer_armed = 1;
233 }
234 }
235 my $dereg = sub {
236 for my $case (@cases) { $case->[0]->_unregister_select_waiter($fid) }
237 $deadline->unregister if defined $deadline;
238 };
239 my $ok = 1;
240 my $err;
241 try { Acme::Parataxis::_park( 'Channel select', 1, $dereg ) }
242 catch ($e) { $ok = 0; $err = $e }
243 finally { $dereg->() } # idempotent: on interrupt _park already ran it; on a natural wake this is the cleanup
244 if ( !$ok ) {
245  
246 # Our own deadline fired -> the API is (undef, undef) on timeout. A timeout sent by an *enclosing*
247 # with_timeout/nursery did not cancel our token, so it propagates instead of being swallowed.
248 if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) {
249 ( $out_ch, $out_val ) = ( undef, undef );
250 last OUTER;
251 }
252 $out_die = $err;
253 last OUTER;
254 }
255 }
256  
257 # Every exit funnels through here so the armed timeout helper is never orphaned: drop the select fiber off
258 # the token first (a running fiber must not receive its own interrupt), then cancel to recall the timer's
259 # sleep job. A deadline that already fired makes both steps no-ops.
260 $deadline->unregister if defined $deadline;
261 $deadline->cancel if defined $deadline;
262 die $out_die if defined $out_die;
263 return ( $out_ch, $out_val );
264 }
265 };
266 #
267 1;