Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/Future.pm view on Meta::CPAN
# You may distribute under the terms of either the GNU General Public License
# or the Artistic License (the same terms as Perl itself)
#
# (C) Paul Evans, 2011-2016 -- leonerd@leonerd.org.uk
package Future;
use strict;
use warnings;
no warnings 'recursion'; # Disable the "deep recursion" warning
our $VERSION = '0.34';
use Carp qw(); # don't import croak
use Scalar::Util qw( weaken blessed reftype );
use B qw( svref_2object );
use Time::HiRes qw( gettimeofday tv_interval );
# we are not overloaded, but we want to check if other objects are
require overload;
our @CARP_NOT = qw( Future::Utils );
use constant DEBUG => $ENV{PERL_FUTURE_DEBUG};
our $TIMES = DEBUG || $ENV{PERL_FUTURE_TIMES};
=head1 NAME
C<Future> - represent an operation awaiting completion
=head1 SYNOPSIS
my $future = Future->new;
perform_some_operation(
on_complete => sub {
$future->done( @_ );
}
);
$future->on_ready( sub {
say "The operation is complete";
} );
=head1 DESCRIPTION
A C<Future> object represents an operation that is currently in progress, or
has recently completed. It can be used in a variety of ways to manage the flow
of control, and data, through an asynchronous program.
Some futures represent a single operation and are explicitly marked as ready
by calling the C<done> or C<fail> methods. These are called "leaf" futures
here, and are returned by the C<new> constructor.
Other futures represent a collection of sub-tasks, and are implicitly marked
as ready depending on the readiness of their component futures as required.
These are called "convergent" futures here as they converge control and
data-flow back into one place. These are the ones returned by the various
C<wait_*> and C<need_*> constructors.
It is intended that library functions that perform asynchronous operations
would use future objects to represent outstanding operations, and allow their
calling programs to control or wait for these operations to complete. The
implementation and the user of such an interface would typically make use of
different methods on the class. The methods below are documented in two
sections; those of interest to each side of the interface.
It should be noted however, that this module does not in any way provide an
actual mechanism for performing this asynchronous activity; it merely provides
a way to create objects that can be used for control and data flow around
those operations. It allows such code to be written in a neater,
forward-reading manner, and simplifies many common patterns that are often
involved in such situations.
See also L<Future::Utils> which contains useful loop-constructing functions,
to run a future-returning function repeatedly in a loop.
Unless otherwise noted, the following methods require at least version
I<0.08>.
=head2 FAILURE CATEGORIES
While not directly required by C<Future> or its related modules, a growing
convention of C<Future>-using code is to encode extra semantics in the
arguments given to the C<fail> method, to represent different kinds of
failure.
The convention is that after the initial message string as the first required
argument (intended for display to humans), the second argument is a short
lowercase string that relates in some way to the kind of failure that
occurred. Following this is a list of details about that kind of failure,
whose exact arrangement or structure are determined by the failure category.
For example, L<IO::Async> and L<Net::Async::HTTP> use this convention to
indicate at what stage a given HTTP request has failed:
->fail( $message, http => ... ) # an HTTP-level error during protocol
->fail( $message, connect => ... ) # a TCP-level failure to connect a
# socket
->fail( $message, resolve => ... ) # a resolver (likely DNS) failure
# to resolve a hostname
By following this convention, a module remains consistent with other
local/lib/perl5/Future.pm view on Meta::CPAN
Remember when writing such a wrapper, that it still needs to invoke the
previous version of the method, so that it plays nicely in combination with
others (see the C<< $orig->( @_ ) >> part).
=cut
sub wrap_cb
{
my $self = shift;
my ( $op, $cb ) = @_;
return $cb;
}
=head1 EXAMPLES
The following examples all demonstrate possible uses of a C<Future>
object to provide a fictional asynchronous API.
For more examples, comparing the use of C<Future> with regular call/return
style Perl code, see also L<Future::Phrasebook>.
=head2 Providing Results
By returning a new C<Future> object each time the asynchronous function is
called, it provides a placeholder for its eventual result, and a way to
indicate when it is complete.
sub foperation
{
my %args = @_;
my $future = Future->new;
do_something_async(
foo => $args{foo},
on_done => sub { $future->done( @_ ); },
);
return $future;
}
In most cases, the C<done> method will simply be invoked with the entire
result list as its arguments. In that case, it is convenient to use the
L<curry> module to form a C<CODE> reference that would invoke the C<done>
method.
my $future = Future->new;
do_something_async(
foo => $args{foo},
on_done => $future->curry::done,
);
The caller may then use this future to wait for a result using the C<on_ready>
method, and obtain the result using C<get>.
my $f = foperation( foo => "something" );
$f->on_ready( sub {
my $f = shift;
say "The operation returned: ", $f->get;
} );
=head2 Indicating Success or Failure
Because the stored exception value of a failed future may not be false, the
C<failure> method can be used in a conditional statement to detect success or
failure.
my $f = foperation( foo => "something" );
$f->on_ready( sub {
my $f = shift;
if( not my $e = $f->failure ) {
say "The operation succeeded with: ", $f->get;
}
else {
say "The operation failed with: ", $e;
}
} );
By using C<not> in the condition, the order of the C<if> blocks can be
arranged to put the successful case first, similar to a C<try>/C<catch> block.
Because the C<get> method re-raises the passed exception if the future failed,
it can be used to control a C<try>/C<catch> block directly. (This is sometimes
called I<Exception Hoisting>).
use Try::Tiny;
$f->on_ready( sub {
my $f = shift;
try {
say "The operation succeeded with: ", $f->get;
}
catch {
say "The operation failed with: ", $_;
};
} );
Even neater still may be the separate use of the C<on_done> and C<on_fail>
methods.
$f->on_done( sub {
my @result = @_;
say "The operation succeeded with: ", @result;
} );
$f->on_fail( sub {
my ( $failure ) = @_;
say "The operation failed with: $failure";
} );
=head2 Immediate Futures
Because the C<done> method returns the future object itself, it can be used to
generate a C<Future> that is immediately ready with a result. This can also be
used as a class method.
my $f = Future->done( $value );
Similarly, the C<fail> and C<die> methods can be used to generate a C<Future>
that is immediately failed.
my $f = Future->die( "This is never going to work" );
This could be considered similarly to a C<die> call.
An C<eval{}> block can be used to turn a C<Future>-returning function that
might throw an exception, into a C<Future> that would indicate this failure.
my $f = eval { function() } || Future->fail( $@ );
This is neater handled by the C<call> class method, which wraps the call in
an C<eval{}> block and tests the result:
my $f = Future->call( \&function );
=head2 Sequencing
The C<then> method can be used to create simple chains of dependent tasks,
each one executing and returning a C<Future> when the previous operation
succeeds.
my $f = do_first()
->then( sub {
return do_second();
})
->then( sub {
return do_third();
});
The result of the C<$f> future itself will be the result of the future
returned by the final function, if none of them failed. If any of them fails
it will fail with the same failure. This can be considered similar to normal
exception handling in synchronous code; the first time a function call throws
an exception, the subsequent calls are not made.
=head2 Merging Control Flow
A C<wait_all> future may be used to resynchronise control flow, while waiting
for multiple concurrent operations to finish.
my $f1 = foperation( foo => "something" );
my $f2 = foperation( bar => "something else" );
my $f = Future->wait_all( $f1, $f2 );
$f->on_ready( sub {
say "Operations are ready:";
say " foo: ", $f1->get;
say " bar: ", $f2->get;
} );
This provides an ability somewhat similar to C<CPS::kpar()> or
L<Async::MergePoint>.
=cut
=head1 KNOWN ISSUES
=head2 Cancellation of Non-Final Sequence Futures
The behaviour of future cancellation still has some unanswered questions
regarding how to handle the situation where a future is cancelled that has a
sequence future constructed from it.
In particular, it is unclear in each of the following examples what the
behaviour of C<$f2> should be, were C<$f1> to be cancelled:
$f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
$f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
$f2 = $f1->followed_by( sub { ... } );
In the C<then>-style case it is likely that this situation should be treated
as if C<$f1> had failed, perhaps with some special message. The C<else>-style
case is more complex, because it may be that the entire operation should still
fail, or it may be that the cancellation of C<$f1> should again be treated
simply as a special kind of failure, and the C<else> logic run as normal.
To be specific; in each case it is unclear what happens if the first future is
cancelled, while the second one is still waiting on it. The semantics for
"normal" top-down cancellation of C<$f2> and how it affects C<$f1> are already
clear and defined.
=head2 Cancellation of Divergent Flow
A further complication of cancellation comes from the case where a given
future is reused multiple times for multiple sequences or convergent trees.
In particular, it is in clear in each of the following examples what the
behaviour of C<$f2> should be, were C<$f1> to be cancelled:
my $f_initial = Future->new; ...
my $f1 = $f_initial->then( ... );
my $f2 = $f_initial->then( ... );
my $f1 = Future->needs_all( $f_initial );
my $f2 = Future->needs_all( $f_initial );
The point of cancellation propagation is to trace backwards through stages of
some larger sequence of operations that now no longer need to happen, because
the final result is no longer required. But in each of these cases, just
because C<$f1> has been cancelled, the initial future C<$f_initial> is still
required because there is another future (C<$f2>) that will still require its
result.
Initially it would appear that some kind of reference-counting mechanism could
solve this question, though that itself is further complicated by the
C<on_ready> handler and its variants.
( run in 2.314 seconds using v1.01-cache-2.11-cpan-364913b4093 )