Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/Future.pm view on Meta::CPAN
} );
=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.
If a future object is destroyed without having been completed or cancelled, a
warning message is printed.
$ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
Note that due to a limitation of perl's C<caller> function within a C<DESTROY>
destructor method, the exact location of the leak cannot be accurately
determined. Often the leak will occur due to falling out of scope by returning
from a function; in this case the leak location may be reported as being the
line following the line calling that function.
$ PERL_FUTURE_DEBUG=1 perl -MFuture
sub foo {
local/lib/perl5/Future.pm view on Meta::CPAN
$future->fail( $exception, @details )
Marks that the leaf future has failed, and provides an exception value. This
exception will be thrown by the C<get> method if called.
The exception must evaluate as a true value; false exceptions are not allowed.
Further details may be provided that will be returned by the C<failure> method
in list context. These details will not be part of the exception string raised
by C<get>.
If the future is already cancelled, this request is ignored. If the future is
already complete with a result or a failure, an exception is thrown.
=cut
sub fail
{
my $self = shift;
my ( $exception, @details ) = @_;
$_[0] or Carp::croak "$self ->fail requires an exception that is true";
if( ref $self ) {
$self->{cancelled} and return $self;
$self->{ready} and Carp::croak "${\$self->__selfstr} is already ".$self->_state." and cannot be ->fail'ed";
$self->{subs} and Carp::croak "${\$self->__selfstr} is not a leaf Future, cannot be ->fail'ed";
$self->{failure} = [ $exception, @details ];
$self->_mark_ready( "fail" );
}
else {
$self = $self->new;
$self->{ready} = 1;
$self->{ready_at} = _shortmess "fail" if DEBUG;
$self->{failure} = [ $exception, @details ];
}
if( DEBUG ) {
my $at = Carp::shortmess( "failed" );
chomp $at; $at =~ s/\.$//;
$self->{ready_at} = $at;
}
return $self;
}
sub fail_cb
{
my $self = shift;
return sub { $self->fail( @_ ) };
}
=head2 die
$future->die( $message, @details )
I<Since version 0.09.>
A convenient wrapper around C<fail>. If the exception is a non-reference that
does not end in a linefeed, its value will be extended by the file and line
number of the caller, similar to the logic that C<die> uses.
Returns the C<$future>.
=cut
sub die :method
{
my $self = shift;
my ( $exception, @details ) = @_;
if( !ref $exception and $exception !~ m/\n$/ ) {
$exception .= sprintf " at %s line %d\n", (caller)[1,2];
}
$self->fail( $exception, @details );
}
=head2 on_cancel
$future->on_cancel( $code )
If the future is not yet ready, adds a callback to be invoked if the future is
cancelled by the C<cancel> method. If the future is already ready, throws an
exception.
If the future is cancelled, the callbacks will be invoked in the reverse order
to that in which they were registered.
$on_cancel->( $future )
If passed another C<Future> instance, the passed instance will be cancelled
when the original future is cancelled. This method does nothing if the future
is already complete.
=cut
sub on_cancel
{
my $self = shift;
my ( $code ) = @_;
my $is_future = blessed( $code ) && $code->isa( "Future" );
$is_future or _callable( $code ) or
Carp::croak "Expected \$code to be callable or a Future in ->on_cancel";
$self->{ready} and return $self;
push @{ $self->{on_cancel} }, $code;
return $self;
}
=head2 is_cancelled
$cancelled = $future->is_cancelled
Returns true if the future has been cancelled by C<cancel>.
=cut
local/lib/perl5/Future.pm view on Meta::CPAN
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
observe the C<$LOGGING_CTX> variable as having the value it held at the time
the callback was saved, even if it is invoked later on when that value is
different.
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,
local/lib/perl5/Future.pm view on Meta::CPAN
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"
L<http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
=back
=cut
=head1 TODO
=over 4
=item *
Consider the ability to pass the constructor an C<await> CODEref, instead of
needing to use a subclass. This might simplify async/etc.. implementations,
and allows the reuse of the idea of subclassing to extend the abilities of
C<Future> itself - for example to allow a kind of Future that can report
incremental progress.
=back
=cut
=head1 AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
=cut
0x55AA;
( run in 2.490 seconds using v1.01-cache-2.11-cpan-6aa56a78535 )