• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

lib/H01-Jan-2021-4,5651,762

t/H01-Jan-2021-3,9232,615

Build.PLH A D01-Jan-20212.7 KiB9066

ChangesH A D01-Jan-202114.8 KiB395325

LICENSEH A D01-Jan-202118 KiB380292

MANIFESTH A D01-Jan-2021750 4645

META.jsonH A D01-Jan-20211.9 KiB7978

META.ymlH A D01-Jan-20211.2 KiB5150

READMEH A D01-Jan-202145 KiB1,325909

README

1NAME
2
3    Future - represent an operation awaiting completion
4
5SYNOPSIS
6
7       my $future = Future->new;
8
9       perform_some_operation(
10          on_complete => sub {
11             $future->done( @_ );
12          }
13       );
14
15       $future->on_ready( sub {
16          say "The operation is complete";
17       } );
18
19DESCRIPTION
20
21    A Future object represents an operation that is currently in progress,
22    or has recently completed. It can be used in a variety of ways to
23    manage the flow of control, and data, through an asynchronous program.
24
25    Some futures represent a single operation and are explicitly marked as
26    ready by calling the done or fail methods. These are called "leaf"
27    futures here, and are returned by the new constructor.
28
29    Other futures represent a collection of sub-tasks, and are implicitly
30    marked as ready depending on the readiness of their component futures
31    as required. These are called "convergent" futures here as they
32    converge control and data-flow back into one place. These are the ones
33    returned by the various wait_* and need_* constructors.
34
35    It is intended that library functions that perform asynchronous
36    operations would use future objects to represent outstanding
37    operations, and allow their calling programs to control or wait for
38    these operations to complete. The implementation and the user of such
39    an interface would typically make use of different methods on the
40    class. The methods below are documented in two sections; those of
41    interest to each side of the interface.
42
43    It should be noted however, that this module does not in any way
44    provide an actual mechanism for performing this asynchronous activity;
45    it merely provides a way to create objects that can be used for control
46    and data flow around those operations. It allows such code to be
47    written in a neater, forward-reading manner, and simplifies many common
48    patterns that are often involved in such situations.
49
50    See also Future::Utils which contains useful loop-constructing
51    functions, to run a future-returning function repeatedly in a loop.
52
53    Unless otherwise noted, the following methods require at least version
54    0.08.
55
56 FAILURE CATEGORIES
57
58    While not directly required by Future or its related modules, a growing
59    convention of Future-using code is to encode extra semantics in the
60    arguments given to the fail method, to represent different kinds of
61    failure.
62
63    The convention is that after the initial message string as the first
64    required argument (intended for display to humans), the second argument
65    is a short lowercase string that relates in some way to the kind of
66    failure that occurred. Following this is a list of details about that
67    kind of failure, whose exact arrangement or structure are determined by
68    the failure category. For example, IO::Async and Net::Async::HTTP use
69    this convention to indicate at what stage a given HTTP request has
70    failed:
71
72       ->fail( $message, http => ... )  # an HTTP-level error during protocol
73       ->fail( $message, connect => ... )  # a TCP-level failure to connect a
74                                           # socket
75       ->fail( $message, resolve => ... )  # a resolver (likely DNS) failure
76                                           # to resolve a hostname
77
78    By following this convention, a module remains consistent with other
79    Future-based modules, and makes it easy for program logic to gracefully
80    handle and manage failures by use of the catch method.
81
82 SUBCLASSING
83
84    This class easily supports being subclassed to provide extra behavior,
85    such as giving the get method the ability to block and wait for
86    completion. This may be useful to provide Future subclasses with event
87    systems, or similar.
88
89    Each method that returns a new future object will use the invocant to
90    construct its return value. If the constructor needs to perform
91    per-instance setup it can override the new method, and take context
92    from the given instance.
93
94       sub new
95       {
96          my $proto = shift;
97          my $self = $proto->SUPER::new;
98
99          if( ref $proto ) {
100             # Prototype was an instance
101          }
102          else {
103             # Prototype was a class
104          }
105
106          return $self;
107       }
108
109    If an instance overrides the "await" method, this will be called by get
110    and failure if the instance is still pending.
111
112    In most cases this should allow future-returning modules to be used as
113    if they were blocking call/return-style modules, by simply appending a
114    get call to the function or method calls.
115
116       my ( $results, $here ) = future_returning_function( @args )->get;
117
118 DEBUGGING
119
120    By the time a Future object is destroyed, it ought to have been
121    completed or cancelled. By enabling debug tracing of objects, this fact
122    can be checked. If a future object is destroyed without having been
123    completed or cancelled, a warning message is printed.
124
125       $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
126       Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
127
128    Note that due to a limitation of perl's caller function within a
129    DESTROY destructor method, the exact location of the leak cannot be
130    accurately determined. Often the leak will occur due to falling out of
131    scope by returning from a function; in this case the leak location may
132    be reported as being the line following the line calling that function.
133
134       $ PERL_FUTURE_DEBUG=1 perl -MFuture
135       sub foo {
136          my $f = Future->new;
137       }
138
139       foo();
140       print "Finished\n";
141
142       Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
143       Finished
144
145    A warning is also printed in debug mode if a Future object is destroyed
146    that completed with a failure, but the object believes that failure has
147    not been reported anywhere.
148
149       $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")'
150       Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops
151
152    Such a failure is considered reported if the get or failure methods are
153    called on it, or it had at least one on_ready or on_fail callback, or
154    its failure is propagated to another Future instance (by a sequencing
155    or converging method).
156
157 Future::AsyncAwait::Awaitable ROLE
158
159    Since version 0.43 this module provides the
160    Future::AsyncAwait::Awaitable API. Subclass authors should note that
161    several of the API methods are provided by special optimised internal
162    methods, which may require overriding in your subclass if your
163    internals are different from that of this module.
164
165CONSTRUCTORS
166
167 new
168
169       $future = Future->new
170
171       $future = $orig->new
172
173    Returns a new Future instance to represent a leaf future. It will be
174    marked as ready by any of the done, fail, or cancel methods. It can be
175    called either as a class method, or as an instance method. Called on an
176    instance it will construct another in the same class, and is useful for
177    subclassing.
178
179    This constructor would primarily be used by implementations of
180    asynchronous interfaces.
181
182 done (class method)
183
184 fail (class method)
185
186       $future = Future->done( @values )
187
188       $future = Future->fail( $exception, $category, @details )
189
190    Since version 0.26.
191
192    Shortcut wrappers around creating a new Future then immediately marking
193    it as done or failed.
194
195 wrap
196
197       $future = Future->wrap( @values )
198
199    Since version 0.14.
200
201    If given a single argument which is already a Future reference, this
202    will be returned unmodified. Otherwise, returns a new Future instance
203    that is already complete, and will yield the given values.
204
205    This will ensure that an incoming argument is definitely a Future, and
206    may be useful in such cases as adapting synchronous code to fit
207    asynchronous libraries driven by Future.
208
209 call
210
211       $future = Future->call( \&code, @args )
212
213    Since version 0.15.
214
215    A convenient wrapper for calling a CODE reference that is expected to
216    return a future. In normal circumstances is equivalent to
217
218       $future = $code->( @args )
219
220    except that if the code throws an exception, it is wrapped in a new
221    immediate fail future. If the return value from the code is not a
222    blessed Future reference, an immediate fail future is returned instead
223    to complain about this fact.
224
225METHODS
226
227    As there are a lare number of methods on this class, they are
228    documented here in several sections.
229
230INSPECTION METHODS
231
232    The following methods query the internal state of a Future instance
233    without modifying it or otherwise causing side-effects.
234
235 is_ready
236
237       $ready = $future->is_ready
238
239    Returns true on a leaf future if a result has been provided to the done
240    method, failed using the fail method, or cancelled using the cancel
241    method.
242
243    Returns true on a convergent future if it is ready to yield a result,
244    depending on its component futures.
245
246 is_done
247
248       $done = $future->is_done
249
250    Returns true on a future if it is ready and completed successfully.
251    Returns false if it is still pending, failed, or was cancelled.
252
253 is_failed
254
255       $failed = $future->is_failed
256
257    Since version 0.26.
258
259    Returns true on a future if it is ready and it failed. Returns false if
260    it is still pending, completed successfully, or was cancelled.
261
262 is_cancelled
263
264       $cancelled = $future->is_cancelled
265
266    Returns true if the future has been cancelled by cancel.
267
268 state
269
270       $str = $future->state
271
272    Since version 0.36.
273
274    Returns a string describing the state of the future, as one of the
275    three states named above; namely done, failed or cancelled, or pending
276    if it is none of these.
277
278IMPLEMENTATION METHODS
279
280    These methods would primarily be used by implementations of
281    asynchronous interfaces.
282
283 done
284
285       $future->done( @result )
286
287    Marks that the leaf future is now ready, and provides a list of values
288    as a result. (The empty list is allowed, and still indicates the future
289    as ready). Cannot be called on a convergent future.
290
291    If the future is already cancelled, this request is ignored. If the
292    future is already complete with a result or a failure, an exception is
293    thrown.
294
295    Since version 0.45: this method is also available under the name
296    resolve.
297
298 fail
299
300       $future->fail( $exception, $category, @details )
301
302    Marks that the leaf future has failed, and provides an exception value.
303    This exception will be thrown by the get method if called.
304
305    The exception must evaluate as a true value; false exceptions are not
306    allowed. A failure category name and other further details may be
307    provided that will be returned by the failure method in list context.
308
309    If the future is already cancelled, this request is ignored. If the
310    future is already complete with a result or a failure, an exception is
311    thrown.
312
313    If passed a Future::Exception instance (i.e. an object previously
314    thrown by the get), the additional details will be preserved. This
315    allows the additional details to be transparently preserved by such
316    code as
317
318       ...
319       catch {
320          return Future->fail($@);
321       }
322
323    Since version 0.45: this method is also available under the name
324    reject.
325
326 die
327
328       $future->die( $message, $category, @details )
329
330    Since version 0.09.
331
332    A convenient wrapper around fail. If the exception is a non-reference
333    that does not end in a linefeed, its value will be extended by the file
334    and line number of the caller, similar to the logic that die uses.
335
336    Returns the $future.
337
338 on_cancel
339
340       $future->on_cancel( $code )
341
342    If the future is not yet ready, adds a callback to be invoked if the
343    future is cancelled by the cancel method. If the future is already
344    ready the method is ignored.
345
346    If the future is later cancelled, the callbacks will be invoked in the
347    reverse order to that in which they were registered.
348
349       $on_cancel->( $future )
350
351    If passed another Future instance, the passed instance will be
352    cancelled when the original future is cancelled. In this case, the
353    reference is only strongly held while the target future remains
354    pending. If it becomes ready, then there is no point trying to cancel
355    it, and so it is removed from the originating future's cancellation
356    list.
357
358USER METHODS
359
360    These methods would primarily be used by users of asynchronous
361    interfaces, on objects returned by such an interface.
362
363 on_ready
364
365       $future->on_ready( $code )
366
367    If the future is not yet ready, adds a callback to be invoked when the
368    future is ready. If the future is already ready, invokes it
369    immediately.
370
371    In either case, the callback will be passed the future object itself.
372    The invoked code can then obtain the list of results by calling the get
373    method.
374
375       $on_ready->( $future )
376
377    If passed another Future instance, the passed instance will have its
378    done, fail or cancel methods invoked when the original future completes
379    successfully, fails, or is cancelled respectively.
380
381    Returns the $future.
382
383 result
384
385       @result = $future->result
386
387       $result = $future->result
388
389    Since version 0.44.
390
391    If the future is ready and completed successfully, returns the list of
392    results that had earlier been given to the done method on a leaf
393    future, or the list of component futures it was waiting for on a
394    convergent future. In scalar context it returns just the first result
395    value.
396
397    If the future is ready but failed, this method raises as an exception
398    the failure that was given to the fail method. If additional details
399    were given to the fail method, an exception object is constructed to
400    wrap them of type Future::Exception.
401
402    If the future was cancelled or is not yet ready an exception is thrown.
403
404 get
405
406       @result = $future->get
407
408       $result = $future->get
409
410    If the future is ready, returns the result or throws the failure
411    exception as per "result".
412
413    If it is not yet ready then "await" is invoked to wait for a ready
414    state, and the result returned as above.
415
416 await
417
418       $f = $f->await
419
420    Since version 0.44.
421
422    Blocks until the future instance is no longer pending.
423
424    Returns the invocant future itself, so it is useful for chaining.
425
426    Usually, calling code would either force the future using "get", or use
427    either then chaining or async/await syntax to wait for results. This
428    method is useful in cases where the exception-throwing part of get is
429    not required, perhaps because other code will be testing the result
430    using "is_done" or similar.
431
432       if( $f->await->is_done ) {
433          ...
434       }
435
436    This method is intended for subclasses to override. The default
437    implementation will throw an exception if called on a still-pending
438    instance.
439
440 block_until_ready
441
442       $f = $f->block_until_ready
443
444    Since version 0.40.
445
446    Now a synonym for "await". New code should invoke await directly.
447
448 unwrap
449
450       @values = Future->unwrap( @values )
451
452    Since version 0.26.
453
454    If given a single argument which is a Future reference, this method
455    will call get on it and return the result. Otherwise, it returns the
456    list of values directly in list context, or the first value in scalar.
457    Since it involves an implicit blocking wait, this method can only be
458    used on immediate futures or subclasses that implement "await".
459
460    This will ensure that an outgoing argument is definitely not a Future,
461    and may be useful in such cases as adapting synchronous code to fit
462    asynchronous libraries that return Future instances.
463
464 on_done
465
466       $future->on_done( $code )
467
468    If the future is not yet ready, adds a callback to be invoked when the
469    future is ready, if it completes successfully. If the future completed
470    successfully, invokes it immediately. If it failed or was cancelled, it
471    is not invoked at all.
472
473    The callback will be passed the result passed to the done method.
474
475       $on_done->( @result )
476
477    If passed another Future instance, the passed instance will have its
478    done method invoked when the original future completes successfully.
479
480    Returns the $future.
481
482 failure
483
484       $exception = $future->failure
485
486       $exception, $category, @details = $future->failure
487
488    If the future is ready, returns the exception passed to the fail method
489    or undef if the future completed successfully via the done method.
490
491    If it is not yet ready then "await" is invoked to wait for a ready
492    state.
493
494    If called in list context, will additionally yield the category name
495    and list of the details provided to the fail method.
496
497    Because the exception value must be true, this can be used in a simple
498    if statement:
499
500       if( my $exception = $future->failure ) {
501          ...
502       }
503       else {
504          my @result = $future->result;
505          ...
506       }
507
508 on_fail
509
510       $future->on_fail( $code )
511
512    If the future is not yet ready, adds a callback to be invoked when the
513    future is ready, if it fails. If the future has already failed, invokes
514    it immediately. If it completed successfully or was cancelled, it is
515    not invoked at all.
516
517    The callback will be passed the exception and other details passed to
518    the fail method.
519
520       $on_fail->( $exception, $category, @details )
521
522    If passed another Future instance, the passed instance will have its
523    fail method invoked when the original future fails.
524
525    To invoke a done method on a future when another one fails, use a CODE
526    reference:
527
528       $future->on_fail( sub { $f->done( @_ ) } );
529
530    Returns the $future.
531
532 cancel
533
534       $future->cancel
535
536    Requests that the future be cancelled, immediately marking it as ready.
537    This will invoke all of the code blocks registered by on_cancel, in the
538    reverse order. When called on a convergent future, all its component
539    futures are also cancelled. It is not an error to attempt to cancel a
540    future that is already complete or cancelled; it simply has no effect.
541
542    Returns the $future.
543
544SEQUENCING METHODS
545
546    The following methods all return a new future to represent the
547    combination of its invocant followed by another action given by a code
548    reference. The combined activity waits for the first future to be
549    ready, then may invoke the code depending on the success or failure of
550    the first, or may run it regardless. The returned sequence future
551    represents the entire combination of activity.
552
553    The invoked code could return a future, or a result directly.
554
555    Since version 0.45: if a non-future result is returned it will be
556    wrapped in a new immediate Future instance. This behaviour can be
557    disabled by setting the PERL_FUTURE_STRICT environment variable to a
558    true value at compiletime:
559
560       $ PERL_FUTURE_STRICT=1 perl ...
561
562    The combined future will then wait for the result of this second one.
563    If the combinined future is cancelled, it will cancel either the first
564    future or the second, depending whether the first had completed. If the
565    code block throws an exception instead of returning a value, the
566    sequence future will fail with that exception as its message and no
567    further values.
568
569    Note that since the code is invoked in scalar context, you cannot
570    directly return a list of values this way. Any list-valued results must
571    be done by returning a Future instance.
572
573       sub {
574          ...
575          return Future->done( @results );
576       }
577
578    As it is always a mistake to call these sequencing methods in void
579    context and lose the reference to the returned future (because
580    exception/error handling would be silently dropped), this method warns
581    in void context.
582
583 then
584
585       $future = $f1->then( \&done_code )
586
587    Since version 0.13.
588
589    Returns a new sequencing Future that runs the code if the first
590    succeeds. Once $f1 succeeds the code reference will be invoked and is
591    passed the list of results. It should return a future, $f2. Once $f2
592    completes the sequence future will then be marked as complete with
593    whatever result $f2 gave. If $f1 fails then the sequence future will
594    immediately fail with the same failure and the code will not be
595    invoked.
596
597       $f2 = $done_code->( @result )
598
599 else
600
601       $future = $f1->else( \&fail_code )
602
603    Since version 0.13.
604
605    Returns a new sequencing Future that runs the code if the first fails.
606    Once $f1 fails the code reference will be invoked and is passed the
607    failure and other details. It should return a future, $f2. Once $f2
608    completes the sequence future will then be marked as complete with
609    whatever result $f2 gave. If $f1 succeeds then the sequence future will
610    immediately succeed with the same result and the code will not be
611    invoked.
612
613       $f2 = $fail_code->( $exception, $category, @details )
614
615 then (2 arguments)
616
617       $future = $f1->then( \&done_code, \&fail_code )
618
619    The then method can also be passed the $fail_code block as well, giving
620    a combination of then and else behaviour.
621
622    This operation is similar to those provided by other future systems,
623    such as Javascript's Q or Promises/A libraries.
624
625 catch
626
627       $future = $f1->catch(
628          name => \&code,
629          name => \&code, ...
630       )
631
632    Since version 0.33.
633
634    Returns a new sequencing Future that behaves like an else call which
635    dispatches to a choice of several alternative handling functions
636    depending on the kind of failure that occurred. If $f1 fails with a
637    category name (i.e. the second argument to the fail call) which exactly
638    matches one of the string names given, then the corresponding code is
639    invoked, being passed the same arguments as a plain else call would
640    take, and is expected to return a Future in the same way.
641
642       $f2 = $code->( $exception, $category, @details )
643
644    If $f1 does not fail, fails without a category name at all, or fails
645    with a category name that does not match any given to the catch method,
646    then the returned sequence future immediately completes with the same
647    result, and no block of code is invoked.
648
649    If passed an odd-sized list, the final argument gives a function to
650    invoke on failure if no other handler matches.
651
652       $future = $f1->catch(
653          name => \&code, ...
654          \&fail_code,
655       )
656
657    This feature is currently still a work-in-progress. It currently can
658    only cope with category names that are literal strings, which are all
659    distinct. A later version may define other kinds of match (e.g.
660    regexp), may specify some sort of ordering on the arguments, or any of
661    several other semantic extensions. For more detail on the ongoing
662    design, see https://rt.cpan.org/Ticket/Display.html?id=103545.
663
664 then (multiple arguments)
665
666       $future = $f1->then( \&done_code, @catch_list, \&fail_code )
667
668    Since version 0.33.
669
670    The then method can be passed an even-sized list inbetween the
671    $done_code and the $fail_code, with the same meaning as the catch
672    method.
673
674 transform
675
676       $future = $f1->transform( %args )
677
678    Returns a new sequencing Future that wraps the one given as $f1. With
679    no arguments this will be a trivial wrapper; $future will complete or
680    fail when $f1 does, and $f1 will be cancelled when $future is.
681
682    By passing the following named arguments, the returned $future can be
683    made to behave differently to $f1:
684
685    done => CODE
686
687      Provides a function to use to modify the result of a successful
688      completion. When $f1 completes successfully, the result of its get
689      method is passed into this function, and whatever it returns is
690      passed to the done method of $future
691
692    fail => CODE
693
694      Provides a function to use to modify the result of a failure. When
695      $f1 fails, the result of its failure method is passed into this
696      function, and whatever it returns is passed to the fail method of
697      $future.
698
699 then_with_f
700
701       $future = $f1->then_with_f( ... )
702
703    Since version 0.21.
704
705    Returns a new sequencing Future that behaves like then, but also passes
706    the original future, $f1, to any functions it invokes.
707
708       $f2 = $done_code->( $f1, @result )
709       $f2 = $catch_code->( $f1, $category, @details )
710       $f2 = $fail_code->( $f1, $category, @details )
711
712    This is useful for conditional execution cases where the code block may
713    just return the same result of the original future. In this case it is
714    more efficient to return the original future itself.
715
716 then_done
717
718 then_fail
719
720       $future = $f->then_done( @result )
721
722       $future = $f->then_fail( $exception, $category, @details )
723
724    Since version 0.22.
725
726    Convenient shortcuts to returning an immediate future from a then
727    block, when the result is already known.
728
729 else_with_f
730
731       $future = $f1->else_with_f( \&code )
732
733    Since version 0.21.
734
735    Returns a new sequencing Future that runs the code if the first fails.
736    Identical to else, except that the code reference will be passed both
737    the original future, $f1, and its exception and other details.
738
739       $f2 = $code->( $f1, $exception, $category, @details )
740
741    This is useful for conditional execution cases where the code block may
742    just return the same result of the original future. In this case it is
743    more efficient to return the original future itself.
744
745 else_done
746
747 else_fail
748
749       $future = $f->else_done( @result )
750
751       $future = $f->else_fail( $exception, $category, @details )
752
753    Since version 0.22.
754
755    Convenient shortcuts to returning an immediate future from a else
756    block, when the result is already known.
757
758 catch_with_f
759
760       $future = $f1->catch_with_f( ... )
761
762    Since version 0.33.
763
764    Returns a new sequencing Future that behaves like catch, but also
765    passes the original future, $f1, to any functions it invokes.
766
767 followed_by
768
769       $future = $f1->followed_by( \&code )
770
771    Returns a new sequencing Future that runs the code regardless of
772    success or failure. Once $f1 is ready the code reference will be
773    invoked and is passed one argument, $f1. It should return a future,
774    $f2. Once $f2 completes the sequence future will then be marked as
775    complete with whatever result $f2 gave.
776
777       $f2 = $code->( $f1 )
778
779 without_cancel
780
781       $future = $f1->without_cancel
782
783    Since version 0.30.
784
785    Returns a new sequencing Future that will complete with the success or
786    failure of the original future, but if cancelled, will not cancel the
787    original. This may be useful if the original future represents an
788    operation that is being shared among multiple sequences; cancelling one
789    should not prevent the others from running too.
790
791    Note that this only prevents cancel propagating from $future to $f1; if
792    the original $f1 instance is cancelled then the returned $future will
793    have to be cancelled too.
794
795 retain
796
797       $f = $f->retain
798
799    Since version 0.36.
800
801    Creates a reference cycle which causes the future to remain in memory
802    until it completes. Returns the invocant future.
803
804    In normal situations, a Future instance does not strongly hold a
805    reference to other futures that it is feeding a result into, instead
806    relying on that to be handled by application logic. This is normally
807    fine because some part of the application will retain the top-level
808    Future, which then strongly refers to each of its components down in a
809    tree. However, certain design patterns, such as mixed Future-based and
810    legacy callback-based API styles might end up creating Futures simply
811    to attach callback functions to them. In that situation, without
812    further attention, the Future may get lost due to having no strong
813    references to it. Calling ->retain on it creates such a reference which
814    ensures it persists until it completes. For example:
815
816       Future->needs_all( $fA, $fB )
817          ->on_done( $on_done )
818          ->on_fail( $on_fail )
819          ->retain;
820
821CONVERGENT FUTURES
822
823    The following constructors all take a list of component futures, and
824    return a new future whose readiness somehow depends on the readiness of
825    those components. The first derived class component future will be used
826    as the prototype for constructing the return value, so it respects
827    subclassing correctly, or failing that a plain Future.
828
829 wait_all
830
831       $future = Future->wait_all( @subfutures )
832
833    Returns a new Future instance that will indicate it is ready once all
834    of the sub future objects given to it indicate that they are ready,
835    either by success, failure or cancellation. Its result will be a list
836    of its component futures.
837
838    When given an empty list this constructor returns a new
839    immediately-done future.
840
841    This constructor would primarily be used by users of asynchronous
842    interfaces.
843
844 wait_any
845
846       $future = Future->wait_any( @subfutures )
847
848    Returns a new Future instance that will indicate it is ready once any
849    of the sub future objects given to it indicate that they are ready,
850    either by success or failure. Any remaining component futures that are
851    not yet ready will be cancelled. Its result will be the result of the
852    first component future that was ready; either success or failure. Any
853    component futures that are cancelled are ignored, apart from the final
854    component left; at which point the result will be a failure.
855
856    When given an empty list this constructor returns an immediately-failed
857    future.
858
859    This constructor would primarily be used by users of asynchronous
860    interfaces.
861
862 needs_all
863
864       $future = Future->needs_all( @subfutures )
865
866    Returns a new Future instance that will indicate it is ready once all
867    of the sub future objects given to it indicate that they have completed
868    successfully, or when any of them indicates that they have failed. If
869    any sub future fails, then this will fail immediately, and the
870    remaining subs not yet ready will be cancelled. Any component futures
871    that are cancelled will cause an immediate failure of the result.
872
873    If successful, its result will be a concatenated list of the results of
874    all its component futures, in corresponding order. If it fails, its
875    failure will be that of the first component future that failed. To
876    access each component future's results individually, use done_futures.
877
878    When given an empty list this constructor returns a new
879    immediately-done future.
880
881    This constructor would primarily be used by users of asynchronous
882    interfaces.
883
884 needs_any
885
886       $future = Future->needs_any( @subfutures )
887
888    Returns a new Future instance that will indicate it is ready once any
889    of the sub future objects given to it indicate that they have completed
890    successfully, or when all of them indicate that they have failed. If
891    any sub future succeeds, then this will succeed immediately, and the
892    remaining subs not yet ready will be cancelled. Any component futures
893    that are cancelled are ignored, apart from the final component left; at
894    which point the result will be a failure.
895
896    If successful, its result will be that of the first component future
897    that succeeded. If it fails, its failure will be that of the last
898    component future to fail. To access the other failures, use
899    failed_futures.
900
901    Normally when this future completes successfully, only one of its
902    component futures will be done. If it is constructed with multiple that
903    are already done however, then all of these will be returned from
904    done_futures. Users should be careful to still check all the results
905    from done_futures in that case.
906
907    When given an empty list this constructor returns an immediately-failed
908    future.
909
910    This constructor would primarily be used by users of asynchronous
911    interfaces.
912
913METHODS ON CONVERGENT FUTURES
914
915    The following methods apply to convergent (i.e. non-leaf) futures, to
916    access the component futures stored by it.
917
918 pending_futures
919
920       @f = $future->pending_futures
921
922 ready_futures
923
924       @f = $future->ready_futures
925
926 done_futures
927
928       @f = $future->done_futures
929
930 failed_futures
931
932       @f = $future->failed_futures
933
934 cancelled_futures
935
936       @f = $future->cancelled_futures
937
938    Return a list of all the pending, ready, done, failed, or cancelled
939    component futures. In scalar context, each will yield the number of
940    such component futures.
941
942TRACING METHODS
943
944 set_label
945
946 label
947
948       $future = $future->set_label( $label )
949
950       $label = $future->label
951
952    Since version 0.28.
953
954    Chaining mutator and accessor for the label of the Future. This should
955    be a plain string value, whose value will be stored by the future
956    instance for use in debugging messages or other tooling, or similar
957    purposes.
958
959 btime
960
961 rtime
962
963       [ $sec, $usec ] = $future->btime
964
965       [ $sec, $usec ] = $future->rtime
966
967    Since version 0.28.
968
969    Accessors that return the tracing timestamps from the instance. These
970    give the time the instance was constructed ("birth" time, btime) and
971    the time the result was determined (the "ready" time, rtime). Each
972    result is returned as a two-element ARRAY ref, containing the epoch
973    time in seconds and microseconds, as given by
974    Time::HiRes::gettimeofday.
975
976    In order for these times to be captured, they have to be enabled by
977    setting $Future::TIMES to a true value. This is initialised true at the
978    time the module is loaded if either PERL_FUTURE_DEBUG or
979    PERL_FUTURE_TIMES are set in the environment.
980
981 elapsed
982
983       $sec = $future->elapsed
984
985    Since version 0.28.
986
987    If both tracing timestamps are defined, returns the number of seconds
988    of elapsed time between them as a floating-point number. If not,
989    returns undef.
990
991 wrap_cb
992
993       $cb = $future->wrap_cb( $operation_name, $cb )
994
995    Since version 0.31.
996
997    Note: This method is experimental and may be changed or removed in a
998    later version.
999
1000    This method is invoked internally by various methods that are about to
1001    save a callback CODE reference supplied by the user, to be invoked
1002    later. The default implementation simply returns the callback argument
1003    as-is; the method is provided to allow users to provide extra
1004    behaviour. This can be done by applying a method modifier of the around
1005    kind, so in effect add a chain of wrappers. Each wrapper can then
1006    perform its own wrapping logic of the callback. $operation_name is a
1007    string giving the reason for which the callback is being saved;
1008    currently one of on_ready, on_done, on_fail or sequence; the latter
1009    being used for all the sequence-returning methods.
1010
1011    This method is intentionally invoked only for CODE references that are
1012    being saved on a pending Future instance to be invoked at some later
1013    point. It does not run for callbacks to be invoked on an
1014    already-complete instance. This is for performance reasons, where the
1015    intended behaviour is that the wrapper can provide some amount of
1016    context save and restore, to return the operating environment for the
1017    callback back to what it was at the time it was saved.
1018
1019    For example, the following wrapper saves the value of a package
1020    variable at the time the callback was saved, and restores that value at
1021    invocation time later on. This could be useful for preserving context
1022    during logging in a Future-based program.
1023
1024       our $LOGGING_CTX;
1025
1026       no warnings 'redefine';
1027
1028       my $orig = Future->can( "wrap_cb" );
1029       *Future::wrap_cb = sub {
1030          my $cb = $orig->( @_ );
1031
1032          my $saved_logging_ctx = $LOGGING_CTX;
1033
1034          return sub {
1035             local $LOGGING_CTX = $saved_logging_ctx;
1036             $cb->( @_ );
1037          };
1038       };
1039
1040    At this point, any code deferred into a Future by any of its callbacks
1041    will observe the $LOGGING_CTX variable as having the value it held at
1042    the time the callback was saved, even if it is invoked later on when
1043    that value is different.
1044
1045    Remember when writing such a wrapper, that it still needs to invoke the
1046    previous version of the method, so that it plays nicely in combination
1047    with others (see the $orig->( @_ ) part).
1048
1049EXAMPLES
1050
1051    The following examples all demonstrate possible uses of a Future object
1052    to provide a fictional asynchronous API.
1053
1054    For more examples, comparing the use of Future with regular call/return
1055    style Perl code, see also Future::Phrasebook.
1056
1057 Providing Results
1058
1059    By returning a new Future object each time the asynchronous function is
1060    called, it provides a placeholder for its eventual result, and a way to
1061    indicate when it is complete.
1062
1063       sub foperation
1064       {
1065          my %args = @_;
1066
1067          my $future = Future->new;
1068
1069          do_something_async(
1070             foo => $args{foo},
1071             on_done => sub { $future->done( @_ ); },
1072          );
1073
1074          return $future;
1075       }
1076
1077    In most cases, the done method will simply be invoked with the entire
1078    result list as its arguments. In that case, it is convenient to use the
1079    curry module to form a CODE reference that would invoke the done
1080    method.
1081
1082        my $future = Future->new;
1083
1084        do_something_async(
1085           foo => $args{foo},
1086           on_done => $future->curry::done,
1087        );
1088
1089    The caller may then use this future to wait for a result using the
1090    on_ready method, and obtain the result using get.
1091
1092       my $f = foperation( foo => "something" );
1093
1094       $f->on_ready( sub {
1095          my $f = shift;
1096          say "The operation returned: ", $f->result;
1097       } );
1098
1099 Indicating Success or Failure
1100
1101    Because the stored exception value of a failed future may not be false,
1102    the failure method can be used in a conditional statement to detect
1103    success or failure.
1104
1105       my $f = foperation( foo => "something" );
1106
1107       $f->on_ready( sub {
1108          my $f = shift;
1109          if( not my $e = $f->failure ) {
1110             say "The operation succeeded with: ", $f->result;
1111          }
1112          else {
1113             say "The operation failed with: ", $e;
1114          }
1115       } );
1116
1117    By using not in the condition, the order of the if blocks can be
1118    arranged to put the successful case first, similar to a try/catch
1119    block.
1120
1121    Because the get method re-raises the passed exception if the future
1122    failed, it can be used to control a try/catch block directly. (This is
1123    sometimes called Exception Hoisting).
1124
1125       use Syntax::Keyword::Try;
1126
1127       $f->on_ready( sub {
1128          my $f = shift;
1129          try {
1130             say "The operation succeeded with: ", $f->result;
1131          }
1132          catch {
1133             say "The operation failed with: ", $_;
1134          }
1135       } );
1136
1137    Even neater still may be the separate use of the on_done and on_fail
1138    methods.
1139
1140       $f->on_done( sub {
1141          my @result = @_;
1142          say "The operation succeeded with: ", @result;
1143       } );
1144       $f->on_fail( sub {
1145          my ( $failure ) = @_;
1146          say "The operation failed with: $failure";
1147       } );
1148
1149 Immediate Futures
1150
1151    Because the done method returns the future object itself, it can be
1152    used to generate a Future that is immediately ready with a result. This
1153    can also be used as a class method.
1154
1155       my $f = Future->done( $value );
1156
1157    Similarly, the fail and die methods can be used to generate a Future
1158    that is immediately failed.
1159
1160       my $f = Future->die( "This is never going to work" );
1161
1162    This could be considered similarly to a die call.
1163
1164    An eval{} block can be used to turn a Future-returning function that
1165    might throw an exception, into a Future that would indicate this
1166    failure.
1167
1168       my $f = eval { function() } || Future->fail( $@ );
1169
1170    This is neater handled by the call class method, which wraps the call
1171    in an eval{} block and tests the result:
1172
1173       my $f = Future->call( \&function );
1174
1175 Sequencing
1176
1177    The then method can be used to create simple chains of dependent tasks,
1178    each one executing and returning a Future when the previous operation
1179    succeeds.
1180
1181       my $f = do_first()
1182                  ->then( sub {
1183                     return do_second();
1184                  })
1185                  ->then( sub {
1186                     return do_third();
1187                  });
1188
1189    The result of the $f future itself will be the result of the future
1190    returned by the final function, if none of them failed. If any of them
1191    fails it will fail with the same failure. This can be considered
1192    similar to normal exception handling in synchronous code; the first
1193    time a function call throws an exception, the subsequent calls are not
1194    made.
1195
1196 Merging Control Flow
1197
1198    A wait_all future may be used to resynchronise control flow, while
1199    waiting for multiple concurrent operations to finish.
1200
1201       my $f1 = foperation( foo => "something" );
1202       my $f2 = foperation( bar => "something else" );
1203
1204       my $f = Future->wait_all( $f1, $f2 );
1205
1206       $f->on_ready( sub {
1207          say "Operations are ready:";
1208          say "  foo: ", $f1->result;
1209          say "  bar: ", $f2->result;
1210       } );
1211
1212    This provides an ability somewhat similar to CPS::kpar() or
1213    Async::MergePoint.
1214
1215KNOWN ISSUES
1216
1217 Cancellation of Non-Final Sequence Futures
1218
1219    The behaviour of future cancellation still has some unanswered
1220    questions regarding how to handle the situation where a future is
1221    cancelled that has a sequence future constructed from it.
1222
1223    In particular, it is unclear in each of the following examples what the
1224    behaviour of $f2 should be, were $f1 to be cancelled:
1225
1226       $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1227
1228       $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1229
1230       $f2 = $f1->followed_by( sub { ... } );
1231
1232    In the then-style case it is likely that this situation should be
1233    treated as if $f1 had failed, perhaps with some special message. The
1234    else-style case is more complex, because it may be that the entire
1235    operation should still fail, or it may be that the cancellation of $f1
1236    should again be treated simply as a special kind of failure, and the
1237    else logic run as normal.
1238
1239    To be specific; in each case it is unclear what happens if the first
1240    future is cancelled, while the second one is still waiting on it. The
1241    semantics for "normal" top-down cancellation of $f2 and how it affects
1242    $f1 are already clear and defined.
1243
1244 Cancellation of Divergent Flow
1245
1246    A further complication of cancellation comes from the case where a
1247    given future is reused multiple times for multiple sequences or
1248    convergent trees.
1249
1250    In particular, it is in clear in each of the following examples what
1251    the behaviour of $f2 should be, were $f1 to be cancelled:
1252
1253       my $f_initial = Future->new; ...
1254       my $f1 = $f_initial->then( ... );
1255       my $f2 = $f_initial->then( ... );
1256
1257       my $f1 = Future->needs_all( $f_initial );
1258       my $f2 = Future->needs_all( $f_initial );
1259
1260    The point of cancellation propagation is to trace backwards through
1261    stages of some larger sequence of operations that now no longer need to
1262    happen, because the final result is no longer required. But in each of
1263    these cases, just because $f1 has been cancelled, the initial future
1264    $f_initial is still required because there is another future ($f2) that
1265    will still require its result.
1266
1267    Initially it would appear that some kind of reference-counting
1268    mechanism could solve this question, though that itself is further
1269    complicated by the on_ready handler and its variants.
1270
1271    It may simply be that a comprehensive useful set of cancellation
1272    semantics can't be universally provided to cover all cases; and that
1273    some use-cases at least would require the application logic to give
1274    extra information to its Future objects on how they should wire up the
1275    cancel propagation logic.
1276
1277    Both of these cancellation issues are still under active design
1278    consideration; see the discussion on RT96685 for more information
1279    (https://rt.cpan.org/Ticket/Display.html?id=96685).
1280
1281SEE ALSO
1282
1283      * Future::AsyncAwait - deferred subroutine syntax for futures
1284
1285      Provides a neat syntax extension for writing future-based code.
1286
1287      * Future::IO - Future-returning IO methods
1288
1289      Provides methods similar to core IO functions, which yield results by
1290      Futures.
1291
1292      * Promises - an implementation of the "Promise/A+" pattern for
1293      asynchronous programming
1294
1295      A different alternative implementation of a similar idea.
1296
1297      * curry - Create automatic curried method call closures for any class
1298      or object
1299
1300      * "The Past, The Present and The Future" - slides from a talk given
1301      at the London Perl Workshop, 2012.
1302
1303      https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit
1304
1305      * "Futures advent calendar 2013"
1306
1307      http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html
1308
1309      * "Asynchronous Programming with Futures" - YAPC::EU 2014
1310
1311      https://www.youtube.com/watch?v=u9dZgFM6FtE
1312
1313TODO
1314
1315      * Consider the ability to pass the constructor a block CODEref,
1316      instead of needing to use a subclass. This might simplify async/etc..
1317      implementations, and allows the reuse of the idea of subclassing to
1318      extend the abilities of Future itself - for example to allow a kind
1319      of Future that can report incremental progress.
1320
1321AUTHOR
1322
1323    Paul Evans <leonerd@leonerd.org.uk>
1324
1325