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

filter: Statementstmt 0.0% 0 / 198 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 62 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 7 Podpod n/a totaltotal 0.0% 0 / 371 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.7 {
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  
61 # The common no-timeout (or ready-channel) case needs no deadline wrapper at all: avoid building a closure and
62 # entering try/cleanup on every put. Only a genuinely blocking put under a channel timeout takes that path.
63 if ( defined $timeout && $timeout > 0 && @data >= $capacity ) {
64 return $self->_with_deadline(
65 1,
66 sub {
67 $sem_put->down( 'Channel put', 5 );
68 push @data, $value;
69 $sem_get->up;
70 $self->_wake_select_waiters('get');
71 1;
72 }
73 );
74 }
75  
76 # Three fewer wrapper frames on the inlined path, so _park()'s caller level still points at user code.
77 $sem_put->down( 'Channel put', 3 );
78 push @data, $value;
79 $sem_get->up;
80 $self->_wake_select_waiters('get');
81 return 1;
82 }
83  
84 method put_priority ($value) {
85 push @data, $value;
86 $sem_get->up;
87 $self->_wake_select_waiters('get');
88 1;
89 }
90  
91 method try_put ($value) {
92 return 0 unless $sem_put->try;
93 push @data, $value;
94 $sem_get->up;
95 $self->_wake_select_waiters('get');
96 return 1;
97 }
98  
99 method get () {
100  
101 # Same fast path as put(): skip the deadline wrapper unless this get can actually block under a timeout.
102 if ( defined $timeout && $timeout > 0 && @data == 0 ) {
103 return $self->_with_deadline(
104 1,
105 sub {
106 $sem_get->down( 'Channel get', 5 );
107 $sem_put->up;
108 my $v = shift @data;
109 $self->_wake_select_waiters('put');
110 return $v;
111 }
112 );
113 }
114  
115 # Three fewer wrapper frames on the inlined path, so _park()'s caller level still points at user code.
116 $sem_get->down( 'Channel get', 3 );
117 $sem_put->up;
118 my $v = shift @data;
119 $self->_wake_select_waiters('put');
120 return $v;
121 }
122  
123 method try_get () {
124 return ( 0, undef ) unless $sem_get->try;
125 $sem_put->up;
126 my $v = shift @data;
127 $self->_wake_select_waiters('put');
128 return ( 1, $v );
129 }
130 method size () { scalar @data }
131  
132 method shutdown () {
133 $sem_get->adjust(1_000_000_000);
134 $self->_wake_select_waiters('get');
135 1;
136 }
137  
138 method adjust ($diff) {
139 $sem_put->adjust($diff);
140 $self->_wake_select_waiters('put');
141 1;
142 }
143 method select_waiters () { scalar @select_waiters } # introspection: how many fibers are parked in select() here
144  
145 method remove_waiter ($fid) { # Unregisters the fiber from any internal wait queue; returns the number of entries removed.
146 $sem_get->remove_waiter($fid) + $sem_put->remove_waiter($fid) + $self->_unregister_select_waiter($fid);
147 }
148 method _register_select_waiter ( $fid, $op ) { push @select_waiters, [ $fid, $op ]; return $fid; }
149  
150 method _unregister_select_waiter ($fid) {
151 my $before = @select_waiters;
152 @select_waiters = grep { $_->[0] != $fid } @select_waiters;
153 return $before - @select_waiters;
154 }
155  
156 method _wake_select_waiters ($op) { # Wakes the select waiters waiting for $op, dropping stale fids
157 return unless @select_waiters;
158 my @still;
159 for my $ent (@select_waiters) {
160 my ( $fid, $want ) = @$ent;
161 next if !defined Acme::Parataxis->by_id($fid); # stale: dropped, not retained for the next wake
162 if ( $want eq $op ) { Acme::Parataxis::_scheduler_enqueue_by_id($fid) }
163 else { push @still, $ent }
164 }
165 @select_waiters = @still;
166 return;
167 }
168  
169 # CSP select: wait on the first ready case and return its (channel, value). A plain package sub rather than a
170 # method, since it has no channel of its own to dispatch on, so it takes the class as $class and is called as
171 # Acme::Parataxis::Channel->select(...). Two probe/register phases -- probe without yielding first, fall back to
172 # registering on every case in the channel's private @select_waiters, arming the shared deadline *after*
173 # registration, then parking.
174 sub select ( $class, @args ) {
175 my ( $timeout, $default );
176 my @cases;
177 while (@args) {
178 my $arg = shift @args;
179 if ( ref $arg eq 'ARRAY' && @$arg >= 2 ) {
180 my ( $ch, $op, @rest ) = @$arg;
181 Carp::croak 'select() case channel must be an Acme::Parataxis::Channel' unless ref($ch) && $ch->isa('Acme::Parataxis::Channel');
182 Carp::croak 'select() case op must be "get" or "put"' unless $op eq 'get' || $op eq 'put';
183 Carp::croak 'select() "put" case requires a value' if $op eq 'put' && @$arg < 3;
184 push @cases, [ $ch, $op, $rest[0] ];
185 }
186 elsif ( $arg eq 'timeout' ) {
187 $timeout = shift @args;
188 Carp::croak 'select() timeout must be a non-negative number of milliseconds' unless defined $timeout && $timeout >= 0;
189 }
190 elsif ( $arg eq 'default' ) {
191 $default = shift @args;
192 Carp::croak 'select() default must be a CODE ref' unless ref $default eq 'CODE';
193 }
194 else {
195 Carp::croak 'select() arguments must be [ $channel, "get" | "put", $value? ] cases, with timeout/default options';
196 }
197 }
198 Carp::croak 'select() needs at least one case' unless @cases;
199 my $fid = Acme::Parataxis->current_fid;
200 Carp::croak 'select() must be called from inside a scheduled fiber' if $fid < 0;
201  
202 # No explicit timeout: each case's channel-level default (Channel->new( timeout => $ms )) applies
203 # and select parks until the earliest fires - so the shared deadline is the smallest positive
204 # default among the cases. An explicit timeout option (including timeout => 0) always wins.
205 if ( !defined $timeout ) {
206 my @bounds = sort { $a <=> $b } grep { defined && $_ > 0 } map { $_->[0]->timeout } @cases;
207 $timeout = @bounds ? $bounds[0] : undef;
208 }
209  
210 # The timeout deadline is armed once on the first park and reused across re-parks, so a spurious wake can
211 # never stack timers. "Register, then arm" (token.register before the sleep job) closes the lost-wakeup
212 # window an await_sleep-only timeout would leave between the probe step and registration.
213 my $deadline;
214 my $timer_armed;
215 my ( $out_ch, $out_val, $out_die ) = ( undef, undef, undef );
216 OUTER: while (1) {
217  
218 # Phase 1 -- probe, no yield: shuffle so no ordering starves a case, commit the first match, and let
219 # default run only when nothing is ready (it never parks).
220 my @order = 0 .. $#cases;
221 for ( my $i = $#order; $i > 0; $i-- ) {
222 my $j = int rand( $i + 1 );
223 @order[ $i, $j ] = @order[ $j, $i ];
224 }
225 for my $i (@order) {
226 my ( $ch, $op, $v ) = @{ $cases[$i] };
227 if ( $op eq 'get' ) {
228 my ( $ok, $got ) = $ch->try_get;
229 if ($ok) { ( $out_ch, $out_val ) = ( $ch, $got ); last OUTER; }
230 }
231 else {
232 if ( $ch->try_put($v) ) { ( $out_ch, $out_val ) = ( $ch, $v ); last OUTER; }
233 }
234 }
235 if ( defined $default ) { ( $out_ch, $out_val ) = ( undef, $default->() ); last OUTER; }
236  
237 # Phase 2 -- register on every involved channel, arm the shared deadline, then park. On wake the
238 # park's deregistrations were already dropped (_resume_hooks) or the per-channel wake skipped the
239 # fiber, so re-probe exactly once and fall back to re-registering; the one-shot re-poll per wake is
240 # natural here because registering happens before the next park.
241 for my $case (@cases) { $case->[0]->_register_select_waiter( $fid, $case->[1] ); }
242 if ( defined $timeout && $timeout > 0 ) {
243 $deadline //= Acme::Parataxis::CancellationToken->new( kind => 'timeout' );
244 $deadline->register;
245 unless ($timer_armed) {
246 my $ms = $timeout;
247  
248 # The timer registers on the shared deadline and swallows its own interrupt, so teardown can
249 # recall it when a case commits first instead of leaving a worker parked for the full $ms.
250 Acme::Parataxis::fiber {
251 $deadline->register;
252 try { Acme::Parataxis::await_sleep($ms); $deadline->cancel } catch ($e) {
253 }
254 };
255 $timer_armed = 1;
256 }
257 }
258 my $dereg = sub {
259 for my $case (@cases) { $case->[0]->_unregister_select_waiter($fid) }
260 $deadline->unregister if defined $deadline;
261 };
262 my $ok = 1;
263 my $err;
264 try { Acme::Parataxis::_park( 'Channel select', 1, $dereg ) }
265 catch ($e) { $ok = 0; $err = $e }
266 finally { $dereg->() } # idempotent: on interrupt _park already ran it; on a natural wake this is the cleanup
267 if ( !$ok ) {
268  
269 # Our own deadline fired -> the API is (undef, undef) on timeout. A timeout sent by an *enclosing*
270 # with_timeout/nursery did not cancel our token, so it propagates instead of being swallowed.
271 if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) {
272 ( $out_ch, $out_val ) = ( undef, undef );
273 last OUTER;
274 }
275 $out_die = $err;
276 last OUTER;
277 }
278 }
279  
280 # Every exit funnels through here so the armed timeout helper is never orphaned: drop the select fiber off
281 # the token first (a running fiber must not receive its own interrupt), then cancel to recall the timer's
282 # sleep job. A deadline that already fired makes both steps no-ops.
283 $deadline->unregister if defined $deadline;
284 $deadline->cancel if defined $deadline;
285 die $out_die if defined $out_die;
286 return ( $out_ch, $out_val );
287 }
288 };
289 #
290 1;