File Coverage

blib/lib/Future.pm
Criterion Covered Total %
statement 82 105 78.1
branch 17 24 70.8
condition 16 30 53.3
subroutine 27 39 69.2
pod 1 1 100.0
total 143 199 71.8


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