Future.pm

filter: Statementstmt 80.5% 83 / 103 Branchbran 69.2% 18 / 26 Conditioncond 53.3% 16 / 30 MC/DCmcdc 17.6% 3 / 17 Subroutinesub 56.1% 23 / 41 Podpod 100% 1 / 1 totaltotal 66.0% 144 / 218 CC 24 SCAR 10.7
CC
24
Cov
74%
CvNAME_FILE_LINE
7.8
unwrap
5.1
wrap
4.1
CRAP 2.9
« Future/Utils.pm ↑ Summary Test/Future.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2011-2026 -- leonerd@leonerd.org.uk
5  
6 package Future 0.54;
7  
8 33 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 33 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 33 ▶no warnings 'recursion'; # Disable the "deep recursion" warning
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # we are not overloaded, but we want to check if other objects are
13 33 require overload;
14 33 require attributes;
15  
16 33 ▶use feature qw( signatures );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 33 ▶no warnings qw( experimental::signatures );
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 33 require Future::Exception;
20  
21 33 our @CARP_NOT = qw( Future::Utils );
22  
23 33 ▶BEGIN {
Subroutine BEGIN: called CC=3 SCAR=12.0
24 33 ▶ if( !$ENV{PERL_FUTURE_NO_XS} and eval { require Future::XS } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ENV{'PERL_FUTURE_NO_XS'} and eval { do { require Future::XS } }) { } 0 33 33
Condition66%2/3
not $ENV{"PERL_FUTURE_NO_XS"} and eval { do { require Future::XS } }
!ll&&!rl&&r
22110
MC/DC0%0/2
not $ENV{"PERL_FUTURE_NO_XS"} and eval { do { require Future::XS } }
not $ENV{"PERL_FUTURE_NO_XS"} eval { do { require Future::XS } }
Truth table66%2/3
not(A) and B
A= not $ENV{"PERL_FUTURE_NO_XS"}B= eval { do { require Future::XS } }
ABresult
0X0
100
111
25 0 our @ISA = qw( Future::XS );
26 0 *DEBUG = \&Future::XS::DEBUG;
27 }
28 else {
29 33 require Future::PP;
30 33 our @ISA = qw( Future::PP );
31 33 *DEBUG = \&Future::PP::DEBUG;
32 }
33 }
34  
35 33 our $TIMES = DEBUG || $ENV{PERL_FUTURE_TIMES};
36  
37 # All of the methods provided in this file actually live in Future::_base::
38 # which is supplied as a base class for actual Future::PP and Future::XS to
39 # use.
40 package
41 Future::_base;
42  
43 33 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
44 33 ▶use B qw( svref_2object );
Subroutine BEGIN: called CC=1 SCAR=0.0
45 33 ▶use Time::HiRes qw( tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 =head1 NAME
48  
49 C<Future> - represent an operation awaiting completion
50  
51 =head1 SYNOPSIS
52  
53 =for highlighter language=perl
54  
55 my $future = Future->new;
56  
57 perform_some_operation(
58 on_complete => sub {
59 $future->done( @_ );
60 }
61 );
62  
63 $future->on_ready( sub {
64 say "The operation is complete";
65 } );
66  
67 =head1 DESCRIPTION
68  
69 A C<Future> object represents an operation that is currently in progress, or
70 has recently completed. It can be used in a variety of ways to manage the flow
71 of control, and data, through an asynchronous program.
72  
73 Some futures represent a single operation and are explicitly marked as ready
74 by calling the C<done> or C<fail> methods. These are called "leaf" futures
75 here, and are returned by the C<new> constructor.
76  
77 Other futures represent a collection of sub-tasks, and are implicitly marked
78 as ready depending on the readiness of their component futures as required.
79 These are called "convergent" futures here as they converge control and
80 data-flow back into one place. These are the ones returned by the various
81 C<wait_*> and C<need_*> constructors.
82  
83 It is intended that library functions that perform asynchronous operations
84 would use future objects to represent outstanding operations, and allow their
85 calling programs to control or wait for these operations to complete. The
86 implementation and the user of such an interface would typically make use of
87 different methods on the class. The methods below are documented in two
88 sections; those of interest to each side of the interface.
89  
90 It should be noted however, that this module does not in any way provide an
91 actual mechanism for performing this asynchronous activity; it merely provides
92 a way to create objects that can be used for control and data flow around
93 those operations. It allows such code to be written in a neater,
94 forward-reading manner, and simplifies many common patterns that are often
95 involved in such situations.
96  
97 See also L<Future::Utils> which contains useful loop-constructing functions,
98 to run a future-returning function repeatedly in a loop.
99  
100 Unless otherwise noted, the following methods require at least version
101 I<0.08>.
102  
103 =head2 FAILURE CATEGORIES
104  
105 While not directly required by C<Future> or its related modules, a growing
106 convention of C<Future>-using code is to encode extra semantics in the
107 arguments given to the C<fail> method, to represent different kinds of
108 failure.
109  
110 The convention is that after the initial message string as the first required
111 argument (intended for display to humans), the second argument is a short
112 lowercase string that relates in some way to the kind of failure that
113 occurred. Following this is a list of details about that kind of failure,
114 whose exact arrangement or structure are determined by the failure category.
115 For example, L<IO::Async> and L<Net::Async::HTTP> use this convention to
116 indicate at what stage a given HTTP request has failed:
117  
118 ->fail( $message, http => ... ) # an HTTP-level error during protocol
119 ->fail( $message, connect => ... ) # a TCP-level failure to connect a
120 # socket
121 ->fail( $message, resolve => ... ) # a resolver (likely DNS) failure
122 # to resolve a hostname
123  
124 By following this convention, a module remains consistent with other
125 C<Future>-based modules, and makes it easy for program logic to gracefully
126 handle and manage failures by use of the C<catch> method.
127  
128 =head2 SUBCLASSING
129  
130 This class easily supports being subclassed to provide extra behavior, such as
131 giving the C<get> method the ability to block and wait for completion. This
132 may be useful to provide C<Future> subclasses with event systems, or similar.
133  
134 Each method that returns a new future object will use the invocant to
135 construct its return value. If the constructor needs to perform per-instance
136 setup it can override the C<new> method, and take context from the given
137 instance.
138  
139 sub new
140 {
141 my $proto = shift;
142 my $self = $proto->SUPER::new;
143  
144 if( ref $proto ) {
145 # Prototype was an instance
146 }
147 else {
148 # Prototype was a class
149 }
150  
151 return $self;
152 }
153  
154 If an instance overrides the L</await> method, this will be called by C<get>
155 and C<failure> if the instance is still pending.
156  
157 In most cases this should allow future-returning modules to be used as if they
158 were blocking call/return-style modules, by simply appending a C<get> call to
159 the function or method calls.
160  
161 my ( $results, $here ) = future_returning_function( @args )->get;
162  
163 =head2 DEBUGGING
164  
165 By the time a C<Future> object is destroyed, it ought to have been completed
166 or cancelled. By enabling debug tracing of objects, this fact can be checked.
167 If a future object is destroyed without having been completed or cancelled, a
168 warning message is printed.
169  
170 =for highlighter
171  
172 $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
173 Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
174  
175 Note that due to a limitation of perl's C<caller> function within a C<DESTROY>
176 destructor method, the exact location of the leak cannot be accurately
177 determined. Often the leak will occur due to falling out of scope by returning
178 from a function; in this case the leak location may be reported as being the
179 line following the line calling that function.
180  
181 $ PERL_FUTURE_DEBUG=1 perl -MFuture
182 sub foo {
183 my $f = Future->new;
184 }
185  
186 foo();
187 print "Finished\n";
188  
189 Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
190 Finished
191  
192 A warning is also printed in debug mode if a C<Future> object is destroyed
193 that completed with a failure, but the object believes that failure has not
194 been reported anywhere.
195  
196 $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")'
197 Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops
198  
199 Such a failure is considered reported if the C<get> or C<failure> methods are
200 called on it, or it had at least one C<on_ready> or C<on_fail> callback, or
201 its failure is propagated to another C<Future> instance (by a sequencing or
202 converging method).
203  
204 =head2 Future::AsyncAwait::Awaitable ROLE
205  
206 Since version 0.43 this module provides the L<Future::AsyncAwait::Awaitable>
207 API. Subclass authors should note that several of the API methods are provided
208 by special optimised internal methods, which may require overriding in your
209 subclass if your internals are different from that of this module.
210  
211 =head2 OPTIONAL XS MODULE
212  
213 This module itself is implemented in pure Perl. Optionally, the CPAN module
214 L<Future::XS> can be installed, which provides an implementation written in
215 XS that may run faster and consume slightly less memory, which may be
216 significant in high-performance cases. Simply installing the module is
217 sufficient to use it; C<Future> will detect and load it automatically.
218  
219 This automatic loading can be disabled by setting the C<PERL_FUTURE_NO_XS>
220 environment variable to some true value. This may be helpful if a bug or other
221 undesirable behaviour is suspected, or simply to compare performance across
222 otherwise-similar programs.
223  
224 $ PERL_FUTURE_NO_XS=1 perl ...
225  
226 =cut
227  
228 =head1 CONSTRUCTORS
229  
230 =for highlighter language=perl
231  
232 =cut
233  
234 =head2 new
235  
236 $future = Future->new;
237  
238 $future = $orig->new;
239  
240 Returns a new C<Future> instance to represent a leaf future. It will be marked
241 as ready by any of the C<done>, C<fail>, or C<cancel> methods. It can be
242 called either as a class method, or as an instance method. Called on an
243 instance it will construct another in the same class, and is useful for
244 subclassing.
245  
246 This constructor would primarily be used by implementations of asynchronous
247 interfaces.
248  
249 =cut
250  
251 0 ▶*AWAIT_CLONE = sub ( $self ) { $self->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
252  
253 # Useful for identifying CODE references
254 3 ▶sub CvNAME_FILE_LINE ( $code )
Subroutine CvNAME_FILE_LINE: called CC=6 SCAR=20.5
255 {
256 3 my $cv = svref_2object( $code );
257  
258 3 my $name = join "::", $cv->STASH->NAME, $cv->GV->NAME;
259 3 ▶ return $name unless $cv->GV->NAME eq "__ANON__";
Branch: 1 branch
BranchTrueFalseTotal
unless $cv->GV->NAME eq "__ANON__" 0 3 3
260  
261 # $cv->GV->LINE isn't reliable, as outside of perl -d mode all anon CODE
262 # in the same file actually shares the same GV. :(
263 # Walk the optree looking for the first COP
264 3 my $cop = $cv->START;
265 3 ▶ $cop = $cop->next while $cop and ref $cop ne "B::COP" and ref $cop ne "B::NULL";
Branch: 1 branch
BranchTrueFalseTotal
$cop and ref $cop ne "B::COP" and ref $cop ne "B::NULL" and do { $cop = $cop->next } 0 3 3
Condition33%2/6
$cop and ref $cop ne "B::COP" and ref $cop ne "B::NULL"
!ll&&!rl&&r
300
$cop and ref $cop ne "B::COP"
!ll&&!rl&&r
030
MC/DC0%0/3
$cop and ref $cop ne "B::COP" and ref $cop ne "B::NULL"
$cop ref $cop ne "B::COP" ref $cop ne "B::NULL"
Truth table25%1/4
A and B and C
A= $copB= ref $cop ne "B::COP"C= ref $cop ne "B::NULL"
ABCresult
0XX0
10X0
1100
1111
266  
267 3 ▶ return $cv->GV->NAME if ref $cop eq "B::NULL";
Branch: 1 branch
BranchTrueFalseTotal
if ref $cop eq "B::NULL" 0 3 3
268 3 sprintf "%s(%s line %d)", $cv->GV->NAME, $cop->file, $cop->line;
269 }
270  
271 =head2 done I<(class method)>
272  
273 =head2 fail I<(class method)>
274  
275 $future = Future->done( @values );
276  
277 $future = Future->fail( $exception, $category, @details );
278  
279 I<Since version 0.26.>
280  
281 Shortcut wrappers around creating a new C<Future> then immediately marking it
282 as done or failed.
283  
284 =head2 wrap
285  
286 $future = Future->wrap( @values );
287  
288 I<Since version 0.14.>
289  
290 If given a single argument which is already a C<Future> reference, this will
291 be returned unmodified. Otherwise, returns a new C<Future> instance that is
292 already complete, and will yield the given values.
293  
294 This will ensure that an incoming argument is definitely a C<Future>, and may
295 be useful in such cases as adapting synchronous code to fit asynchronous
296 libraries driven by C<Future>.
297  
298 =cut
299  
300 2 ▶sub wrap ( $class, @values )
Subroutine wrap: called CC=4 SCAR=14.1
301 {
302 2 ▶ if( @values == 1 and blessed $values[0] and $values[0]->isa( __PACKAGE__ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)) { } 1 1 2
Condition66%4/6
@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)
!ll&&!rl&&r
101
@values == 1 and builtin::blessed($values[0])
!ll&&!rl&&r
011
MC/DC33%1/3
@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)
@values == 1 builtin::blessed($values[0]) $values[0]->isa(__PACKAGE__)
Truth table50%2/4
A and B and C
A= @values == 1B= builtin::blessed($values[0])C= $values[0]->isa(__PACKAGE__)
ABCresult
0XX0
10X0
1100
1111
303 1 return $values[0];
304 }
305 else {
306 1 return $class->done( @values );
307 }
308 }
309  
310 =head2 call
311  
312 $future = Future->call( \&code, @args );
313  
314 I<Since version 0.15.>
315  
316 A convenient wrapper for calling a C<CODE> reference that is expected to
317 return a future. In normal circumstances is equivalent to
318  
319 $future = $code->( @args );
320  
321 except that if the code throws an exception, it is wrapped in a new immediate
322 fail future. If the return value from the code is not a blessed C<Future>
323 reference, an immediate fail future is returned instead to complain about this
324 fact.
325  
326 =cut
327  
328 107 ▶sub call ( $class, $code, @args )
Subroutine call: called CC=4 SCAR=13.9
329 {
330 107 my $f;
331 107 ▶ eval { $f = $code->( @args ); 1 } or $f = $class->fail( $@ );
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $f = &$code(@args); 1 } } or $f = $class->fail($@) 98 9 107
332 107 ▶ blessed $f and $f->isa( "Future" ) or $f = $class->fail( "Expected " . CvNAME_FILE_LINE($code) . " to return a Future" );
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($f) and $f->isa("Future") or $f = $class->fail('Expected ' . CvNAME_FILE_LINE($code) . ' to return a Future') 104 3 107
Condition66%2/3
builtin::blessed($f) and $f->isa("Future")
!ll&&!rl&&r
30104
MC/DC50%1/2
builtin::blessed($f) and $f->isa("Future")
builtin::blessed($f) $f->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($f)B= $f->isa("Future")
ABresult
0X0
100
111
333  
334 107 return $f;
335 }
336  
337 =head1 METHODS
338  
339 As there are a lare number of methods on this class, they are documented here
340 in several sections.
341  
342 =cut
343  
344 =head1 INSPECTION METHODS
345  
346 The following methods query the internal state of a Future instance without
347 modifying it or otherwise causing side-effects.
348  
349 =cut
350  
351 =head2 is_ready
352  
353 $ready = $future->is_ready;
354  
355 Returns true on a leaf future if a result has been provided to the C<done>
356 method, failed using the C<fail> method, or cancelled using the C<cancel>
357 method.
358  
359 Returns true on a convergent future if it is ready to yield a result,
360 depending on its component futures.
361  
362 =cut
363  
364 0 ▶*AWAIT_IS_READY = sub ( $self ) { $self->is_ready };
Subroutine __ANON__: not called CC=1 SCAR=1.2
365  
366 =head2 is_done
367  
368 $done = $future->is_done;
369  
370 Returns true on a future if it is ready and completed successfully. Returns
371 false if it is still pending, failed, or was cancelled.
372  
373 =cut
374  
375 =head2 is_failed
376  
377 $failed = $future->is_failed;
378  
379 I<Since version 0.26.>
380  
381 Returns true on a future if it is ready and it failed. Returns false if it is
382 still pending, completed successfully, or was cancelled.
383  
384 =cut
385  
386 =head2 is_cancelled
387  
388 $cancelled = $future->is_cancelled;
389  
390 Returns true if the future has been cancelled by C<cancel>.
391  
392 =cut
393  
394 0 ▶*AWAIT_IS_CANCELLED = sub ( $self ) { $self->is_cancelled };
Subroutine __ANON__: not called CC=1 SCAR=1.2
395  
396 =head2 state
397  
398 $str = $future->state;
399  
400 I<Since version 0.36.>
401  
402 Returns a string describing the state of the future, as one of the three
403 states named above; namely C<done>, C<failed> or C<cancelled>, or C<pending>
404 if it is none of these.
405  
406 =cut
407  
408 =head1 IMPLEMENTATION METHODS
409  
410 These methods would primarily be used by implementations of asynchronous
411 interfaces.
412  
413 =cut
414  
415 =head2 done
416  
417 $future->done( @result );
418  
419 Marks that the leaf future is now ready, and provides a list of values as a
420 result. (The empty list is allowed, and still indicates the future as ready).
421 Cannot be called on a convergent future.
422  
423 If the future is already cancelled, this request is ignored. If the future is
424 already complete with a result or a failure, an exception is thrown.
425  
426 I<Since version 0.45:> this method is also available under the name
427 C<resolve>.
428  
429 =cut
430  
431 1 ▶*resolve = sub ( $self, @result ) { $self->done( @result ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
432  
433 # TODO: For efficiency we can implement better versions of these as individual
434 # methods know which case is being invoked
435 0 ▶*AWAIT_NEW_DONE = *AWAIT_DONE = sub ( $self, @result ) { $self->done( @result ) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
436  
437 =head2 fail
438  
439 $future->fail( $exception, $category, @details );
440  
441 Marks that the leaf future has failed, and provides an exception value. This
442 exception will be thrown by the C<get> method if called.
443  
444 The exception must evaluate as a true value; false exceptions are not allowed.
445 A failure category name and other further details may be provided that will be
446 returned by the C<failure> method in list context.
447  
448 If the future is already cancelled, this request is ignored. If the future is
449 already complete with a result or a failure, an exception is thrown.
450  
451 If passed a L<Future::Exception> instance (i.e. an object previously thrown by
452 the C<get>), the additional details will be preserved. This allows the
453 additional details to be transparently preserved by such code as
454  
455 ...
456 catch {
457 return Future->fail($@);
458 }
459  
460 I<Since version 0.45:> this method is also available under the name C<reject>.
461  
462 =cut
463  
464 1 ▶*reject = sub ( $self, @failure ) { $self->fail( @failure ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
465  
466 # TODO: For efficiency we can implement better versions of these as individual
467 # methods know which case is being invoked
468 0 ▶*AWAIT_NEW_FAIL = *AWAIT_FAIL = sub ( $self, @failure ) { $self->fail( @failure ) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
469  
470 =head2 die
471  
472 $future->die( $message, $category, @details );
473  
474 I<Since version 0.09.>
475  
476 A convenient wrapper around C<fail>. If the exception is a non-reference that
477 does not end in a linefeed, its value will be extended by the file and line
478 number of the caller, similar to the logic that C<die> uses.
479  
480 Returns the C<$future>.
481  
482 =cut
483  
484 1 ▶sub die ( $self, $exception, @more )
Subroutine die: called CC=3 SCAR=12.5
485 {
486 1 ▶ if( !ref $exception and $exception !~ m/\n$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $exception or $exception =~ /\n$/u) 1 0 1
Condition33%1/3
ref $exception or $exception =~ /\n$/u
l!l&&r!l&&!r
001
MC/DC0%0/2
ref $exception or $exception =~ /\n$/u
ref $exception $exception =~ /\n$/u
Truth table33%1/3
A or B
A= ref $exceptionB= $exception =~ /\n$/u
ABresult
1X1
011
000
487 1 $exception .= sprintf " at %s line %d\n", (caller)[1,2];
488 }
489  
490 1 $self->fail( $exception, @more );
491 }
492 # :method with signatures is difficult before Perl 5.28
493 33 attributes::->import( __PACKAGE__, \&die, 'method' );
494  
495 =head2 on_cancel
496  
497 $future->on_cancel( $code );
498  
499 If the future is not yet ready, adds a callback to be invoked if the future is
500 cancelled by the C<cancel> method. If the future is already ready the method
501 is ignored.
502  
503 If the future is later cancelled, the callbacks will be invoked in the reverse
504 order to that in which they were registered.
505  
506 $on_cancel->( $future );
507  
508 If passed another C<Future> instance, the passed instance will be cancelled
509 when the original future is cancelled. In this case, the reference is only
510 strongly held while the target future remains pending. If it becomes ready,
511 then there is no point trying to cancel it, and so it is removed from the
512 originating future's cancellation list.
513  
514 =cut
515  
516 0 ▶*AWAIT_ON_CANCEL = *AWAIT_CHAIN_CANCEL = sub ( $self, $cb ) { $self->on_cancel( $cb ) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
517  
518 =head1 USER METHODS
519  
520 These methods would primarily be used by users of asynchronous interfaces, on
521 objects returned by such an interface.
522  
523 =cut
524  
525 =head2 on_ready
526  
527 $future->on_ready( $code );
528  
529 If the future is not yet ready, adds a callback to be invoked when the future
530 is ready. If the future is already ready, invokes it immediately.
531  
532 In either case, the callback will be passed the future object itself. The
533 invoked code can then obtain the list of results by calling the C<get> method.
534  
535 $on_ready->( $future );
536  
537 If passed another C<Future> instance, the passed instance will have its
538 C<done>, C<fail> or C<cancel> methods invoked when the original future
539 completes successfully, fails, or is cancelled respectively.
540  
541 Returns the C<$future>.
542  
543 =cut
544  
545 0 ▶*AWAIT_ON_READY = sub ( $self, $cb ) { $self->on_ready( $cb ) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
546  
547 =head2 result
548  
549 @result = $future->result;
550  
551 $result = $future->result;
552  
553 I<Since version 0.44.>
554  
555 If the future is ready and completed successfully, returns the list of
556 results that had earlier been given to the C<done> method on a leaf future,
557 or the list of component futures it was waiting for on a convergent future. In
558 scalar context it returns just the first result value.
559  
560 If the future is ready but failed, this method raises as an exception the
561 failure that was given to the C<fail> method. If additional details were given
562 to the C<fail> method, an exception object is constructed to wrap them of type
563 L<Future::Exception>.
564  
565 If the future was cancelled or is not yet ready an exception is thrown.
566  
567 =cut
568  
569 0 ▶*AWAIT_RESULT = *AWAIT_GET = sub ( $self ) { $self->result };
Subroutine __ANON__: not called CC=1 SCAR=1.2
570  
571 =head2 get
572  
573 @result = $future->get;
574  
575 $result = $future->get;
576  
577 If the future is ready, returns the result or throws the failure exception as
578 per L</result>.
579  
580 If it is not yet ready then L</await> is invoked to wait for a ready state, and
581 the result returned as above.
582  
583 =cut
584  
585 0 ▶*AWAIT_WAIT = sub ( $self ) { $self->get };
Subroutine __ANON__: not called CC=1 SCAR=1.2
586  
587 =head2 await
588  
589 $f = $f->await;
590  
591 I<Since version 0.44.>
592  
593 Blocks until the future instance is no longer pending.
594  
595 Returns the invocant future itself, so it is useful for chaining.
596  
597 Usually, calling code would either force the future using L</get>, or use
598 either C<then> chaining or C<async/await> syntax to wait for results. This
599 method is useful in cases where the exception-throwing part of C<get> is not
600 required, perhaps because other code will be testing the result using
601 L</is_done> or similar.
602  
603 if( $f->await->is_done ) {
604 ...
605 }
606  
607 This method is intended for subclasses to override. The default implementation
608 will throw an exception if called on a still-pending instance.
609  
610 =cut
611  
612 =head2 block_until_ready
613  
614 $f = $f->block_until_ready;
615  
616 I<Since version 0.40.>
617  
618 Now a synonym for L</await>. New code should invoke C<await> directly.
619  
620 =cut
621  
622 0 ▶sub block_until_ready ( $self )
Subroutine block_until_ready: not called CC=1 SCAR=6.9
623 {
624 0 return $self->await;
625 }
626  
627 =head2 unwrap
628  
629 @values = Future->unwrap( @values );
630  
631 I<Since version 0.26.>
632  
633 If given a single argument which is a C<Future> reference, this method will
634 call C<get> on it and return the result. Otherwise, it returns the list of
635 values directly in list context, or the first value in scalar. Since it
636 involves an implicit blocking wait, this method can only be used on immediate
637 futures or subclasses that implement L</await>.
638  
639 This will ensure that an outgoing argument is definitely not a C<Future>, and
640 may be useful in such cases as adapting synchronous code to fit asynchronous
641 libraries that return C<Future> instances.
642  
643 =cut
644  
645 4 ▶sub unwrap ( $class, @values )
Subroutine unwrap: called CC=5 SCAR=16.2
646 {
647 4 ▶ if( @values == 1 and blessed $values[0] and $values[0]->isa( __PACKAGE__ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)) { } 2 2 4
Condition66%4/6
@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)
!ll&&!rl&&r
202
@values == 1 and builtin::blessed($values[0])
!ll&&!rl&&r
202
MC/DC33%1/3
@values == 1 and builtin::blessed($values[0]) and $values[0]->isa(__PACKAGE__)
@values == 1 builtin::blessed($values[0]) $values[0]->isa(__PACKAGE__)
Truth table50%2/4
A and B and C
A= @values == 1B= builtin::blessed($values[0])C= $values[0]->isa(__PACKAGE__)
ABCresult
0XX0
10X0
1100
1111
648 2 return $values[0]->get;
649 }
650 else {
651 2 ▶ return $values[0] if !wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 1 1 2
652 1 return @values;
653 }
654 }
655  
656 =head2 on_done
657  
658 $future->on_done( $code );
659  
660 If the future is not yet ready, adds a callback to be invoked when the future
661 is ready, if it completes successfully. If the future completed successfully,
662 invokes it immediately. If it failed or was cancelled, it is not invoked at
663 all.
664  
665 The callback will be passed the result passed to the C<done> method.
666  
667 $on_done->( @result );
668  
669 If passed another C<Future> instance, the passed instance will have its
670 C<done> method invoked when the original future completes successfully.
671  
672 Returns the C<$future>.
673  
674 =cut
675  
676 =head2 failure
677  
678 $exception = $future->failure;
679  
680 $exception, $category, @details = $future->failure;
681  
682 If the future is ready, returns the exception passed to the C<fail> method or
683 C<undef> if the future completed successfully via the C<done> method.
684  
685 If it is not yet ready then L</await> is invoked to wait for a ready state.
686  
687 If called in list context, will additionally yield the category name and list
688 of the details provided to the C<fail> method.
689  
690 Because the exception value must be true, this can be used in a simple C<if>
691 statement:
692  
693 if( my $exception = $future->failure ) {
694 ...
695 }
696 else {
697 my @result = $future->result;
698 ...
699 }
700  
701 =cut
702  
703 =head2 on_fail
704  
705 $future->on_fail( $code );
706  
707 If the future is not yet ready, adds a callback to be invoked when the future
708 is ready, if it fails. If the future has already failed, invokes it
709 immediately. If it completed successfully or was cancelled, it is not invoked
710 at all.
711  
712 The callback will be passed the exception and other details passed to the
713 C<fail> method.
714  
715 $on_fail->( $exception, $category, @details );
716  
717 If passed another C<Future> instance, the passed instance will have its
718 C<fail> method invoked when the original future fails.
719  
720 To invoke a C<done> method on a future when another one fails, use a CODE
721 reference:
722  
723 $future->on_fail( sub { $f->done( @_ ) } );
724  
725 Returns the C<$future>.
726  
727 =cut
728  
729 =head2 cancel
730  
731 $future->cancel;
732  
733 Requests that the future be cancelled, immediately marking it as ready. This
734 will invoke all of the code blocks registered by C<on_cancel>, in the reverse
735 order. When called on a convergent future, all its component futures are also
736 cancelled. It is not an error to attempt to cancel a future that is already
737 complete or cancelled; it simply has no effect.
738  
739 Returns the C<$future>.
740  
741 =cut
742  
743 =head1 SEQUENCING METHODS
744  
745 The following methods all return a new future to represent the combination of
746 its invocant followed by another action given by a code reference. The
747 combined activity waits for the first future to be ready, then may invoke the
748 code depending on the success or failure of the first, or may run it
749 regardless. The returned sequence future represents the entire combination of
750 activity.
751  
752 The invoked code could return a future, or a result directly.
753  
754 I<Since version 0.45:> if a non-future result is returned it will be wrapped
755 in a new immediate Future instance. This behaviour can be disabled by setting
756 the C<PERL_FUTURE_STRICT> environment variable to a true value at compiletime:
757  
758 =for highlighter
759  
760 $ PERL_FUTURE_STRICT=1 perl ...
761  
762 The combined future will then wait for the result of this second one. If the
763 combinined future is cancelled, it will cancel either the first future or the
764 second, depending whether the first had completed. If the code block throws an
765 exception instead of returning a value, the sequence future will fail with
766 that exception as its message and no further values.
767  
768 Note that since the code is invoked in scalar context, you cannot directly
769 return a list of values this way. Any list-valued results must be done by
770 returning a C<Future> instance.
771  
772 =for highlighter language=perl
773  
774 sub {
775 ...
776 return Future->done( @results );
777 }
778  
779 As it is always a mistake to call these sequencing methods in void context and lose the
780 reference to the returned future (because exception/error handling would be
781 silently dropped), this method warns in void context.
782  
783 =cut
784  
785 =head2 then
786  
787 $future = $f1->then( \&done_code );
788  
789 I<Since version 0.13.>
790  
791 Returns a new sequencing C<Future> that runs the code if the first succeeds.
792 Once C<$f1> succeeds the code reference will be invoked and is passed the list
793 of results. It should return a future, C<$f2>. Once C<$f2> completes the
794 sequence future will then be marked as complete with whatever result C<$f2>
795 gave. If C<$f1> fails then the sequence future will immediately fail with the
796 same failure and the code will not be invoked.
797  
798 $f2 = $done_code->( @result );
799  
800 =head2 else
801  
802 $future = $f1->else( \&fail_code );
803  
804 I<Since version 0.13.>
805  
806 Returns a new sequencing C<Future> that runs the code if the first fails. Once
807 C<$f1> fails the code reference will be invoked and is passed the failure and
808 other details. It should return a future, C<$f2>. Once C<$f2> completes the
809 sequence future will then be marked as complete with whatever result C<$f2>
810 gave. If C<$f1> succeeds then the sequence future will immediately succeed
811 with the same result and the code will not be invoked.
812  
813 $f2 = $fail_code->( $exception, $category, @details );
814  
815 =head2 then I<(2 arguments)>
816  
817 $future = $f1->then( \&done_code, \&fail_code );
818  
819 The C<then> method can also be passed the C<$fail_code> block as well, giving
820 a combination of C<then> and C<else> behaviour.
821  
822 This operation is similar to those provided by other future systems, such as
823 Javascript's Q or Promises/A libraries.
824  
825 =cut
826  
827 =head2 catch
828  
829 $future = $f1->catch(
830 name => \&code,
831 name => \&code, ...
832 );
833  
834 I<Since version 0.33.>
835  
836 Returns a new sequencing C<Future> that behaves like an C<else> call which
837 dispatches to a choice of several alternative handling functions depending on
838 the kind of failure that occurred. If C<$f1> fails with a category name (i.e.
839 the second argument to the C<fail> call) which exactly matches one of the
840 string names given, then the corresponding code is invoked, being passed the
841 same arguments as a plain C<else> call would take, and is expected to return a
842 C<Future> in the same way.
843  
844 $f2 = $code->( $exception, $category, @details );
845  
846 If C<$f1> does not fail, fails without a category name at all, or fails with a
847 category name that does not match any given to the C<catch> method, then the
848 returned sequence future immediately completes with the same result, and no
849 block of code is invoked.
850  
851 If passed an odd-sized list, the final argument gives a function to invoke on
852 failure if no other handler matches.
853  
854 $future = $f1->catch(
855 name => \&code, ...
856 \&fail_code,
857 );
858  
859 This feature is currently still a work-in-progress. It currently can only cope
860 with category names that are literal strings, which are all distinct. A later
861 version may define other kinds of match (e.g. regexp), may specify some sort
862 of ordering on the arguments, or any of several other semantic extensions. For
863 more detail on the ongoing design, see
864 L<https://rt.cpan.org/Ticket/Display.html?id=103545>.
865  
866 =head2 then I<(multiple arguments)>
867  
868 $future = $f1->then( \&done_code, @catch_list, \&fail_code );
869  
870 I<Since version 0.33.>
871  
872 The C<then> method can be passed an even-sized list inbetween the
873 C<$done_code> and the C<$fail_code>, with the same meaning as the C<catch>
874 method.
875  
876 =cut
877  
878 =head2 transform
879  
880 $future = $f1->transform( %args );
881  
882 Returns a new sequencing C<Future> that wraps the one given as C<$f1>. With no
883 arguments this will be a trivial wrapper; C<$future> will complete or fail
884 when C<$f1> does, and C<$f1> will be cancelled when C<$future> is.
885  
886 By passing the following named arguments, the returned C<$future> can be made
887 to behave differently to C<$f1>:
888  
889 =over 8
890  
891 =item done => CODE
892  
893 Provides a function to use to modify the result of a successful completion.
894 When C<$f1> completes successfully, the result of its C<get> method is passed
895 into this function, and whatever it returns is passed to the C<done> method of
896 C<$future>
897  
898 =item fail => CODE
899  
900 Provides a function to use to modify the result of a failure. When C<$f1>
901 fails, the result of its C<failure> method is passed into this function, and
902 whatever it returns is passed to the C<fail> method of C<$future>.
903  
904 =back
905  
906 =cut
907  
908 6 ▶sub transform ( $self, %args )
Subroutine transform: called CC=1 SCAR=0.1
909 {
910 6 my $xfrm_done = $args{done};
911 6 my $xfrm_fail = $args{fail};
912  
913 return $self->then_with_f(
914 3 ▶ sub ( $f, @result ) {
Subroutine __ANON__: called CC=2 SCAR=7.2
915 3 ▶ return $f unless $xfrm_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $xfrm_done 0 3 3
916 3 return $f->new->done( $xfrm_done->( @result ) );
917 },
918 1 ▶ sub ( $f, @failure ) {
Subroutine __ANON__: called CC=2 SCAR=7.2
919 1 ▶ return $f unless $xfrm_fail;
Branch: 1 branch
BranchTrueFalseTotal
unless $xfrm_fail 0 1 1
920 1 return $f->new->fail( $xfrm_fail->( @failure ) );
921 }
922 6 );
923 }
924  
925 =head2 then_with_f
926  
927 $future = $f1->then_with_f( ... );
928  
929 I<Since version 0.21.>
930  
931 Returns a new sequencing C<Future> that behaves like C<then>, but also passes
932 the original future, C<$f1>, to any functions it invokes.
933  
934 $f2 = $done_code->( $f1, @result );
935 $f2 = $catch_code->( $f1, $category, @details );
936 $f2 = $fail_code->( $f1, $category, @details );
937  
938 This is useful for conditional execution cases where the code block may just
939 return the same result of the original future. In this case it is more
940 efficient to return the original future itself.
941  
942 =cut
943  
944 =head2 then_done
945  
946 =head2 then_fail
947  
948 $future = $f->then_done( @result );
949  
950 $future = $f->then_fail( $exception, $category, @details );
951  
952 I<Since version 0.22.>
953  
954 Convenient shortcuts to returning an immediate future from a C<then> block,
955 when the result is already known.
956  
957 =cut
958  
959 0 ▶sub then_done ( $self, @result )
Subroutine then_done: not called CC=1 SCAR=6.9
960 {
961 0 ▶ return $self->then_with_f( sub ( $f, @ ) { return $f->new->done( @result ) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
962 }
963  
964 0 ▶sub then_fail ( $self, @failure )
Subroutine then_fail: not called CC=1 SCAR=6.9
965 {
966 0 ▶ return $self->then_with_f( sub ( $f, @ ) { return $f->new->fail( @failure ) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
967 }
968  
969 =head2 else_with_f
970  
971 $future = $f1->else_with_f( \&code );
972  
973 I<Since version 0.21.>
974  
975 Returns a new sequencing C<Future> that runs the code if the first fails.
976 Identical to C<else>, except that the code reference will be passed both the
977 original future, C<$f1>, and its exception and other details.
978  
979 $f2 = $code->( $f1, $exception, $category, @details );
980  
981 This is useful for conditional execution cases where the code block may just
982 return the same result of the original future. In this case it is more
983 efficient to return the original future itself.
984  
985 =cut
986  
987 =head2 else_done
988  
989 =head2 else_fail
990  
991 $future = $f->else_done( @result );
992  
993 $future = $f->else_fail( $exception, $category, @details );
994  
995 I<Since version 0.22.>
996  
997 Convenient shortcuts to returning an immediate future from a C<else> block,
998 when the result is already known.
999  
1000 =cut
1001  
1002 0 ▶sub else_done ( $self, @result )
Subroutine else_done: not called CC=1 SCAR=6.9
1003 {
1004 0 ▶ return $self->else_with_f( sub ( $f, @ ) { return $f->new->done( @result ) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
1005 }
1006  
1007 0 ▶sub else_fail ( $self, @failure )
Subroutine else_fail: not called CC=1 SCAR=6.9
1008 {
1009 0 ▶ return $self->else_with_f( sub ( $f, @ ) { return $f->new->fail( @failure ) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
1010 }
1011  
1012 =head2 catch_with_f
1013  
1014 $future = $f1->catch_with_f( ... );
1015  
1016 I<Since version 0.33.>
1017  
1018 Returns a new sequencing C<Future> that behaves like C<catch>, but also passes
1019 the original future, C<$f1>, to any functions it invokes.
1020  
1021 =cut
1022  
1023 =head2 followed_by
1024  
1025 $future = $f1->followed_by( \&code );
1026  
1027 Returns a new sequencing C<Future> that runs the code regardless of success or
1028 failure. Once C<$f1> is ready the code reference will be invoked and is passed
1029 one argument, C<$f1>. It should return a future, C<$f2>. Once C<$f2> completes
1030 the sequence future will then be marked as complete with whatever result
1031 C<$f2> gave.
1032  
1033 $f2 = $code->( $f1 );
1034  
1035 =cut
1036  
1037 =head2 without_cancel
1038  
1039 $future = $f1->without_cancel;
1040  
1041 I<Since version 0.30.>
1042  
1043 Returns a new sequencing C<Future> that will complete with the success or
1044 failure of the original future, but if cancelled, will not cancel the
1045 original. This may be useful if the original future represents an operation
1046 that is being shared among multiple sequences; cancelling one should not
1047 prevent the others from running too.
1048  
1049 Note that this only prevents cancel propagating from C<$future> to C<$f1>; if
1050 the original C<$f1> instance is cancelled then the returned C<$future> will
1051 have to be cancelled too.
1052  
1053 Also note that for the common case of using these with convergent futures such
1054 as L</needs_any>, the C<"also"> ability of version 0.51 may be a better
1055 solution.
1056  
1057 =cut
1058  
1059 =head2 retain
1060  
1061 $f = $f->retain;
1062  
1063 I<Since version 0.36.>
1064  
1065 Creates a reference cycle which causes the future to remain in memory until
1066 it completes. Returns the invocant future.
1067  
1068 In normal situations, a C<Future> instance does not strongly hold a reference
1069 to other futures that it is feeding a result into, instead relying on that to
1070 be handled by application logic. This is normally fine because some part of
1071 the application will retain the top-level Future, which then strongly refers
1072 to each of its components down in a tree. However, certain design patterns,
1073 such as mixed Future-based and legacy callback-based API styles might end up
1074 creating Futures simply to attach callback functions to them. In that
1075 situation, without further attention, the Future may get lost due to having no
1076 strong references to it. Calling C<< ->retain >> on it creates such a
1077 reference which ensures it persists until it completes. For example:
1078  
1079 Future->needs_all( $fA, $fB )
1080 ->on_done( $on_done )
1081 ->on_fail( $on_fail )
1082 ->retain;
1083  
1084 =cut
1085  
1086 6 ▶sub retain ( $self )
Subroutine retain: called CC=1 SCAR=0.0
1087 {
1088 6 ▶ return $self->on_ready( sub ( $ ) { undef $self } );
Subroutine __ANON__: called CC=1 SCAR=0.0
1089 }
1090  
1091 =head1 CONVERGENT FUTURES
1092  
1093 The following constructors all take a list of component futures, and return a
1094 new future whose readiness somehow depends on the readiness of those
1095 components. The first derived class component future will be used as the
1096 prototype for constructing the return value, so it respects subclassing
1097 correctly, or failing that a plain C<Future>.
1098  
1099 Except for C<wait_all>, it is possible that the result of the convergent
1100 future is already determined by the completion of at least one component
1101 future while others remain pending. In this situation, any other components
1102 that are still pending will normally be cancelled. Also, if the convergent
1103 future itself is cancelled then all of its components will be cancelled.
1104  
1105 I<Since version 0.51> it is possible to request that individual components
1106 not be cancelled in this manner. Any component future prefixed with the string
1107 C<"also"> is not cancelled when the convergent is. This is somewhat equivalent
1108 to using L</without_cancel>, but more performant as it does not have to create
1109 the intermediate future inbetween just for the purpose of ignoring a C<cancel>
1110 method.
1111  
1112 For example here, the futures C<$f3> and C<$f4> will not be cancelled, but the
1113 other three might be:
1114  
1115 Future->needs_all(
1116 $f1,
1117 $f2,
1118 also => $f3,
1119 also => $f4,
1120 $f5,
1121 );
1122  
1123 This makes it possible to observe futures in shared caches, or other
1124 situations where there may be multiple futures waiting for the result of a
1125 given initial component, but that component should not be cancelled just
1126 because any particular observer is stopped.
1127  
1128 my $f = Future->wait_any(
1129 timeout_future( delay => 10 ),
1130  
1131 also => ( $cache{$key} //= get_key_async($key) ),
1132 );
1133  
1134 # if $f is cancelled now, its timeout is cancelled but the
1135 # (possibly-shared) future in the %cache hash is not.
1136  
1137 =cut
1138  
1139 =head2 wait_all
1140  
1141 $future = Future->wait_all( @subfutures );
1142  
1143 Returns a new C<Future> instance that will indicate it is ready once all of
1144 the sub future objects given to it indicate that they are ready, either by
1145 success, failure or cancellation. Its result will be a list of its component
1146 futures.
1147  
1148 When given an empty list this constructor returns a new immediately-done
1149 future.
1150  
1151 This constructor would primarily be used by users of asynchronous interfaces.
1152  
1153 =cut
1154  
1155 =head2 wait_any
1156  
1157 $future = Future->wait_any( @subfutures );
1158  
1159 Returns a new C<Future> instance that will indicate it is ready once any of
1160 the sub future objects given to it indicate that they are ready, either by
1161 success or failure. Any remaining component futures that are not yet ready
1162 will be cancelled. Its result will be the result of the first component future
1163 that was ready; either success or failure. Any component futures that are
1164 cancelled are ignored, apart from the final component left; at which point the
1165 result will be a failure.
1166  
1167 When given an empty list this constructor returns an immediately-failed
1168 future.
1169  
1170 This constructor would primarily be used by users of asynchronous interfaces.
1171  
1172 =cut
1173  
1174 =head2 needs_all
1175  
1176 $future = Future->needs_all( @subfutures );
1177  
1178 Returns a new C<Future> instance that will indicate it is ready once all of the
1179 sub future objects given to it indicate that they have completed successfully,
1180 or when any of them indicates that they have failed. If any sub future fails,
1181 then this will fail immediately, and the remaining subs not yet ready will be
1182 cancelled. Any component futures that are cancelled will cause an immediate
1183 failure of the result.
1184  
1185 If successful, its result will be a concatenated list of the results of all
1186 its component futures, in corresponding order. If it fails, its failure will
1187 be that of the first component future that failed. To access each component
1188 future's results individually, use C<done_futures>.
1189  
1190 When given an empty list this constructor returns a new immediately-done
1191 future.
1192  
1193 This constructor would primarily be used by users of asynchronous interfaces.
1194  
1195 =cut
1196  
1197 =head2 needs_any
1198  
1199 $future = Future->needs_any( @subfutures );
1200  
1201 Returns a new C<Future> instance that will indicate it is ready once any of
1202 the sub future objects given to it indicate that they have completed
1203 successfully, or when all of them indicate that they have failed. If any sub
1204 future succeeds, then this will succeed immediately, and the remaining subs
1205 not yet ready will be cancelled. Any component futures that are cancelled are
1206 ignored, apart from the final component left; at which point the result will
1207 be a failure.
1208  
1209 If successful, its result will be that of the first component future that
1210 succeeded. If it fails, its failure will be that of the last component future
1211 to fail. To access the other failures, use C<failed_futures>.
1212  
1213 Normally when this future completes successfully, only one of its component
1214 futures will be done. If it is constructed with multiple that are already done
1215 however, then all of these will be returned from C<done_futures>. Users should
1216 be careful to still check all the results from C<done_futures> in that case.
1217  
1218 When given an empty list this constructor returns an immediately-failed
1219 future.
1220  
1221 This constructor would primarily be used by users of asynchronous interfaces.
1222  
1223 =cut
1224  
1225 =head1 METHODS ON CONVERGENT FUTURES
1226  
1227 The following methods apply to convergent (i.e. non-leaf) futures, to access
1228 the component futures stored by it.
1229  
1230 =cut
1231  
1232 =head2 pending_futures
1233  
1234 @f = $future->pending_futures;
1235  
1236 =head2 ready_futures
1237  
1238 @f = $future->ready_futures;
1239  
1240 =head2 done_futures
1241  
1242 @f = $future->done_futures;
1243  
1244 =head2 failed_futures
1245  
1246 @f = $future->failed_futures;
1247  
1248 =head2 cancelled_futures
1249  
1250 @f = $future->cancelled_futures;
1251  
1252 Return a list of all the pending, ready, done, failed, or cancelled
1253 component futures. In scalar context, each will yield the number of such
1254 component futures.
1255  
1256 =cut
1257  
1258 =head1 SUBCLASSING METHODS
1259  
1260 These methods are not intended for end-users of C<Future> instances, but
1261 instead provided for authors of classes that subclass from C<Future> itself.
1262  
1263 =cut
1264  
1265 =head2 set_udata
1266  
1267 $future = $future->set_udata( $name, $value );
1268  
1269 I<Since version 0.49>
1270  
1271 Stores a Perl value within the instance, under the given name. Subclasses can
1272 use this to store extra data that the implementation may require.
1273  
1274 This is a safer version of attempting to use the C<$future> instance itself as
1275 a hash reference.
1276  
1277 =cut
1278  
1279 =head2 udata
1280  
1281 $value = $future->udata( $name );
1282  
1283 I<Since version 0.49>
1284  
1285 Returns a Perl value from the instance that was previously set with
1286 L</set_udata>.
1287  
1288 =cut
1289  
1290 =head1 TRACING METHODS
1291  
1292 =head2 set_label
1293  
1294 =head2 label
1295  
1296 $future = $future->set_label( $label );
1297  
1298 $label = $future->label;
1299  
1300 I<Since version 0.28.>
1301  
1302 Chaining mutator and accessor for the label of the C<Future>. This should be a
1303 plain string value, whose value will be stored by the future instance for use
1304 in debugging messages or other tooling, or similar purposes.
1305  
1306 =cut
1307  
1308 =head2 btime
1309  
1310 =head2 rtime
1311  
1312 [ $sec, $usec ] = $future->btime;
1313  
1314 [ $sec, $usec ] = $future->rtime;
1315  
1316 I<Since version 0.28.>
1317  
1318 Accessors that return the tracing timestamps from the instance. These give the
1319 time the instance was constructed ("birth" time, C<btime>) and the time the
1320 result was determined (the "ready" time, C<rtime>). Each result is returned as
1321 a two-element ARRAY ref, containing the epoch time in seconds and
1322 microseconds, as given by C<Time::HiRes::gettimeofday>.
1323  
1324 In order for these times to be captured, they have to be enabled by setting
1325 C<$Future::TIMES> to a true value. This is initialised true at the time the
1326 module is loaded if either C<PERL_FUTURE_DEBUG> or C<PERL_FUTURE_TIMES> are
1327 set in the environment.
1328  
1329 =cut
1330  
1331 =head2 elapsed
1332  
1333 $sec = $future->elapsed;
1334  
1335 I<Since version 0.28.>
1336  
1337 If both tracing timestamps are defined, returns the number of seconds of
1338 elapsed time between them as a floating-point number. If not, returns
1339 C<undef>.
1340  
1341 =cut
1342  
1343 4 ▶sub elapsed ( $self )
Subroutine elapsed: called CC=3 SCAR=13.1
1344 {
1345 4 ▶ return undef unless defined( my $btime = $self->btime ) and
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $btime = $self->btime) and defined(my $rtime = $self->rtime) 0 4 4
Condition33%1/3
defined(my $btime = $self->btime) and defined(my $rtime = $self->rtime)
!ll&&!rl&&r
004
MC/DC0%0/2
defined(my $btime = $self->btime) and defined(my $rtime = $self->rtime)
defined(my $btime = $self->btime) defined(my $rtime = $self->rtime)
Truth table33%1/3
A and B
A= defined(my $btime = $self->btime)B= defined(my $rtime = $self->rtime)
ABresult
0X0
100
111
1346 defined( my $rtime = $self->rtime );
1347 4 return tv_interval( $self->btime, $self->rtime );
1348 }
1349  
1350 =head2 wrap_cb
1351  
1352 $cb = $future->wrap_cb( $operation_name, $cb );
1353  
1354 I<Since version 0.31.>
1355  
1356 I<Note: This method is experimental and may be changed or removed in a later
1357 version.>
1358  
1359 This method is invoked internally by various methods that are about to save a
1360 callback CODE reference supplied by the user, to be invoked later. The default
1361 implementation simply returns the callback argument as-is; the method is
1362 provided to allow users to provide extra behaviour. This can be done by
1363 applying a method modifier of the C<around> kind, so in effect add a chain of
1364 wrappers. Each wrapper can then perform its own wrapping logic of the
1365 callback. C<$operation_name> is a string giving the reason for which the
1366 callback is being saved; currently one of C<on_ready>, C<on_done>, C<on_fail>
1367 or C<sequence>; the latter being used for all the sequence-returning methods.
1368  
1369 This method is intentionally invoked only for CODE references that are being
1370 saved on a pending C<Future> instance to be invoked at some later point. It
1371 does not run for callbacks to be invoked on an already-complete instance. This
1372 is for performance reasons, where the intended behaviour is that the wrapper
1373 can provide some amount of context save and restore, to return the operating
1374 environment for the callback back to what it was at the time it was saved.
1375  
1376 For example, the following wrapper saves the value of a package variable at
1377 the time the callback was saved, and restores that value at invocation time
1378 later on. This could be useful for preserving context during logging in a
1379 Future-based program.
1380  
1381 our $LOGGING_CTX;
1382  
1383 no warnings 'redefine';
1384  
1385 my $orig = Future->can( "wrap_cb" );
1386 *Future::wrap_cb = sub {
1387 my $cb = $orig->( @_ );
1388  
1389 my $saved_logging_ctx = $LOGGING_CTX;
1390  
1391 return sub {
1392 local $LOGGING_CTX = $saved_logging_ctx;
1393 $cb->( @_ );
1394 };
1395 };
1396  
1397 At this point, any code deferred into a C<Future> by any of its callbacks will
1398 observe the C<$LOGGING_CTX> variable as having the value it held at the time
1399 the callback was saved, even if it is invoked later on when that value is
1400 different.
1401  
1402 Remember when writing such a wrapper, that it still needs to invoke the
1403 previous version of the method, so that it plays nicely in combination with
1404 others (see the C<< $orig->( @_ ) >> part).
1405  
1406 =cut
1407  
1408 # Callers expect to find this in the real Future:: package
1409 325 ▶sub Future::wrap_cb ( $self, $op, $cb )
Subroutine wrap_cb: called CC=1 SCAR=0.0
Pod documented
1410 {
1411 325 return $cb;
1412 }
1413  
1414 =head1 EXAMPLES
1415  
1416 The following examples all demonstrate possible uses of a C<Future>
1417 object to provide a fictional asynchronous API.
1418  
1419 For more examples, comparing the use of C<Future> with regular call/return
1420 style Perl code, see also L<Future::Phrasebook>.
1421  
1422 =head2 Providing Results
1423  
1424 By returning a new C<Future> object each time the asynchronous function is
1425 called, it provides a placeholder for its eventual result, and a way to
1426 indicate when it is complete.
1427  
1428 sub foperation
1429 {
1430 my %args = @_;
1431  
1432 my $future = Future->new;
1433  
1434 do_something_async(
1435 foo => $args{foo},
1436 on_done => sub { $future->done( @_ ); },
1437 );
1438  
1439 return $future;
1440 }
1441  
1442 In most cases, the C<done> method will simply be invoked with the entire
1443 result list as its arguments. In that case, it is convenient to use the
1444 L<curry> module to form a C<CODE> reference that would invoke the C<done>
1445 method.
1446  
1447 my $future = Future->new;
1448  
1449 do_something_async(
1450 foo => $args{foo},
1451 on_done => $future->curry::done,
1452 );
1453  
1454 The caller may then use this future to wait for a result using the C<on_ready>
1455 method, and obtain the result using C<get>.
1456  
1457 my $f = foperation( foo => "something" );
1458  
1459 $f->on_ready( sub {
1460 my $f = shift;
1461 say "The operation returned: ", $f->result;
1462 } );
1463  
1464 =head2 Indicating Success or Failure
1465  
1466 Because the stored exception value of a failed future may not be false, the
1467 C<failure> method can be used in a conditional statement to detect success or
1468 failure.
1469  
1470 my $f = foperation( foo => "something" );
1471  
1472 $f->on_ready( sub {
1473 my $f = shift;
1474 if( not my $e = $f->failure ) {
1475 say "The operation succeeded with: ", $f->result;
1476 }
1477 else {
1478 say "The operation failed with: ", $e;
1479 }
1480 } );
1481  
1482 By using C<not> in the condition, the order of the C<if> blocks can be
1483 arranged to put the successful case first, similar to a C<try>/C<catch> block.
1484  
1485 Because the C<get> method re-raises the passed exception if the future failed,
1486 it can be used to control a C<try>/C<catch> block directly. (This is sometimes
1487 called I<Exception Hoisting>).
1488  
1489 use Syntax::Keyword::Try;
1490  
1491 $f->on_ready( sub {
1492 my $f = shift;
1493 try {
1494 say "The operation succeeded with: ", $f->result;
1495 }
1496 catch {
1497 say "The operation failed with: ", $_;
1498 }
1499 } );
1500  
1501 Even neater still may be the separate use of the C<on_done> and C<on_fail>
1502 methods.
1503  
1504 $f->on_done( sub {
1505 my @result = @_;
1506 say "The operation succeeded with: ", @result;
1507 } );
1508 $f->on_fail( sub {
1509 my ( $failure ) = @_;
1510 say "The operation failed with: $failure";
1511 } );
1512  
1513 =head2 Immediate Futures
1514  
1515 Because the C<done> method returns the future object itself, it can be used to
1516 generate a C<Future> that is immediately ready with a result. This can also be
1517 used as a class method.
1518  
1519 my $f = Future->done( $value );
1520  
1521 Similarly, the C<fail> and C<die> methods can be used to generate a C<Future>
1522 that is immediately failed.
1523  
1524 my $f = Future->die( "This is never going to work" );
1525  
1526 This could be considered similarly to a C<die> call.
1527  
1528 An C<eval{}> block can be used to turn a C<Future>-returning function that
1529 might throw an exception, into a C<Future> that would indicate this failure.
1530  
1531 my $f = eval { function() } || Future->fail( $@ );
1532  
1533 This is neater handled by the C<call> class method, which wraps the call in
1534 an C<eval{}> block and tests the result:
1535  
1536 my $f = Future->call( \&function );
1537  
1538 =head2 Sequencing
1539  
1540 The C<then> method can be used to create simple chains of dependent tasks,
1541 each one executing and returning a C<Future> when the previous operation
1542 succeeds.
1543  
1544 my $f = do_first()
1545 ->then( sub {
1546 return do_second();
1547 })
1548 ->then( sub {
1549 return do_third();
1550 });
1551  
1552 The result of the C<$f> future itself will be the result of the future
1553 returned by the final function, if none of them failed. If any of them fails
1554 it will fail with the same failure. This can be considered similar to normal
1555 exception handling in synchronous code; the first time a function call throws
1556 an exception, the subsequent calls are not made.
1557  
1558 =head2 Merging Control Flow
1559  
1560 A C<wait_all> future may be used to resynchronise control flow, while waiting
1561 for multiple concurrent operations to finish.
1562  
1563 my $f1 = foperation( foo => "something" );
1564 my $f2 = foperation( bar => "something else" );
1565  
1566 my $f = Future->wait_all( $f1, $f2 );
1567  
1568 $f->on_ready( sub {
1569 say "Operations are ready:";
1570 say " foo: ", $f1->result;
1571 say " bar: ", $f2->result;
1572 } );
1573  
1574 This provides an ability somewhat similar to C<CPS::kpar()> or
1575 L<Async::MergePoint>.
1576  
1577 =cut
1578  
1579 =head1 KNOWN ISSUES
1580  
1581 =head2 Cancellation of Non-Final Sequence Futures
1582  
1583 The behaviour of future cancellation still has some unanswered questions
1584 regarding how to handle the situation where a future is cancelled that has a
1585 sequence future constructed from it.
1586  
1587 In particular, it is unclear in each of the following examples what the
1588 behaviour of C<$f2> should be, were C<$f1> to be cancelled:
1589  
1590 $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1591  
1592 $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1593  
1594 $f2 = $f1->followed_by( sub { ... } );
1595  
1596 In the C<then>-style case it is likely that this situation should be treated
1597 as if C<$f1> had failed, perhaps with some special message. The C<else>-style
1598 case is more complex, because it may be that the entire operation should still
1599 fail, or it may be that the cancellation of C<$f1> should again be treated
1600 simply as a special kind of failure, and the C<else> logic run as normal.
1601  
1602 To be specific; in each case it is unclear what happens if the first future is
1603 cancelled, while the second one is still waiting on it. The semantics for
1604 "normal" top-down cancellation of C<$f2> and how it affects C<$f1> are already
1605 clear and defined.
1606  
1607 =head2 Cancellation of Divergent Flow
1608  
1609 A further complication of cancellation comes from the case where a given
1610 future is reused multiple times for multiple sequences or convergent trees.
1611  
1612 In particular, it is in clear in each of the following examples what the
1613 behaviour of C<$f2> should be, were C<$f1> to be cancelled:
1614  
1615 my $f_initial = Future->new; ...
1616 my $f1 = $f_initial->then( ... );
1617 my $f2 = $f_initial->then( ... );
1618  
1619 my $f1 = Future->needs_all( $f_initial );
1620 my $f2 = Future->needs_all( $f_initial );
1621  
1622 The point of cancellation propagation is to trace backwards through stages of
1623 some larger sequence of operations that now no longer need to happen, because
1624 the final result is no longer required. But in each of these cases, just
1625 because C<$f1> has been cancelled, the initial future C<$f_initial> is still
1626 required because there is another future (C<$f2>) that will still require its
1627 result.
1628  
1629 Initially it would appear that some kind of reference-counting mechanism could
1630 solve this question, though that itself is further complicated by the
1631 C<on_ready> handler and its variants.
1632  
1633 It may simply be that a comprehensive useful set of cancellation semantics
1634 can't be universally provided to cover all cases; and that some use-cases at
1635 least would require the application logic to give extra information to its
1636 C<Future> objects on how they should wire up the cancel propagation logic.
1637  
1638 Both of these cancellation issues are still under active design consideration;
1639 see the discussion on RT96685 for more information
1640 (L<https://rt.cpan.org/Ticket/Display.html?id=96685>).
1641  
1642 =cut
1643  
1644 =head1 SEE ALSO
1645  
1646 =over 4
1647  
1648 =item *
1649  
1650 L<Future::AsyncAwait> - deferred subroutine syntax for futures
1651  
1652 Provides a neat syntax extension for writing future-based code.
1653  
1654 =item *
1655  
1656 L<Future::IO> - Future-returning IO methods
1657  
1658 Provides methods similar to core IO functions, which yield results by Futures.
1659  
1660 =item *
1661  
1662 L<Promises> - an implementation of the "Promise/A+" pattern for asynchronous
1663 programming
1664  
1665 A different alternative implementation of a similar idea.
1666  
1667 =item *
1668  
1669 L<curry> - Create automatic curried method call closures for any class or
1670 object
1671  
1672 =item *
1673  
1674 "The Past, The Present and The Future" - slides from a talk given at the
1675 London Perl Workshop, 2012.
1676  
1677 L<https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1678  
1679 =item *
1680  
1681 "Futures advent calendar 2013"
1682  
1683 L<http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1684  
1685 =item *
1686  
1687 "Asynchronous Programming with Futures" - YAPC::EU 2014
1688  
1689 L<https://www.youtube.com/watch?v=u9dZgFM6FtE>
1690  
1691 =back
1692  
1693 =cut
1694  
1695 =head1 TODO
1696  
1697 =over 4
1698  
1699 =item *
1700  
1701 Consider the ability to pass the constructor a C<block> CODEref, instead of
1702 needing to use a subclass. This might simplify async/etc.. implementations,
1703 and allows the reuse of the idea of subclassing to extend the abilities of
1704 C<Future> itself - for example to allow a kind of Future that can report
1705 incremental progress.
1706  
1707 =back
1708  
1709 =cut
1710  
1711 =head1 AUTHOR
1712  
1713 Paul Evans <leonerd@leonerd.org.uk>
1714  
1715 =cut
1716  
1717 33 0x55AA;
« Future/Utils.pm ↑ Summary Test/Future.pm »