| 1 | use v5.40; | ||
| 2 | |||
| 3 | package Acme::Parataxis::Compat v0.1.6 { | ||
| 4 | use Errno qw[EAGAIN EWOULDBLOCK]; | ||
| 5 | use IO::Handle (); # loaded only: the overrides call IO::Handle::blocking() fully qualified | ||
| 6 | use Carp qw[croak]; | ||
| 7 | use Time::HiRes (); # loaded only: the overrides call Time::HiRes::time() fully qualified | ||
| 8 | |||
| 9 | # | ||
| 10 | # Transparent unblocking (CORE::GLOBAL overrides). This module is an opt-in | ||
| 11 | # convenience: Acme::Parataxis->enable_transparent_unblocking() installs overrides | ||
| 12 | # that make the blocking builtins `sleep`, `read` and `sysread` cooperative inside | ||
| 13 | # scheduled fibers, and delegate to the raw CORE:: builtin everywhere else (top | ||
| 14 | # level, foreign threads), so nothing outside the scheduler changes. | ||
| 15 | # | ||
| 16 | # The override subs are installed, not compiled with the module, so only code that | ||
| 17 | # is *compiled after installation* is affected - exactly the gevent-style contract. | ||
| 18 | # Every override calls the real builtin through its CORE:: name, so none of them can | ||
| 19 | # recurse into themselves. | ||
| 20 | # | ||
| 21 | my $INSTALLED = 0; | ||
| 22 | my @SAVED; # [ name, saved-glob ] per installed override, for disable() | ||
| 23 | |||
| 24 | # The readiness budget, in ms, that the read/sysread overrides give each await_read probe. A probe that comes | ||
| 25 | # back short of it means a real wait timed out, so the override keeps waiting rather than block the process. | ||
| 26 | my $PROBE_MS = 5000; | ||
| 27 | |||
| 28 | # How much of that budget a probe has to burn before its -1 is read as "the handle is watchable, it just had | ||
| 29 | # nothing to say" rather than "this platform cannot watch this handle at all". Win32's select() takes sockets | ||
| 30 | # and nothing else, so a pipe or a regular file there answers -1 instantly, while a socket that truly timed out | ||
| 31 | # takes the full budget. Anything under this fraction is the former. | ||
| 32 | my $UNWATCHED = 0.9; | ||
| 33 | |||
| 34 | # Write the framed read's result back into the caller's scalar (a reference to its | ||
| 35 | # @_ slot), mimicking the builtin: undef (error) and 0 (EOF) leave the caller's | ||
| 36 | # buffer alone; otherwise bytes before OFFSET are preserved and the read data is | ||
| 37 | # placed at OFFSET. | ||
| 38 | sub _store ( $slot, $off, $rc, $buf ) { | ||
| 39 | return undef unless defined $rc; | ||
| 40 | return 0 if 0 == $rc; | ||
| 41 | $$slot = ( $off ? substr( $$slot // '', 0, $off ) : q{} ) . $buf; | ||
| 42 | return $rc; | ||
| 43 | } | ||
| 44 | |||
| 45 | # Put a handle into non-blocking mode, answering the mode it was in, or undef when the platform will not. | ||
| 46 | sub _try_nonblocking ($fh) { | ||
| 47 | |||
| 48 | # `blocking` with no argument reports the current mode, and undef is its answer for a handle it cannot | ||
| 49 | # interrogate: an already-closed glob, a dirhandle, a driver-supplied handle - and on Win32, a socket. | ||
| 50 | # Winsock's FIONBIO can *set* a socket's mode but has no way to report one, so there the save half of a | ||
| 51 | # save/restore does not exist. Nothing is lost by asking rather than assuming a platform: on the one | ||
| 52 | # platform that cannot answer, the answer this read needs is already "no mode change", because sysread | ||
| 53 | # hands back a short count on its own (see _read_nonblocking). | ||
| 54 | my $was = IO::Handle::blocking($fh); | ||
| 55 | return undef unless defined $was; | ||
| 56 | |||
| 57 | # The setter answers with the mode it *replaced*, and -1 when it could not do the job at all. -1 is true, so | ||
| 58 | # the return cannot be read as a success flag the way an undef could be; comparing against -1 is what tells | ||
| 59 | # the two apart. | ||
| 60 | my $replaced = IO::Handle::blocking( $fh, 0 ); | ||
| 61 | return defined $replaced && $replaced >= 0 ? $was : undef; | ||
| 62 | } | ||
| 63 | |||
| 64 | # Put a handle back the way the caller had it. The caller's own mode is what the handle looks like to every other | ||
| 65 | # bit of code that touches it, including code compiled *before* installation, which still gets a raw blocking read | ||
| 66 | # from this same handle. Restoring is what keeps transparent unblocking transparent. | ||
| 67 | sub _restore_blocking ( $fh, $was ) { | ||
| 68 | IO::Handle::blocking( $fh, $was ? 1 : 0 ); | ||
| 69 | return; | ||
| 70 | } | ||
| 71 | |||
| 72 | # Perform one read on a handle that is already known to be readable, WITHOUT letting a | ||
| 73 | # short read park the OS thread. | ||
| 74 | # | ||
| 75 | # This is the whole point of the exercise. Perl's read() builtin does not return when *one* byte is available, | ||
| 76 | # it keeps going until it has the *requested count* - so "await_read says ready, now read" froze the entire run | ||
| 77 | # the moment a caller asked for more bytes than the peer had sent. Every fiber stalled, and because the fiber | ||
| 78 | # was inside a syscall rather than parked in the scheduler, no deadline or token could rescue it either. | ||
| 79 | # | ||
| 80 | # So the handle is put into non-blocking mode for the duration of the read and put back afterwards, and the read | ||
| 81 | # itself is done with the builtin that stops at whatever arrived. | ||
| 82 | # | ||
| 83 | # The mode is read and set through IO::Handle->blocking rather than through fcntl, and that is the whole | ||
| 84 | # portability story. Fcntl's constant table has no F_GETFL or F_SETFL on Win32 at all, and naming one there does | ||
| 85 | # not fail at compile time - it compiles as a call to a sub that does not exist and croaks at *runtime*, with | ||
| 86 | # "Your vendor has not defined Fcntl macro F_GETFL" - so a POSIX-only fcntl call compiles silently on every | ||
| 87 | # platform and then explodes exactly where it matters. IO::Handle already does the platform's own dispatch: fcntl | ||
| 88 | # where that exists, Winsock's FIONBIO where it does not. FIONBIO is the same request number the hand-rolled | ||
| 89 | # mode-flip carries, reached through a module that already knows it, and it comes back with an answer a caller | ||
| 90 | # can act on instead of an exception. | ||
| 91 | # | ||
| 92 | # Only the *buffered* builtin needs the mode changed, and only where there is a mode to change. sysread stops at | ||
| 93 | # a short count on every platform, on a blocking handle included: Winsock's recv - which is what a sysread on a | ||
| 94 | # socket calls - hands back whatever has arrived rather than waiting for the caller's count. read's buffered | ||
| 95 | # layer does loop internally until it has the full count, and it honours a non-blocking descriptor by stopping, | ||
| 96 | # but only where one can be set. So the buffered read is used when the flip took and sysread otherwise, on either | ||
| 97 | # side of that decision; the two agree on the count they return and differ only in whether perl's per-handle | ||
| 98 | # buffer is in the path, which is invisible to a caller that does not mix buffered and unbuffered reads on one | ||
| 99 | # handle (already undefined behaviour in perl). | ||
| 100 | sub _read_nonblocking ( $fh, $len, $is_sys ) { | ||
| 101 | no warnings 'io'; | ||
| 102 | my $was = $is_sys ? undef : _try_nonblocking($fh); | ||
| 103 | my $buf = q{}; | ||
| 104 | my $rc = defined $was ? CORE::read( $fh, $buf, $len, 0 ) : CORE::sysread( $fh, $buf, $len, 0 ); | ||
| 105 | _restore_blocking( $fh, $was ) if defined $was; | ||
| 106 | return ( $rc, $buf ); | ||
| 107 | } | ||
| 108 | |||
| 109 | sub install ( $class = () ) { | ||
| 110 | return 1 if $INSTALLED; | ||
| 111 | { | ||
| 112 | no strict 'refs'; | ||
| 113 | no warnings 'redefine'; | ||
| 114 | |||
| 115 | # The three closures are built here as named lexicals and their coderefs are kept in @SAVED, so disable() | ||
| 116 | # can withdraw the fabricated pad depth from the CV itself instead of looking the override back up with | ||
| 117 | # *{ 'CORE::GLOBAL::read' }{CODE} -- a name lookup into a glob slot is a fragile thing to depend on when | ||
| 118 | # holding the coderef costs nothing. (That lookup was not what was wrong on Win32 either: it returns a | ||
| 119 | # proper CODE ref there, measured. The actual cause of the old croak was the signature of the C entry | ||
| 120 | # point the override calls; see the note on para_release_cv_depth().) What disable() actually restores is | ||
| 121 | # snapshotted just before the assignments below, so the coderef's own home glob is never the saved state. | ||
| 122 | # | ||
| 123 | # sleep [;$] maps to await_sleep. Fractional seconds are honored as | ||
| 124 | # milliseconds (CORE::sleep truncates them away) and are impossible to | ||
| 125 | # signal-interrupt inside a fiber, so the return value is the requested | ||
| 126 | # duration. The $_ default is reproduced by hand: a CORE::GLOBAL override | ||
| 127 | # does not get the builtin's implicit argument. | ||
| 128 | my $sleep_override = sub : prototype(;$) { | ||
| 129 | my $secs = @_ ? $_[0] : $_; | ||
| 130 | $secs = 0 if !defined $secs || $secs < 0; | ||
| 131 | return $secs if 0 == $secs; | ||
| 132 | return CORE::sleep($secs) if Acme::Parataxis->current_fid < 0; | ||
| 133 | Acme::Parataxis->await_sleep( $secs * 1000 ); | ||
| 134 | return $secs; | ||
| 135 | }; | ||
| 136 | |||
| 137 | # read/sysread frame a single CORE:: read on await_read readiness. A blocking | ||
| 138 | # handle that select() marks readable hands over whatever is already buffered | ||
| 139 | # (at least one byte, or 0 at EOF) without parking the OS thread, so one | ||
| 140 | # readiness probe then one blocking read is cooperative. If the read races | ||
| 141 | # EAGAIN/EWOULDBLOCK anyway, the loop re-waits; a read with no data cycles | ||
| 142 | # the 5s await_read default forever, matching a blocking read. | ||
| 143 | # | ||
| 144 | # Note: the compiler passes the builtin's second argument BY VALUE to a | ||
| 145 | # CORE::GLOBAL override (an lvalue like read()/sysread() accept is not | ||
| 146 | # aliased), so the overrides are deliberately left WITHOUT a prototype and | ||
| 147 | # read into a private $buf, then write the result back through _store. That | ||
| 148 | # also keeps the `read $fh, $buf, 8` (no-parens) form working. | ||
| 149 | my $read_override = sub { | ||
| 150 | my $off = defined $_[3] ? $_[3] : 0; | ||
| 151 | if ( 'Acme::Parataxis'->current_fid < 0 ) { | ||
| 152 | my $buf = ''; | ||
| 153 | my $rc = CORE::read( $_[0], $buf, $_[2], 0 ); | ||
| 154 | return _store( \$_[1], $off, $rc, $buf ); | ||
| 155 | } | ||
| 156 | while (1) { | ||
| 157 | my $t0 = Time::HiRes::time(); | ||
| 158 | my $ready = Acme::Parataxis->await_read( $_[0], $PROBE_MS ); | ||
| 159 | if ( $ready < 0 ) { | ||
| 160 | |||
| 161 | # A probe that gave up *short of its budget* means this platform cannot watch this handle | ||
| 162 | # at all - Win32's select() takes sockets only, so a pipe or a regular file answers -1 | ||
| 163 | # immediately - rather than that a watchable handle merely had nothing to say. Read those | ||
| 164 | # directly, because there is nothing else left to try: a handle that cannot be watched | ||
| 165 | # cannot be parked on either, so a read of it is the only thing that can make progress, and | ||
| 166 | # refusing would mean such a handle never reads at all. | ||
| 167 | # | ||
| 168 | # The cost of that is real and is why it is reached only here: a read of a handle with | ||
| 169 | # nothing buffered yet parks the OS thread, and on Win32 a pipe is in exactly that state | ||
| 170 | # whenever a writer has not run yet - and the writer is usually a fiber, which cannot run | ||
| 171 | # because the thread that would run it is the one now inside the read. There is no fixing | ||
| 172 | # that from perl without a native overlapped-I/O wait, so a fiber that needs to *wait* on a | ||
| 173 | # non-socket handle on Win32 has to be driven from a socket or a driver instead. | ||
| 174 | # | ||
| 175 | # The test is re-armed every round rather than spent once, so one slow round does not cost | ||
| 176 | # the fallback permanently and leave the loop spinning a 5s probe at a time forever, and it | ||
| 177 | # is measured on a high-resolution clock so a probe that merely crosses a clock second is | ||
| 178 | # still recognised as short. A round that really did burn the whole budget is a genuine | ||
| 179 | # timeout, and raw-blocking on it would stall the process instead. | ||
| 180 | if ( Time::HiRes::time() - $t0 < $PROBE_MS / 1000 * $UNWATCHED ) { | ||
| 181 | my ( $rc, $buf ) = _read_nonblocking( $_[0], $_[2], 0 ); | ||
| 182 | return _store( \$_[1], $off, $rc, $buf ); | ||
| 183 | } | ||
| 184 | next; | ||
| 185 | } | ||
| 186 | my ( $rc, $buf ) = _read_nonblocking( $_[0], $_[2], 0 ); | ||
| 187 | return _store( \$_[1], $off, $rc, $buf ) if defined $rc; | ||
| 188 | return undef unless $!{EAGAIN} || $!{EWOULDBLOCK}; | ||
| 189 | } | ||
| 190 | }; | ||
| 191 | my $sysread_override = sub { | ||
| 192 | my $off = defined $_[3] ? $_[3] : 0; | ||
| 193 | if ( 'Acme::Parataxis'->current_fid < 0 ) { | ||
| 194 | my $buf = ''; | ||
| 195 | my $rc = CORE::sysread( $_[0], $buf, $_[2], 0 ); | ||
| 196 | return _store( \$_[1], $off, $rc, $buf ); | ||
| 197 | } | ||
| 198 | while (1) { | ||
| 199 | my $t0 = Time::HiRes::time(); | ||
| 200 | my $ready = Acme::Parataxis->await_read( $_[0], $PROBE_MS ); | ||
| 201 | if ( $ready < 0 ) { | ||
| 202 | |||
| 203 | # See the read override: a probe that gave up short of its budget is a handle this platform | ||
| 204 | # cannot watch, so read it raw rather than spin. | ||
| 205 | if ( Time::HiRes::time() - $t0 < $PROBE_MS / 1000 * $UNWATCHED ) { | ||
| 206 | my ( $rc, $buf ) = _read_nonblocking( $_[0], $_[2], 1 ); | ||
| 207 | return _store( \$_[1], $off, $rc, $buf ); | ||
| 208 | } | ||
| 209 | next; | ||
| 210 | } | ||
| 211 | my ( $rc, $buf ) = _read_nonblocking( $_[0], $_[2], 1 ); | ||
| 212 | return _store( \$_[1], $off, $rc, $buf ) if defined $rc; | ||
| 213 | return undef unless $!{EAGAIN} || $!{EWOULDBLOCK}; | ||
| 214 | } | ||
| 215 | }; | ||
| 216 | |||
| 217 | # Snapshot what each glob already holds *before* the assignments below rewrite it: disable() has to hand | ||
| 218 | # the prior state back, and the glob itself cannot be the snapshot. \*{'CORE::GLOBAL::read'} taken here is | ||
| 219 | # a live reference to the very glob this block then overwrites, so a disable that "restores" it is a | ||
| 220 | # self-assignment -- a no-op that leaves the override in the glob once @SAVED and $INSTALLED are cleared. | ||
| 221 | # The sole witness is the CODE slot: an installed override is a CODE slot on the CORE::GLOBAL::%s glob, and | ||
| 222 | # a builtin occupies no slot at all, so undef *is* the builtin's identity and restoring is "empty the slot". | ||
| 223 | my $sleep_prior = *{'CORE::GLOBAL::sleep'}{CODE}; | ||
| 224 | my $read_prior = *{'CORE::GLOBAL::read'}{CODE}; | ||
| 225 | my $sysread_prior = *{'CORE::GLOBAL::sysread'}{CODE}; | ||
| 226 | push @SAVED, [ sleep => $sleep_prior, $sleep_override ]; | ||
| 227 | push @SAVED, [ read => $read_prior, $read_override ]; | ||
| 228 | push @SAVED, [ sysread => $sysread_prior, $sysread_override ]; | ||
| 229 | *{'CORE::GLOBAL::sleep'} = $sleep_override; | ||
| 230 | *{'CORE::GLOBAL::read'} = $read_override; | ||
| 231 | *{'CORE::GLOBAL::sysread'} = $sysread_override; | ||
| 232 | } | ||
| 233 | $INSTALLED = 1; | ||
| 234 | return 1; | ||
| 235 | } | ||
| 236 | |||
| 237 | sub disable ( $class = () ) { | ||
| 238 | return 1 unless $INSTALLED; | ||
| 239 | { | ||
| 240 | no strict 'refs'; | ||
| 241 | no warnings 'redefine'; | ||
| 242 | |||
| 243 | # Hand back the pad bookkeeping for each override before the glob is touched. Fiber swaps fabricate a | ||
| 244 | # CvDEPTH for a CV some fiber is parked inside, so that the next call lands above the parked pad -- but | ||
| 245 | # nothing withdraws that value once the parked frame is gone, and the CV then looks permanently active to | ||
| 246 | # perl. Overwriting such a CV finalises it (a hard "Can't undef active subroutine" pointing at the | ||
| 247 | # *replaced* sub's own definition site, which is nowhere near the cause), so the count is withdrawn while | ||
| 248 | # nothing else is happening to the CV. $entry->[2] is the coderef install() created; see the note there | ||
| 249 | # for why it is held directly rather than re-looked-up, and why that was not the Win32 croak's cause. | ||
| 250 | # | ||
| 251 | # The restore itself is driven by the snapshot taken before install() overwrote each glob. A prior | ||
| 252 | # override (someone else's, present before install) is handed back as the CODE slot it was; otherwise the | ||
| 253 | # slot is emptied, which is the one way to tell perl the builtin is in effect again. The glob reference the | ||
| 254 | # old code stored was a live alias of the glob install() was about to rewrite, so restoring it was a | ||
| 255 | # self-assignment that uninstalled nothing. | ||
| 256 | for my $entry (@SAVED) { | ||
| 257 | my ( $name, $prior, $cv ) = @$entry; | ||
| 258 | Acme::Parataxis::para_release_cv_depth($cv) if $cv; | ||
| 259 | my $glob = 'CORE::GLOBAL::' . $name; | ||
| 260 | if ( defined $prior && ref($prior) eq 'CODE' ) { | ||
| 261 | *{$glob} = $prior; # hand the override that predated install() back | ||
| 262 | } | ||
| 263 | else { | ||
| 264 | undef *{$glob}; # builtin: no CODE slot is how perl knows the builtin is in effect | ||
| 265 | } | ||
| 266 | } | ||
| 267 | } | ||
| 268 | @SAVED = (); | ||
| 269 | $INSTALLED = 0; | ||
| 270 | return 1; | ||
| 271 | } | ||
| 272 | sub installed ( $class = () ) { !!$INSTALLED } | ||
| 273 | }; | ||
| 274 | # | ||
| 275 | 1; |