Forked/Future.pm

filter: Statementstmt 97.1% 136 / 140 Branchbran 74.2% 49 / 66 Conditioncond 52.1% 12 / 23 MC/DCmcdc 15.3% 2 / 13 Subroutinesub 100% 27 / 27 Podpod 100% 10 / 10 totaltotal 84.5% 236 / 279 CC 44 SCAR 19.2
CC
44
Cov
86%
_resolve_derived
16.5
_finish_leaf
9.5
_resolve_leaf
8.8
CRAP 6.8
« Forked/Storage.pm ↑ Summary Forked.pm »
1 package DBIO::Forked::Future;
2 # ABSTRACT: Loop-free, pipe-backed Future for DBIO::Forked
3  
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Errno ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Storable ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14  
15 # A future is in one of two modes:
16 # leaf -- backed by a forked child: { read_fh, pid, buffer }. A leaf built
17 # already-resolved (done/fail) has no child: read_fh/pid undef,
18 # ready+reaped set.
19 # derived -- lazy over a source future: { source, on_done, on_fail }
20 # Both share the resolution slots { ready, failed, result, reaped }.
21 # On success, result is an arrayref of the resolved values; on failure it is
22 # the error scalar.
23  
24  
25 20 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
26 20 my ($class, %args) = @_;
27 return bless {
28 mode => 'leaf',
29 read_fh => $args{read_fh},
30 pid => $args{pid},
31 20 buffer => '',
32 ready => 0,
33 failed => 0,
34 result => undef,
35 reaped => 0,
36 }, $class;
37 }
38  
39 # Internal constructor for a derived (then/catch) future.
40 7 ▶sub _derived {
Subroutine _derived: called CC=1 SCAR=0.0
41 7 my ($class, $source, $on_done, $on_fail) = @_;
42 7 return bless {
43 mode => 'derived',
44 source => $source,
45 on_done => $on_done,
46 on_fail => $on_fail,
47 ready => 0,
48 failed => 0,
49 result => undef,
50 reaped => 1, # a derived future owns no child
51 }, $class;
52 }
53  
54 # --- Immediately-settled constructors (Test::Future-compatible surface) ---
55 #
56 # done/fail/needs_all are CLASS methods. Core's ResultSet async helpers build
57 # futures via $storage->future_class->done(@rows) / ->fail($err), so this class
58 # must answer them as a class, not just an instance. A settled future is just a
59 # pre-resolved leaf with no child, so _resolve short-circuits on {ready} and the
60 # existing get/is_ready/is_failed work unchanged.
61 17 ▶sub _settled {
Subroutine _settled: called CC=1 SCAR=0.0
62 17 my ($class, $failed, $result) = @_;
63 17 return bless {
64 mode => 'leaf',
65 read_fh => undef,
66 pid => undef,
67 buffer => '',
68 ready => 1,
69 failed => $failed,
70 result => $result,
71 reaped => 1,
72 }, $class;
73 }
74  
75  
76 12 ▶sub done {
Subroutine done: called CC=1 SCAR=0.0
Pod documented
77 12 my $class = shift;
78 12 return $class->_settled(0, [ @_ ]);
79 }
80  
81  
82 5 ▶sub fail {
Subroutine fail: called CC=1 SCAR=0.0
Pod documented
83 5 my ($class, $error) = @_;
84 5 return $class->_settled(1, $error);
85 }
86  
87  
88 3 ▶sub needs_all {
Subroutine needs_all: called CC=3 SCAR=11.0
Pod documented
89 3 my $class = shift;
90 3 my @results;
91 3 for my $f (@_) {
92 8 my @r = eval { $f->get };
93 8 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 1 7 8
94 1 return $class->fail($err);
95 }
96 7 push @results, @r;
97 }
98 2 return $class->done(@results);
99 }
100  
101  
102 5 ▶sub then {
Subroutine then: called CC=1 SCAR=0.0
Pod documented
103 5 my ($self, $on_done, $on_fail) = @_;
104 5 return ref($self)->_derived($self, $on_done, $on_fail);
105 }
106  
107  
108 2 ▶sub catch {
Subroutine catch: called CC=1 SCAR=0.0
Pod documented
109 2 my ($self, $on_fail) = @_;
110 2 return ref($self)->_derived($self, undef, $on_fail);
111 }
112  
113  
114 1 ▶sub and_then {
Subroutine and_then: called CC=1 SCAR=0.0
Pod documented
115 1 my ($self, $cb) = @_;
116 1 return $self->then($cb);
117 }
118  
119  
120 35 ▶sub get {
Subroutine get: called CC=4 SCAR=13.9
Pod documented
121 35 my $self = shift;
122 35 $self->_resolve(1);
123 35 ▶ croak $self->{result} if $self->{failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"failed"} 9 26 35
124 26 ▶ my @r = @{ $self->{result} || [] };
Condition50%1/2
$self->{'result'} || []
l!l
260
MC/DC0%0/1
$self->{'result'} || []
$self->{'result'}
Truth table50%1/2
A
A= $self->{'result'}
Aresult
11
00
125 26 ▶ return wantarray ? @r : $r[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 22 4 26
126 }
127  
128  
129 9 ▶sub is_ready {
Subroutine is_ready: called CC=2 SCAR=6.9
Pod documented
130 9 my $self = shift;
131 9 ▶ return $self->_resolve(0) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_resolve(0) ? : 7 2 9
132 }
133  
134  
135 10 ▶sub is_failed {
Subroutine is_failed: called CC=3 SCAR=11.1
Pod documented
136 10 my $self = shift;
137 10 ▶ return 0 unless $self->_resolve(0);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_resolve(0) 0 10 10
138 10 ▶ return $self->{failed} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'failed'} ? : 7 3 10
139 }
140  
141 # --- Resolution machinery ---
142  
143 # Try to resolve. With $blocking true, block until resolved and return true;
144 # with $blocking false, do as much as can be done without blocking and return
145 # whether the future is now resolved.
146 63 ▶sub _resolve {
Subroutine _resolve: called CC=3 SCAR=11.0
147 63 my ($self, $blocking) = @_;
148 63 ▶ return 1 if $self->{ready};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ready"} 35 28 63
149 28 ▶ return $self->{mode} eq 'derived'
Branch: 1 branch
BranchTrueFalseTotal
$self->{'mode'} eq 'derived' ? : 7 21 28
150 ? $self->_resolve_derived($blocking)
151 : $self->_resolve_leaf($blocking);
152 }
153  
154 # Drain the pipe. Non-blocking: read what is available, accumulate, return 0
155 # until EOF. Blocking: read until EOF. On EOF, thaw + reap + cache.
156 21 ▶sub _resolve_leaf {
Subroutine _resolve_leaf: called CC=8 SCAR=21.8
157 21 my ($self, $blocking) = @_;
158 21 my $fh = $self->{read_fh};
159 21 ▶ croak 'DBIO::Forked::Future: no read handle to resolve' unless defined $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fh 0 21 21
160 21 ▶ my $sel = $self->{_select} ||= IO::Select->new($fh);
Condition66%2/3
$self->{"_select"} ||= "IO::Select"->new($fh)
l!l&&r!l&&!r
2190
MC/DC0%0/2
$self->{"_select"} ||= "IO::Select"->new($fh)
$self->{"_select"} "IO::Select"->new($fh)
Truth table66%2/3
A ||= B
A= $self->{"_select"}B= "IO::Select"->new($fh)
ABresult
1X1
011
000
161  
162 21 while (1) {
163 40 ▶ if (!$blocking) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($blocking) 10 30 40
164 10 ▶ return 0 unless $sel->can_read(0);
Branch: 1 branch
BranchTrueFalseTotal
unless $sel->can_read(0) 2 8 10
165 }
166 38 my $n = sysread($fh, my $chunk, 65536);
167 38 ▶ if (!defined $n) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $n) 0 38 38
168 0 ▶ next if $!{EINTR}; # interrupted by a signal -- retry
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EINTR"} 0 0 0
169 0 croak "DBIO::Forked::Future: read error: $!";
170 }
171 38 ▶ if ($n == 0) { # EOF: the child closed its write end
Branch: 1 branch
BranchTrueFalseTotal
if ($n == 0) 19 19 38
172 19 $self->_finish_leaf;
173 19 return 1;
174 }
175 19 $self->{buffer} .= $chunk;
176 }
177 }
178  
179 19 ▶sub _finish_leaf {
Subroutine _finish_leaf: called CC=9 SCAR=22.6
180 19 my $self = shift;
181  
182 19 my $blob = $self->{buffer};
183 19 $self->{buffer} = undef;
184 19 delete $self->{_select};
185 19 ▶ if (defined $self->{read_fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"read_fh"}) 19 0 19
186 19 close $self->{read_fh};
187 19 $self->{read_fh} = undef;
188 }
189 19 $self->_reap;
190  
191 19 my $data;
192 19 ▶ $data = eval { Storable::thaw($blob) } if defined $blob && length $blob;
Branch: 1 branch
BranchTrueFalseTotal
if defined $blob and length $blob 19 0 19
Condition33%1/3
defined $blob and length $blob
!ll&&!rl&&r
0019
MC/DC0%0/2
defined $blob and length $blob
defined $blob length $blob
Truth table33%1/3
A and B
A= defined $blobB= length $blob
ABresult
0X0
100
111
193 19 ▶ if (!$data || ref $data ne 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (not $data or ref $data ne 'HASH') { } 1 18 19
elsif (exists $data->{'error'}) { } 6 12 18
Condition66%2/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
1018
MC/DC50%1/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table66%2/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
194 1 $self->{failed} = 1;
195 1 ▶ $self->{result} = 'DBIO::Forked::Future: corrupt or empty result from child'
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 1 0 1
196 . ($@ ? ": $@" : '');
197 }
198 elsif (exists $data->{error}) {
199 6 $self->{failed} = 1;
200 6 $self->{result} = $data->{error};
201 }
202 else {
203 12 $self->{failed} = 0;
204 12 ▶ $self->{result} = $data->{rows} || [];
Condition50%1/2
$data->{'rows'} || []
l!l
120
MC/DC0%0/1
$data->{'rows'} || []
$data->{'rows'}
Truth table50%1/2
A
A= $data->{'rows'}
Aresult
11
00
205 }
206 19 $self->{ready} = 1;
207 }
208  
209 # Resolve a derived future: force the source, then apply the callback. Runs the
210 # callback synchronously (the source is ready by now). Returns 0 without effect
211 # if the source is not ready and we are non-blocking.
212 7 ▶sub _resolve_derived {
Subroutine _resolve_derived: called CC=14 SCAR=28.0
213 7 my ($self, $blocking) = @_;
214 7 my $source = $self->{source};
215 7 ▶ return 0 unless $source->_resolve($blocking);
Branch: 1 branch
BranchTrueFalseTotal
unless $source->_resolve($blocking) 0 7 7
216  
217 7 my @out;
218 7 ▶ if (!$source->{failed}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $source->{'failed'}) { } 4 3 7
219 4 ▶ if (my $cb = $self->{on_done}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->{'on_done'}) { } 4 0 4
220 4 ▶ @out = eval { $cb->(@{ $source->{result} || [] }) };
Condition50%1/2
$source->{'result'} || []
l!l
40
MC/DC0%0/1
$source->{'result'} || []
$source->{'result'}
Truth table50%1/2
A
A= $source->{'result'}
Aresult
11
00
221 4 ▶ return $self->_settle_failed("$@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
222 }
223 else {
224 0 ▶ @out = @{ $source->{result} || [] }; # pass-through (bare catch)
Condition0%0/2
$source->{'result'} || []
l!l
00
MC/DC0%0/1
$source->{'result'} || []
$source->{'result'}
Truth table0%0/2
A
A= $source->{'result'}
Aresult
11
00
225 }
226 }
227 else {
228 3 ▶ if (my $cb = $self->{on_fail}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->{'on_fail'}) { } 2 1 3
229 2 @out = eval { $cb->($source->{result}) };
230 2 ▶ return $self->_settle_failed("$@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
231 }
232 else {
233 1 return $self->_settle_failed($source->{result}); # no handler -- propagate
234 }
235 }
236  
237 # Flatten a single returned future (chaining).
238 6 ▶ if (@out == 1 && Scalar::Util::blessed($out[0]) && $out[0]->isa(__PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@out == 1 and builtin::blessed($out[0]) and $out[0]->isa(__PACKAGE__)) 2 4 6
Condition66%4/6
@out == 1 and builtin::blessed($out[0]) and $out[0]->isa(__PACKAGE__)
!ll&&!rl&&r
402
@out == 1 and builtin::blessed($out[0])
!ll&&!rl&&r
042
MC/DC33%1/3
@out == 1 and builtin::blessed($out[0]) and $out[0]->isa(__PACKAGE__)
@out == 1 builtin::blessed($out[0]) $out[0]->isa(__PACKAGE__)
Truth table50%2/4
A and B and C
A= @out == 1B= builtin::blessed($out[0])C= $out[0]->isa(__PACKAGE__)
ABCresult
0XX0
10X0
1100
1111
239 2 my $inner = $out[0];
240 2 ▶ return 0 unless $inner->_resolve($blocking);
Branch: 1 branch
BranchTrueFalseTotal
unless $inner->_resolve($blocking) 0 2 2
241 2 ▶ $self->{failed} = $inner->{failed} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$inner->{'failed'} ? : 0 2 2
242 2 $self->{result} = $inner->{result};
243 2 $self->{ready} = 1;
244 2 return 1;
245 }
246  
247 4 $self->{failed} = 0;
248 4 $self->{result} = \@out;
249 4 $self->{ready} = 1;
250 4 return 1;
251 }
252  
253 1 ▶sub _settle_failed {
Subroutine _settle_failed: called CC=1 SCAR=0.0
254 1 my ($self, $err) = @_;
255 1 $self->{failed} = 1;
256 1 $self->{result} = $err;
257 1 $self->{ready} = 1;
258 1 return 1;
259 }
260  
261 19 ▶sub _reap {
Subroutine _reap: called CC=3 SCAR=11.0
262 19 my $self = shift;
263 19 ▶ return if $self->{reaped};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"reaped"} 0 19 19
264 19 ▶ waitpid($self->{pid}, 0) if defined $self->{pid};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"pid"} 11 8 19
265 19 $self->{reaped} = 1;
266 }
267  
268 # Reap an un-collected child so it does not become a zombie.
269 44 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=14.1
270 44 my $self = shift;
271 44 ▶ return if $self->{reaped};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"reaped"} 43 1 44
272 1 ▶ close $self->{read_fh} if defined $self->{read_fh};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"read_fh"} 0 1 1
273 1 ▶ waitpid($self->{pid}, 0) if defined $self->{pid};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"pid"} 0 1 1
274 1 $self->{reaped} = 1;
275 }
276  
277 6 1;
278  
279 __END__
280  
281 =pod
282  
283 =encoding UTF-8
284  
285 =head1 NAME
286  
287 DBIO::Forked::Future - Loop-free, pipe-backed Future for DBIO::Forked
288  
289 =head1 VERSION
290  
291 version 0.900001
292  
293 =head1 DESCRIPTION
294  
295 A loop-free Future implementation over a pipe read fd, with no L<Future>, no
296 L<Future::IO> and no event loop. It is what L<DBIO::Forked::Storage> hands back
297 from its C<*_async> methods.
298  
299 It fulfils both the minimal core L<DBIO::Future> contract (C<then> / C<catch> /
300 C<get> / C<is_ready> / C<is_failed>) AND the fuller, L<DBIO::Future::Immediate>-compatible
301 surface (the C<done> / C<fail> / C<needs_all> class constructors, plus
302 C<and_then>), so it works as a live C<future_class> for core's ResultSet async
303 helpers (C<all_async> / C<first_async> / C<single_async> / C<count_async> /
304 C<create_async>), which build futures via C<< $storage->future_class->done(@rows) >>
305 and C<< ->fail($err) >>.
306  
307 The model is deliberately simple, matching Model A (one forked child per
308 query):
309  
310 =over 4
311  
312 =item *
313  
314 B<is_ready> is an EOF-clean, non-blocking drain. C<< IO::Select->can_read(0) >>
315 goes true as soon as the child writes I<anything>, not when it is done, so a
316 bare peek would be premature. Instead C<is_ready> reads whatever is available
317 without blocking and accumulates it across calls; it returns true only once the
318 child closes its write end (C<sysread> returns 0 = EOF), at which point the blob
319 is thawed, cached and the child reaped.
320  
321 =item *
322  
323 B<get> blocks until EOF, C<Storable>-thaws the accumulated blob, C<waitpid>-reaps
324 the child, and returns the rows -- or re-throws the child's error. It is
325 idempotent: the result is cached, so a second C<get> does not read or reap
326 again.
327  
328 =item *
329  
330 B<then> / B<catch> / B<and_then> compose lazily. A derived future stores its
331 callbacks and a reference to its source; it resolves (running the callback
332 synchronously, since the source is by then ready) the first time it is forced
333 via C<get>, or via C<is_ready>/C<is_failed> once the source is ready. No
334 callback runs before its source has resolved, and nothing blocks unless C<get>
335 is called.
336  
337 =item *
338  
339 B<done> / B<fail> / B<needs_all> are immediate class constructors (no fork): a
340 settled future is a pre-resolved leaf with no child, so it flows through the
341 same resolution machinery. C<needs_all> blocks on each input via C<get> in turn
342 (the children already run in parallel).
343  
344 =back
345  
346 =head1 METHODS
347  
348 =head2 new
349  
350 my $future = DBIO::Forked::Future->new(read_fh => $fh, pid => $pid);
351  
352 Construct a leaf future bound to the pipe read handle C<read_fh> and the forked
353 child C<pid>. Both are optional so the object can be built before the fork
354 wiring is in place.
355  
356 =head2 done
357  
358 my $f = DBIO::Forked::Future->done(@values);
359  
360 Class method: an immediately-resolved successful future carrying @values, with
361 no fork and no pipe. This is the constructor core's ResultSet async helpers call
362 as C<< $storage->future_class->done(@rows) >>.
363  
364 =head2 fail
365  
366 my $f = DBIO::Forked::Future->fail($error);
367  
368 Class method: an immediately-resolved failed future; L</get> re-throws $error.
369 The ResultSet async helpers call C<< $storage->future_class->fail($err) >>.
370  
371 =head2 needs_all
372  
373 my $f = DBIO::Forked::Future->needs_all(@futures);
374  
375 Class method: resolves once ALL @futures have resolved, collecting their values
376 in order; fails as soon as any one fails, with that future's error. Under Model A
377 the forked children already run in parallel; C<needs_all> just blocks on each in
378 turn via L</get>. Because collection is serial and each child holds its result
379 in the pipe until read, a batch of many large results can stall on the
380 pipe-buffer ceiling (see C<docs/adr/0003>); fine for modest result sets.
381  
382 =head2 then
383  
384 my $g = $future->then(sub { my @result = @_; ... });
385  
386 Success continuation. Returns a new C<DBIO::Forked::Future> that, when forced,
387 runs the callback with this future's resolved values and resolves to the
388 callback's return values. On failure the callback is skipped and the failure
389 propagates (unless an optional second C<$on_fail> argument is given).
390  
391 =head2 catch
392  
393 my $g = $future->catch(sub { my $error = shift; ... });
394  
395 Failure continuation. Returns a new C<DBIO::Forked::Future>; on failure it runs
396 the callback with the error and resolves to its return values, on success it
397 passes the values through unchanged.
398  
399 =head2 and_then
400  
401 my $g = $future->and_then(sub { my @r = @_; return DBIO::Forked::Future->done(...) });
402  
403 Like L</then>, but the callback is expected to return a future, which is
404 flattened into the chain (no future-wrapping-a-future). Mirrors
405 L<DBIO::Future::Immediate/and_then>. (C<then> already flattens a returned future, so
406 C<and_then> is C<then> with future-returning intent made explicit.)
407  
408 =head2 get
409  
410 my @result = $future->get;
411  
412 Block until resolved, then return the resolved values -- or C<croak> with the
413 child's error if it failed. Idempotent. Like L<DBIO::Future::Immediate/get>, in
414 scalar context it returns the first value (not the count).
415  
416 =head2 is_ready
417  
418 if ($future->is_ready) { ... }
419  
420 Non-blocking. True once resolved (the child has finished and its blob been
421 read, or the source of a derived future has resolved). Never blocks.
422  
423 =head2 is_failed
424  
425 if ($future->is_failed) { ... }
426  
427 Non-blocking. True once resolved I<and> the result is an error.
428  
429 =head1 STATUS
430  
431 Full C<future_class> surface implemented: the minimal L<DBIO::Future> contract
432 plus the L<DBIO::Future::Immediate>-compatible C<done> / C<fail> / C<needs_all> /
433 C<and_then>. L</then> / L</catch> / L</and_then> flatten a single returned
434 C<DBIO::Forked::Future> (chaining) but do not otherwise inspect nested
435 structures.
436  
437 =head1 AUTHOR
438  
439 DBIO Authors
440  
441 =head1 COPYRIGHT AND LICENSE
442  
443 Copyright (C) 2026 DBIO Authors
444  
445 This is free software; you can redistribute it and/or modify it under
446 the same terms as the Perl 5 programming language system itself.
447  
448 =cut
« Forked/Storage.pm ↑ Summary Forked.pm »