| 1 | use v5.40; | ||
| 2 | no warnings 'recursion'; # fibers run on separate heap stacks; Perl's C-stack-depth heuristic misfires there | ||
| 3 | use experimental qw[class try]; | ||
| 4 | |||
| 5 | package Acme::Parataxis v0.1.7 { | ||
| 6 | use Affix qw[affix :types]; | ||
| 7 | use Config; | ||
| 8 | use File::Spec; | ||
| 9 | use File::Basename qw[dirname]; | ||
| 10 | use Time::HiRes qw[usleep]; | ||
| 11 | use Exporter qw[import]; | ||
| 12 | use Carp qw[croak]; | ||
| 13 | use builtin qw[refaddr]; | ||
| 14 | use Acme::Parataxis::Error; | ||
| 15 | our %EXPORT_TAGS = ( | ||
| 16 | all => [ | ||
| 17 | our @EXPORT_OK | ||
| 18 | = qw[ | ||
| 19 | run spawn yield await stop async fiber | ||
| 20 | await_sleep await_read await_write await_core_id | ||
| 21 | current_fid tid root maybe_yield on_wake with_timeout with_cancel nursery pmap wait_all wait_any | ||
| 22 | set_max_threads max_threads set_max_fibers max_fibers dump_fibers fd_setsize | ||
| 23 | backtrace_depth | ||
| 24 | atomically retry | ||
| 25 | set_preempt_threshold | ||
| 26 | ] | ||
| 27 | ] | ||
| 28 | ); | ||
| 29 | # | ||
| 30 | our @IPC_BUFFER; | ||
| 31 | my $lib; | ||
| 32 | my @SCHEDULER_QUEUE; | ||
| 33 | my $HAS_PRIORITIES = 0; # true once any fiber has been given a non-default priority | ||
| 34 | my $IS_RUNNING = 0; | ||
| 35 | my $DRIVER; # the attached Acme::Parataxis::Driver (undef = the worker-pool fallback path), see attach_loop | ||
| 36 | our %FIBER_LOCALS; # fiber-object refaddr => { local-id => value }; stashes for Acme::Parataxis::Local | ||
| 37 | our @INHERIT_LOCAL_IDS; # ids of Acme::Parataxis::Local objects created with inherit => 1; spawn seeds these from parent to child | ||
| 38 | our %ACTOR_REGISTRY; # registered actor names => Acme::Parataxis::Actor handles; the actor(name)/whereis table | ||
| 39 | my $BACKTRACE_DEPTH = 6; # max user-side caller frames captured at each park (0 disables the capture) | ||
| 40 | my @WAITING_DEPOSIT = ('WAITING'); # shared one-element marker handed to the scheduler by every parked fiber | ||
| 41 | my $PREEMPT_THRESHOLD = 0; # mirror of the C threshold, so disabled preemption needs no FFI call | ||
| 42 | my $VIRTUAL_CLOCK; # undef = wall clock; a running virtual run sets this to the current virtual ms | ||
| 43 | my %VIRTUAL_DEADLINES; # fid => absolute virtual-ms deadline of that fiber's one armed virtual timer | ||
| 44 | my @VIRTUAL_DEADLINES; # deadline_ms ascending; paired with @VIRTUAL_TIMER_FIDS; lazy deletion via %VIRTUAL_DEADLINES | ||
| 45 | my @VIRTUAL_TIMER_FIDS; # fid for each deadline; avoids one two-element AV per armed timer | ||
| 46 | my $VIRTUAL_TIMER_HEAD = 0; # fired prefix of the parallel timer arrays, compacted lazily | ||
| 47 | |||
| 48 | # Fiber object layout: a flat arrayref of slots rather than perlclass objects (array access is much cheaper than | ||
| 49 | # classes and even hash lookup on the hot spawn/await path). | ||
| 50 | use constant { | ||
| 51 | F_CODE => 0, | ||
| 52 | F_IS_DONE => 1, | ||
| 53 | F_ERROR => 2, | ||
| 54 | F_RESULT => 3, | ||
| 55 | F_FID => 4, | ||
| 56 | F_IS_READY => 5, | ||
| 57 | F_CALLBACKS => 6, | ||
| 58 | F_WAITER => 7, | ||
| 59 | F_LAST_STATUS => 8, | ||
| 60 | F_PRIORITY => 9, | ||
| 61 | F_WAIT_REASON => 10, | ||
| 62 | F_WAKE_HOOKS => 11, | ||
| 63 | F_INTERRUPT => 12, | ||
| 64 | F_CANCEL_SCOPES => 13, | ||
| 65 | F_DEADLINE_SCOPES => 14, | ||
| 66 | F_DEADLINE_ARMED => 15, | ||
| 67 | F_PARKED => 16, # true while suspended in a blocking wait (was %PARKED) | ||
| 68 | F_PARK_DEREG => 17, # coderef removing this fiber from its waiter list on an interrupted park | ||
| 69 | F_QUEUED => 18 # true while sitting in @SCHEDULER_QUEUE (was %SCHEDULER_QUEUED) | ||
| 70 | }; | ||
| 71 | |||
| 72 | # Parked fibers used to be tracked in %PARKED/%PARK_REGS keyed by fid, and queued ones in %SCHEDULER_QUEUED. | ||
| 73 | # Those hashes cost a lookup on every park, wake and enqueue; the flags now live in flat slots on the fiber | ||
| 74 | # object instead. Destroying a fiber drops its flags with it, and run() clears them explicitly on the cold | ||
| 75 | # teardown paths (the hot loop clears them as it drains the queue). | ||
| 76 | sub _take_park_dereg ($fiber) { | ||
| 77 | my $dereg = $fiber->[F_PARK_DEREG]; | ||
| 78 | $fiber->[F_PARK_DEREG] = undef; | ||
| 79 | return $dereg; | ||
| 80 | } | ||
| 81 | |||
| 82 | # Clears stale queue flags and returns the same live-id snapshot run() needs for %PRESET_FIBERS. This used to | ||
| 83 | # enumerate ids and then fetch every object a second time; one pass is enough on both startup and teardown paths. | ||
| 84 | sub _clear_queued_flags () { | ||
| 85 | my $snapshot = Acme::Parataxis::snapshot_live_fibers(); | ||
| 86 | return () unless ref $snapshot eq 'ARRAY'; | ||
| 87 | my @ids; | ||
| 88 | for ( my $i = 0; $i < @$snapshot; $i += 2 ) { | ||
| 89 | my $fiber = $snapshot->[$i]; | ||
| 90 | my $fid = $snapshot->[ $i + 1 ]; | ||
| 91 | $fiber->[F_QUEUED] = 0; | ||
| 92 | push @ids, $fid; | ||
| 93 | } | ||
| 94 | return @ids; | ||
| 95 | } | ||
| 96 | |||
| 97 | # Scheduler run queue. Kept sorted by descending priority (stable for equal priorities, so a group of same-priority fibers stays FIFO). | ||
| 98 | sub _enqueue ($fiber) { | ||
| 99 | return if $fiber->[F_QUEUED]; | ||
| 100 | $fiber->[F_QUEUED] = 1; | ||
| 101 | if ( !$HAS_PRIORITIES ) { | ||
| 102 | push @SCHEDULER_QUEUE, $fiber; | ||
| 103 | return; | ||
| 104 | } | ||
| 105 | my $prio = $fiber->[F_PRIORITY] // 0; | ||
| 106 | my $i = 0; | ||
| 107 | $i++ while $i < @SCHEDULER_QUEUE && ( $SCHEDULER_QUEUE[$i]->[F_PRIORITY] // 0 ) >= $prio; | ||
| 108 | splice @SCHEDULER_QUEUE, $i, 0, $fiber; | ||
| 109 | } | ||
| 110 | |||
| 111 | # All C fiber ids that are currently live. Used by run() to snapshot the fibers that predate a run so its | ||
| 112 | # deadlock detector only considers fibers the run actually created (fibers leaked by a prior deadlocked run stay | ||
| 113 | # parked forever and would otherwise poison every later run). | ||
| 114 | sub _live_fiber_ids () { | ||
| 115 | my @ids; | ||
| 116 | my $cap = Acme::Parataxis::get_fiber_capacity(); | ||
| 117 | for ( my $fid = 0; $fid < $cap; $fid++ ) { | ||
| 118 | my $obj = Acme::Parataxis::get_fiber_by_id($fid); | ||
| 119 | push @ids, $fid if defined $obj && ( ref $obj || '' ) ne ''; | ||
| 120 | } | ||
| 121 | return @ids; | ||
| 122 | } | ||
| 123 | |||
| 124 | # Diagnostics: a snapshot of every live fiber, riding entirely on wait_reason: _park records | ||
| 125 | # [reason, file, line] on the fiber before it yields and _resume_hooks clears it on a natural wake, so a | ||
| 126 | # live fiber that still carries a reason (or has its parked slot set) is blocked, not merely preempted. WAITING = | ||
| 127 | # parked on a wait; READY = in the scheduler run queue; RUNNING = the fiber calling the snapshot (only | ||
| 128 | # when taken from inside a run); RUNNABLE = live but neither parked nor queued (e.g. a generator's body | ||
| 129 | # or a fiber surrendered mid-quantum). Each record also carries the bounded user-side caller | ||
| 130 | # chain (its fourth element) captured at the park; the top site is still the wait_reason site (the user's | ||
| 131 | # call for direct waits like await_sleep, the wait's own method for Sync/Channel waits whose level | ||
| 132 | # targeting is tuned for their error messages). | ||
| 133 | sub _fiber_snapshot () { | ||
| 134 | my $current = get_current_parataxis_id(); | ||
| 135 | my @rows; | ||
| 136 | for my $fid ( _live_fiber_ids() ) { | ||
| 137 | my $fiber = Acme::Parataxis::get_fiber_by_id($fid); | ||
| 138 | next unless $fiber && ref $fiber; | ||
| 139 | my $reason = $fiber->[F_WAIT_REASON]; # undef once the fiber is woken normally | ||
| 140 | my $state | ||
| 141 | = ( defined $reason || $fiber->[F_PARKED] ) ? 'WAITING' : | ||
| 142 | $fiber->[F_QUEUED] ? 'READY' : | ||
| 143 | ( $current >= 0 && $fid == $current ) ? 'RUNNING' : | ||
| 144 | 'RUNNABLE'; | ||
| 145 | push @rows, { fid => $fid, state => $state, reason => $reason }; | ||
| 146 | } | ||
| 147 | return [ sort { $a->{fid} <=> $b->{fid} } @rows ]; | ||
| 148 | } | ||
| 149 | |||
| 150 | # Dumps every live fiber. Returns the arrayref of { fid, state, reason (wait_reason site; its fourth element is | ||
| 151 | # the backtrace arrayref of [pkg, file, line, sub] user-side frames, [] when the capture is off or empty) } | ||
| 152 | # records and, when called with a filehandle, also prints a human-readable report there (dump_fibers() with no | ||
| 153 | # argument only returns the data). Safe to call from anywhere: top-level (outside a run) reports fibers leaked by | ||
| 154 | # an earlier deadlocked run, inside a run it classifies each live fiber exactly. | ||
| 155 | sub dump_fibers { | ||
| 156 | my $invocant = shift; | ||
| 157 | if ( !defined $invocant || | ||
| 158 | ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) { | ||
| 159 | unshift @_, $invocant if defined $invocant; | ||
| 160 | $invocant = __PACKAGE__; | ||
| 161 | } | ||
| 162 | my $fh = shift; | ||
| 163 | my $rows = _fiber_snapshot(); | ||
| 164 | return $rows unless $fh; | ||
| 165 | say $fh 'Acme::Parataxis live fiber dump'; | ||
| 166 | say $fh ' fid state wait reason where'; | ||
| 167 | for my $r (@$rows) { | ||
| 168 | my ( $file, $line ) = $r->{reason} ? @{ $r->{reason} }[ 1, 2 ] : ( '-', '-' ); | ||
| 169 | say $fh sprintf ' %-4d %-8s %-17s %s:%s', $r->{fid}, $r->{state}, ( $r->{reason} && $r->{reason}[0] ) // '-', $file, $line; | ||
| 170 | for my $bt ( @{ $r->{reason}[3] // [] } ) { | ||
| 171 | say $fh sprintf ' at %s:%d %s', @$bt[ 1, 2, 3 ]; | ||
| 172 | } | ||
| 173 | } | ||
| 174 | return $rows; | ||
| 175 | } | ||
| 176 | |||
| 177 | sub _bind_functions ($l) { | ||
| 178 | affix $l, 'init_system', [], Int; | ||
| 179 | affix $l, 'create_fiber', [ Pointer [SV], Pointer [SV] ], Int; | ||
| 180 | affix $l, 'spawn_fiber', [ Pointer [SV], Pointer [SV] ], Pointer [SV]; | ||
| 181 | affix $l, 'coro_call', [ Int, Pointer [SV] ], Pointer [SV]; | ||
| 182 | affix $l, 'run_fiber_checked', [ Int, Pointer [SV] ], Int; | ||
| 183 | affix $l, 'coro_transfer', [ Int, Pointer [SV] ], Pointer [SV]; | ||
| 184 | affix $l, 'coro_yield', [ Pointer [SV] ], Pointer [SV]; | ||
| 185 | affix $l, 'is_finished', [Int], Int; | ||
| 186 | affix $l, 'get_fiber_by_id', [Int], Pointer [SV]; | ||
| 187 | affix $l, 'snapshot_live_fibers', [], Pointer [SV]; | ||
| 188 | affix $l, 'get_live_fiber_count', [], Int; | ||
| 189 | affix $l, 'get_fiber_capacity', [], Int; | ||
| 190 | affix $l, 'destroy_coro', [Int], Void; | ||
| 191 | affix $l, 'para_release_cv_depth', [ Pointer [SV] ], Void; | ||
| 192 | affix $l, 'para_cvreg_purge_fiber', [Int], Void; | ||
| 193 | affix $l, 'force_depth_zero', [ Pointer [SV] ], Void; | ||
| 194 | affix $l, 'cleanup', [], Void; | ||
| 195 | affix $l, 'get_os_thread_id_export', [], Int; | ||
| 196 | affix $l, 'get_current_parataxis_id', [], Int; | ||
| 197 | affix $l, 'submit_c_job', [ Int, LongLong, Int ], Int; | ||
| 198 | affix $l, 'drain_jobs', [ Pointer [SV] ], Void; | ||
| 199 | affix $l, 'check_for_completion', [], Int; | ||
| 200 | affix $l, 'get_outstanding_jobs', [], Int; | ||
| 201 | affix $l, 'get_short_sleep_jobs', [], Int; | ||
| 202 | affix $l, 'recall_sleep_jobs_for_fiber', [Int], Int; | ||
| 203 | affix $l, 'get_job_result', [Int], Pointer [SV]; | ||
| 204 | affix $l, 'get_job_coro_id', [Int], Int; | ||
| 205 | affix $l, 'free_job_slot', [Int], Void; | ||
| 206 | affix $l, 'get_thread_pool_size', [], Int; | ||
| 207 | affix $l, 'get_max_thread_pool_size', [], Int; | ||
| 208 | affix $l, 'get_fd_setsize', [], Int; | ||
| 209 | affix $l, 'set_max_threads', [Int], Void; | ||
| 210 | affix $l, 'get_max_fibers', [], Int; | ||
| 211 | affix $l, 'set_max_fibers', [Int], Void; | ||
| 212 | affix $l, [ 'set_preempt_threshold' => '_set_preempt_threshold' ], [LongLong], Void; | ||
| 213 | affix $l, [ 'maybe_yield' => '_maybe_yield' ], [], Pointer [SV]; | ||
| 214 | affix $l, 'get_preempt_count', [], LongLong; | ||
| 215 | |||
| 216 | # Capture the main interpreter context | ||
| 217 | init_system(); | ||
| 218 | if ( $^O eq 'MSWin32' ) { | ||
| 219 | my $perl_dll = $Config{libperl}; | ||
| 220 | $perl_dll =~ s/^lib//; | ||
| 221 | $perl_dll =~ s/\.a$//; | ||
| 222 | $perl_dll .= '.' . $Config{so}; | ||
| 223 | my $p = Affix::load_library($perl_dll); | ||
| 224 | affix $p, 'win32_get_osfhandle', [Int], LongLong; | ||
| 225 | } | ||
| 226 | } | ||
| 227 | |||
| 228 | BEGIN { | ||
| 229 | my $lib_name = ( $^O eq 'MSWin32' ? '' : 'lib' ) . 'parataxis.' . $Config{so}; | ||
| 230 | my @paths; | ||
| 231 | push @paths, File::Spec->catfile( dirname(__FILE__), $lib_name ); | ||
| 232 | push @paths, File::Spec->catfile( dirname(__FILE__), '..', 'arch', 'auto', 'Acme', 'Parataxis', $lib_name ); | ||
| 233 | push @paths, File::Spec->catfile( dirname(__FILE__), '..', '..', 'arch', 'auto', 'Acme', 'Parataxis', $lib_name ); | ||
| 234 | push @paths, File::Spec->catfile( dirname(__FILE__), 'auto', 'Acme', 'Parataxis', $lib_name ); | ||
| 235 | for my $inc (@INC) { | ||
| 236 | next if ref $inc; | ||
| 237 | push @paths, File::Spec->catfile( $inc, 'auto', 'Acme', 'Parataxis', $lib_name ); | ||
| 238 | } | ||
| 239 | for my $path (@paths) { | ||
| 240 | if ( -e $path ) { | ||
| 241 | $lib = Affix::load_library($path); | ||
| 242 | last if $lib; | ||
| 243 | } | ||
| 244 | } | ||
| 245 | if ( !$lib ) { | ||
| 246 | my $why = eval { Affix::get_last_error_message() }; | ||
| 247 | $why = '' unless defined $why; | ||
| 248 | $why =~ s/\s+\z//; | ||
| 249 | die 'Could not find or load ' . $lib_name . ( length $why ? ": $why" : '' ) . ' (tried ' . scalar(@paths) . ' paths)'; | ||
| 250 | } | ||
| 251 | _bind_functions($lib); | ||
| 252 | } | ||
| 253 | |||
| 254 | # API aliases and wrappers | ||
| 255 | sub fiber : prototype(&) ($code) { spawn( __PACKAGE__, $code ) } | ||
| 256 | sub async : prototype(&) ($code) { return run($code) } | ||
| 257 | |||
| 258 | # Index at which user arguments start in @_: 0 when it is a plain call, 1 when $_[0] is a self (package name or | ||
| 259 | # blessed object). This mirrors the shift/unshift invocant dance used elsewhere, but reads $_[0] instead of | ||
| 260 | # shifting, so calling it never reifies the caller's pad @_. A reified @_ left behind in a parked frame trips | ||
| 261 | # pp_entersub's assert(!AvREAL(av))/assert(AvFILLp(av) == -1) when a different fiber later enters the same sub at | ||
| 262 | # the same depth. | ||
| 263 | sub _arg_offset { | ||
| 264 | my $self = $_[0]; | ||
| 265 | return ( defined $self && ( ( ref $self || $self ) eq __PACKAGE__ || ( builtin::blessed($self) && $self->isa(__PACKAGE__) ) ) ) ? 1 : 0; | ||
| 266 | } | ||
| 267 | |||
| 268 | # Aggregate a list of futures into one that resolves when every input has: the result is an arrayref of each | ||
| 269 | # input's result, in input order, or the stored error of the first input to fail (reject-fast, Promise.all style). | ||
| 270 | # Inputs are not cancelled on a rejection; they are independent and keep running, and their later results are | ||
| 271 | # discarded. Zero futures resolve immediately with [] (matching Promise.all([])). An already-resolved input | ||
| 272 | # fires its on_ready callback inline, so a wait_all of ready inputs resolves inline (no fiber needed) and any | ||
| 273 | # mixed ready/pending input resolves the moment the last straggler lands. Inputs must be Acme::Parataxis::Future | ||
| 274 | # objects else croaks. Also callable as Acme::Parataxis->wait_all(...). | ||
| 275 | sub wait_all { | ||
| 276 | my $o = _arg_offset( $_[0] ); | ||
| 277 | my @futures = @_[ $o .. $#_ ]; | ||
| 278 | @_ = (); | ||
| 279 | croak 'wait_all() requires Acme::Parataxis::Future inputs' | ||
| 280 | if grep { !( defined $_ && ref $_ && $_->isa('Acme::Parataxis::Future') ) } @futures; | ||
| 281 | require Acme::Parataxis::Future; | ||
| 282 | my $all = Acme::Parataxis::Future->new; | ||
| 283 | if ( @futures == 0 ) { | ||
| 284 | $all->set_result( [] ); | ||
| 285 | return $all; | ||
| 286 | } | ||
| 287 | my @results; | ||
| 288 | my $pending = scalar @futures; | ||
| 289 | for my $i ( 0 .. $#futures ) { | ||
| 290 | my $idx = $i; | ||
| 291 | my $fut = $futures[$i]; | ||
| 292 | $fut->on_ready( | ||
| 293 | sub ($f) { | ||
| 294 | return if $all->is_ready; | ||
| 295 | if ( defined $f->error ) { | ||
| 296 | $all->set_error( $f->error ); # reject-fast: the first failure wins, copied wholesale | ||
| 297 | return; | ||
| 298 | } | ||
| 299 | $results[$idx] = $f->result; | ||
| 300 | $all->set_result( \@results ) if --$pending == 0; | ||
| 301 | } | ||
| 302 | ); | ||
| 303 | } | ||
| 304 | return $all; | ||
| 305 | } | ||
| 306 | |||
| 307 | # Aggregate a list of futures into one that settles with a wholesale copy of the first input to settle - success | ||
| 308 | # or failure (Promise.race). The losers are untouched and keep running; their eventual results are dropped by the | ||
| 309 | # is_ready guard. An already-ready input settles the aggregate inline. At least one input is required (an empty | ||
| 310 | # race would never settle) and each input must be an Acme::Parataxis::Future else croaks. Also callable as | ||
| 311 | # Acme::Parataxis->wait_any(...). | ||
| 312 | sub wait_any { | ||
| 313 | my $o = _arg_offset( $_[0] ); | ||
| 314 | my @futures = @_[ $o .. $#_ ]; | ||
| 315 | @_ = (); | ||
| 316 | croak 'wait_any() requires at least one Acme::Parataxis::Future input' unless @futures; | ||
| 317 | croak 'wait_any() requires Acme::Parataxis::Future inputs' | ||
| 318 | if grep { !( defined $_ && ref $_ && $_->isa('Acme::Parataxis::Future') ) } @futures; | ||
| 319 | require Acme::Parataxis::Future; | ||
| 320 | my $any = Acme::Parataxis::Future->new; | ||
| 321 | for my $f (@futures) { | ||
| 322 | $f->on_ready( | ||
| 323 | sub ($f) { | ||
| 324 | return if $any->is_ready; | ||
| 325 | if ( defined $f->error ) { $any->set_error( $f->error ) } # wholesale copy of the failure | ||
| 326 | else { $any->set_result( $f->result ) } | ||
| 327 | } | ||
| 328 | ); | ||
| 329 | } | ||
| 330 | return $any; | ||
| 331 | } | ||
| 332 | |||
| 333 | sub yield { | ||
| 334 | my $is_self = _arg_offset( $_[0] ); | ||
| 335 | my @deposit = (); | ||
| 336 | push @deposit, $_[$_] for ( $is_self ? 1 : 0 ) .. $#_; | ||
| 337 | if ( !$is_self && @deposit && !defined $deposit[0] ) { | ||
| 338 | shift @deposit; | ||
| 339 | } | ||
| 340 | @_ = (); | ||
| 341 | my $result = coro_yield( \@deposit ); | ||
| 342 | return unless defined $result; | ||
| 343 | return ( ref $result eq 'ARRAY' ) ? ( wantarray ? @$result : $result->[-1] ) : $result; | ||
| 344 | } | ||
| 345 | |||
| 346 | # Park the current fiber in a blocking wait, recording why and where (for diagnostics and cancellation). | ||
| 347 | # $level is the caller stack depth (relative to _park) of the *user* frame whose location should be attributed: | ||
| 348 | # 1 for direct wait sites, 2 for a Semaphore down(), 3 for a Channel get()/put(). | ||
| 349 | # | ||
| 350 | # The wait-reason record is [reason, file, line] plus a fourth element, a bounded backtrace of the | ||
| 351 | # user-side callchain (caller frames from just below the recorded site back to the fiber body). Capturing it | ||
| 352 | # is a short caller() loop (~100ns per frame), so it runs unconditionally; backtrace_depth(0) disables it. | ||
| 353 | # On the *re-entry* after the yield returns, a pending interrupt (set by _interrupt) is consumed and thrown, so a | ||
| 354 | # cancelled wait unwinds with Acme::Parataxis::Error::Cancelled (or ::Timeout) right here the caller of the wait | ||
| 355 | # sees the parked wait's own reason in the error's wait_reason. | ||
| 356 | # | ||
| 357 | # $dereg, when given, is a coderef that removes the *parking* fiber from whatever waiter list it is parked on | ||
| 358 | # (Semaphore/Signal/Future/child-await). It runs only when this park is interrupted, before the error is thrown, so | ||
| 359 | # a cancelled fiber never leaves a stale id behind that a later wake could fire at a reused fiber. | ||
| 360 | sub backtrace_depth { | ||
| 361 | my $invocant = shift; | ||
| 362 | if ( !defined $invocant || | ||
| 363 | ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) { | ||
| 364 | unshift @_, $invocant if defined $invocant; | ||
| 365 | $invocant = __PACKAGE__; | ||
| 366 | } | ||
| 367 | return $BACKTRACE_DEPTH unless @_; | ||
| 368 | my ($depth) = @_; | ||
| 369 | croak 'backtrace_depth must be a non-negative integer' if !defined $depth || $depth !~ /^\d+$/; | ||
| 370 | $BACKTRACE_DEPTH = $depth; | ||
| 371 | return $BACKTRACE_DEPTH; | ||
| 372 | } | ||
| 373 | |||
| 374 | sub _park ( $reason, $level = 1, $dereg = undef, $nodl = 0 ) { | ||
| 375 | my $fid = get_current_parataxis_id(); | ||
| 376 | croak '_park() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 377 | my $fiber = get_fiber_by_id($fid); | ||
| 378 | return unless $fiber; # already finished; nothing to park | ||
| 379 | |||
| 380 | # Fail fast: a fiber that was interrupted while it was running (not parked), then reached a wait point, throws | ||
| 381 | # at the park entry instead of parking, so a cancellation never gets stranded until some unrelated wake. The | ||
| 382 | # C job table may still have armed the sleep/read this wait was about to submit, so the run can stay alive | ||
| 383 | # until those fire - but no wait is entered after its cancellation. | ||
| 384 | if ( defined( my $pre = $fiber->[F_INTERRUPT] ) ) { | ||
| 385 | my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ]; | ||
| 386 | my $pre_site = [ $pre, $pfile, $pline ]; | ||
| 387 | warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d ENTRY failfast pre=%s site=%s\n", ( time - $^T ) * 1000, $fid, $pre, "$pfile:$pline" | ||
| 388 | if $ENV{PARATAXIS_TRACE}; | ||
| 389 | $fiber->[F_INTERRUPT] = undef; | ||
| 390 | $fiber->[F_PARKED] = 0; | ||
| 391 | if ( my $dereg = _take_park_dereg($fiber) ) { $dereg->() } | ||
| 392 | warn "PARATAXIS_TRACE park RE-ENTRY fail-fast fid=$fid reason=$reason pre=$pre\n" if $ENV{PARATAXIS_TRACE}; | ||
| 393 | my $err = $pre eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $pre_site ) : | ||
| 394 | Acme::Parataxis::Error::Cancelled->new( wait_reason => $pre_site ); | ||
| 395 | die $err; | ||
| 396 | } | ||
| 397 | |||
| 398 | # A cancellation scope whose token already fired makes every further wait fail fast too: once the fiber's | ||
| 399 | # pending marker has been consumed (a park threw Error::Cancelled and the user caught it), a re-park inside | ||
| 400 | # the still-active scope must not wait in vain. Same shape as the entry fail-fast above, but keyed off the | ||
| 401 | # innermost scope token's own cancelled flag instead of the fiber's interrupt slot. | ||
| 402 | if ( my $scopes = $fiber->[F_CANCEL_SCOPES] ) { | ||
| 403 | my $scope = $scopes->[-1]; | ||
| 404 | if ( $scope && $scope->cancelled ) { | ||
| 405 | my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ]; | ||
| 406 | $fiber->[F_PARKED] = 0; | ||
| 407 | if ( my $old = _take_park_dereg($fiber) ) { $old->() } | ||
| 408 | $dereg->() if $dereg; # this park's waiter entry (pushed before _park) is stale: remove it too | ||
| 409 | die Acme::Parataxis::Error::Cancelled->new( wait_reason => [ 'cancel', $pfile, $pline ] ); | ||
| 410 | } | ||
| 411 | } | ||
| 412 | |||
| 413 | # Enclosing with_timeout deadlines bound this park. Every with_timeout whose execution this fiber is | ||
| 414 | # inside pushed an absolute deadline (in ms) onto F_DEADLINE_SCOPES; the innermost/soonest one wins as the | ||
| 415 | # effective bound and the outermost is the backstop. Three consequences, in order: | ||
| 416 | # (a) an already-passed effective bound makes a fresh wait fail fast with Error::Timeout instead of parking | ||
| 417 | # forever - without this, a caught Timeout followed by a re-park under the same fired deadline deadlocked | ||
| 418 | # (nothing was left to interrupt the wait); the check is the bound's own cancellable token being set, not | ||
| 419 | # just the arithmetic (left <= 0), because the deadline helper's timer may fire marginally before the wall | ||
| 420 | # clock reaches abs - a re-park landing in that window would otherwise be missed by the arithmetic and | ||
| 421 | # (since the bound is armed already) would park with nothing left to interrupt it; | ||
| 422 | # (b) exactly one deadline helper is armed per fiber for its effective bound and reused across re-parks | ||
| 423 | # (F_DEADLINE_ARMED), so a re-park never stacks a second timer for the same bound; the helper cancels the | ||
| 424 | # bound's token, which interrupts the registered fiber via the usual _interrupt path and recalls its jobs; | ||
| 425 | # (c) a helper is only armed for a bound the fiber itself owns (own => 1). An *inherited* bound (an enclosing | ||
| 426 | # ancestor's with_timeout, whose token this fiber is not registered on) is always enforced by that | ||
| 427 | # ancestor's own await-park, so arming it here would be redundant - though its absolute deadline still | ||
| 428 | # participates in (a), so an inherited scope whose time has already come fails fast too. | ||
| 429 | # $nodl (now the reap re-park and other transient non-user waits) opts out: a wait whose only job is to reap a | ||
| 430 | # dying child must not fail fast nor arm, since it must linger until the child's death is observed. | ||
| 431 | if ( !$nodl && $fiber->[F_DEADLINE_SCOPES] ) { | ||
| 432 | my $eff; | ||
| 433 | for my $sc ( @{ $fiber->[F_DEADLINE_SCOPES] } ) { | ||
| 434 | next unless defined $sc->{abs}; | ||
| 435 | $eff = $sc if !defined $eff || $sc->{abs} < $eff->{abs}; | ||
| 436 | } | ||
| 437 | if ( defined $eff ) { | ||
| 438 | my $now = _now_ms(); | ||
| 439 | my $left = $eff->{abs} - $now; | ||
| 440 | if ( $left <= 0 || $eff->{tok}->cancelled ) { | ||
| 441 | |||
| 442 | # This bound is being delivered to this fiber right now. Remember that so with_timeout's boundary | ||
| 443 | # backstop does not synthesise a second Timeout after the user catches this one and the block | ||
| 444 | # returns normally. | ||
| 445 | $eff->{served} = 1; | ||
| 446 | my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ]; | ||
| 447 | $fiber->[F_PARKED] = 0; | ||
| 448 | if ( my $old = _take_park_dereg($fiber) ) { $old->() } | ||
| 449 | $dereg->() if $dereg; # as above: this park's own waiter entry is stale too | ||
| 450 | warn "PARATAXIS_TRACE park DEADLINE fail-fast fid=$fid reason=$reason abs=" . $eff->{abs} . " now=$now\n" | ||
| 451 | if $ENV{PARATAXIS_TRACE}; | ||
| 452 | die Acme::Parataxis::Error::Timeout->new( wait_reason => [ 'timeout', $pfile, $pline ] ); | ||
| 453 | } | ||
| 454 | if ( $eff->{own} ) { | ||
| 455 | my $already = $fiber->[F_DEADLINE_ARMED]; | ||
| 456 | if ( defined $already && $already == $eff->{abs} ) { | ||
| 457 | warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d park DEADLINE reuse abs=%.0f (already armed)\n", ( time - $^T ) * 1000, $fid, | ||
| 458 | $eff->{abs} | ||
| 459 | if $ENV{PARATAXIS_TRACE}; | ||
| 460 | } | ||
| 461 | else { | ||
| 462 | my $tok = $eff->{tok}; | ||
| 463 | warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d park DEADLINE arm abs=%.0f left=%.0f was=%s\n", ( time - $^T ) * 1000, $fid, | ||
| 464 | $eff->{abs}, $left, defined $already ? $already : 'undef' | ||
| 465 | if $ENV{PARATAXIS_TRACE}; | ||
| 466 | fiber { | ||
| 467 | $tok->register; | ||
| 468 | try { await_sleep($left); $tok->cancel } catch ($e) { | ||
| 469 | } | ||
| 470 | }; | ||
| 471 | $fiber->[F_DEADLINE_ARMED] = $eff->{abs}; | ||
| 472 | } | ||
| 473 | } | ||
| 474 | } | ||
| 475 | } | ||
| 476 | my ( $file, $line ) = ( caller($level) )[ 1, 2 ]; | ||
| 477 | my $bt = []; | ||
| 478 | if ($BACKTRACE_DEPTH) { | ||
| 479 | for ( my $i = 1; $i <= $BACKTRACE_DEPTH; $i++ ) { | ||
| 480 | my @c = caller( $level + $i ); | ||
| 481 | last unless defined $c[0]; | ||
| 482 | |||
| 483 | # The fiber body is the last user frame; above it sits the library's spawn wrapper. Once we reach | ||
| 484 | # library code there are no more user frames to collect, and caller() is expensive enough that | ||
| 485 | # walking the remaining slots (all skipped before) was a measurable cost on every park. | ||
| 486 | last if index( $c[0], 'Acme::Parataxis' ) == 0; | ||
| 487 | push @$bt, [ $c[0], $c[1], $c[2], $c[3] ]; | ||
| 488 | } | ||
| 489 | } | ||
| 490 | my $site = [ $reason, $file, $line, $bt ]; | ||
| 491 | $fiber->[F_WAIT_REASON] = $site; | ||
| 492 | $fiber->[F_PARKED] = 1; | ||
| 493 | $fiber->[F_PARK_DEREG] = $dereg if defined $dereg; | ||
| 494 | |||
| 495 | # Bypass yield()'s general argument marshalling here: every park deposits the same immutable ['WAITING'] | ||
| 496 | # marker, and the scheduler reads it directly from run_fiber_checked(). Keep yield()'s scalar-context | ||
| 497 | # unwrapping: job completions resume the fiber with an argument arrayref, while callers of the waits in this | ||
| 498 | # module expect the last element (the job result), not the transport arrayref. | ||
| 499 | my $res = coro_yield( \@WAITING_DEPOSIT ); | ||
| 500 | $res = $res->[-1] if ref $res eq 'ARRAY'; | ||
| 501 | if ( defined( my $kind = $fiber->[F_INTERRUPT] ) ) { | ||
| 502 | if ( $kind eq 'timeout' ) { | ||
| 503 | |||
| 504 | # The timer cancelled its bound token before waking us. Mark every fired deadline scope on this fiber | ||
| 505 | # as served: if the block catches this Timeout and keeps going, the boundary check must not fire again. | ||
| 506 | for my $sc ( @{ $fiber->[F_DEADLINE_SCOPES] // [] } ) { | ||
| 507 | $sc->{served} = 1 if $sc->{tok} && $sc->{tok}->cancelled; | ||
| 508 | } | ||
| 509 | } | ||
| 510 | my $wsite = $fiber->[F_WAIT_REASON] // [ 'undef', 'undef', 'undef' ]; | ||
| 511 | warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d re-entry interrupt consumed kind=%s wait_reason=%s wait_site=%s park_site=%s\n", | ||
| 512 | ( time - $^T ) * 1000, $fid, $kind, $wsite->[0] // 'undef', $wsite->[1] . ':' . $wsite->[2], | ||
| 513 | ( defined $site ? $site->[1] . ':' . $site->[2] : 'n/a' ) | ||
| 514 | if $ENV{PARATAXIS_TRACE}; | ||
| 515 | $fiber->[F_INTERRUPT] = undef; | ||
| 516 | $fiber->[F_PARKED] = 0; | ||
| 517 | if ( my $dereg = _take_park_dereg($fiber) ) { $dereg->() } | ||
| 518 | my $err = $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $site ) : | ||
| 519 | Acme::Parataxis::Error::Cancelled->new( wait_reason => $site ); | ||
| 520 | die $err; | ||
| 521 | } | ||
| 522 | return $res; | ||
| 523 | } | ||
| 524 | |||
| 525 | # Marks a fiber as interrupted and, if it is currently parked, wakes it so the interrupt is observed at the park's | ||
| 526 | # re-entry. A fiber that is not parked keeps the marker and the first park it (re)enters afterwards throws. $kind is | ||
| 527 | # 'cancel' or 'timeout' and selects which error the fiber throws. | ||
| 528 | sub _interrupt ( $fid, $kind ) { | ||
| 529 | my $fiber = Acme::Parataxis->by_id($fid); | ||
| 530 | return unless $fiber; | ||
| 531 | return if $fiber->[F_IS_DONE]; | ||
| 532 | $fiber->[F_INTERRUPT] = $kind if $kind eq 'cancel' || $kind eq 'timeout'; | ||
| 533 | recall_sleep_jobs_for_fiber($fid); | ||
| 534 | _recall_virtual_timer($fid); # a virtual timer has no C job; drop it so a recalled fiber is never re-woken | ||
| 535 | _scheduler_enqueue_by_id($fid) if $fiber->[F_PARKED]; | ||
| 536 | return $fiber; | ||
| 537 | } | ||
| 538 | |||
| 539 | # On a natural wake the park's deregistrations are dropped (the park is over); on an interrupt wake they are kept | ||
| 540 | # for the throw in _park, which runs them before the fiber unwinds. | ||
| 541 | sub _resume_hooks ($fiber) { | ||
| 542 | return unless $fiber->[F_PARKED]; | ||
| 543 | $fiber->[F_PARKED] = 0; | ||
| 544 | $fiber->[F_WAIT_REASON] = undef; | ||
| 545 | $fiber->[F_PARK_DEREG] = undef unless defined $fiber->[F_INTERRUPT]; | ||
| 546 | my $hooks = $fiber->[F_WAKE_HOOKS]; | ||
| 547 | $fiber->[F_WAKE_HOOKS] = undef; | ||
| 548 | if ($hooks) { $_->($fiber) for @$hooks } | ||
| 549 | } | ||
| 550 | |||
| 551 | # -- deterministic mock time. Inside run( virtual => 1, ... ) every timer-based wait (await_sleep, | ||
| 552 | # -- with_timeout deadlines, Channel bounds, select, Ticker/RateLimiter) and every wall-clock read consulted | ||
| 553 | # -- through the helpers below rides the virtual clock a test drives with advance(); outside such a run they all | ||
| 554 | # -- fall back to the real wall clock, so real runs are untouched. A virtual run never submits a TASK_SLEEP job: | ||
| 555 | # -- the armed virtual timer parks the fiber in-process and the scheduler idle path fast-forwards the clock to the | ||
| 556 | # -- earliest outstanding deadline instead of sleeping, so an hour-long timeout costs microseconds. | ||
| 557 | sub virtual_now { | ||
| 558 | my $o = _arg_offset( $_[0] ); | ||
| 559 | @_ = (); | ||
| 560 | return $VIRTUAL_CLOCK; # undef when not inside a virtual run, else current virtual ms | ||
| 561 | } | ||
| 562 | |||
| 563 | sub mock_time { | ||
| 564 | my $o = _arg_offset( $_[0] ); | ||
| 565 | @_ = (); | ||
| 566 | return defined $VIRTUAL_CLOCK ? $VIRTUAL_CLOCK / 1000 : Time::HiRes::time(); | ||
| 567 | } | ||
| 568 | sub _now_ms { return defined $VIRTUAL_CLOCK ? $VIRTUAL_CLOCK : Time::HiRes::time() * 1000 } | ||
| 569 | |||
| 570 | # Arm a virtual-timer deadline for $fid, $ms from the current virtual clock. A fiber only ever parks in one | ||
| 571 | # timer-backed wait at a time (a wait never returns until its wake), so one deadline per fiber suffices. | ||
| 572 | sub _arm_virtual_timer ( $fid, $ms ) { | ||
| 573 | return if $fid < 0; | ||
| 574 | my $dl = $VIRTUAL_CLOCK + $ms; | ||
| 575 | $VIRTUAL_DEADLINES{$fid} = $dl; | ||
| 576 | my $lo = $VIRTUAL_TIMER_HEAD; | ||
| 577 | my $hi = @VIRTUAL_DEADLINES; | ||
| 578 | while ( $lo < $hi ) { | ||
| 579 | my $mid = ( $lo + $hi ) >> 1; | ||
| 580 | my $cmp = $VIRTUAL_DEADLINES[$mid] <=> $dl || $VIRTUAL_TIMER_FIDS[$mid] <=> $fid; | ||
| 581 | if ( $cmp < 0 ) { $lo = $mid + 1 } | ||
| 582 | else { $hi = $mid } | ||
| 583 | } | ||
| 584 | splice @VIRTUAL_DEADLINES, $lo, 0, $dl; | ||
| 585 | splice @VIRTUAL_TIMER_FIDS, $lo, 0, $fid; | ||
| 586 | return $dl; | ||
| 587 | } | ||
| 588 | |||
| 589 | # Drop a fiber's armed virtual timer (interrupt, completion, or fiber teardown). Lazy: the sorted array entry | ||
| 590 | # stays until the next fire, where the deadline-hash mismatch skips it. | ||
| 591 | sub _recall_virtual_timer ($fid) { delete $VIRTUAL_DEADLINES{$fid} } | ||
| 592 | |||
| 593 | # Wake every fiber whose virtual deadline is at or before $now. Returns how many were actually woken (recalled | ||
| 594 | # timers are popped and skipped, never woken). | ||
| 595 | sub _fire_virtual ($now) { | ||
| 596 | my $fired = 0; | ||
| 597 | while ( $VIRTUAL_TIMER_HEAD < @VIRTUAL_DEADLINES && $VIRTUAL_DEADLINES[$VIRTUAL_TIMER_HEAD] <= $now ) { | ||
| 598 | my $dl = $VIRTUAL_DEADLINES[$VIRTUAL_TIMER_HEAD]; | ||
| 599 | my $fid = $VIRTUAL_TIMER_FIDS[$VIRTUAL_TIMER_HEAD]; | ||
| 600 | $VIRTUAL_TIMER_HEAD++; | ||
| 601 | next unless exists $VIRTUAL_DEADLINES{$fid} && $VIRTUAL_DEADLINES{$fid} == $dl; | ||
| 602 | delete $VIRTUAL_DEADLINES{$fid}; | ||
| 603 | Acme::Parataxis::_scheduler_enqueue_by_id($fid); | ||
| 604 | $fired++; | ||
| 605 | } | ||
| 606 | if ( $VIRTUAL_TIMER_HEAD == @VIRTUAL_DEADLINES ) { | ||
| 607 | @VIRTUAL_DEADLINES = (); | ||
| 608 | @VIRTUAL_TIMER_FIDS = (); | ||
| 609 | $VIRTUAL_TIMER_HEAD = 0; | ||
| 610 | } | ||
| 611 | elsif ( $VIRTUAL_TIMER_HEAD > 64 && $VIRTUAL_TIMER_HEAD * 2 >= @VIRTUAL_DEADLINES ) { | ||
| 612 | splice @VIRTUAL_DEADLINES, 0, $VIRTUAL_TIMER_HEAD; | ||
| 613 | splice @VIRTUAL_TIMER_FIDS, 0, $VIRTUAL_TIMER_HEAD; | ||
| 614 | $VIRTUAL_TIMER_HEAD = 0; | ||
| 615 | } | ||
| 616 | return $fired; | ||
| 617 | } | ||
| 618 | |||
| 619 | # The per-fiber stash behind Acme::Parataxis::Local, created lazily. Keyed by the fiber OBJECT (not its fid): | ||
| 620 | # a spawned fiber that finishes inline has its fid recycled in C with no Perl-side completion hook, so a fid key | ||
| 621 | # would survive into the recycled id and leak state into the next fiber. The object is the fiber's identity for | ||
| 622 | # as long as it lives; entries are pruned where the object's fid is released (_mark_done, is_done) and on DESTROY. | ||
| 623 | sub _fiber_locals ($fiber) { return $FIBER_LOCALS{ refaddr($fiber) } //= {} } | ||
| 624 | |||
| 625 | sub on_wake { | ||
| 626 | my $invocant = shift; | ||
| 627 | if ( !defined $invocant || | ||
| 628 | ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) { | ||
| 629 | unshift @_, $invocant if defined $invocant; | ||
| 630 | $invocant = __PACKAGE__; | ||
| 631 | } | ||
| 632 | my $code = shift; | ||
| 633 | croak 'on_wake() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 634 | croak 'on_wake() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 635 | my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid ); | ||
| 636 | push @{ $fiber->[F_WAKE_HOOKS] }, $code; | ||
| 637 | return $code; | ||
| 638 | } | ||
| 639 | |||
| 640 | # Runs $code as a child fiber with a deadline of $ms milliseconds and returns its value, or throws | ||
| 641 | # Acme::Parataxis::Error::Timeout when the deadline fires first. An optional Acme::Parataxis::CancellationToken | ||
| 642 | # before $code cancels the block like an external deadline. A 0 or undef $ms means no deadline. | ||
| 643 | # | ||
| 644 | # The block runs as a child fiber in the same scheduler, so cooperative waits inside it (await_sleep, ->await, | ||
| 645 | # ->wait, semaphore/signal/channel ops) suspend only the block's fiber. When a token fires, the child's parked wait | ||
| 646 | # is interrupted at its park re-entry and the child unwinds (unregistering from the tokens as it goes); | ||
| 647 | # with_timeout rethrows the resulting error (::Timeout or ::Cancelled) in this fiber, so it can be caught with | ||
| 648 | # eval/try. | ||
| 649 | # | ||
| 650 | # The deadline is enforced per-park by _park from a per-fiber scope stack (F_DEADLINE_SCOPES). This | ||
| 651 | # child pushes its bound onto that stack (inheriting the enclosing with_timeouts of the spawning fiber, so a | ||
| 652 | # nested block's parks are bounded by the whole chain, innermost/soonest first and the outermost as the backstop) | ||
| 653 | # and _park derives the effective bound, fails fast when it has already passed (a caught Timeout followed by a | ||
| 654 | # re-park under the same fired deadline throws again instead of deadlocking), and arms exactly one deadline helper | ||
| 655 | # per fiber for its bound - reused across re-parks, so no second timer is ever stacked for the same bound. When | ||
| 656 | # the block finishes (or is itself interrupted) teardown's token cancel recalls the helper's armed sleep and the | ||
| 657 | # worker is freed instead of staying occupied for the whole bound; no helper is armed at all when the block never | ||
| 658 | # parks or when $ms is 0. | ||
| 659 | sub with_timeout { | ||
| 660 | my $o = _arg_offset( $_[0] ); | ||
| 661 | $o++ if $o == 0 && !defined $_[0]; | ||
| 662 | my $ms = $_[$o]; | ||
| 663 | croak 'with_timeout() requires a duration in milliseconds' unless defined $ms && $ms >= 0; | ||
| 664 | my $tok; | ||
| 665 | my $code; | ||
| 666 | if ( ref $_[ $o + 1 ] eq 'Acme::Parataxis::CancellationToken' ) { | ||
| 667 | $tok = $_[ $o + 1 ]; | ||
| 668 | $code = $_[ $o + 2 ]; | ||
| 669 | } | ||
| 670 | else { | ||
| 671 | $code = $_[ $o + 1 ]; | ||
| 672 | } | ||
| 673 | croak 'with_timeout() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 674 | croak 'with_timeout() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 675 | @_ = (); | ||
| 676 | if ( $tok && $tok->cancelled ) { # the user already cancelled: fail without running the block | ||
| 677 | die Acme::Parataxis::Error::Cancelled->new; | ||
| 678 | } | ||
| 679 | state $have_token = do { require Acme::Parataxis::CancellationToken; 1; }; | ||
| 680 | my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' ); | ||
| 681 | $tok = $deadline unless $tok; # no explicit token: the deadline alone governs the block | ||
| 682 | |||
| 683 | # The absolute (ms-clock) bound this block's parks must respect, and a shallow copy of the spawning fiber's | ||
| 684 | # enclosing scopes to seed the child's stack with (marked as inherited so the child never arms a helper for a | ||
| 685 | # token it is not registered on - the owning ancestor enforces those). | ||
| 686 | my $scope_abs = $ms > 0 ? _now_ms() + $ms : undef; | ||
| 687 | my $scope = defined $scope_abs ? { abs => $scope_abs, tok => $deadline, own => 1, served => 0 } : undef; | ||
| 688 | my $inherited = do { | ||
| 689 | my $pfid = Acme::Parataxis->current_fid; | ||
| 690 | my $pf = $pfid >= 0 ? Acme::Parataxis->by_id($pfid) : undef; | ||
| 691 | my $stk = $pf && $pf->[F_DEADLINE_SCOPES] ? $pf->[F_DEADLINE_SCOPES] : undef; | ||
| 692 | $stk ? | ||
| 693 | [ | ||
| 694 | map { | ||
| 695 | { %$_, own => 0 } | ||
| 696 | } @$stk | ||
| 697 | ] : | ||
| 698 | []; | ||
| 699 | }; | ||
| 700 | my $child = fiber { | ||
| 701 | my $cf = Acme::Parataxis->by_id( Acme::Parataxis->current_fid ); | ||
| 702 | $cf->[F_DEADLINE_SCOPES] = $scope ? [ @$inherited, $scope ] : $inherited; | ||
| 703 | $deadline->register; | ||
| 704 | $tok->register if $tok ne $deadline; | ||
| 705 | my $val; | ||
| 706 | my $err; | ||
| 707 | my $done_at; | ||
| 708 | try { | ||
| 709 | $val = $code->(); | ||
| 710 | $done_at = defined $scope_abs ? _now_ms() : undef; | ||
| 711 | } | ||
| 712 | catch ($e) { | ||
| 713 | $err = $e | ||
| 714 | } | ||
| 715 | |||
| 716 | # A deadline helper can fire late on a busy host (or the awaited result can land just after the bound | ||
| 717 | # without any park being re-entered). Record the completion time at the boundary so an overdue block still | ||
| 718 | # fails, rather than reporting success merely because its timer had not woken us yet. A bound already | ||
| 719 | # delivered at a park (and therefore catchable inside the block) is not overdue here: rethrowing would | ||
| 720 | # turn a handled timeout into a second, uncatchable one at with_timeout's own boundary. | ||
| 721 | my $overdue = $scope && defined $done_at && $done_at > $scope->{abs} && !$scope->{served}; | ||
| 722 | $deadline->unregister; | ||
| 723 | $tok->unregister if $tok ne $deadline; | ||
| 724 | pop @{ $cf->[F_DEADLINE_SCOPES] } if defined $scope_abs; # leave the stack for any enclosing scope | ||
| 725 | die $err if $err; # the ::Timeout/::Cancelled throw (or any real error) unwinds out of the child | ||
| 726 | die Acme::Parataxis::Error::Timeout->new if $overdue; | ||
| 727 | return $val; | ||
| 728 | }; | ||
| 729 | |||
| 730 | # The block finished synchronously: the value (or an inline error, already rethrown by spawn) is final. Skipping | ||
| 731 | # the deadline also means a quick inlined block never pins its run. | ||
| 732 | if ( $child->is_done ) { | ||
| 733 | die $child->error if defined $child->error; | ||
| 734 | return $child->result; | ||
| 735 | } | ||
| 736 | my $rv; | ||
| 737 | my $ok = 1; | ||
| 738 | my $err; | ||
| 739 | try { $rv = $child->await } catch ($e) { | ||
| 740 | $ok = 0; | ||
| 741 | $err = $e | ||
| 742 | } | ||
| 743 | warn "with_timeout teardown: ok=$ok child_done=" . | ||
| 744 | $child->is_done . | ||
| 745 | " child_error=" . | ||
| 746 | ( defined $child->error ? ref( $child->error || '' ) || 'plain:' . $child->error : 'undef' ) . | ||
| 747 | " deadline_cancelled=" . | ||
| 748 | $deadline->cancelled . | ||
| 749 | " deadline_waiters=" . | ||
| 750 | $deadline->waiters . | ||
| 751 | " tok_waiters=" . | ||
| 752 | ( $tok->waiters // 'undef' ) . " err=" . | ||
| 753 | ( ref( $err || '' ) || 'plain:' . $err ) . "\n" | ||
| 754 | if $ENV{PARATAXIS_TRACE}; | ||
| 755 | |||
| 756 | # The child is final, so nothing else may keep waiting under these tokens. Even if *this* fiber was just | ||
| 757 | # cancelled out from under the await (an enclosing nursery/with_timeout interrupted us, or a user token fired): | ||
| 758 | # cancel the deadline now so a still-registered grandchild (a nested block, or the deadline helper _park armed | ||
| 759 | # for our bound) is itself interrupted instead of outliving its parent and running to completion. The recall | ||
| 760 | # now wakes the helper immediately, so its abandoned sleep job aborts in sub-millisecond time and no live work | ||
| 761 | # continues past its parent. | ||
| 762 | # A grandchild woken this way dies observer-gated (its parent's await had registered _wake_waiter on it), so it | ||
| 763 | # unwinds silently rather than killing the run. | ||
| 764 | $deadline->cancel; | ||
| 765 | $tok->cancel if $tok ne $deadline; | ||
| 766 | warn sprintf "with_timeout re-park branch: fid=%d child_done=%d err=%s\n", Acme::Parataxis->current_fid, $child->is_done, | ||
| 767 | ref( $err || '' ) || 'plain:' . $err | ||
| 768 | if $ENV{PARATAXIS_TRACE}; | ||
| 769 | if ( !$ok && !$child->is_done ) { | ||
| 770 | |||
| 771 | # We were cancelled out of the await while the child is still parked. It is interrupted and will die on its | ||
| 772 | # next resume. Re-park here, registered for the child's death, so the scheduler lets the child run its own | ||
| 773 | # unwind (unregistering from its tokens and running destructors) and reaps it before this frame unwinds and | ||
| 774 | # frees $child. Freeing the child mid-park no longer crashes (a C-level coroutine-lifecycle fix), so this | ||
| 775 | # branch is no longer load-bearing for safety - it is kept so an abandoned child dies by unwinding rather | ||
| 776 | # than being yanked. The interrupt marker on this fiber was consumed by the throwing await, so returning | ||
| 777 | # from this park (rather than throwing again) is certain. $nodl is set: this is a transient reap wait, not | ||
| 778 | # a user wait, so it must neither fail fast on an already-passed deadline nor arm a deadline helper. | ||
| 779 | my $fid = Acme::Parataxis->current_fid; | ||
| 780 | $child->on_ready( sub { Acme::Parataxis::_scheduler_enqueue_by_id($fid) } ); | ||
| 781 | Acme::Parataxis::_park( 'fiber await', 1, undef, 1 ); | ||
| 782 | $child->is_done; # reap the coroutine now that its death has been observed | ||
| 783 | } | ||
| 784 | die $err unless $ok; | ||
| 785 | return $rv; | ||
| 786 | } | ||
| 787 | |||
| 788 | # Runs $code as a cancellation *scope* on the current fiber: while the block is active, every wait it enters is | ||
| 789 | # interruptible by one token - the scope token returned here - without the caller having to thread that token | ||
| 790 | # into each primitive. Unlike with_timeout, no child fiber is spawned; the block runs on this fiber, so interior | ||
| 791 | # awaits and parks suspend only the normal way. The token registers this fiber for the block's whole duration | ||
| 792 | # (a register/unregister pair, not a per-park one), so an outer cancel() both interrupts a wait parked now and | ||
| 793 | # stamps the fiber so the *next* wait entered inside the scope fails fast. Scopes stack LIFO in a per-fiber slot | ||
| 794 | # (_park reads the innermost one); nesting with_timeout or nursery tokens shares the park, and whichever token | ||
| 795 | # fires first ends the wait while teardown drops the others' registrations. | ||
| 796 | # | ||
| 797 | # Return convention (context aware): the scope token alone in scalar/void context, the token prepended to the | ||
| 798 | # block's value(s) in list context (my ($tok, @vals) = with_cancel sub { ... }). On failure the block's own | ||
| 799 | # error propagates unchanged (the real error wins over a concurrently arriving cancel); if the scope itself was | ||
| 800 | # cancelled by an outer token while the block ran to completion, Error::Cancelled (or Timeout for a deadline) | ||
| 801 | # is thrown at the scope boundary instead of swallowing the interrupt. | ||
| 802 | sub with_cancel { | ||
| 803 | my $o = _arg_offset( $_[0] ); | ||
| 804 | my $code = $_[$o]; | ||
| 805 | @_ = (); | ||
| 806 | croak 'with_cancel() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 807 | croak 'with_cancel() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 808 | state $have_token = do { require Acme::Parataxis::CancellationToken; 1 }; | ||
| 809 | my $tok = Acme::Parataxis::CancellationToken->new( kind => 'cancel' ); | ||
| 810 | my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid ); | ||
| 811 | push @{ $fiber->[F_CANCEL_SCOPES] }, $tok; | ||
| 812 | $tok->register; # block-wide: this fiber stays registered while the scope is open | ||
| 813 | my @val; | ||
| 814 | my $err; | ||
| 815 | |||
| 816 | if (wantarray) { | ||
| 817 | try { @val = $code->($tok) } catch ($e) { | ||
| 818 | $err = $e | ||
| 819 | } | ||
| 820 | } | ||
| 821 | else { | ||
| 822 | try { $val[0] = $code->($tok) } catch ($e) { | ||
| 823 | $err = $e | ||
| 824 | } | ||
| 825 | } | ||
| 826 | $tok->unregister; | ||
| 827 | pop @{ $fiber->[F_CANCEL_SCOPES] }; | ||
| 828 | if ($err) { | ||
| 829 | |||
| 830 | # The block's own error wins: drop any interrupt still pending so it cannot resurface at an outer scope | ||
| 831 | # after this one has already reported the real failure. | ||
| 832 | $fiber->[F_INTERRUPT] = undef; | ||
| 833 | die $err; | ||
| 834 | } | ||
| 835 | if ( my $kind = $fiber->[F_INTERRUPT] ) { | ||
| 836 | |||
| 837 | # The block returned normally but an outer token/deadline fired while it ran: consume the marker and | ||
| 838 | # convert it to the matching error so the cancellation is never silently swallowed at this boundary. | ||
| 839 | $fiber->[F_INTERRUPT] = undef; | ||
| 840 | die $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new : Acme::Parataxis::Error::Cancelled->new; | ||
| 841 | } | ||
| 842 | return wantarray ? ( $tok, @val ) : $tok; | ||
| 843 | } | ||
| 844 | |||
| 845 | # STM (software transactional memory). atomically() runs $code as one transaction on the calling fiber: reads are | ||
| 846 | # journaled, writes stay in a write set until the outermost atomically commits (validating | ||
| 847 | # every read first, re-running on conflict), and retry() parks the fiber until a TVar it | ||
| 848 | # read changes. The block may run many times - no irreversible side effects inside it. | ||
| 849 | # See Acme::Parataxis::TVar for the semantics and the SIDE EFFECTS warning. | ||
| 850 | sub atomically : prototype(&) { | ||
| 851 | my $o = _arg_offset( $_[0] ); | ||
| 852 | my $code = $_[$o]; | ||
| 853 | croak 'atomically() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 854 | croak 'atomically() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 855 | @_ = (); | ||
| 856 | require Acme::Parataxis::TVar; | ||
| 857 | return Acme::Parataxis::TVar::_atomically($code); | ||
| 858 | } | ||
| 859 | |||
| 860 | # STM. Aborts the enclosing atomically block and re-runs it once a TVar the | ||
| 861 | # transaction has read changes; croaks anywhere else. | ||
| 862 | sub retry { | ||
| 863 | my $o = _arg_offset( $_[0] ); | ||
| 864 | croak 'retry() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 865 | @_ = (); | ||
| 866 | require Acme::Parataxis::TVar; | ||
| 867 | Acme::Parataxis::TVar::_retry(); | ||
| 868 | } | ||
| 869 | |||
| 870 | # Structured concurrency. $code runs in the calling fiber with an Acme::Parataxis::Nursery | ||
| 871 | # as its argument; every child spawned through $n->spawn is guaranteed to finish before nursery() | ||
| 872 | # returns, and the first child that dies cancels all of its siblings. Children never run inline | ||
| 873 | # into the block (Nursery::spawn parks each at birth), so a child failure always surfaces through | ||
| 874 | # the scheduler and is aggregated as Acme::Parataxis::Error::Nursery rather than thrown here. | ||
| 875 | # If $code itself dies, its children are cancelled and drained before its error is rethrown. | ||
| 876 | sub nursery { | ||
| 877 | my $o = _arg_offset( $_[0] ); | ||
| 878 | $o++ if $o == 0 && !defined $_[0]; | ||
| 879 | my $code = $_[$o]; | ||
| 880 | croak 'nursery() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 881 | croak 'nursery() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 882 | @_ = (); | ||
| 883 | state $have_nursery = do { require Acme::Parataxis::Nursery; 1 }; | ||
| 884 | my $nursery = Acme::Parataxis::Nursery->new; | ||
| 885 | my $rv; | ||
| 886 | my $ok = 1; | ||
| 887 | my $err; | ||
| 888 | try { $rv = $code->($nursery) } catch ($e) { | ||
| 889 | $ok = 0; | ||
| 890 | $err = $e | ||
| 891 | } | ||
| 892 | |||
| 893 | # The block died: its children must not be orphaned, so cancel them and drain below. | ||
| 894 | $nursery->token->cancel unless $ok; | ||
| 895 | |||
| 896 | # All-children-join. A child failure has already cancelled the rest via the observer, | ||
| 897 | # so the drain is fast; it unwinds every sibling before control returns to the parent. | ||
| 898 | my @failures = $nursery->_join; | ||
| 899 | die $err if !$ok; # the block's own error wins over its children's | ||
| 900 | if (@failures) { | ||
| 901 | die Acme::Parataxis::Error::Nursery->new( failures => \@failures ); | ||
| 902 | } | ||
| 903 | return $rv; | ||
| 904 | } | ||
| 905 | |||
| 906 | # Parallel map over a bounded fiber pool. $code runs once per item, each call in its own worker fiber (so a | ||
| 907 | # mapper may await, park, or use any primitive), with at most $opts{concurrency} workers in flight at once | ||
| 908 | # (default: one fiber per item). The caller parks while the pool works and the results come back in input order | ||
| 909 | # even when items finish out of order. A mapper that dies cancels the pool (the sibling workers stop at their | ||
| 910 | # next item boundary) and its error is rethrown once every worker has drained; later results are discarded. | ||
| 911 | # Must be called from inside a scheduled fiber, like nursery; an empty item list returns immediately; the | ||
| 912 | # concurrency option must be a positive integer. | ||
| 913 | sub pmap { | ||
| 914 | my $origin = _arg_offset( $_[0] ); | ||
| 915 | my %opts; | ||
| 916 | my $i = $origin; | ||
| 917 | if ( ref $_[$i] eq 'HASH' ) { | ||
| 918 | %opts = %{ $_[ $i++ ] }; | ||
| 919 | } | ||
| 920 | my $code = $_[ $i++ ]; | ||
| 921 | my @items = @_[ $i .. $#_ ]; | ||
| 922 | @_ = (); | ||
| 923 | croak 'pmap() requires a CODE ref' unless ref $code eq 'CODE'; | ||
| 924 | croak 'pmap() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 925 | return unless @items; | ||
| 926 | my $concurrency = $opts{concurrency} // scalar @items; | ||
| 927 | croak 'pmap() concurrency must be a positive integer' unless defined $concurrency && $concurrency =~ /\A[1-9]\d*\z/; | ||
| 928 | $concurrency = @items if $concurrency > @items; | ||
| 929 | require Acme::Parataxis::Channel; | ||
| 930 | require Acme::Parataxis::Sync::WaitGroup; | ||
| 931 | require Acme::Parataxis::CancellationToken; | ||
| 932 | my $jobs = Acme::Parataxis::Channel->new( capacity => $concurrency ); | ||
| 933 | my $wg = Acme::Parataxis::Sync::WaitGroup->new; | ||
| 934 | my $tok = Acme::Parataxis::CancellationToken->new; | ||
| 935 | my ( @results, $first_error ); | ||
| 936 | |||
| 937 | # One unit for the feeder plus one per worker; the call parks below until they all land. | ||
| 938 | $wg->add( $concurrency + 1 ); | ||
| 939 | |||
| 940 | # Workers pull one job envelope per iteration. A job carries its input index so the results land back in | ||
| 941 | # input order; a job whose index is negative is the worker's STOP marker (one per worker, so every worker | ||
| 942 | # terminates even when mappers fail). A cancelled pool skips further work instead of mapping it but keeps | ||
| 943 | # draining to its STOP, so no worker is ever left parked on an empty channel by a sibling's failure. | ||
| 944 | for ( 1 .. $concurrency ) { | ||
| 945 | fiber { | ||
| 946 | while (1) { | ||
| 947 | my $job = $jobs->get; | ||
| 948 | my ( $i, $val ) = @$job; | ||
| 949 | last if $i < 0; | ||
| 950 | next if $tok->cancelled; | ||
| 951 | my $rv; | ||
| 952 | my $map_err; | ||
| 953 | try { $rv = $code->($val) } catch ($e) { | ||
| 954 | $map_err = $e | ||
| 955 | } | ||
| 956 | if ($map_err) { | ||
| 957 | $first_error //= $map_err; # the first mapper error wins | ||
| 958 | $tok->cancel; # fail fast: siblings stop at their next item boundary | ||
| 959 | last; | ||
| 960 | } | ||
| 961 | $results[$i] = $rv; | ||
| 962 | } | ||
| 963 | $wg->done; | ||
| 964 | }; | ||
| 965 | } | ||
| 966 | |||
| 967 | # The feeder delivers every envelope (the items, then the STOP markers) without ever parking on the | ||
| 968 | # channel: a full channel is drained by the workers, so try_put + yield makes progress and finishes. | ||
| 969 | fiber { | ||
| 970 | my $idx = 0; | ||
| 971 | my @envelopes = map { [ $idx++, $_ ] } @items; | ||
| 972 | push @envelopes, ( [-1] ) x $concurrency; | ||
| 973 | for my $env (@envelopes) { | ||
| 974 | while ( !$jobs->try_put($env) ) { | ||
| 975 | yield; | ||
| 976 | } | ||
| 977 | } | ||
| 978 | $wg->done; | ||
| 979 | }; | ||
| 980 | my $ok = 1; | ||
| 981 | my $err; | ||
| 982 | try { $wg->wait } catch ($e) { | ||
| 983 | $ok = 0; | ||
| 984 | $err = $e | ||
| 985 | } | ||
| 986 | unless ($ok) { | ||
| 987 | |||
| 988 | # The caller was interrupted while parked (an enclosing nursery/with_timeout): cancel the pool and | ||
| 989 | # drain it so no worker outlives the caller, then rethrow the caller's own error. | ||
| 990 | $tok->cancel; | ||
| 991 | |||
| 992 | # A separate variable on purpose: $err is the caller's own error and is rethrown below. | ||
| 993 | try { $wg->wait } catch ($drain_err) { | ||
| 994 | } | ||
| 995 | die $err; | ||
| 996 | } | ||
| 997 | die $first_error if defined $first_error; | ||
| 998 | return wantarray ? @results : \@results; | ||
| 999 | } | ||
| 1000 | |||
| 1001 | sub spawn { | ||
| 1002 | my $class = $_[0]; | ||
| 1003 | my $code; | ||
| 1004 | if ( ref $class eq 'CODE' ) { | ||
| 1005 | $code = $class; | ||
| 1006 | $class = __PACKAGE__; | ||
| 1007 | } | ||
| 1008 | else { | ||
| 1009 | $code = $_[1]; | ||
| 1010 | } | ||
| 1011 | @_ = (); | ||
| 1012 | |||
| 1013 | # Trace propagation: Local slots created with inherit => 1 have their current value copied | ||
| 1014 | # from the spawning fiber (the one resolving the spawn args - our caller, even after a nursery or actor | ||
| 1015 | # birth park) into the child before the child's body first reads it. The seed is captured here, before | ||
| 1016 | # spawn_fiber eagerly runs the body, and applied by a wrapper that runs in the child's own context, so | ||
| 1017 | # the child's stash is seeded before any get in the body. The parent's stash is untouched: the child | ||
| 1018 | # owns a shallow copy of each seeded value, so later set()s never cross either direction, exactly | ||
| 1019 | # today's per-fiber isolation, only seeded. With no inherit slots (or no values set) nothing is captured | ||
| 1020 | # and no wrapper is built, so the common spawn path is unchanged. | ||
| 1021 | my @seed; | ||
| 1022 | if (@INHERIT_LOCAL_IDS) { | ||
| 1023 | my $fid = current_fid(); | ||
| 1024 | my $parent = $fid >= 0 ? Acme::Parataxis->by_id($fid) : undef; | ||
| 1025 | if ($parent) { | ||
| 1026 | my $stash = _fiber_locals($parent); | ||
| 1027 | for my $id (@INHERIT_LOCAL_IDS) { | ||
| 1028 | push @seed, [ $id, $stash->{$id} ] if exists $stash->{$id}; | ||
| 1029 | } | ||
| 1030 | } | ||
| 1031 | } | ||
| 1032 | if (@seed) { | ||
| 1033 | my $orig = $code; | ||
| 1034 | $code = sub { | ||
| 1035 | my $child = Acme::Parataxis->by_id( current_fid() ); | ||
| 1036 | if ($child) { | ||
| 1037 | my $stash = _fiber_locals($child); | ||
| 1038 | $stash->{ $_->[0] } = $_->[1] for @seed; | ||
| 1039 | } | ||
| 1040 | return $orig->(@_); | ||
| 1041 | }; | ||
| 1042 | } | ||
| 1043 | my $fiber = Acme::Parataxis::spawn_fiber( $code, $class ); | ||
| 1044 | if ( !ref $fiber ) { | ||
| 1045 | croak defined $fiber && | ||
| 1046 | $fiber == -3 ? | ||
| 1047 | 'could not allocate a fiber: this platform has no MAP_NORESERVE and the process has hit its address-space / data-segment budget (raise RLIMIT_DATA or lower set_max_fibers)' | ||
| 1048 | : | ||
| 1049 | 'could not allocate a fiber: the fiber table is full (destroy some fibers first, or raise the limit with set_max_fibers)'; | ||
| 1050 | } | ||
| 1051 | my $status = $fiber->[F_LAST_STATUS]; | ||
| 1052 | if ( $status == 1 ) { | ||
| 1053 | my $err = $fiber->[F_ERROR]; | ||
| 1054 | die $err if defined $err; | ||
| 1055 | } | ||
| 1056 | elsif ( $status == 0 ) { | ||
| 1057 | $fiber->[F_PRIORITY] //= 0; | ||
| 1058 | _enqueue($fiber); | ||
| 1059 | } | ||
| 1060 | return $fiber; | ||
| 1061 | } | ||
| 1062 | |||
| 1063 | sub _submit_job ( $type, $arg, $timeout ) { | ||
| 1064 | my $rc = submit_c_job( $type, $arg, $timeout ); | ||
| 1065 | if ( $rc < 0 ) { | ||
| 1066 | |||
| 1067 | # The 1024-slot job queue is full. Yield once so the scheduler can drain completed jobs, then retry. | ||
| 1068 | Acme::Parataxis->yield; | ||
| 1069 | $rc = submit_c_job( $type, $arg, $timeout ); | ||
| 1070 | croak "job queue full: could not submit the job after a scheduler tick (submit_c_job returned $rc)" if $rc < 0; | ||
| 1071 | } | ||
| 1072 | return 0; | ||
| 1073 | } | ||
| 1074 | |||
| 1075 | # -- event-loop driver. When an event loop is attached (attach_loop), await_read / await_write / | ||
| 1076 | # -- await_sleep stop submitting blocking OS-thread-pool jobs per filehandle/sleep and instead register watches | ||
| 1077 | # -- and timers on the loop; run() hands control to the loop whenever every fiber is parked. The public contract | ||
| 1078 | # -- is unchanged (readiness with the pool path's result values; timeout resumes -1; an enclosing with_timeout / | ||
| 1079 | # -- nursery interrupt still throws), only the backing mechanism differs. | ||
| 1080 | sub attach_loop { | ||
| 1081 | my $o = _arg_offset( $_[0] ); | ||
| 1082 | my $thing = $_[$o]; | ||
| 1083 | croak 'attach_loop() requires an event-loop object (Mojo::IOLoop, Mojo::Reactor or IO::Async::Loop)' unless defined $thing && ref $thing; | ||
| 1084 | @_ = (); | ||
| 1085 | croak 'attach_loop() cannot run while a run is already active' if $IS_RUNNING; | ||
| 1086 | require Acme::Parataxis::Driver; | ||
| 1087 | my $driver = Acme::Parataxis::Driver::wrap($thing); | ||
| 1088 | my $old = $DRIVER; | ||
| 1089 | $DRIVER = $driver; | ||
| 1090 | return $old; | ||
| 1091 | } | ||
| 1092 | |||
| 1093 | # Detach the event-loop driver, returning it and unwinding every watch/timer it still held (loops attached to a | ||
| 1094 | # shared scheduler are racy at best, so a driver session is always short: attach, run, detach). | ||
| 1095 | sub detach_loop { | ||
| 1096 | my $o = _arg_offset( $_[0] ); | ||
| 1097 | @_ = (); | ||
| 1098 | croak 'detach_loop() cannot run while a run is already active' if $IS_RUNNING; | ||
| 1099 | my $old = $DRIVER; | ||
| 1100 | $old->reset if $old; | ||
| 1101 | $DRIVER = undef; | ||
| 1102 | return $old; | ||
| 1103 | } | ||
| 1104 | |||
| 1105 | # The currently attached driver (undef when the pool path is in effect). Mostly for diagnostics. | ||
| 1106 | sub loop { | ||
| 1107 | my $o = _arg_offset( $_[0] ); | ||
| 1108 | @_ = (); | ||
| 1109 | return $DRIVER; | ||
| 1110 | } | ||
| 1111 | |||
| 1112 | # -- transparent unblocking (CORE::GLOBAL overrides). Opt-in only: never | ||
| 1113 | # -- installed by default. enable_transparent_unblocking() makes sleep/read/sysread | ||
| 1114 | # -- cooperative inside scheduled fibers (sleep -> await_sleep, read/sysread framed | ||
| 1115 | # -- on await_read) and delegates to the raw builtin outside one, so synchronous | ||
| 1116 | # -- CPAN modules become cooperative once they are compiled after installation. | ||
| 1117 | # -- Full coverage table and caveats live in Acme::Parataxis::Compat. | ||
| 1118 | sub enable_transparent_unblocking { | ||
| 1119 | my $o = _arg_offset( $_[0] ); | ||
| 1120 | @_ = (); | ||
| 1121 | require Acme::Parataxis::Compat; | ||
| 1122 | Acme::Parataxis::Compat->install; | ||
| 1123 | return 1; | ||
| 1124 | } | ||
| 1125 | |||
| 1126 | sub disable_transparent_unblocking { | ||
| 1127 | my $o = _arg_offset( $_[0] ); | ||
| 1128 | @_ = (); | ||
| 1129 | require Acme::Parataxis::Compat; | ||
| 1130 | Acme::Parataxis::Compat->disable; | ||
| 1131 | return 1; | ||
| 1132 | } | ||
| 1133 | |||
| 1134 | sub transparent_unblocking { | ||
| 1135 | my $o = _arg_offset( $_[0] ); | ||
| 1136 | @_ = (); | ||
| 1137 | return 0 unless $INC{'Acme/Parataxis/Compat.pm'}; | ||
| 1138 | return Acme::Parataxis::Compat->installed ? 1 : 0; | ||
| 1139 | } | ||
| 1140 | |||
| 1141 | sub _driver_sleep ( $driver, $ms ) { | ||
| 1142 | my $fid = Acme::Parataxis->current_fid; | ||
| 1143 | croak 'await_sleep() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 1144 | my $fired = 0; | ||
| 1145 | my $id = $driver->timer( $ms, sub { $fired = 1; Acme::Parataxis::_scheduler_enqueue_by_id($fid) } ); | ||
| 1146 | my $dereg = sub { $driver->cancel_timer($id) unless $fired }; | ||
| 1147 | return _park( 'await_sleep', 1, $dereg ); | ||
| 1148 | } | ||
| 1149 | |||
| 1150 | # Register a read/write watch on the attached loop, arm the wait's own deadline timer, and park. Natural wake | ||
| 1151 | # returns 1; the wait's own deadline swallows its ::Timeout and returns -1 like the pool path does; an *enclosing* | ||
| 1152 | # with_timeout / nursery interrupt did not cancel our deadline token, so it propagates by dying. | ||
| 1153 | # | ||
| 1154 | my $WARNED_FD_SETSIZE = 0; | ||
| 1155 | |||
| 1156 | sub _driver_wait ( $driver, $fh, $dir, $timeout, $reason ) { | ||
| 1157 | my $fid = Acme::Parataxis->current_fid; | ||
| 1158 | croak "$reason() must be called from inside a scheduled fiber" if $fid < 0; | ||
| 1159 | |||
| 1160 | # A loop whose readiness comes from select() cannot name a descriptor at or past the platform's | ||
| 1161 | # FD_SETSIZE - 256 on NetBSD, 64 for winsock, 1024 on Linux - and the fd_set in that case belongs to | ||
| 1162 | # the loop library rather than to us, so there is nothing here to widen. Registering the watch anyway | ||
| 1163 | # would either never fire or corrupt the loop's own stack, so refuse it. The worker-pool path answers | ||
| 1164 | # the same way for the same reason (see worker_thread in Parataxis.c), and -1 is what a deadline | ||
| 1165 | # produces too, so a caller already knows how to read it. Worth saying out loud once, because the | ||
| 1166 | # limit is the platform's and a workload sized on another OS can sail past it unnoticed. | ||
| 1167 | # | ||
| 1168 | # fileno croaks on something that is not a handle at all, and whatever the driver says about that is a | ||
| 1169 | # better message than anything invented here, so an answer of undef means "no descriptor to check" and | ||
| 1170 | # the handle goes on to the driver as it always did. An in-memory file answers -1, which is under any | ||
| 1171 | # ceiling, and needs no watch anyway. | ||
| 1172 | my $fd; | ||
| 1173 | try { $fd = fileno $fh } catch ($e) { | ||
| 1174 | } # not a handle at all: no descriptor to check | ||
| 1175 | if ( defined $fd && $fd >= Acme::Parataxis::fd_setsize() ) { | ||
| 1176 | warn "Acme::Parataxis: $reason() refused: descriptor $fd is at or past this platform's FD_SETSIZE (" . | ||
| 1177 | Acme::Parataxis::fd_setsize() . | ||
| 1178 | "), which a select()-based readiness stack cannot name. Further refusals will not be reported.\n" | ||
| 1179 | unless $WARNED_FD_SETSIZE++; | ||
| 1180 | return -1; | ||
| 1181 | } | ||
| 1182 | my $wake = sub { Acme::Parataxis::_scheduler_enqueue_by_id($fid) }; | ||
| 1183 | if ( $dir eq 'read' ) { $driver->watch_read( $fh, $wake ) } | ||
| 1184 | else { $driver->watch_write( $fh, $wake ) } | ||
| 1185 | my $deadline; | ||
| 1186 | my $timer_id; | ||
| 1187 | $timeout //= 5000; # match the worker-pool default, which also maps 0/negative to 5000 | ||
| 1188 | $timeout = 5000 if $timeout <= 0; | ||
| 1189 | |||
| 1190 | if ( $timeout > 0 ) { | ||
| 1191 | my $have_ct = do { require Acme::Parataxis::CancellationToken; 1 }; | ||
| 1192 | $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' ) if $have_ct; | ||
| 1193 | $deadline->register; | ||
| 1194 | $timer_id = $driver->timer( $timeout, sub { $deadline->cancel } ); | ||
| 1195 | } | ||
| 1196 | my $out = 1; | ||
| 1197 | my $dying; | ||
| 1198 | my $dereg = sub { | ||
| 1199 | $driver->unwatch($fh); | ||
| 1200 | $driver->cancel_timer($timer_id) if defined $timer_id; | ||
| 1201 | $deadline->unregister if defined $deadline; | ||
| 1202 | }; | ||
| 1203 | my $ok = 1; | ||
| 1204 | my $err; | ||
| 1205 | try { Acme::Parataxis::_park( $reason, 1, $dereg ) } | ||
| 1206 | catch ($e) { $ok = 0; $err = $e } | ||
| 1207 | finally { $dereg->() } # idempotent: on an interrupt _park already ran it, on a natural wake this is the cleanup | ||
| 1208 | if ( !$ok ) { | ||
| 1209 | if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) { | ||
| 1210 | $out = -1; # this wait's own deadline expired; the pool path resumes (not throws) on timeout | ||
| 1211 | } | ||
| 1212 | else { $dying = $err } | ||
| 1213 | } | ||
| 1214 | $deadline->unregister if defined $deadline; | ||
| 1215 | $deadline->cancel if defined $deadline; | ||
| 1216 | die $dying if defined $dying; | ||
| 1217 | return $out; | ||
| 1218 | } | ||
| 1219 | |||
| 1220 | # Acme::Parataxis->advance($ms): inside a virtual run, jump the virtual clock forward $ms and wake everything that | ||
| 1221 | # fires as of the new time. A nudge, not a wait: the calling fiber keeps running (woken fibers run on the next | ||
| 1222 | # scheduler pass), so the "advance, then yield/return, then observe" test choreography in the docs is the idiom. | ||
| 1223 | # Returns the new virtual time in ms. Croaks outside a virtual run - the wall clock cannot be wound forward. | ||
| 1224 | sub advance { | ||
| 1225 | my $o = _arg_offset( $_[0] ); | ||
| 1226 | my $ms = $_[$o] // 0; | ||
| 1227 | @_ = (); | ||
| 1228 | croak 'advance() only makes sense inside run( virtual => 1, ... )' unless defined $VIRTUAL_CLOCK; | ||
| 1229 | croak 'advance() requires a non-negative number of milliseconds' if $ms < 0; | ||
| 1230 | $VIRTUAL_CLOCK += $ms; | ||
| 1231 | _fire_virtual($VIRTUAL_CLOCK); | ||
| 1232 | return $VIRTUAL_CLOCK; | ||
| 1233 | } | ||
| 1234 | |||
| 1235 | sub await_sleep { | ||
| 1236 | my $o = _arg_offset( $_[0] ); | ||
| 1237 | $o++ if $o == 0 && !defined $_[0]; | ||
| 1238 | my $ms = $_[$o] // 0; | ||
| 1239 | @_ = (); | ||
| 1240 | if ( defined $VIRTUAL_CLOCK && $ms > 0 ) { | ||
| 1241 | my $fid = Acme::Parataxis->current_fid; | ||
| 1242 | croak 'await_sleep() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 1243 | _arm_virtual_timer( $fid, $ms ); | ||
| 1244 | return _park('await_sleep'); | ||
| 1245 | } | ||
| 1246 | if ( $DRIVER && $ms > 0 ) { | ||
| 1247 | return _driver_sleep( $DRIVER, $ms ); | ||
| 1248 | } | ||
| 1249 | _submit_job( 0, $ms, 0 ); | ||
| 1250 | return _park('await_sleep'); | ||
| 1251 | } | ||
| 1252 | |||
| 1253 | sub await_core_id { | ||
| 1254 | @_ = (); | ||
| 1255 | _submit_job( 1, 0, 0 ); | ||
| 1256 | return _park('await_core_id'); | ||
| 1257 | } | ||
| 1258 | |||
| 1259 | sub await_read { | ||
| 1260 | my $o = _arg_offset( $_[0] ); | ||
| 1261 | $o++ if $o == 0 && !defined $_[0]; | ||
| 1262 | my $fh = $_[$o]; | ||
| 1263 | my $timeout = $_[ $o + 1 ] // 5000; | ||
| 1264 | @_ = (); | ||
| 1265 | my $fileno = fileno($fh); | ||
| 1266 | die 'Not a valid filehandle' unless defined $fileno; | ||
| 1267 | if ($DRIVER) { | ||
| 1268 | return _driver_wait( $DRIVER, $fh, 'read', $timeout, 'await_read' ); | ||
| 1269 | } | ||
| 1270 | my $handle = $^O eq 'MSWin32' ? win32_get_osfhandle($fileno) : $fileno; | ||
| 1271 | _submit_job( 2, $handle, $timeout ); | ||
| 1272 | return _park('await_read'); | ||
| 1273 | } | ||
| 1274 | |||
| 1275 | sub await_write { | ||
| 1276 | my $o = _arg_offset( $_[0] ); | ||
| 1277 | $o++ if $o == 0 && !defined $_[0]; | ||
| 1278 | my $fh = $_[$o]; | ||
| 1279 | my $timeout = $_[ $o + 1 ] // 5000; | ||
| 1280 | @_ = (); | ||
| 1281 | my $fileno = fileno($fh); | ||
| 1282 | die 'Not a valid filehandle' unless defined $fileno; | ||
| 1283 | if ($DRIVER) { | ||
| 1284 | return _driver_wait( $DRIVER, $fh, 'write', $timeout, 'await_write' ); | ||
| 1285 | } | ||
| 1286 | my $handle = $^O eq 'MSWin32' ? win32_get_osfhandle($fileno) : $fileno; | ||
| 1287 | _submit_job( 3, $handle, $timeout ); | ||
| 1288 | return _park('await_write'); | ||
| 1289 | } | ||
| 1290 | |||
| 1291 | sub maybe_yield { | ||
| 1292 | return unless $PREEMPT_THRESHOLD; # disabled preemption is a no-op; don't clear @_ or cross FFI for it | ||
| 1293 | @_ = (); # drop caller args before the C call can yield | ||
| 1294 | my $result = Acme::Parataxis::_maybe_yield(); | ||
| 1295 | return unless defined $result; | ||
| 1296 | return wantarray ? @$result : $result->[-1]; | ||
| 1297 | } | ||
| 1298 | |||
| 1299 | sub set_preempt_threshold { | ||
| 1300 | my $o = _arg_offset( $_[0] ); | ||
| 1301 | croak 'set_preempt_threshold() expects a threshold value' unless @_ > $o; | ||
| 1302 | my $threshold = $_[$o] // 0; | ||
| 1303 | $PREEMPT_THRESHOLD = $threshold; | ||
| 1304 | Acme::Parataxis::_set_preempt_threshold($threshold); | ||
| 1305 | } | ||
| 1306 | sub tid { get_os_thread_id_export() } | ||
| 1307 | sub current_fid { get_current_parataxis_id() } | ||
| 1308 | sub root { state $root //= Acme::Parataxis::Root->new() } | ||
| 1309 | sub max_threads () { Acme::Parataxis::get_max_thread_pool_size() } | ||
| 1310 | sub max_fibers () { Acme::Parataxis::get_max_fibers() } | ||
| 1311 | |||
| 1312 | # The highest descriptor number an fd_set can name on this platform: 1024 on Linux, macOS and FreeBSD, | ||
| 1313 | # 256 on NetBSD, 64 for winsock. It is a property of the C library rather than a constant, and it bounds | ||
| 1314 | # the descriptor NUMBER, not the number of handles - so size a workload of N watched sockets against it | ||
| 1315 | # and not against N. Read it from C because nothing in perl can: `getconf FD_SETSIZE` is not a valid | ||
| 1316 | # symbol and answers 20, and Fcntl::FD_SETSIZE() dies at runtime. | ||
| 1317 | sub fd_setsize () { Acme::Parataxis::get_fd_setsize() } | ||
| 1318 | |||
| 1319 | # Scheduler internals | ||
| 1320 | sub _scheduler_enqueue_by_id ($fid) { | ||
| 1321 | if ( my $fiber = Acme::Parataxis->by_id($fid) ) { | ||
| 1322 | return if $fiber->[F_QUEUED]; | ||
| 1323 | _enqueue($fiber); | ||
| 1324 | } | ||
| 1325 | } | ||
| 1326 | |||
| 1327 | sub poll_io { | ||
| 1328 | my @ready; | ||
| 1329 | while (1) { | ||
| 1330 | my $job_idx = check_for_completion(); | ||
| 1331 | last if $job_idx == -1; | ||
| 1332 | my $fid = get_job_coro_id($job_idx); | ||
| 1333 | my $res = get_job_result($job_idx); | ||
| 1334 | push @ready, [ $fid, $res ]; | ||
| 1335 | free_job_slot($job_idx); | ||
| 1336 | } | ||
| 1337 | return @ready; | ||
| 1338 | } | ||
| 1339 | |||
| 1340 | sub _handle_run ( $fiber, $status ) { | ||
| 1341 | if ( $status == 1 ) { | ||
| 1342 | Acme::Parataxis::_mark_done($fiber); | ||
| 1343 | my $err = $fiber->[F_ERROR]; | ||
| 1344 | |||
| 1345 | # A scheduled fiber that dies unwinds the whole run *unless* it has an observer (an awaiting parent, an | ||
| 1346 | # on_ready callback). With an observer the error is deliberately left for the observer to rethrow at the | ||
| 1347 | # await/call site, which lets a cancelled wait surface to its own awaiter without killing the block. | ||
| 1348 | die $err if defined $err && !@{ $fiber->[F_CALLBACKS] || [] }; | ||
| 1349 | $fiber->[F_CALLBACKS] = []; # one-shot, already fired by set_result/set_error; dropping the refs lets | ||
| 1350 | return 1; # a callback that captured the fiber (e.g. a nursery observer) cycle out | ||
| 1351 | } | ||
| 1352 | if ( $status == 0 ) { | ||
| 1353 | $fiber->[F_PRIORITY] //= 0; | ||
| 1354 | _enqueue($fiber); | ||
| 1355 | } | ||
| 1356 | return $status; | ||
| 1357 | } | ||
| 1358 | |||
| 1359 | sub run (@raw) { | ||
| 1360 | my $o = _arg_offset( $raw[0] ); | ||
| 1361 | my @a = @raw[ $o .. $#raw ]; | ||
| 1362 | my ( $code, $virtual, $on_shutdown ); | ||
| 1363 | if ( @a == 1 && ref $a[0] eq 'CODE' ) { | ||
| 1364 | $code = $a[0]; | ||
| 1365 | } | ||
| 1366 | elsif ( @a >= 2 && @a % 2 == 0 ) { | ||
| 1367 | my %opt = @a; | ||
| 1368 | my @bad = grep { $_ ne 'code' && $_ ne 'virtual' && $_ ne 'on_shutdown' } keys %opt; | ||
| 1369 | croak 'run() unknown option(s): ' . join( ', ', @bad ) if @bad; | ||
| 1370 | croak 'run() needs the code option' unless ref $opt{code} eq 'CODE'; | ||
| 1371 | $code = $opt{code}; | ||
| 1372 | $virtual = $opt{virtual} ? 1 : 0; | ||
| 1373 | $on_shutdown = $opt{on_shutdown}; | ||
| 1374 | if ( defined $on_shutdown && ref $on_shutdown ) { | ||
| 1375 | require Acme::Parataxis::CancellationToken; | ||
| 1376 | my $is_tok = 0; | ||
| 1377 | if ( ref $on_shutdown ne 'CODE' ) { | ||
| 1378 | try { $is_tok = $on_shutdown->isa('Acme::Parataxis::CancellationToken') || 0 } catch ($e) { | ||
| 1379 | $is_tok = 0 | ||
| 1380 | } | ||
| 1381 | } | ||
| 1382 | croak 'run() on_shutdown must be a true value, a code ref, or a CancellationToken' unless ref $on_shutdown eq 'CODE' || $is_tok; | ||
| 1383 | } | ||
| 1384 | } | ||
| 1385 | croak 'run() needs a CODE ref: run( $code ), or run( code => $code, ... )' unless ref $code eq 'CODE'; | ||
| 1386 | if ($IS_RUNNING) { | ||
| 1387 | |||
| 1388 | # Nested run/async inside a shared global scheduler. Queue a fresh fiber for the block and park the current | ||
| 1389 | # fiber until it completes. The on_shutdown option is only for the outermost run: an inner run must not | ||
| 1390 | # touch %SIG (the global handler table belongs to the top-level process lifecycle). | ||
| 1391 | my $fiber = __PACKAGE__->new( code => $code ); | ||
| 1392 | _enqueue($fiber); | ||
| 1393 | return $fiber->await; | ||
| 1394 | } | ||
| 1395 | @SCHEDULER_QUEUE = (); | ||
| 1396 | my @preset_ids = _clear_queued_flags(); | ||
| 1397 | $IS_RUNNING = 1; | ||
| 1398 | |||
| 1399 | # run( virtual => 1 ) turns on the virtual clock for the whole run. Everything the scheduler waits | ||
| 1400 | # on (and every mock_time read) then rides $VIRTUAL_CLOCK, and the idle path fast-forwards it instead of | ||
| 1401 | # sleeping, so timeouts can be exercised in microseconds. Saved/restored so a non-virtual run after a virtual | ||
| 1402 | # one (or vice versa) is exactly wall-clock behavior again. | ||
| 1403 | my $saved_clock = $VIRTUAL_CLOCK; | ||
| 1404 | if ($virtual) { | ||
| 1405 | $VIRTUAL_CLOCK = 0; | ||
| 1406 | %VIRTUAL_DEADLINES = (); | ||
| 1407 | @VIRTUAL_DEADLINES = (); | ||
| 1408 | @VIRTUAL_TIMER_FIDS = (); | ||
| 1409 | $VIRTUAL_TIMER_HEAD = 0; | ||
| 1410 | } | ||
| 1411 | |||
| 1412 | # Snapshot the fibers that were already alive before this run. A fiber parked by a *previous* deadlocked run | ||
| 1413 | # can never be woken again, but the C table still counts it as live; the deadlock detector below must only | ||
| 1414 | # consider fibers that actually belong to this run, otherwise any run after a deadlock would be misread as | ||
| 1415 | # another deadlock. (Leaked fibers keep their C slot occupied, so their fids cannot be reused in between.) | ||
| 1416 | my %PRESET_FIBERS = map { $_ => 1 } @preset_ids; | ||
| 1417 | my $main_fiber = __PACKAGE__->new( code => $code ); | ||
| 1418 | |||
| 1419 | # on_shutdown => opts the OUTERMOST run into installing SIGINT/SIGTERM handlers for the run's lifetime | ||
| 1420 | # (the previous handlers are restored when it ends). The first signal - or, when the option is a pre-made | ||
| 1421 | # CancellationToken, its cancel() from anywhere - fires the shutdown token and interrupts every fiber this run | ||
| 1422 | # created (the run's root fiber included), so they unwind, run their own cleanup (defers/DESTROYs), and the | ||
| 1423 | # loop drains them; run() then returns the conventional interrupted status (130 for INT, 143 for TERM) instead | ||
| 1424 | # of rethrowing their Error::Cancelled. A second signal restores the previous handlers and re-raises the signal | ||
| 1425 | # so the default disposition kills the process - the handler never blocks a second Ctrl+C. A code ref passed as | ||
| 1426 | # the option receives the token (already fired) so a process can flush logs or stop servers before run() reports | ||
| 1427 | # the status; passing a CancellationToken means the caller owns the token and can begin the shutdown | ||
| 1428 | # programmatically (a health port, a parent process, a test) as well as from a signal. | ||
| 1429 | my ( $shutdown_token, $shutdown_status, $shutdown_fired, $shutdown_cb ); | ||
| 1430 | my ( $old_int, $old_term ); | ||
| 1431 | my ( $fire, $sig_pending ); | ||
| 1432 | my $interrupt_run_fibers = sub { | ||
| 1433 | for my $fid ( _live_fiber_ids() ) { | ||
| 1434 | next if $PRESET_FIBERS{$fid}; | ||
| 1435 | my $fiber = __PACKAGE__->by_id($fid); | ||
| 1436 | _interrupt( $fid, 'cancel' ) if $fiber && !$fiber->is_done; | ||
| 1437 | } | ||
| 1438 | }; | ||
| 1439 | if ($on_shutdown) { | ||
| 1440 | require Acme::Parataxis::CancellationToken; | ||
| 1441 | my $is_shutdown_token = 0; | ||
| 1442 | if ( ref $on_shutdown ne 'CODE' ) { | ||
| 1443 | try { $is_shutdown_token = $on_shutdown->isa('Acme::Parataxis::CancellationToken') || 0 } catch ($e) { | ||
| 1444 | $is_shutdown_token = 0 | ||
| 1445 | } | ||
| 1446 | } | ||
| 1447 | $shutdown_token = $is_shutdown_token ? $on_shutdown : Acme::Parataxis::CancellationToken->new; | ||
| 1448 | $shutdown_cb = ref $on_shutdown eq 'CODE' ? $on_shutdown : undef; | ||
| 1449 | $shutdown_status = 130; | ||
| 1450 | $old_int = $SIG{INT}; | ||
| 1451 | $old_term = $SIG{TERM}; | ||
| 1452 | $fire = sub ($sig) { | ||
| 1453 | if ($shutdown_fired) { # second signal: stop catching it; the restored default kills the process | ||
| 1454 | $SIG{INT} = $old_int; | ||
| 1455 | $SIG{TERM} = $old_term; | ||
| 1456 | kill $sig => $$; | ||
| 1457 | return; | ||
| 1458 | } | ||
| 1459 | $shutdown_fired = 1; | ||
| 1460 | $shutdown_status = $sig eq 'TERM' ? 143 : 130; | ||
| 1461 | $shutdown_token->cancel; | ||
| 1462 | $interrupt_run_fibers->(); | ||
| 1463 | }; | ||
| 1464 | |||
| 1465 | # The async handlers only record a pending signal. $fire - the token cancel, the run-fiber interrupt sweep, | ||
| 1466 | # the scheduler queueing - runs at run()'s own checkpoint atop the scheduler loop instead: from inside the | ||
| 1467 | # handler it would execute at an arbitrary point mid-iteration, possibly while the loop is draining jobs / | ||
| 1468 | # resuming @ready fibers / mutating @SCHEDULER_QUEUE, where its effects on those fibers can be lost and the | ||
| 1469 | # run stalls until an outstanding C job finishes on its own schedule (a sleeping fiber rides out its full | ||
| 1470 | # deadline, so a Ctrl-C or kill can fire tens of seconds late). The checkpoint is the same place the | ||
| 1471 | # programmatic token-cancel sweep runs, which is what keeps the two paths deterministic under load. | ||
| 1472 | $SIG{INT} = sub { $sig_pending ||= 'INT' }; | ||
| 1473 | $SIG{TERM} = sub { $sig_pending ||= 'TERM' }; | ||
| 1474 | } | ||
| 1475 | _enqueue($main_fiber); | ||
| 1476 | my $run_ok = 1; | ||
| 1477 | my $run_failure; | ||
| 1478 | my $idle_polls = 0; # short poll budget, replenished when job activity changes | ||
| 1479 | my $spin_short = 0; # true while a sub-tick sleep is armed, so only sleeps get the longer wall-clock spin | ||
| 1480 | my $fast_until = 0; # wall-clock deadline for the longer spin | ||
| 1481 | my $last_job_count = 0; | ||
| 1482 | try { | ||
| 1483 | while ($IS_RUNNING) { | ||
| 1484 | |||
| 1485 | # Process a deferred signal at (and only at) this checkpoint - the one place in the loop | ||
| 1486 | # where no drain/@ready/@SCHEDULER_QUEUE manipulation is in flight, so the shutdown sweep below | ||
| 1487 | # cannot race the fibers it interrupts. See the comment at the $SIG{...} installs above. | ||
| 1488 | if ($sig_pending) { | ||
| 1489 | ( my $sig, $sig_pending ) = ( $sig_pending, undef ); | ||
| 1490 | $fire->($sig); | ||
| 1491 | } | ||
| 1492 | |||
| 1493 | # A shutdown token cancelled from inside the run (not just by a signal handler) begins the | ||
| 1494 | # graceful drain too. The token's own cancel() already interrupted whatever was registered against it; | ||
| 1495 | # this pass interrupts the rest of the run's fibers so every fiber winds down together. | ||
| 1496 | if ( $on_shutdown && !$shutdown_fired && $shutdown_token->cancelled ) { | ||
| 1497 | $shutdown_fired = 1; | ||
| 1498 | $interrupt_run_fibers->(); | ||
| 1499 | } | ||
| 1500 | my @ready; # flat fiber_id/result pairs written by drain_jobs() | ||
| 1501 | my $job_count = get_outstanding_jobs(); | ||
| 1502 | if ( $job_count != $last_job_count ) { | ||
| 1503 | $idle_polls = 0; | ||
| 1504 | $spin_short = get_short_sleep_jobs() > 0; | ||
| 1505 | $fast_until = $spin_short ? Time::HiRes::time() + 0.002 : 0; | ||
| 1506 | $last_job_count = $job_count; | ||
| 1507 | } | ||
| 1508 | if ($job_count) { | ||
| 1509 | drain_jobs( \@ready ); | ||
| 1510 | } | ||
| 1511 | for ( my $i = 0; $i < @ready; $i += 2 ) { | ||
| 1512 | my $fid = $ready[$i]; | ||
| 1513 | my $res = $ready[ $i + 1 ]; | ||
| 1514 | my $fiber = get_fiber_by_id($fid); | ||
| 1515 | next unless $fiber; | ||
| 1516 | _resume_hooks($fiber); | ||
| 1517 | my $yield_val = $fiber->call($res); | ||
| 1518 | if ( defined $fiber && !$fiber->is_done ) { | ||
| 1519 | _enqueue($fiber) unless defined $yield_val && $yield_val eq 'WAITING'; | ||
| 1520 | } | ||
| 1521 | } | ||
| 1522 | |||
| 1523 | # Refresh after resumed fibers have submitted their next job. drain_jobs() has already released the | ||
| 1524 | # completed slot by this point, so sampling here sees only newly armed sleeps. | ||
| 1525 | if (@ready) { | ||
| 1526 | $idle_polls = 0; | ||
| 1527 | $spin_short = get_short_sleep_jobs() > 0; | ||
| 1528 | $fast_until = $spin_short ? Time::HiRes::time() + 0.002 : 0; | ||
| 1529 | } | ||
| 1530 | if (@SCHEDULER_QUEUE) { | ||
| 1531 | my @work = @SCHEDULER_QUEUE; | ||
| 1532 | @SCHEDULER_QUEUE = (); | ||
| 1533 | for my $current (@work) { | ||
| 1534 | next unless $current; | ||
| 1535 | $current->[F_QUEUED] = 0; | ||
| 1536 | _resume_hooks($current); | ||
| 1537 | _handle_run( $current, run_fiber_checked( $current->[F_FID], undef ) ); | ||
| 1538 | } | ||
| 1539 | } | ||
| 1540 | my $active_count = get_live_fiber_count(); | ||
| 1541 | if ( $IS_RUNNING && !@SCHEDULER_QUEUE && !@ready ) { | ||
| 1542 | my $remaining_jobs = get_outstanding_jobs(); | ||
| 1543 | unless ($remaining_jobs) { | ||
| 1544 | $idle_polls = 0; | ||
| 1545 | $spin_short = 0; | ||
| 1546 | $fast_until = 0; | ||
| 1547 | } | ||
| 1548 | if ($remaining_jobs) { | ||
| 1549 | $DRIVER->poll_ready() if $DRIVER; # fire any already-live driver events, best effort | ||
| 1550 | |||
| 1551 | # Poll briefly at sub-millisecond granularity after job activity: C jobs often finish well | ||
| 1552 | # inside one scheduler tick, and a 1 ms usleep is a full 15 ms timer tick on Windows. Short | ||
| 1553 | # sleeps get a wall-clock-bounded spin; CPU jobs keep the fixed poll budget so the scheduler | ||
| 1554 | # does not steal the core from the worker that needs to finish the job. | ||
| 1555 | if ( $spin_short && Time::HiRes::time() < $fast_until ) { | ||
| 1556 | usleep(200); | ||
| 1557 | } | ||
| 1558 | elsif ( $idle_polls < 64 ) { | ||
| 1559 | usleep(200); | ||
| 1560 | $idle_polls++; | ||
| 1561 | } | ||
| 1562 | else { | ||
| 1563 | usleep(1000); | ||
| 1564 | } | ||
| 1565 | } | ||
| 1566 | elsif ( $DRIVER && $DRIVER->pending ) { | ||
| 1567 | |||
| 1568 | # Every fiber is parked and the attached event loop still has live watches/timers: hand the | ||
| 1569 | # processor to the loop. Its readiness callbacks only ever enqueue fibers (_scheduler_enqueue_by_id), | ||
| 1570 | # never run them, so no re-entrancy into the scheduler is possible; the outer loop runs them back | ||
| 1571 | # on the next iteration. | ||
| 1572 | $DRIVER->drive(); | ||
| 1573 | } | ||
| 1574 | else { | ||
| 1575 | # Virtual clock: the scheduler has no runnable work and no real jobs (real I/O never | ||
| 1576 | # reaches here), but fibers are parked on virtual timers. Instead of sleeping on the wall clock | ||
| 1577 | # (or declaring a deadlock), wind the virtual clock up to the earliest outstanding deadline and | ||
| 1578 | # fire anything due, then re-loop to run the woken fibers. The clock never moves while any fiber | ||
| 1579 | # is runnable or any real job is in flight, so only real waiting is accelerated. | ||
| 1580 | if ( defined $VIRTUAL_CLOCK && $VIRTUAL_TIMER_HEAD < @VIRTUAL_DEADLINES ) { | ||
| 1581 | my $earliest = $VIRTUAL_DEADLINES[$VIRTUAL_TIMER_HEAD]; | ||
| 1582 | $VIRTUAL_CLOCK = $earliest if $VIRTUAL_CLOCK < $earliest; | ||
| 1583 | if ( _fire_virtual($VIRTUAL_CLOCK) ) {next} | ||
| 1584 | } | ||
| 1585 | if ( $active_count > scalar( keys %PRESET_FIBERS ) ) { | ||
| 1586 | |||
| 1587 | # A live fiber is stuck with nothing to do and no one to wake it and no timer to fire: this | ||
| 1588 | # run is deadlocked. Leave the scheduler in a clean, reusable state: stop this run, clear the | ||
| 1589 | # queues, and do NOT treat it as a nested inner run (that path requires an enclosing scheduled | ||
| 1590 | # fiber). Preset (leaked) fibers from a previously deadlocked run are excluded from the count | ||
| 1591 | # above so they cannot make a later healthy run look deadlocked; they stay parked forever in | ||
| 1592 | # the C table but are harmless because the count below only ever triggers on fibers created | ||
| 1593 | # by this run. | ||
| 1594 | $IS_RUNNING = 0; | ||
| 1595 | @SCHEDULER_QUEUE = (); | ||
| 1596 | _clear_queued_flags(); | ||
| 1597 | my $rows = _fiber_snapshot(); | ||
| 1598 | my @mine = grep { !$PRESET_FIBERS{ $_->{fid} } } @$rows; | ||
| 1599 | my $body = ''; | ||
| 1600 | for my $r (@mine) { | ||
| 1601 | $body .= sprintf( | ||
| 1602 | " fiber #%-3d %-8s %-17s %s\n", | ||
| 1603 | $r->{fid}, $r->{state}, | ||
| 1604 | $r->{reason} ? $r->{reason}[0] : '-', | ||
| 1605 | $r->{reason} ? sprintf( '%s:%d', @{ $r->{reason} }[ 1, 2 ] ) : '-' | ||
| 1606 | ); | ||
| 1607 | for my $bt ( @{ $r->{reason}[3] // [] } ) { | ||
| 1608 | $body .= sprintf( " at %s:%d %s\n", @$bt[ 1, 2, 3 ] ); | ||
| 1609 | } | ||
| 1610 | } | ||
| 1611 | $body .= " (no live fibers from this run)\n" unless @mine; | ||
| 1612 | my $leaked = @$rows - @mine; | ||
| 1613 | $body .= " ($leaked previously leaked fiber(s) from an older deadlocked run, omitted)\n" if $leaked; | ||
| 1614 | |||
| 1615 | # Tear the deadlocked run's own parked fibers out of the depth registry -- destroy_coro-equivalent | ||
| 1616 | # purging at the moment this run's torn-down stack is detected. They are parked and nothing will | ||
| 1617 | # ever resume them (this run is ending and the records stay leaked so their fids cannot be reused), | ||
| 1618 | # so their parked claims must leave now: left in place they pin CvDEPTH above depths no live frame | ||
| 1619 | # occupies, and every later park of the same CV enters one level high ("poisoned depth"). With the | ||
| 1620 | # claims gone and the frames unwound (si_cxix = -1), the next swap's Pass 1c releases any pinned level. | ||
| 1621 | para_cvreg_purge_fiber($_) for map { $_->{fid} } @mine; | ||
| 1622 | die 'FATAL: deadlock detected: no runnable work and no outstanding jobs, but ' . | ||
| 1623 | $active_count . | ||
| 1624 | " live fiber(s). Parked in this run:\n" . | ||
| 1625 | $body; | ||
| 1626 | } | ||
| 1627 | $IS_RUNNING = 0 if defined $main_fiber && $main_fiber->is_done; | ||
| 1628 | } | ||
| 1629 | } | ||
| 1630 | } | ||
| 1631 | |||
| 1632 | # No success marker is needed here, and deliberately so. This used to be an eval whose return | ||
| 1633 | # value was read as the success flag, so a *clean* exit whose last expression happened to be | ||
| 1634 | # false produced a defined-but-empty $@ that was then rethrown -- every normal run ended in | ||
| 1635 | # die '' ("Died at ..."). The catch below is the only thing that can set $run_failure. | ||
| 1636 | } | ||
| 1637 | catch ($e) { $run_ok = 0; $run_failure = $e } | ||
| 1638 | |||
| 1639 | # An abort (an unobserved fiber death unwound the whole loop) ends the run with its remaining | ||
| 1640 | # fibers parked, abandoned exactly like a deadlocked run's. Nothing resumes them now, so purge | ||
| 1641 | # their parked claims the same way the deadlock branch does, before the next run can re-park in | ||
| 1642 | # a shared CV ("poisoned depth"). The fiber records stay leaked, so only this run's OWN fibers | ||
| 1643 | # are touched -- fibers from an older deadlocked run were already purged when their run died. | ||
| 1644 | # A clean stop must NOT purge: its parked leftovers are still resumable (their own jobs/waits will | ||
| 1645 | # fire), and the next run drains them -- tearing them down here would leak unusable records that | ||
| 1646 | # pin get_live_fiber_count() forever, which the cross-run stress tests assert against. | ||
| 1647 | if ( !$run_ok ) { | ||
| 1648 | para_cvreg_purge_fiber($_) for grep { !$PRESET_FIBERS{$_} } _live_fiber_ids(); | ||
| 1649 | } | ||
| 1650 | $IS_RUNNING = 0; # always leave the scheduler reusable, even when a fiber blew up | ||
| 1651 | $DRIVER->reset if $DRIVER; # unwind every watch/timer this run left on the attached loop | ||
| 1652 | if ($on_shutdown) { # the handler table is global: restore it no matter how the run ended | ||
| 1653 | $SIG{INT} = $old_int; | ||
| 1654 | $SIG{TERM} = $old_term; | ||
| 1655 | } | ||
| 1656 | %VIRTUAL_DEADLINES = (); | ||
| 1657 | @VIRTUAL_DEADLINES = (); # a virtual run's timers die with the run | ||
| 1658 | @VIRTUAL_TIMER_FIDS = (); | ||
| 1659 | $VIRTUAL_TIMER_HEAD = 0; | ||
| 1660 | $VIRTUAL_CLOCK = $saved_clock; # whatever the next run does, the wall clock is the default | ||
| 1661 | if ( $on_shutdown && $shutdown_fired ) { | ||
| 1662 | $shutdown_cb->($shutdown_token) if $shutdown_cb; | ||
| 1663 | |||
| 1664 | # The shutdown interrupt makes the run's fibers die with Error::Cancelled, which is the expected, drained | ||
| 1665 | # outcome of a signal, not a failure: run() reports the conventional interrupted status instead of | ||
| 1666 | # rethrowing it. Any other error still propagates. | ||
| 1667 | if ( defined $run_failure && ref $run_failure && $run_failure->isa('Acme::Parataxis::Error::Cancelled') ) { | ||
| 1668 | $run_failure = undef; | ||
| 1669 | } | ||
| 1670 | die $run_failure if defined $run_failure; | ||
| 1671 | return $shutdown_status; | ||
| 1672 | } | ||
| 1673 | die $run_failure if defined $run_failure; # rethrow a fiber's uncaught error only after cleaning up | ||
| 1674 | return $main_fiber->[F_RESULT]; | ||
| 1675 | } | ||
| 1676 | sub stop () { $IS_RUNNING = 0 } | ||
| 1677 | |||
| 1678 | sub new ( $class, %args ) { | ||
| 1679 | my $self = bless [ $args{code}, 0, undef, undef, undef, 0, [], undef, undef, 0, undef, undef, undef, [], (undef) x 5 ], $class; | ||
| 1680 | my $fid = Acme::Parataxis::create_fiber( $args{code}, $self ); | ||
| 1681 | croak 'could not allocate a fiber: ' . | ||
| 1682 | ( $fid == -3 ? | ||
| 1683 | 'this platform has no MAP_NORESERVE and the process has hit its address-space / data-segment budget (raise RLIMIT_DATA or lower set_max_fibers)' | ||
| 1684 | : | ||
| 1685 | 'the fiber table is full (destroy some fibers first, or raise the limit with set_max_fibers)' ) | ||
| 1686 | if $fid < 0; | ||
| 1687 | $self->[F_FID] = $fid; | ||
| 1688 | return $self; | ||
| 1689 | } | ||
| 1690 | sub fid ($self) { $self->[F_FID] } | ||
| 1691 | sub code ($self) { $self->[F_CODE] } | ||
| 1692 | sub error ($self) { $self->[F_ERROR] } | ||
| 1693 | |||
| 1694 | # Higher numbers run first; ties are broken in the FIFO order they were enqueued in. The default is 0. | ||
| 1695 | sub priority { | ||
| 1696 | my $self = shift; | ||
| 1697 | my $prio = $self->[F_PRIORITY] // 0; | ||
| 1698 | return $prio unless @_; | ||
| 1699 | my $n = shift; | ||
| 1700 | $self->[F_PRIORITY] = $n; | ||
| 1701 | $HAS_PRIORITIES = 1 if $n; | ||
| 1702 | if ( $self->[F_QUEUED] ) { | ||
| 1703 | my $fid = $self->[F_FID]; | ||
| 1704 | $self->[F_QUEUED] = 0; | ||
| 1705 | @SCHEDULER_QUEUE = grep { $_->[F_FID] != $fid } @SCHEDULER_QUEUE; | ||
| 1706 | _enqueue($self); | ||
| 1707 | } | ||
| 1708 | return $n; | ||
| 1709 | } | ||
| 1710 | sub is_ready ($self) { $self->[F_IS_READY] } | ||
| 1711 | |||
| 1712 | sub set_result { | ||
| 1713 | my ( $self, $val ) = @_; | ||
| 1714 | return if $self->[F_IS_READY]; | ||
| 1715 | $self->[F_RESULT] = $val; | ||
| 1716 | $self->[F_IS_READY] = 1; | ||
| 1717 | $_->($self) for @{ $self->[F_CALLBACKS] }; | ||
| 1718 | } | ||
| 1719 | |||
| 1720 | sub set_error ( $self, $err ) { | ||
| 1721 | return if $self->[F_IS_READY]; | ||
| 1722 | $self->[F_ERROR] = $err; | ||
| 1723 | $self->[F_IS_READY] = 1; | ||
| 1724 | $_->($self) for @{ $self->[F_CALLBACKS] }; | ||
| 1725 | } | ||
| 1726 | |||
| 1727 | sub _result ($self) { | ||
| 1728 | croak 'Future not ready' unless $self->[F_IS_READY]; | ||
| 1729 | return $self->[F_RESULT]; | ||
| 1730 | } | ||
| 1731 | sub result ($self) { return _result($self) } | ||
| 1732 | |||
| 1733 | sub _clear_result ($self) { | ||
| 1734 | $self->[F_RESULT] = undef; | ||
| 1735 | $self->[F_ERROR] = undef; | ||
| 1736 | } | ||
| 1737 | |||
| 1738 | sub _mark_done ($self) { | ||
| 1739 | return if $self->[F_IS_DONE]; | ||
| 1740 | $self->[F_IS_DONE] = 1; | ||
| 1741 | if ( defined $self->[F_FID] && $self->[F_FID] >= 0 ) { | ||
| 1742 | $self->[F_PARKED] = 0; | ||
| 1743 | $self->[F_PARK_DEREG] = undef; | ||
| 1744 | _recall_virtual_timer( $self->[F_FID] ); # a finished fiber must not leave a virtual timer behind | ||
| 1745 | delete $FIBER_LOCALS{ refaddr($self) } if %FIBER_LOCALS; | ||
| 1746 | $self->[F_FID] = -1; | ||
| 1747 | } | ||
| 1748 | } | ||
| 1749 | |||
| 1750 | sub call ( $self, @args ) { | ||
| 1751 | croak 'Cannot call a finished fiber' if $self->[F_IS_DONE]; | ||
| 1752 | my $rv = Acme::Parataxis::coro_call( $self->[F_FID], \@args ); | ||
| 1753 | return unless defined $self; | ||
| 1754 | if ( $self->is_done ) { | ||
| 1755 | my $err = $self->[F_ERROR]; | ||
| 1756 | |||
| 1757 | # Observer-gated rethrow, like _handle_run: a fiber that died while watched (an awaiting parent or an | ||
| 1758 | # on_ready callback) keeps its error for the observer to rethrow at its await/call site instead of | ||
| 1759 | # killing the run loop. This is the wake-by-job-completion path (@ready), whose deaths are the one | ||
| 1760 | # observer-gated hole left open: a child that dies right after its own sleep job must not kill run(). | ||
| 1761 | die $err if defined $err && !@{ $self->[F_CALLBACKS] || [] }; | ||
| 1762 | } | ||
| 1763 | return unless defined $rv; | ||
| 1764 | return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv; | ||
| 1765 | } | ||
| 1766 | |||
| 1767 | sub transfer ( $self, @args ) { | ||
| 1768 | croak 'Cannot transfer to a finished fiber' if $self->is_done; | ||
| 1769 | my $rv = Acme::Parataxis::coro_transfer( $self->[F_FID], \@args ); | ||
| 1770 | if ( $self->is_done ) { | ||
| 1771 | my $err = $self->[F_ERROR]; | ||
| 1772 | die $err if defined $err; | ||
| 1773 | } | ||
| 1774 | return unless defined $rv; | ||
| 1775 | return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv; | ||
| 1776 | } | ||
| 1777 | |||
| 1778 | sub is_done ($self) { | ||
| 1779 | if ( $self->[F_IS_DONE] ) { | ||
| 1780 | delete $FIBER_LOCALS{ refaddr($self) } if %FIBER_LOCALS; | ||
| 1781 | return 1; | ||
| 1782 | } | ||
| 1783 | if ( defined $self->[F_FID] && $self->[F_FID] >= 0 && Acme::Parataxis::is_finished( $self->[F_FID] ) ) { | ||
| 1784 | $self->[F_IS_DONE] = 1; | ||
| 1785 | my $old_fid = $self->[F_FID]; | ||
| 1786 | $self->[F_PARKED] = 0; | ||
| 1787 | $self->[F_PARK_DEREG] = undef; | ||
| 1788 | delete $FIBER_LOCALS{ refaddr($self) } if %FIBER_LOCALS; | ||
| 1789 | $self->[F_FID] = -1; | ||
| 1790 | Acme::Parataxis::destroy_coro($old_fid); | ||
| 1791 | return 1; | ||
| 1792 | } | ||
| 1793 | return 0; | ||
| 1794 | } | ||
| 1795 | sub wait_reason ($self) { $self->[F_WAIT_REASON] } # [reason, file, line, backtrace] while parked, undef otherwise | ||
| 1796 | |||
| 1797 | sub wait ($self) { | ||
| 1798 | if ( !$self->is_done && Acme::Parataxis->current_fid < 0 ) { | ||
| 1799 | croak 'wait() must be called from inside the scheduler, or the fiber must already be done'; | ||
| 1800 | } | ||
| 1801 | my $fid = Acme::Parataxis->current_fid; | ||
| 1802 | my $waiter = $fid >= 0 ? Acme::Parataxis->by_id($fid) : undef; # the fiber doing the busy-wait | ||
| 1803 | $waiter->[F_WAIT_REASON] = [ 'fiber wait', (caller)[ 1, 2 ] ] if $waiter; | ||
| 1804 | Acme::Parataxis->yield('WAITING_FOR_CHILD') until $self->is_done; | ||
| 1805 | $waiter->[F_WAIT_REASON] = undef if $waiter; | ||
| 1806 | return _result($self); | ||
| 1807 | } | ||
| 1808 | |||
| 1809 | sub on_ready ( $self, $cb ) { | ||
| 1810 | if ( $self->[F_IS_READY] ) { $cb->($self) } | ||
| 1811 | else { push @{ $self->[F_CALLBACKS] }, $cb } | ||
| 1812 | } | ||
| 1813 | |||
| 1814 | sub await ($target) { | ||
| 1815 | |||
| 1816 | # await() is exported as a plain function; await($fut) must delegate to the await-capable receiver's own | ||
| 1817 | # method (e.g. Future), while fiber objects (which ARE Acme::Parataxis) keep the arrayref-slot path. | ||
| 1818 | # The signature keeps @_ unreified here: await() parks and is resumed on this same pad. | ||
| 1819 | if ( builtin::blessed($target) && $target->can('await') && !$target->isa(__PACKAGE__) ) { | ||
| 1820 | return $target->await; | ||
| 1821 | } | ||
| 1822 | my $self = $target; | ||
| 1823 | my $ready = $self->[F_IS_READY]; | ||
| 1824 | if ( !$ready ) { | ||
| 1825 | croak 'await() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0; | ||
| 1826 | my $fid = Acme::Parataxis->current_fid; | ||
| 1827 | $self->[F_WAITER] = $fid; | ||
| 1828 | $self->on_ready( \&_wake_waiter ); | ||
| 1829 | _park( 'fiber await', 1, sub { $self->[F_WAITER] = undef if defined $self->[F_WAITER] && $self->[F_WAITER] == $fid } ); | ||
| 1830 | $ready = $self->[F_IS_READY]; | ||
| 1831 | } | ||
| 1832 | croak 'Future not ready' unless $ready; | ||
| 1833 | delete $FIBER_LOCALS{ refaddr($self) } if %FIBER_LOCALS; # the fiber is done now; its locals die with it (no-op for Futures) | ||
| 1834 | die $self->[F_ERROR] if defined $self->[F_ERROR]; | ||
| 1835 | $self->[F_RESULT]; | ||
| 1836 | } | ||
| 1837 | |||
| 1838 | sub _wake_waiter ($self) { | ||
| 1839 | return unless defined $self->[F_WAITER]; | ||
| 1840 | Acme::Parataxis::_scheduler_enqueue_by_id( $self->[F_WAITER] ); | ||
| 1841 | $self->[F_WAITER] = undef; | ||
| 1842 | } | ||
| 1843 | |||
| 1844 | sub DESTROY($self) { | ||
| 1845 | return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; | ||
| 1846 | delete $FIBER_LOCALS{ refaddr($self) } if %FIBER_LOCALS; | ||
| 1847 | if ( defined $self->[F_FID] && $self->[F_FID] >= 0 ) { | ||
| 1848 | $self->[F_PARKED] = 0; | ||
| 1849 | $self->[F_PARK_DEREG] = undef; | ||
| 1850 | Acme::Parataxis::destroy_coro( $self->[F_FID] ); | ||
| 1851 | $self->[F_FID] = -1; | ||
| 1852 | } | ||
| 1853 | } | ||
| 1854 | sub by_id ( $class, $fid ) { Acme::Parataxis::get_fiber_by_id($fid) } | ||
| 1855 | |||
| 1856 | # Registered-actor lookup (the whereis table). Returns the handle of the actor spawned with that name, or undef | ||
| 1857 | # when nothing (or nobody alive) answers to it. Registration is removed when an actor stops, dies, or is | ||
| 1858 | # destroyed, so a dead actor never answers a lookup. Works as a plain function (Acme::Parataxis::actor('x')) or | ||
| 1859 | # a class method (Acme::Parataxis->actor('x')); whereis is an alias. | ||
| 1860 | sub actor { | ||
| 1861 | my $o = _arg_offset( $_[0] ); | ||
| 1862 | my $name = $_[$o]; | ||
| 1863 | @_ = (); | ||
| 1864 | return undef unless defined $name; | ||
| 1865 | return $ACTOR_REGISTRY{$name}; | ||
| 1866 | } | ||
| 1867 | |||
| 1868 | sub whereis { | ||
| 1869 | my $o = _arg_offset( $_[0] ); | ||
| 1870 | my $name = $_[$o]; | ||
| 1871 | @_ = (); | ||
| 1872 | return actor($name); | ||
| 1873 | } | ||
| 1874 | |||
| 1875 | sub _dispatch_callbacks ($self) { | ||
| 1876 | $_->($self) for @{ $self->[F_CALLBACKS] }; | ||
| 1877 | } | ||
| 1878 | class # | ||
| 1879 | Acme::Parataxis::Root { | ||
| 1880 | field $fid : reader = -1; # For now | ||
| 1881 | |||
| 1882 | method transfer (@args) { | ||
| 1883 | my $rv = Acme::Parataxis::coro_transfer( -1, \@args ); | ||
| 1884 | return unless defined $rv; | ||
| 1885 | return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv; | ||
| 1886 | } | ||
| 1887 | } | ||
| 1888 | END { cleanup() unless ${^GLOBAL_PHASE} eq 'DESTRUCT' } | ||
| 1889 | } | ||
| 1890 | 1; |