Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/Future.pm view on Meta::CPAN
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
C<Future>-based modules, and makes it easy for program logic to gracefully
handle and manage failures by use of the C<catch> method.
=head2 SUBCLASSING
This class easily supports being subclassed to provide extra behavior, such as
giving the C<get> method the ability to block and wait for completion. This
may be useful to provide C<Future> subclasses with event systems, or similar.
Each method that returns a new future object will use the invocant to
construct its return value. If the constructor needs to perform per-instance
setup it can override the C<new> method, and take context from the given
instance.
sub new
{
my $proto = shift;
my $self = $proto->SUPER::new;
if( ref $proto ) {
# Prototype was an instance
}
else {
# Prototype was a class
}
return $self;
}
If an instance provides a method called C<await>, this will be called by the
C<get> and C<failure> methods if the instance is pending.
$f->await
In most cases this should allow future-returning modules to be used as if they
were blocking call/return-style modules, by simply appending a C<get> call to
the function or method calls.
my ( $results, $here ) = future_returning_function( @args )->get;
The F<examples> directory in the distribution contains some examples of how
futures might be integrated with various event systems.
=head2 DEBUGGING
By the time a C<Future> object is destroyed, it ought to have been completed
or cancelled. By enabling debug tracing of objects, this fact can be checked.
local/lib/perl5/Future.pm view on Meta::CPAN
$self->{reported} = 1;
$is_future ? $code->fail( $self->failure )
: $code->( $self->failure );
}
else {
push @{ $self->{callbacks} }, [ CB_FAIL|CB_RESULT, $self->wrap_cb( on_fail => $code ) ];
}
return $self;
}
=head2 cancel
$future->cancel
Requests that the future be cancelled, immediately marking it as ready. This
will invoke all of the code blocks registered by C<on_cancel>, in the reverse
order. When called on a convergent future, all its component futures are also
cancelled. It is not an error to attempt to cancel a future that is already
complete or cancelled; it simply has no effect.
Returns the C<$future>.
=cut
sub cancel
{
my $self = shift;
return $self if $self->{ready};
$self->{cancelled}++;
foreach my $code ( reverse @{ $self->{on_cancel} || [] } ) {
my $is_future = blessed( $code ) && $code->isa( "Future" );
$is_future ? $code->cancel
: $code->( $self );
}
$self->_mark_ready( "cancel" );
return $self;
}
sub cancel_cb
{
my $self = shift;
return sub { $self->cancel };
}
=head1 SEQUENCING METHODS
The following methods all return a new future to represent the combination of
its invocant followed by another action given by a code reference. The
combined activity waits for the first future to be ready, then may invoke the
code depending on the success or failure of the first, or may run it
regardless. The returned sequence future represents the entire combination of
activity.
In some cases the code should return a future; in some it should return an
immediate result. If a future is returned, the combined future will then wait
for the result of this second one. If the combinined future is cancelled, it
will cancel either the first future or the second, depending whether the first
had completed. If the code block throws an exception instead of returning a
value, the sequence future will fail with that exception as its message and no
further values.
As it is always a mistake to call these sequencing methods in void context and lose the
reference to the returned future (because exception/error handling would be
silently dropped), this method warns in void context.
=cut
sub _sequence
{
my $f1 = shift;
my ( $code, $flags ) = @_;
# For later, we might want to know where we were called from
my $func = (caller 1)[3];
$func =~ s/^.*:://;
$flags & (CB_SEQ_IMDONE|CB_SEQ_IMFAIL) or _callable( $code ) or
Carp::croak "Expected \$code to be callable in ->$func";
if( !defined wantarray ) {
Carp::carp "Calling ->$func in void context";
}
if( $f1->is_ready ) {
# Take a shortcut
return $f1 if $f1->is_done and not( $flags & CB_SEQ_ONDONE ) or
$f1->failure and not( $flags & CB_SEQ_ONFAIL );
if( $flags & CB_SEQ_IMDONE ) {
return Future->done( @$code );
}
elsif( $flags & CB_SEQ_IMFAIL ) {
return Future->fail( @$code );
}
my @args = (
( $flags & CB_SELF ? $f1 : () ),
( $flags & CB_RESULT ? $f1->is_done ? $f1->get :
$f1->failure ? $f1->failure :
() : () ),
);
my $fseq;
unless( eval { $fseq = $code->( @args ); 1 } ) {
return Future->fail( $@ );
}
unless( blessed $fseq and $fseq->isa( "Future" ) ) {
return Future->fail( "Expected " . CvNAME_FILE_LINE($code) . " to return a Future" );
}
return $fseq;
}
my $fseq = $f1->new;
$fseq->on_cancel( $f1 );
local/lib/perl5/Future.pm view on Meta::CPAN
_callable( $catch_handlers{$_} ) or
Carp::croak "Expected catch handler for '$_' to be callable in ->$func"
for keys %catch_handlers;
sub {
my $self = shift;
my @maybe_self = $with_f ? ( $self ) : ();
if( !$self->{failure} ) {
return $self unless $done_code;
return $done_code->( @maybe_self, $self->get );
}
else {
my $name = $self->{failure}[1];
if( defined $name and $catch_handlers{$name} ) {
return $catch_handlers{$name}->( @maybe_self, $self->failure );
}
return $self unless $fail_code;
return $fail_code->( @maybe_self, $self->failure );
}
};
};
sub then
{
my $self = shift;
my $done_code = shift;
my $fail_code = ( @_ % 2 ) ? pop : undef;
my @catch_list = @_;
if( $done_code and !@catch_list and !$fail_code ) {
return $self->_sequence( $done_code, CB_SEQ_ONDONE|CB_RESULT );
}
# Complex
return $self->_sequence( $make_donecatchfail_sub->(
0, $done_code, $fail_code, @catch_list,
), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF );
}
sub else
{
my $self = shift;
my ( $fail_code ) = @_;
return $self->_sequence( $fail_code, CB_SEQ_ONFAIL|CB_RESULT );
}
=head2 catch
$future = $f1->catch(
name => \&code,
name => \&code, ...
)
I<Since version 0.33.>
Returns a new sequencing C<Future> that behaves like an C<else> call which
dispatches to a choice of several alternative handling functions depending on
the kind of failure that occurred. If C<$f1> fails with a category name (i.e.
the second argument to the C<fail> call) which exactly matches one of the
string names given, then the corresponding code is invoked, being passed the
same arguments as a plain C<else> call would take, and is expected to return a
C<Future> in the same way.
$f2 = $code->( $exception, $name, @other_details )
If C<$f1> does not fail, fails without a category name at all, or fails with a
category name that does not match any given to the C<catch> method, then the
returned sequence future immediately completes with the same result, and no
block of code is invoked.
If passed an odd-sized list, the final argument gives a function to invoke on
failure if no other handler matches.
$future = $f1->catch(
name => \&code, ...
\&fail_code,
)
This feature is currently still a work-in-progress. It currently can only cope
with category names that are literal strings, which are all distinct. A later
version may define other kinds of match (e.g. regexp), may specify some sort
of ordering on the arguments, or any of several other semantic extensions. For
more detail on the ongoing design, see
L<https://rt.cpan.org/Ticket/Display.html?id=103545>.
=head2 then I<(multiple arguments)>
$future = $f1->then( \&done_code, @catch_list, \&fail_code )
I<Since version 0.33.>
The C<then> method can be passed an even-sized list inbetween the
C<$done_code> and the C<$fail_code>, with the same meaning as the C<catch>
method.
=cut
sub catch
{
my $self = shift;
my $fail_code = ( @_ % 2 ) ? pop : undef;
my @catch_list = @_;
return $self->_sequence( $make_donecatchfail_sub->(
0, undef, $fail_code, @catch_list,
), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF );
}
=head2 transform
$future = $f1->transform( %args )
Returns a new sequencing C<Future> that wraps the one given as C<$f1>. With no
arguments this will be a trivial wrapper; C<$future> will complete or fail
when C<$f1> does, and C<$f1> will be cancelled when C<$future> is.
By passing the following named arguments, the returned C<$future> can be made
to behave differently to C<$f1>:
local/lib/perl5/Future.pm view on Meta::CPAN
$self->{subs} or Carp::croak "Cannot call ->done_futures on a non-convergent Future";
return grep { $_->{ready} and not $_->{failure} and not $_->{cancelled} } @{ $self->{subs} };
}
sub failed_futures
{
my $self = shift;
$self->{subs} or Carp::croak "Cannot call ->failed_futures on a non-convergent Future";
return grep { $_->{ready} and $_->{failure} } @{ $self->{subs} };
}
sub cancelled_futures
{
my $self = shift;
$self->{subs} or Carp::croak "Cannot call ->cancelled_futures on a non-convergent Future";
return grep { $_->{ready} and $_->{cancelled} } @{ $self->{subs} };
}
=head1 TRACING METHODS
=head2 set_label
=head2 label
$future = $future->set_label( $label )
$label = $future->label
I<Since version 0.28.>
Chaining mutator and accessor for the label of the C<Future>. This should be a
plain string value, whose value will be stored by the future instance for use
in debugging messages or other tooling, or similar purposes.
=cut
sub set_label
{
my $self = shift;
( $self->{label} ) = @_;
return $self;
}
sub label
{
my $self = shift;
return $self->{label};
}
sub __selfstr
{
my $self = shift;
return "$self" unless defined $self->{label};
return "$self (\"$self->{label}\")";
}
=head2 btime
=head2 rtime
[ $sec, $usec ] = $future->btime
[ $sec, $usec ] = $future->rtime
I<Since version 0.28.>
Accessors that return the tracing timestamps from the instance. These give the
time the instance was contructed ("birth" time, C<btime>) and the time the
result was determined (the "ready" time, C<rtime>). Each result is returned as
a two-element ARRAY ref, containing the epoch time in seconds and
microseconds, as given by C<Time::HiRes::gettimeofday>.
In order for these times to be captured, they have to be enabled by setting
C<$Future::TIMES> to a true value. This is initialised true at the time the
module is loaded if either C<PERL_FUTURE_DEBUG> or C<PERL_FUTURE_TIMES> are
set in the environment.
=cut
sub btime
{
my $self = shift;
return $self->{btime};
}
sub rtime
{
my $self = shift;
return $self->{rtime};
}
=head2 elapsed
$sec = $future->elapsed
I<Since version 0.28.>
If both tracing timestamps are defined, returns the number of seconds of
elapsed time between them as a floating-point number. If not, returns
C<undef>.
=cut
sub elapsed
{
my $self = shift;
return undef unless defined $self->{btime} and defined $self->{rtime};
return $self->{elapsed} ||= tv_interval( $self->{btime}, $self->{rtime} );
}
=head2 wrap_cb
$cb = $future->wrap_cb( $operation_name, $cb )
I<Since version 0.31.>
I<Note: This method is experimental and may be changed or removed in a later
version.>
This method is invoked internally by various methods that are about to save a
callback CODE reference supplied by the user, to be invoked later. The default
implementation simply returns the callback agument as-is; the method is
provided to allow users to provide extra behaviour. This can be done by
applying a method modifier of the C<around> kind, so in effect add a chain of
wrappers. Each wrapper can then perform its own wrapping logic of the
callback. C<$operation_name> is a string giving the reason for which the
callback is being saved; currently one of C<on_ready>, C<on_done>, C<on_fail>
or C<sequence>; the latter being used for all the sequence-returning methods.
This method is intentionally invoked only for CODE references that are being
saved on a pending C<Future> instance to be invoked at some later point. It
does not run for callbacks to be invoked on an already-complete instance. This
is for performance reasons, where the intended behaviour is that the wrapper
can provide some amount of context save and restore, to return the operating
environment for the callback back to what it was at the time it was saved.
For example, the following wrapper saves the value of a package variable at
the time the callback was saved, and restores that value at invocation time
later on. This could be useful for preserving context during logging in a
Future-based program.
our $LOGGING_CTX;
no warnings 'redefine';
my $orig = Future->can( "wrap_cb" );
*Future::wrap_cb = sub {
my $cb = $orig->( @_ );
my $saved_logging_ctx = $LOGGING_CTX;
return sub {
local $LOGGING_CTX = $saved_logging_ctx;
$cb->( @_ );
};
};
At this point, any code deferred into a C<Future> by any of its callbacks will
local/lib/perl5/Future.pm view on Meta::CPAN
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.
It may simply be that a comprehensive useful set of cancellation semantics
can't be universally provided to cover all cases; and that some use-cases at
least would require the application logic to give extra information to its
C<Future> objects on how they should wire up the cancel propagation logic.
Both of these cancellation issues are still under active design consideration;
see the discussion on RT96685 for more information
(L<https://rt.cpan.org/Ticket/Display.html?id=96685>).
=cut
=head1 SEE ALSO
=over 4
=item *
L<curry> - Create automatic curried method call closures for any class or
object
=item *
"The Past, The Present and The Future" - slides from a talk given at the
London Perl Workshop, 2012.
L<https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
=item *
"Futures advent calendar 2013"
( run in 2.078 seconds using v1.01-cache-2.11-cpan-d8267643d1d )