1# You may distribute under the terms of either the GNU General Public License 2# or the Artistic License (the same terms as Perl itself) 3# 4# (C) Paul Evans, 2011-2020 -- leonerd@leonerd.org.uk 5 6package Future; 7 8use v5.10; 9use strict; 10use warnings; 11no warnings 'recursion'; # Disable the "deep recursion" warning 12 13our $VERSION = '0.47'; 14 15use Carp qw(); # don't import croak 16use Scalar::Util qw( weaken blessed reftype ); 17use B qw( svref_2object ); 18use Time::HiRes qw( gettimeofday tv_interval ); 19 20# we are not overloaded, but we want to check if other objects are 21require overload; 22 23require Future::Exception; 24 25our @CARP_NOT = qw( Future::Utils ); 26 27use constant DEBUG => !!$ENV{PERL_FUTURE_DEBUG}; 28 29use constant STRICT => !!$ENV{PERL_FUTURE_STRICT}; 30 31our $TIMES = DEBUG || $ENV{PERL_FUTURE_TIMES}; 32 33=head1 NAME 34 35C<Future> - represent an operation awaiting completion 36 37=head1 SYNOPSIS 38 39 my $future = Future->new; 40 41 perform_some_operation( 42 on_complete => sub { 43 $future->done( @_ ); 44 } 45 ); 46 47 $future->on_ready( sub { 48 say "The operation is complete"; 49 } ); 50 51=head1 DESCRIPTION 52 53A C<Future> object represents an operation that is currently in progress, or 54has recently completed. It can be used in a variety of ways to manage the flow 55of control, and data, through an asynchronous program. 56 57Some futures represent a single operation and are explicitly marked as ready 58by calling the C<done> or C<fail> methods. These are called "leaf" futures 59here, and are returned by the C<new> constructor. 60 61Other futures represent a collection of sub-tasks, and are implicitly marked 62as ready depending on the readiness of their component futures as required. 63These are called "convergent" futures here as they converge control and 64data-flow back into one place. These are the ones returned by the various 65C<wait_*> and C<need_*> constructors. 66 67It is intended that library functions that perform asynchronous operations 68would use future objects to represent outstanding operations, and allow their 69calling programs to control or wait for these operations to complete. The 70implementation and the user of such an interface would typically make use of 71different methods on the class. The methods below are documented in two 72sections; those of interest to each side of the interface. 73 74It should be noted however, that this module does not in any way provide an 75actual mechanism for performing this asynchronous activity; it merely provides 76a way to create objects that can be used for control and data flow around 77those operations. It allows such code to be written in a neater, 78forward-reading manner, and simplifies many common patterns that are often 79involved in such situations. 80 81See also L<Future::Utils> which contains useful loop-constructing functions, 82to run a future-returning function repeatedly in a loop. 83 84Unless otherwise noted, the following methods require at least version 85I<0.08>. 86 87=head2 FAILURE CATEGORIES 88 89While not directly required by C<Future> or its related modules, a growing 90convention of C<Future>-using code is to encode extra semantics in the 91arguments given to the C<fail> method, to represent different kinds of 92failure. 93 94The convention is that after the initial message string as the first required 95argument (intended for display to humans), the second argument is a short 96lowercase string that relates in some way to the kind of failure that 97occurred. Following this is a list of details about that kind of failure, 98whose exact arrangement or structure are determined by the failure category. 99For example, L<IO::Async> and L<Net::Async::HTTP> use this convention to 100indicate at what stage a given HTTP request has failed: 101 102 ->fail( $message, http => ... ) # an HTTP-level error during protocol 103 ->fail( $message, connect => ... ) # a TCP-level failure to connect a 104 # socket 105 ->fail( $message, resolve => ... ) # a resolver (likely DNS) failure 106 # to resolve a hostname 107 108By following this convention, a module remains consistent with other 109C<Future>-based modules, and makes it easy for program logic to gracefully 110handle and manage failures by use of the C<catch> method. 111 112=head2 SUBCLASSING 113 114This class easily supports being subclassed to provide extra behavior, such as 115giving the C<get> method the ability to block and wait for completion. This 116may be useful to provide C<Future> subclasses with event systems, or similar. 117 118Each method that returns a new future object will use the invocant to 119construct its return value. If the constructor needs to perform per-instance 120setup it can override the C<new> method, and take context from the given 121instance. 122 123 sub new 124 { 125 my $proto = shift; 126 my $self = $proto->SUPER::new; 127 128 if( ref $proto ) { 129 # Prototype was an instance 130 } 131 else { 132 # Prototype was a class 133 } 134 135 return $self; 136 } 137 138If an instance overrides the L</await> method, this will be called by C<get> 139and C<failure> if the instance is still pending. 140 141In most cases this should allow future-returning modules to be used as if they 142were blocking call/return-style modules, by simply appending a C<get> call to 143the function or method calls. 144 145 my ( $results, $here ) = future_returning_function( @args )->get; 146 147=head2 DEBUGGING 148 149By the time a C<Future> object is destroyed, it ought to have been completed 150or cancelled. By enabling debug tracing of objects, this fact can be checked. 151If a future object is destroyed without having been completed or cancelled, a 152warning message is printed. 153 154 $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new' 155 Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready. 156 157Note that due to a limitation of perl's C<caller> function within a C<DESTROY> 158destructor method, the exact location of the leak cannot be accurately 159determined. Often the leak will occur due to falling out of scope by returning 160from a function; in this case the leak location may be reported as being the 161line following the line calling that function. 162 163 $ PERL_FUTURE_DEBUG=1 perl -MFuture 164 sub foo { 165 my $f = Future->new; 166 } 167 168 foo(); 169 print "Finished\n"; 170 171 Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready. 172 Finished 173 174A warning is also printed in debug mode if a C<Future> object is destroyed 175that completed with a failure, but the object believes that failure has not 176been reported anywhere. 177 178 $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")' 179 Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops 180 181Such a failure is considered reported if the C<get> or C<failure> methods are 182called on it, or it had at least one C<on_ready> or C<on_fail> callback, or 183its failure is propagated to another C<Future> instance (by a sequencing or 184converging method). 185 186=head2 Future::AsyncAwait::Awaitable ROLE 187 188Since version 0.43 this module provides the L<Future::AsyncAwait::Awaitable> 189API. Subclass authors should note that several of the API methods are provided 190by special optimised internal methods, which may require overriding in your 191subclass if your internals are different from that of this module. 192 193=cut 194 195=head1 CONSTRUCTORS 196 197=cut 198 199=head2 new 200 201 $future = Future->new 202 203 $future = $orig->new 204 205Returns a new C<Future> instance to represent a leaf future. It will be marked 206as ready by any of the C<done>, C<fail>, or C<cancel> methods. It can be 207called either as a class method, or as an instance method. Called on an 208instance it will construct another in the same class, and is useful for 209subclassing. 210 211This constructor would primarily be used by implementations of asynchronous 212interfaces. 213 214=cut 215 216# Callback flags 217use constant { 218 CB_DONE => 1<<0, # Execute callback on done 219 CB_FAIL => 1<<1, # Execute callback on fail 220 CB_CANCEL => 1<<2, # Execute callback on cancellation 221 222 CB_SELF => 1<<3, # Pass $self as first argument 223 CB_RESULT => 1<<4, # Pass result/failure as a list 224 225 CB_SEQ_ONDONE => 1<<5, # Sequencing on success (->then) 226 CB_SEQ_ONFAIL => 1<<6, # Sequencing on failure (->else) 227 228 CB_SEQ_IMDONE => 1<<7, # $code is in fact immediate ->done result 229 CB_SEQ_IMFAIL => 1<<8, # $code is in fact immediate ->fail result 230 231 CB_SEQ_STRICT => 1<<9, # Complain if $code didn't return a Future 232}; 233 234use constant CB_ALWAYS => CB_DONE|CB_FAIL|CB_CANCEL; 235 236# Useful for identifying CODE references 237sub CvNAME_FILE_LINE 238{ 239 my ( $code ) = @_; 240 my $cv = svref_2object( $code ); 241 242 my $name = join "::", $cv->STASH->NAME, $cv->GV->NAME; 243 return $name unless $cv->GV->NAME eq "__ANON__"; 244 245 # $cv->GV->LINE isn't reliable, as outside of perl -d mode all anon CODE 246 # in the same file actually shares the same GV. :( 247 # Walk the optree looking for the first COP 248 my $cop = $cv->START; 249 $cop = $cop->next while $cop and ref $cop ne "B::COP" and ref $cop ne "B::NULL"; 250 251 return $cv->GV->NAME if ref $cop eq "B::NULL"; 252 sprintf "%s(%s line %d)", $cv->GV->NAME, $cop->file, $cop->line; 253} 254 255sub _callable 256{ 257 my ( $cb ) = @_; 258 defined $cb and ( reftype($cb) eq 'CODE' || overload::Method($cb, '&{}') ); 259} 260 261sub new 262{ 263 my $proto = shift; 264 return bless { 265 ready => 0, 266 callbacks => [], # [] = [$type, ...] 267 ( DEBUG ? 268 ( do { my $at = Carp::shortmess( "constructed" ); 269 chomp $at; $at =~ s/\.$//; 270 constructed_at => $at } ) 271 : () ), 272 ( $TIMES ? 273 ( btime => [ gettimeofday ] ) 274 : () ), 275 }, ( ref $proto || $proto ); 276} 277 278*AWAIT_CLONE = sub { shift->new }; 279 280my $GLOBAL_END; 281END { $GLOBAL_END = 1; } 282 283sub DESTROY_debug { 284 my $self = shift; 285 return if $GLOBAL_END; 286 return if $self->{ready} and ( $self->{reported} or !$self->{failure} ); 287 288 my $lost_at = join " line ", (caller)[1,2]; 289 # We can't actually know the real line where the last reference was lost; 290 # a variable set to 'undef' or close of scope, because caller can't see it; 291 # the current op has already been updated. The best we can do is indicate 292 # 'near'. 293 294 if( $self->{ready} and $self->{failure} ) { 295 warn "${\$self->__selfstr} was $self->{constructed_at} and was lost near $lost_at with an unreported failure of: " . 296 $self->{failure}[0] . "\n"; 297 } 298 elsif( !$self->{ready} ) { 299 warn "${\$self->__selfstr} was $self->{constructed_at} and was lost near $lost_at before it was ready.\n"; 300 } 301} 302*DESTROY = \&DESTROY_debug if DEBUG; 303 304=head2 done I<(class method)> 305 306=head2 fail I<(class method)> 307 308 $future = Future->done( @values ) 309 310 $future = Future->fail( $exception, $category, @details ) 311 312I<Since version 0.26.> 313 314Shortcut wrappers around creating a new C<Future> then immediately marking it 315as done or failed. 316 317=head2 wrap 318 319 $future = Future->wrap( @values ) 320 321I<Since version 0.14.> 322 323If given a single argument which is already a C<Future> reference, this will 324be returned unmodified. Otherwise, returns a new C<Future> instance that is 325already complete, and will yield the given values. 326 327This will ensure that an incoming argument is definitely a C<Future>, and may 328be useful in such cases as adapting synchronous code to fit asynchronous 329libraries driven by C<Future>. 330 331=cut 332 333sub wrap 334{ 335 my $class = shift; 336 my @values = @_; 337 338 if( @values == 1 and blessed $values[0] and $values[0]->isa( __PACKAGE__ ) ) { 339 return $values[0]; 340 } 341 else { 342 return $class->done( @values ); 343 } 344} 345 346=head2 call 347 348 $future = Future->call( \&code, @args ) 349 350I<Since version 0.15.> 351 352A convenient wrapper for calling a C<CODE> reference that is expected to 353return a future. In normal circumstances is equivalent to 354 355 $future = $code->( @args ) 356 357except that if the code throws an exception, it is wrapped in a new immediate 358fail future. If the return value from the code is not a blessed C<Future> 359reference, an immediate fail future is returned instead to complain about this 360fact. 361 362=cut 363 364sub call 365{ 366 my $class = shift; 367 my ( $code, @args ) = @_; 368 369 my $f; 370 eval { $f = $code->( @args ); 1 } or $f = $class->fail( $@ ); 371 blessed $f and $f->isa( "Future" ) or $f = $class->fail( "Expected " . CvNAME_FILE_LINE($code) . " to return a Future" ); 372 373 return $f; 374} 375 376sub _shortmess 377{ 378 my $at = Carp::shortmess( $_[0] ); 379 chomp $at; $at =~ s/\.$//; 380 return $at; 381} 382 383sub _mark_ready 384{ 385 my $self = shift; 386 $self->{ready} = 1; 387 $self->{ready_at} = _shortmess $_[0] if DEBUG; 388 389 if( $TIMES ) { 390 $self->{rtime} = [ gettimeofday ]; 391 } 392 393 delete $self->{on_cancel}; 394 $_->[0] and $_->[0]->_revoke_on_cancel( $_->[1] ) for @{ $self->{revoke_when_ready} }; 395 delete $self->{revoke_when_ready}; 396 397 my $callbacks = delete $self->{callbacks} or return; 398 399 my $cancelled = $self->{cancelled}; 400 my $fail = defined $self->{failure}; 401 my $done = !$fail && !$cancelled; 402 403 my @result = $done ? @{ $self->{result} } : 404 $fail ? @{ $self->{failure} } : 405 (); 406 407 foreach my $cb ( @$callbacks ) { 408 my ( $flags, $code ) = @$cb; 409 my $is_future = blessed( $code ) && $code->isa( "Future" ); 410 411 next if $done and not( $flags & CB_DONE ); 412 next if $fail and not( $flags & CB_FAIL ); 413 next if $cancelled and not( $flags & CB_CANCEL ); 414 415 $self->{reported} = 1 if $fail; 416 417 if( $is_future ) { 418 $done ? $code->done( @result ) : 419 $fail ? $code->fail( @result ) : 420 $code->cancel; 421 } 422 elsif( $flags & (CB_SEQ_ONDONE|CB_SEQ_ONFAIL) ) { 423 my ( undef, undef, $fseq ) = @$cb; 424 if( !$fseq ) { # weaken()ed; it might be gone now 425 # This warning should always be printed, even not in DEBUG mode. 426 # It's always an indication of a bug 427 Carp::carp +(DEBUG ? "${\$self->__selfstr} ($self->{constructed_at})" 428 : "${\$self->__selfstr} $self" ) . 429 " lost a sequence Future"; 430 next; 431 } 432 433 my $f2; 434 if( $done and $flags & CB_SEQ_ONDONE or 435 $fail and $flags & CB_SEQ_ONFAIL ) { 436 437 if( $flags & CB_SEQ_IMDONE ) { 438 $fseq->done( @$code ); 439 next; 440 } 441 elsif( $flags & CB_SEQ_IMFAIL ) { 442 $fseq->fail( @$code ); 443 next; 444 } 445 446 my @args = ( 447 ( $flags & CB_SELF ? $self : () ), 448 ( $flags & CB_RESULT ? @result : () ), 449 ); 450 451 unless( eval { $f2 = $code->( @args ); 1 } ) { 452 $fseq->fail( $@ ); 453 next; 454 } 455 456 unless( blessed $f2 and $f2->isa( "Future" ) ) { 457 # Upgrade a non-Future result, or complain in strict mode 458 if( $flags & CB_SEQ_STRICT ) { 459 $fseq->fail( "Expected " . CvNAME_FILE_LINE($code) . " to return a Future" ); 460 next; 461 } 462 $f2 = Future->done( $f2 ); 463 } 464 465 $fseq->on_cancel( $f2 ); 466 } 467 else { 468 $f2 = $self; 469 } 470 471 if( $f2->is_ready ) { 472 $f2->on_ready( $fseq ) if !$f2->{cancelled}; 473 } 474 else { 475 push @{ $f2->{callbacks} }, [ CB_DONE|CB_FAIL, $fseq ]; 476 weaken( $f2->{callbacks}[-1][1] ); 477 } 478 } 479 else { 480 $code->( 481 ( $flags & CB_SELF ? $self : () ), 482 ( $flags & CB_RESULT ? @result : () ), 483 ); 484 } 485 } 486} 487 488=head1 METHODS 489 490As there are a lare number of methods on this class, they are documented here 491in several sections. 492 493=cut 494 495=head1 INSPECTION METHODS 496 497The following methods query the internal state of a Future instance without 498modifying it or otherwise causing side-effects. 499 500=cut 501 502=head2 is_ready 503 504 $ready = $future->is_ready 505 506Returns true on a leaf future if a result has been provided to the C<done> 507method, failed using the C<fail> method, or cancelled using the C<cancel> 508method. 509 510Returns true on a convergent future if it is ready to yield a result, 511depending on its component futures. 512 513=cut 514 515sub is_ready 516{ 517 my $self = shift; 518 return $self->{ready}; 519} 520 521*AWAIT_IS_READY = sub { shift->is_ready }; 522 523=head2 is_done 524 525 $done = $future->is_done 526 527Returns true on a future if it is ready and completed successfully. Returns 528false if it is still pending, failed, or was cancelled. 529 530=cut 531 532sub is_done 533{ 534 my $self = shift; 535 return $self->{ready} && !$self->{failure} && !$self->{cancelled}; 536} 537 538=head2 is_failed 539 540 $failed = $future->is_failed 541 542I<Since version 0.26.> 543 544Returns true on a future if it is ready and it failed. Returns false if it is 545still pending, completed successfully, or was cancelled. 546 547=cut 548 549sub is_failed 550{ 551 my $self = shift; 552 return $self->{ready} && !!$self->{failure}; # boolify 553} 554 555=head2 is_cancelled 556 557 $cancelled = $future->is_cancelled 558 559Returns true if the future has been cancelled by C<cancel>. 560 561=cut 562 563sub is_cancelled 564{ 565 my $self = shift; 566 return $self->{cancelled}; 567} 568 569*AWAIT_IS_CANCELLED = sub { shift->is_cancelled }; 570 571=head2 state 572 573 $str = $future->state 574 575I<Since version 0.36.> 576 577Returns a string describing the state of the future, as one of the three 578states named above; namely C<done>, C<failed> or C<cancelled>, or C<pending> 579if it is none of these. 580 581=cut 582 583sub state 584{ 585 my $self = shift; 586 return !$self->{ready} ? "pending" : 587 DEBUG ? $self->{ready_at} : 588 $self->{failure} ? "failed" : 589 $self->{cancelled} ? "cancelled" : 590 "done"; 591} 592 593=head1 IMPLEMENTATION METHODS 594 595These methods would primarily be used by implementations of asynchronous 596interfaces. 597 598=cut 599 600=head2 done 601 602 $future->done( @result ) 603 604Marks that the leaf future is now ready, and provides a list of values as a 605result. (The empty list is allowed, and still indicates the future as ready). 606Cannot be called on a convergent future. 607 608If the future is already cancelled, this request is ignored. If the future is 609already complete with a result or a failure, an exception is thrown. 610 611I<Since version 0.45:> this method is also available under the name 612C<resolve>. 613 614=cut 615 616sub done 617{ 618 my $self = shift; 619 620 if( ref $self ) { 621 $self->{cancelled} and return $self; 622 $self->{ready} and Carp::croak "${\$self->__selfstr} is already ".$self->state." and cannot be ->done"; 623 $self->{subs} and Carp::croak "${\$self->__selfstr} is not a leaf Future, cannot be ->done"; 624 $self->{result} = [ @_ ]; 625 $self->_mark_ready( "done" ); 626 } 627 else { 628 $self = $self->new; 629 $self->{ready} = 1; 630 $self->{ready_at} = _shortmess "done" if DEBUG; 631 $self->{result} = [ @_ ]; 632 } 633 634 return $self; 635} 636 637*resolve = sub { shift->done( @_ ) }; 638 639# TODO: For efficiency we can implement better versions of these as individual 640# methods know which case is being invoked 641*AWAIT_NEW_DONE = *AWAIT_DONE = sub { shift->done( @_ ) }; 642 643=head2 fail 644 645 $future->fail( $exception, $category, @details ) 646 647Marks that the leaf future has failed, and provides an exception value. This 648exception will be thrown by the C<get> method if called. 649 650The exception must evaluate as a true value; false exceptions are not allowed. 651A failure category name and other further details may be provided that will be 652returned by the C<failure> method in list context. 653 654If the future is already cancelled, this request is ignored. If the future is 655already complete with a result or a failure, an exception is thrown. 656 657If passed a L<Future::Exception> instance (i.e. an object previously thrown by 658the C<get>), the additional details will be preserved. This allows the 659additional details to be transparently preserved by such code as 660 661 ... 662 catch { 663 return Future->fail($@); 664 } 665 666I<Since version 0.45:> this method is also available under the name C<reject>. 667 668=cut 669 670sub fail 671{ 672 my $self = shift; 673 my ( $exception, @more ) = @_; 674 675 if( ref $exception eq "Future::Exception" ) { 676 @more = ( $exception->category, $exception->details ); 677 $exception = $exception->message; 678 } 679 680 $exception or Carp::croak "$self ->fail requires an exception that is true"; 681 682 if( ref $self ) { 683 $self->{cancelled} and return $self; 684 $self->{ready} and Carp::croak "${\$self->__selfstr} is already ".$self->state." and cannot be ->fail'ed"; 685 $self->{subs} and Carp::croak "${\$self->__selfstr} is not a leaf Future, cannot be ->fail'ed"; 686 $self->{failure} = [ $exception, @more ]; 687 $self->_mark_ready( "failed" ); 688 } 689 else { 690 $self = $self->new; 691 $self->{ready} = 1; 692 $self->{ready_at} = _shortmess "failed" if DEBUG; 693 $self->{failure} = [ $exception, @more ]; 694 } 695 696 return $self; 697} 698 699*reject = sub { shift->fail( @_ ) }; 700 701# TODO: For efficiency we can implement better versions of these as individual 702# methods know which case is being invoked 703*AWAIT_NEW_FAIL = *AWAIT_FAIL = sub { shift->fail( @_ ) }; 704 705=head2 die 706 707 $future->die( $message, $category, @details ) 708 709I<Since version 0.09.> 710 711A convenient wrapper around C<fail>. If the exception is a non-reference that 712does not end in a linefeed, its value will be extended by the file and line 713number of the caller, similar to the logic that C<die> uses. 714 715Returns the C<$future>. 716 717=cut 718 719sub die :method 720{ 721 my $self = shift; 722 my ( $exception, @more ) = @_; 723 724 if( !ref $exception and $exception !~ m/\n$/ ) { 725 $exception .= sprintf " at %s line %d\n", (caller)[1,2]; 726 } 727 728 $self->fail( $exception, @more ); 729} 730 731=head2 on_cancel 732 733 $future->on_cancel( $code ) 734 735If the future is not yet ready, adds a callback to be invoked if the future is 736cancelled by the C<cancel> method. If the future is already ready the method 737is ignored. 738 739If the future is later cancelled, the callbacks will be invoked in the reverse 740order to that in which they were registered. 741 742 $on_cancel->( $future ) 743 744If passed another C<Future> instance, the passed instance will be cancelled 745when the original future is cancelled. In this case, the reference is only 746strongly held while the target future remains pending. If it becomes ready, 747then there is no point trying to cancel it, and so it is removed from the 748originating future's cancellation list. 749 750=cut 751 752sub on_cancel 753{ 754 my $self = shift; 755 my ( $code ) = @_; 756 757 my $is_future = blessed( $code ) && $code->isa( "Future" ); 758 $is_future or _callable( $code ) or 759 Carp::croak "Expected \$code to be callable or a Future in ->on_cancel"; 760 761 $self->{ready} and return $self; 762 763 push @{ $self->{on_cancel} }, $code; 764 if( $is_future ) { 765 push @{ $code->{revoke_when_ready} }, my $r = [ $self, \$self->{on_cancel}[-1] ]; 766 weaken( $r->[0] ); 767 weaken( $r->[1] ); 768 } 769 770 return $self; 771} 772 773# An optimised version for Awaitable role 774sub AWAIT_ON_CANCEL 775{ 776 my $self = shift; 777 my ( $f2 ) = @_; 778 779 push @{ $self->{on_cancel} }, $f2; 780 push @{ $f2->{revoke_when_ready} }, my $r = [ $self, \$self->{on_cancel}[-1] ]; 781 weaken( $r->[0] ); 782 weaken( $r->[1] ); 783} 784 785# New name for it 786*AWAIT_CHAIN_CANCEL = \&AWAIT_ON_CANCEL; 787 788sub _revoke_on_cancel 789{ 790 my $self = shift; 791 my ( $ref ) = @_; 792 793 undef $$ref; 794 $self->{empty_on_cancel_slots}++; 795 796 my $on_cancel = $self->{on_cancel} or return; 797 798 # If the list is nontrivally large and over half-empty / under half-full, compact it 799 if( @$on_cancel >= 8 and $self->{empty_on_cancel_slots} >= 0.5 * @$on_cancel ) { 800 # We can't grep { defined } because that will break all the existing SCALAR refs 801 my $idx = 0; 802 while( $idx < @$on_cancel ) { 803 defined $on_cancel->[$idx] and $idx++, next; 804 splice @$on_cancel, $idx, 1, (); 805 } 806 $self->{empty_on_cancel_slots} = 0; 807 } 808} 809 810=head1 USER METHODS 811 812These methods would primarily be used by users of asynchronous interfaces, on 813objects returned by such an interface. 814 815=cut 816 817=head2 on_ready 818 819 $future->on_ready( $code ) 820 821If the future is not yet ready, adds a callback to be invoked when the future 822is ready. If the future is already ready, invokes it immediately. 823 824In either case, the callback will be passed the future object itself. The 825invoked code can then obtain the list of results by calling the C<get> method. 826 827 $on_ready->( $future ) 828 829If passed another C<Future> instance, the passed instance will have its 830C<done>, C<fail> or C<cancel> methods invoked when the original future 831completes successfully, fails, or is cancelled respectively. 832 833Returns the C<$future>. 834 835=cut 836 837sub on_ready 838{ 839 my $self = shift; 840 my ( $code ) = @_; 841 842 my $is_future = blessed( $code ) && $code->isa( "Future" ); 843 $is_future or _callable( $code ) or 844 Carp::croak "Expected \$code to be callable or a Future in ->on_ready"; 845 846 if( $self->{ready} ) { 847 my $fail = defined $self->{failure}; 848 my $done = !$fail && !$self->{cancelled}; 849 850 $self->{reported} = 1 if $fail; 851 852 $is_future ? ( $done ? $code->done( @{ $self->{result} } ) : 853 $fail ? $code->fail( @{ $self->{failure} } ) : 854 $code->cancel ) 855 : $code->( $self ); 856 } 857 else { 858 push @{ $self->{callbacks} }, [ CB_ALWAYS|CB_SELF, $self->wrap_cb( on_ready => $code ) ]; 859 } 860 861 return $self; 862} 863 864# An optimised version for Awaitable role 865sub AWAIT_ON_READY 866{ 867 my $self = shift; 868 my ( $code ) = @_; 869 push @{ $self->{callbacks} }, [ CB_ALWAYS|CB_SELF, $self->wrap_cb( on_ready => $code ) ]; 870} 871 872=head2 result 873 874 @result = $future->result 875 876 $result = $future->result 877 878I<Since version 0.44.> 879 880If the future is ready and completed successfully, returns the list of 881results that had earlier been given to the C<done> method on a leaf future, 882or the list of component futures it was waiting for on a convergent future. In 883scalar context it returns just the first result value. 884 885If the future is ready but failed, this method raises as an exception the 886failure that was given to the C<fail> method. If additional details were given 887to the C<fail> method, an exception object is constructed to wrap them of type 888L<Future::Exception>. 889 890If the future was cancelled or is not yet ready an exception is thrown. 891 892=cut 893 894sub result 895{ 896 my $self = shift; 897 $self->{ready} or 898 Carp::croak( "${\$self->__selfstr} is not yet ready" ); 899 if( my $failure = $self->{failure} ) { 900 $self->{reported} = 1; 901 my $exception = $failure->[0]; 902 $exception = Future::Exception->new( @$failure ) if @$failure > 1; 903 !ref $exception && $exception =~ m/\n$/ ? CORE::die $exception : Carp::croak $exception; 904 } 905 $self->{cancelled} and Carp::croak "${\$self->__selfstr} was cancelled"; 906 return $self->{result}->[0] unless wantarray; 907 return @{ $self->{result} }; 908} 909 910*AWAIT_RESULT = *AWAIT_GET = sub { shift->result }; 911 912=head2 get 913 914 @result = $future->get 915 916 $result = $future->get 917 918If the future is ready, returns the result or throws the failure exception as 919per L</result>. 920 921If it is not yet ready then L</await> is invoked to wait for a ready state, and 922the result returned as above. 923 924=cut 925 926sub get 927{ 928 my $self = shift; 929 $self->await unless $self->{ready}; 930 return $self->result; 931} 932 933=head2 await 934 935 $f = $f->await 936 937I<Since version 0.44.> 938 939Blocks until the future instance is no longer pending. 940 941Returns the invocant future itself, so it is useful for chaining. 942 943Usually, calling code would either force the future using L</get>, or use 944either C<then> chaining or C<async/await> syntax to wait for results. This 945method is useful in cases where the exception-throwing part of C<get> is not 946required, perhaps because other code will be testing the result using 947L</is_done> or similar. 948 949 if( $f->await->is_done ) { 950 ... 951 } 952 953This method is intended for subclasses to override. The default implementation 954will throw an exception if called on a still-pending instance. 955 956=cut 957 958sub await 959{ 960 my $self = shift; 961 return $self if $self->{ready}; 962 Carp::croak "$self is not yet complete and does not provide ->await"; 963} 964 965=head2 block_until_ready 966 967 $f = $f->block_until_ready 968 969I<Since version 0.40.> 970 971Now a synonym for L</await>. New code should invoke C<await> directly. 972 973=cut 974 975sub block_until_ready 976{ 977 my $self = shift; 978 return $self->await; 979} 980 981=head2 unwrap 982 983 @values = Future->unwrap( @values ) 984 985I<Since version 0.26.> 986 987If given a single argument which is a C<Future> reference, this method will 988call C<get> on it and return the result. Otherwise, it returns the list of 989values directly in list context, or the first value in scalar. Since it 990involves an implicit blocking wait, this method can only be used on immediate 991futures or subclasses that implement L</await>. 992 993This will ensure that an outgoing argument is definitely not a C<Future>, and 994may be useful in such cases as adapting synchronous code to fit asynchronous 995libraries that return C<Future> instances. 996 997=cut 998 999sub unwrap 1000{ 1001 shift; # $class 1002 my @values = @_; 1003 1004 if( @values == 1 and blessed $values[0] and $values[0]->isa( __PACKAGE__ ) ) { 1005 return $values[0]->get; 1006 } 1007 else { 1008 return $values[0] if !wantarray; 1009 return @values; 1010 } 1011} 1012 1013=head2 on_done 1014 1015 $future->on_done( $code ) 1016 1017If the future is not yet ready, adds a callback to be invoked when the future 1018is ready, if it completes successfully. If the future completed successfully, 1019invokes it immediately. If it failed or was cancelled, it is not invoked at 1020all. 1021 1022The callback will be passed the result passed to the C<done> method. 1023 1024 $on_done->( @result ) 1025 1026If passed another C<Future> instance, the passed instance will have its 1027C<done> method invoked when the original future completes successfully. 1028 1029Returns the C<$future>. 1030 1031=cut 1032 1033sub on_done 1034{ 1035 my $self = shift; 1036 my ( $code ) = @_; 1037 1038 my $is_future = blessed( $code ) && $code->isa( "Future" ); 1039 $is_future or _callable( $code ) or 1040 Carp::croak "Expected \$code to be callable or a Future in ->on_done"; 1041 1042 if( $self->{ready} ) { 1043 return $self if $self->{failure} or $self->{cancelled}; 1044 1045 $is_future ? $code->done( @{ $self->{result} } ) 1046 : $code->( @{ $self->{result} } ); 1047 } 1048 else { 1049 push @{ $self->{callbacks} }, [ CB_DONE|CB_RESULT, $self->wrap_cb( on_done => $code ) ]; 1050 } 1051 1052 return $self; 1053} 1054 1055=head2 failure 1056 1057 $exception = $future->failure 1058 1059 $exception, $category, @details = $future->failure 1060 1061If the future is ready, returns the exception passed to the C<fail> method or 1062C<undef> if the future completed successfully via the C<done> method. 1063 1064If it is not yet ready then L</await> is invoked to wait for a ready state. 1065 1066If called in list context, will additionally yield the category name and list 1067of the details provided to the C<fail> method. 1068 1069Because the exception value must be true, this can be used in a simple C<if> 1070statement: 1071 1072 if( my $exception = $future->failure ) { 1073 ... 1074 } 1075 else { 1076 my @result = $future->result; 1077 ... 1078 } 1079 1080=cut 1081 1082sub failure 1083{ 1084 my $self = shift; 1085 $self->await unless $self->{ready}; 1086 return unless $self->{failure}; 1087 $self->{reported} = 1; 1088 return $self->{failure}->[0] if !wantarray; 1089 return @{ $self->{failure} }; 1090} 1091 1092=head2 on_fail 1093 1094 $future->on_fail( $code ) 1095 1096If the future is not yet ready, adds a callback to be invoked when the future 1097is ready, if it fails. If the future has already failed, invokes it 1098immediately. If it completed successfully or was cancelled, it is not invoked 1099at all. 1100 1101The callback will be passed the exception and other details passed to the 1102C<fail> method. 1103 1104 $on_fail->( $exception, $category, @details ) 1105 1106If passed another C<Future> instance, the passed instance will have its 1107C<fail> method invoked when the original future fails. 1108 1109To invoke a C<done> method on a future when another one fails, use a CODE 1110reference: 1111 1112 $future->on_fail( sub { $f->done( @_ ) } ); 1113 1114Returns the C<$future>. 1115 1116=cut 1117 1118sub on_fail 1119{ 1120 my $self = shift; 1121 my ( $code ) = @_; 1122 1123 my $is_future = blessed( $code ) && $code->isa( "Future" ); 1124 $is_future or _callable( $code ) or 1125 Carp::croak "Expected \$code to be callable or a Future in ->on_fail"; 1126 1127 if( $self->{ready} ) { 1128 return $self if not $self->{failure}; 1129 $self->{reported} = 1; 1130 1131 $is_future ? $code->fail( @{ $self->{failure} } ) 1132 : $code->( @{ $self->{failure} } ); 1133 } 1134 else { 1135 push @{ $self->{callbacks} }, [ CB_FAIL|CB_RESULT, $self->wrap_cb( on_fail => $code ) ]; 1136 } 1137 1138 return $self; 1139} 1140 1141=head2 cancel 1142 1143 $future->cancel 1144 1145Requests that the future be cancelled, immediately marking it as ready. This 1146will invoke all of the code blocks registered by C<on_cancel>, in the reverse 1147order. When called on a convergent future, all its component futures are also 1148cancelled. It is not an error to attempt to cancel a future that is already 1149complete or cancelled; it simply has no effect. 1150 1151Returns the C<$future>. 1152 1153=cut 1154 1155sub cancel 1156{ 1157 my $self = shift; 1158 1159 return $self if $self->{ready}; 1160 1161 $self->{cancelled}++; 1162 my $on_cancel = delete $self->{on_cancel}; 1163 foreach my $code ( $on_cancel ? reverse @$on_cancel : () ) { 1164 defined $code or next; 1165 my $is_future = blessed( $code ) && $code->isa( "Future" ); 1166 $is_future ? $code->cancel 1167 : $code->( $self ); 1168 } 1169 $self->_mark_ready( "cancel" ); 1170 1171 return $self; 1172} 1173 1174=head1 SEQUENCING METHODS 1175 1176The following methods all return a new future to represent the combination of 1177its invocant followed by another action given by a code reference. The 1178combined activity waits for the first future to be ready, then may invoke the 1179code depending on the success or failure of the first, or may run it 1180regardless. The returned sequence future represents the entire combination of 1181activity. 1182 1183The invoked code could return a future, or a result directly. 1184 1185I<Since version 0.45:> if a non-future result is returned it will be wrapped 1186in a new immediate Future instance. This behaviour can be disabled by setting 1187the C<PERL_FUTURE_STRICT> environment variable to a true value at compiletime: 1188 1189 $ PERL_FUTURE_STRICT=1 perl ... 1190 1191The combined future will then wait for the result of this second one. If the 1192combinined future is cancelled, it will cancel either the first future or the 1193second, depending whether the first had completed. If the code block throws an 1194exception instead of returning a value, the sequence future will fail with 1195that exception as its message and no further values. 1196 1197Note that since the code is invoked in scalar context, you cannot directly 1198return a list of values this way. Any list-valued results must be done by 1199returning a C<Future> instance. 1200 1201 sub { 1202 ... 1203 return Future->done( @results ); 1204 } 1205 1206As it is always a mistake to call these sequencing methods in void context and lose the 1207reference to the returned future (because exception/error handling would be 1208silently dropped), this method warns in void context. 1209 1210=cut 1211 1212sub _sequence 1213{ 1214 my $f1 = shift; 1215 my ( $code, $flags ) = @_; 1216 1217 $flags |= CB_SEQ_STRICT if STRICT; 1218 1219 # For later, we might want to know where we were called from 1220 my $func = (caller 1)[3]; 1221 $func =~ s/^.*:://; 1222 1223 $flags & (CB_SEQ_IMDONE|CB_SEQ_IMFAIL) or _callable( $code ) or 1224 Carp::croak "Expected \$code to be callable in ->$func"; 1225 1226 if( !defined wantarray ) { 1227 Carp::carp "Calling ->$func in void context"; 1228 } 1229 1230 if( $f1->is_ready ) { 1231 # Take a shortcut 1232 return $f1 if $f1->is_done and not( $flags & CB_SEQ_ONDONE ) or 1233 $f1->{failure} and not( $flags & CB_SEQ_ONFAIL ); 1234 1235 if( $flags & CB_SEQ_IMDONE ) { 1236 return Future->done( @$code ); 1237 } 1238 elsif( $flags & CB_SEQ_IMFAIL ) { 1239 return Future->fail( @$code ); 1240 } 1241 1242 my @args = ( 1243 ( $flags & CB_SELF ? $f1 : () ), 1244 ( $flags & CB_RESULT ? $f1->is_done ? @{ $f1->{result} } : 1245 $f1->{failure} ? @{ $f1->{failure} } : 1246 () : () ), 1247 ); 1248 1249 my $fseq; 1250 unless( eval { $fseq = $code->( @args ); 1 } ) { 1251 return Future->fail( $@ ); 1252 } 1253 1254 unless( blessed $fseq and $fseq->isa( "Future" ) ) { 1255 # Upgrade a non-Future result, or complain in strict mode 1256 $flags & CB_SEQ_STRICT and 1257 return Future->fail( "Expected " . CvNAME_FILE_LINE($code) . " to return a Future" ); 1258 1259 $fseq = $f1->new->done( $fseq ); 1260 } 1261 1262 return $fseq; 1263 } 1264 1265 my $fseq = $f1->new; 1266 $fseq->on_cancel( $f1 ); 1267 1268 # TODO: if anyone cares about the op name, we might have to synthesize it 1269 # from $flags 1270 $code = $f1->wrap_cb( sequence => $code ) unless $flags & (CB_SEQ_IMDONE|CB_SEQ_IMFAIL); 1271 1272 push @{ $f1->{callbacks} }, [ CB_DONE|CB_FAIL|$flags, $code, $fseq ]; 1273 weaken( $f1->{callbacks}[-1][2] ); 1274 1275 return $fseq; 1276} 1277 1278=head2 then 1279 1280 $future = $f1->then( \&done_code ) 1281 1282I<Since version 0.13.> 1283 1284Returns a new sequencing C<Future> that runs the code if the first succeeds. 1285Once C<$f1> succeeds the code reference will be invoked and is passed the list 1286of results. It should return a future, C<$f2>. Once C<$f2> completes the 1287sequence future will then be marked as complete with whatever result C<$f2> 1288gave. If C<$f1> fails then the sequence future will immediately fail with the 1289same failure and the code will not be invoked. 1290 1291 $f2 = $done_code->( @result ) 1292 1293=head2 else 1294 1295 $future = $f1->else( \&fail_code ) 1296 1297I<Since version 0.13.> 1298 1299Returns a new sequencing C<Future> that runs the code if the first fails. Once 1300C<$f1> fails the code reference will be invoked and is passed the failure and 1301other details. It should return a future, C<$f2>. Once C<$f2> completes the 1302sequence future will then be marked as complete with whatever result C<$f2> 1303gave. If C<$f1> succeeds then the sequence future will immediately succeed 1304with the same result and the code will not be invoked. 1305 1306 $f2 = $fail_code->( $exception, $category, @details ) 1307 1308=head2 then I<(2 arguments)> 1309 1310 $future = $f1->then( \&done_code, \&fail_code ) 1311 1312The C<then> method can also be passed the C<$fail_code> block as well, giving 1313a combination of C<then> and C<else> behaviour. 1314 1315This operation is similar to those provided by other future systems, such as 1316Javascript's Q or Promises/A libraries. 1317 1318=cut 1319 1320my $make_donecatchfail_sub = sub { 1321 my ( $with_f, $done_code, $fail_code, @catch_list ) = @_; 1322 1323 my $func = (caller 1)[3]; 1324 $func =~ s/^.*:://; 1325 1326 !$done_code or _callable( $done_code ) or 1327 Carp::croak "Expected \$done_code to be callable in ->$func"; 1328 !$fail_code or _callable( $fail_code ) or 1329 Carp::croak "Expected \$fail_code to be callable in ->$func"; 1330 1331 my %catch_handlers = @catch_list; 1332 _callable( $catch_handlers{$_} ) or 1333 Carp::croak "Expected catch handler for '$_' to be callable in ->$func" 1334 for keys %catch_handlers; 1335 1336 sub { 1337 my $self = shift; 1338 my @maybe_self = $with_f ? ( $self ) : (); 1339 1340 if( !$self->{failure} ) { 1341 return $self unless $done_code; 1342 return $done_code->( @maybe_self, @{ $self->{result} } ); 1343 } 1344 else { 1345 my $name = $self->{failure}[1]; 1346 if( defined $name and $catch_handlers{$name} ) { 1347 return $catch_handlers{$name}->( @maybe_self, @{ $self->{failure} } ); 1348 } 1349 return $self unless $fail_code; 1350 return $fail_code->( @maybe_self, @{ $self->{failure} } ); 1351 } 1352 }; 1353}; 1354 1355sub then 1356{ 1357 my $self = shift; 1358 my $done_code = shift; 1359 my $fail_code = ( @_ % 2 ) ? pop : undef; 1360 my @catch_list = @_; 1361 1362 if( $done_code and !@catch_list and !$fail_code ) { 1363 return $self->_sequence( $done_code, CB_SEQ_ONDONE|CB_RESULT ); 1364 } 1365 1366 # Complex 1367 return $self->_sequence( $make_donecatchfail_sub->( 1368 0, $done_code, $fail_code, @catch_list, 1369 ), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1370} 1371 1372sub else 1373{ 1374 my $self = shift; 1375 my ( $fail_code ) = @_; 1376 1377 return $self->_sequence( $fail_code, CB_SEQ_ONFAIL|CB_RESULT ); 1378} 1379 1380=head2 catch 1381 1382 $future = $f1->catch( 1383 name => \&code, 1384 name => \&code, ... 1385 ) 1386 1387I<Since version 0.33.> 1388 1389Returns a new sequencing C<Future> that behaves like an C<else> call which 1390dispatches to a choice of several alternative handling functions depending on 1391the kind of failure that occurred. If C<$f1> fails with a category name (i.e. 1392the second argument to the C<fail> call) which exactly matches one of the 1393string names given, then the corresponding code is invoked, being passed the 1394same arguments as a plain C<else> call would take, and is expected to return a 1395C<Future> in the same way. 1396 1397 $f2 = $code->( $exception, $category, @details ) 1398 1399If C<$f1> does not fail, fails without a category name at all, or fails with a 1400category name that does not match any given to the C<catch> method, then the 1401returned sequence future immediately completes with the same result, and no 1402block of code is invoked. 1403 1404If passed an odd-sized list, the final argument gives a function to invoke on 1405failure if no other handler matches. 1406 1407 $future = $f1->catch( 1408 name => \&code, ... 1409 \&fail_code, 1410 ) 1411 1412This feature is currently still a work-in-progress. It currently can only cope 1413with category names that are literal strings, which are all distinct. A later 1414version may define other kinds of match (e.g. regexp), may specify some sort 1415of ordering on the arguments, or any of several other semantic extensions. For 1416more detail on the ongoing design, see 1417L<https://rt.cpan.org/Ticket/Display.html?id=103545>. 1418 1419=head2 then I<(multiple arguments)> 1420 1421 $future = $f1->then( \&done_code, @catch_list, \&fail_code ) 1422 1423I<Since version 0.33.> 1424 1425The C<then> method can be passed an even-sized list inbetween the 1426C<$done_code> and the C<$fail_code>, with the same meaning as the C<catch> 1427method. 1428 1429=cut 1430 1431sub catch 1432{ 1433 my $self = shift; 1434 my $fail_code = ( @_ % 2 ) ? pop : undef; 1435 my @catch_list = @_; 1436 1437 return $self->_sequence( $make_donecatchfail_sub->( 1438 0, undef, $fail_code, @catch_list, 1439 ), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1440} 1441 1442=head2 transform 1443 1444 $future = $f1->transform( %args ) 1445 1446Returns a new sequencing C<Future> that wraps the one given as C<$f1>. With no 1447arguments this will be a trivial wrapper; C<$future> will complete or fail 1448when C<$f1> does, and C<$f1> will be cancelled when C<$future> is. 1449 1450By passing the following named arguments, the returned C<$future> can be made 1451to behave differently to C<$f1>: 1452 1453=over 8 1454 1455=item done => CODE 1456 1457Provides a function to use to modify the result of a successful completion. 1458When C<$f1> completes successfully, the result of its C<get> method is passed 1459into this function, and whatever it returns is passed to the C<done> method of 1460C<$future> 1461 1462=item fail => CODE 1463 1464Provides a function to use to modify the result of a failure. When C<$f1> 1465fails, the result of its C<failure> method is passed into this function, and 1466whatever it returns is passed to the C<fail> method of C<$future>. 1467 1468=back 1469 1470=cut 1471 1472sub transform 1473{ 1474 my $self = shift; 1475 my %args = @_; 1476 1477 my $xfrm_done = $args{done}; 1478 my $xfrm_fail = $args{fail}; 1479 1480 return $self->_sequence( sub { 1481 my $self = shift; 1482 if( !$self->{failure} ) { 1483 return $self unless $xfrm_done; 1484 my @result = $xfrm_done->( @{ $self->{result} } ); 1485 return $self->new->done( @result ); 1486 } 1487 else { 1488 return $self unless $xfrm_fail; 1489 my @failure = $xfrm_fail->( @{ $self->{failure} } ); 1490 return $self->new->fail( @failure ); 1491 } 1492 }, CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1493} 1494 1495=head2 then_with_f 1496 1497 $future = $f1->then_with_f( ... ) 1498 1499I<Since version 0.21.> 1500 1501Returns a new sequencing C<Future> that behaves like C<then>, but also passes 1502the original future, C<$f1>, to any functions it invokes. 1503 1504 $f2 = $done_code->( $f1, @result ) 1505 $f2 = $catch_code->( $f1, $category, @details ) 1506 $f2 = $fail_code->( $f1, $category, @details ) 1507 1508This is useful for conditional execution cases where the code block may just 1509return the same result of the original future. In this case it is more 1510efficient to return the original future itself. 1511 1512=cut 1513 1514sub then_with_f 1515{ 1516 my $self = shift; 1517 my $done_code = shift; 1518 my $fail_code = ( @_ % 2 ) ? pop : undef; 1519 my @catch_list = @_; 1520 1521 if( $done_code and !@catch_list and !$fail_code ) { 1522 return $self->_sequence( $done_code, CB_SEQ_ONDONE|CB_SELF|CB_RESULT ); 1523 } 1524 1525 return $self->_sequence( $make_donecatchfail_sub->( 1526 1, $done_code, $fail_code, @catch_list, 1527 ), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1528} 1529 1530=head2 then_done 1531 1532=head2 then_fail 1533 1534 $future = $f->then_done( @result ) 1535 1536 $future = $f->then_fail( $exception, $category, @details ) 1537 1538I<Since version 0.22.> 1539 1540Convenient shortcuts to returning an immediate future from a C<then> block, 1541when the result is already known. 1542 1543=cut 1544 1545sub then_done 1546{ 1547 my $self = shift; 1548 my ( @result ) = @_; 1549 return $self->_sequence( \@result, CB_SEQ_ONDONE|CB_SEQ_IMDONE ); 1550} 1551 1552sub then_fail 1553{ 1554 my $self = shift; 1555 my ( @failure ) = @_; 1556 return $self->_sequence( \@failure, CB_SEQ_ONDONE|CB_SEQ_IMFAIL ); 1557} 1558 1559=head2 else_with_f 1560 1561 $future = $f1->else_with_f( \&code ) 1562 1563I<Since version 0.21.> 1564 1565Returns a new sequencing C<Future> that runs the code if the first fails. 1566Identical to C<else>, except that the code reference will be passed both the 1567original future, C<$f1>, and its exception and other details. 1568 1569 $f2 = $code->( $f1, $exception, $category, @details ) 1570 1571This is useful for conditional execution cases where the code block may just 1572return the same result of the original future. In this case it is more 1573efficient to return the original future itself. 1574 1575=cut 1576 1577sub else_with_f 1578{ 1579 my $self = shift; 1580 my ( $fail_code ) = @_; 1581 1582 return $self->_sequence( $fail_code, CB_SEQ_ONFAIL|CB_SELF|CB_RESULT ); 1583} 1584 1585=head2 else_done 1586 1587=head2 else_fail 1588 1589 $future = $f->else_done( @result ) 1590 1591 $future = $f->else_fail( $exception, $category, @details ) 1592 1593I<Since version 0.22.> 1594 1595Convenient shortcuts to returning an immediate future from a C<else> block, 1596when the result is already known. 1597 1598=cut 1599 1600sub else_done 1601{ 1602 my $self = shift; 1603 my ( @result ) = @_; 1604 return $self->_sequence( \@result, CB_SEQ_ONFAIL|CB_SEQ_IMDONE ); 1605} 1606 1607sub else_fail 1608{ 1609 my $self = shift; 1610 my ( @failure ) = @_; 1611 return $self->_sequence( \@failure, CB_SEQ_ONFAIL|CB_SEQ_IMFAIL ); 1612} 1613 1614=head2 catch_with_f 1615 1616 $future = $f1->catch_with_f( ... ) 1617 1618I<Since version 0.33.> 1619 1620Returns a new sequencing C<Future> that behaves like C<catch>, but also passes 1621the original future, C<$f1>, to any functions it invokes. 1622 1623=cut 1624 1625sub catch_with_f 1626{ 1627 my $self = shift; 1628 my $fail_code = ( @_ % 2 ) ? pop : undef; 1629 my @catch_list = @_; 1630 1631 return $self->_sequence( $make_donecatchfail_sub->( 1632 1, undef, $fail_code, @catch_list, 1633 ), CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1634} 1635 1636=head2 followed_by 1637 1638 $future = $f1->followed_by( \&code ) 1639 1640Returns a new sequencing C<Future> that runs the code regardless of success or 1641failure. Once C<$f1> is ready the code reference will be invoked and is passed 1642one argument, C<$f1>. It should return a future, C<$f2>. Once C<$f2> completes 1643the sequence future will then be marked as complete with whatever result 1644C<$f2> gave. 1645 1646 $f2 = $code->( $f1 ) 1647 1648=cut 1649 1650sub followed_by 1651{ 1652 my $self = shift; 1653 my ( $code ) = @_; 1654 1655 return $self->_sequence( $code, CB_SEQ_ONDONE|CB_SEQ_ONFAIL|CB_SELF ); 1656} 1657 1658=head2 without_cancel 1659 1660 $future = $f1->without_cancel 1661 1662I<Since version 0.30.> 1663 1664Returns a new sequencing C<Future> that will complete with the success or 1665failure of the original future, but if cancelled, will not cancel the 1666original. This may be useful if the original future represents an operation 1667that is being shared among multiple sequences; cancelling one should not 1668prevent the others from running too. 1669 1670Note that this only prevents cancel propagating from C<$future> to C<$f1>; if 1671the original C<$f1> instance is cancelled then the returned C<$future> will 1672have to be cancelled too. 1673 1674=cut 1675 1676sub without_cancel 1677{ 1678 my $self = shift; 1679 my $new = $self->new; 1680 1681 $self->on_ready( sub { 1682 my $self = shift; 1683 if( $self->{cancelled} ) { 1684 $new->cancel; 1685 } 1686 elsif( $self->{failure} ) { 1687 $new->fail( @{ $self->{failure} } ); 1688 } 1689 else { 1690 $new->done( @{ $self->{result} } ); 1691 } 1692 }); 1693 1694 $new->{orig} = $self; # just to strongref it - RT122920 1695 $new->on_ready( sub { undef $_[0]->{orig} } ); 1696 1697 return $new; 1698} 1699 1700=head2 retain 1701 1702 $f = $f->retain 1703 1704I<Since version 0.36.> 1705 1706Creates a reference cycle which causes the future to remain in memory until 1707it completes. Returns the invocant future. 1708 1709In normal situations, a C<Future> instance does not strongly hold a reference 1710to other futures that it is feeding a result into, instead relying on that to 1711be handled by application logic. This is normally fine because some part of 1712the application will retain the top-level Future, which then strongly refers 1713to each of its components down in a tree. However, certain design patterns, 1714such as mixed Future-based and legacy callback-based API styles might end up 1715creating Futures simply to attach callback functions to them. In that 1716situation, without further attention, the Future may get lost due to having no 1717strong references to it. Calling C<< ->retain >> on it creates such a 1718reference which ensures it persists until it completes. For example: 1719 1720 Future->needs_all( $fA, $fB ) 1721 ->on_done( $on_done ) 1722 ->on_fail( $on_fail ) 1723 ->retain; 1724 1725=cut 1726 1727sub retain 1728{ 1729 my $self = shift; 1730 return $self->on_ready( sub { undef $self } ); 1731} 1732 1733=head1 CONVERGENT FUTURES 1734 1735The following constructors all take a list of component futures, and return a 1736new future whose readiness somehow depends on the readiness of those 1737components. The first derived class component future will be used as the 1738prototype for constructing the return value, so it respects subclassing 1739correctly, or failing that a plain C<Future>. 1740 1741=cut 1742 1743sub _new_convergent 1744{ 1745 shift; # ignore this class 1746 my ( $subs ) = @_; 1747 1748 foreach my $sub ( @$subs ) { 1749 blessed $sub and $sub->isa( "Future" ) or Carp::croak "Expected a Future, got $sub"; 1750 } 1751 1752 # Find the best prototype. Ideally anything derived if we can find one. 1753 my $self; 1754 ref($_) eq "Future" or $self = $_->new, last for @$subs; 1755 1756 # No derived ones; just have to be a basic class then 1757 $self ||= Future->new; 1758 1759 $self->{subs} = $subs; 1760 1761 # This might be called by a DESTROY during global destruction so it should 1762 # be as defensive as possible (see RT88967) 1763 $self->on_cancel( sub { 1764 foreach my $sub ( @$subs ) { 1765 $sub->cancel if $sub and !$sub->{ready}; 1766 } 1767 } ); 1768 1769 return $self; 1770} 1771 1772=head2 wait_all 1773 1774 $future = Future->wait_all( @subfutures ) 1775 1776Returns a new C<Future> instance that will indicate it is ready once all of 1777the sub future objects given to it indicate that they are ready, either by 1778success, failure or cancellation. Its result will be a list of its component 1779futures. 1780 1781When given an empty list this constructor returns a new immediately-done 1782future. 1783 1784This constructor would primarily be used by users of asynchronous interfaces. 1785 1786=cut 1787 1788sub wait_all 1789{ 1790 my $class = shift; 1791 my @subs = @_; 1792 1793 unless( @subs ) { 1794 my $self = $class->done; 1795 $self->{subs} = []; 1796 return $self; 1797 } 1798 1799 my $self = Future->_new_convergent( \@subs ); 1800 1801 my $pending = 0; 1802 $_->{ready} or $pending++ for @subs; 1803 1804 # Look for immediate ready 1805 if( !$pending ) { 1806 $self->{result} = [ @subs ]; 1807 $self->_mark_ready( "wait_all" ); 1808 return $self; 1809 } 1810 1811 weaken( my $weakself = $self ); 1812 my $sub_on_ready = sub { 1813 return unless my $self = $weakself; 1814 1815 $pending--; 1816 $pending and return; 1817 1818 $self->{result} = [ @subs ]; 1819 $self->_mark_ready( "wait_all" ); 1820 }; 1821 1822 foreach my $sub ( @subs ) { 1823 $sub->{ready} or $sub->on_ready( $sub_on_ready ); 1824 } 1825 1826 return $self; 1827} 1828 1829=head2 wait_any 1830 1831 $future = Future->wait_any( @subfutures ) 1832 1833Returns a new C<Future> instance that will indicate it is ready once any of 1834the sub future objects given to it indicate that they are ready, either by 1835success or failure. Any remaining component futures that are not yet ready 1836will be cancelled. Its result will be the result of the first component future 1837that was ready; either success or failure. Any component futures that are 1838cancelled are ignored, apart from the final component left; at which point the 1839result will be a failure. 1840 1841When given an empty list this constructor returns an immediately-failed 1842future. 1843 1844This constructor would primarily be used by users of asynchronous interfaces. 1845 1846=cut 1847 1848sub wait_any 1849{ 1850 my $class = shift; 1851 my @subs = @_; 1852 1853 unless( @subs ) { 1854 my $self = $class->fail( "Cannot ->wait_any with no subfutures" ); 1855 $self->{subs} = []; 1856 return $self; 1857 } 1858 1859 my $self = Future->_new_convergent( \@subs ); 1860 1861 # Look for immediate ready 1862 my $immediate_ready; 1863 foreach my $sub ( @subs ) { 1864 $sub->{ready} and $immediate_ready = $sub, last; 1865 } 1866 1867 if( $immediate_ready ) { 1868 foreach my $sub ( @subs ) { 1869 $sub->{ready} or $sub->cancel; 1870 } 1871 1872 if( $immediate_ready->{failure} ) { 1873 $self->{failure} = [ @{ $immediate_ready->{failure} } ]; 1874 } 1875 else { 1876 $self->{result} = [ @{ $immediate_ready->{result} } ]; 1877 } 1878 $self->_mark_ready( "wait_any" ); 1879 return $self; 1880 } 1881 1882 my $pending = 0; 1883 1884 weaken( my $weakself = $self ); 1885 my $sub_on_ready = sub { 1886 return unless my $self = $weakself; 1887 return if $self->{result} or $self->{failure}; # don't recurse on child ->cancel 1888 1889 return if --$pending and $_[0]->{cancelled}; 1890 1891 if( $_[0]->{cancelled} ) { 1892 $self->{failure} = [ "All component futures were cancelled" ]; 1893 } 1894 elsif( $_[0]->{failure} ) { 1895 $self->{failure} = [ @{ $_[0]->{failure} } ]; 1896 } 1897 else { 1898 $self->{result} = [ @{ $_[0]->{result} } ]; 1899 } 1900 1901 foreach my $sub ( @subs ) { 1902 $sub->{ready} or $sub->cancel; 1903 } 1904 1905 $self->_mark_ready( "wait_any" ); 1906 }; 1907 1908 foreach my $sub ( @subs ) { 1909 # No need to test $sub->{ready} since we know none of them are 1910 $sub->on_ready( $sub_on_ready ); 1911 $pending++; 1912 } 1913 1914 return $self; 1915} 1916 1917=head2 needs_all 1918 1919 $future = Future->needs_all( @subfutures ) 1920 1921Returns a new C<Future> instance that will indicate it is ready once all of the 1922sub future objects given to it indicate that they have completed successfully, 1923or when any of them indicates that they have failed. If any sub future fails, 1924then this will fail immediately, and the remaining subs not yet ready will be 1925cancelled. Any component futures that are cancelled will cause an immediate 1926failure of the result. 1927 1928If successful, its result will be a concatenated list of the results of all 1929its component futures, in corresponding order. If it fails, its failure will 1930be that of the first component future that failed. To access each component 1931future's results individually, use C<done_futures>. 1932 1933When given an empty list this constructor returns a new immediately-done 1934future. 1935 1936This constructor would primarily be used by users of asynchronous interfaces. 1937 1938=cut 1939 1940sub needs_all 1941{ 1942 my $class = shift; 1943 my @subs = @_; 1944 1945 unless( @subs ) { 1946 my $self = $class->done; 1947 $self->{subs} = []; 1948 return $self; 1949 } 1950 1951 my $self = Future->_new_convergent( \@subs ); 1952 1953 # Look for immediate fail 1954 my $immediate_fail; 1955 foreach my $sub ( @subs ) { 1956 $sub->{ready} and $sub->{failure} and $immediate_fail = $sub, last; 1957 } 1958 1959 if( $immediate_fail ) { 1960 foreach my $sub ( @subs ) { 1961 $sub->{ready} or $sub->cancel; 1962 } 1963 1964 $self->{failure} = [ @{ $immediate_fail->{failure} } ]; 1965 $self->_mark_ready( "needs_all" ); 1966 return $self; 1967 } 1968 1969 my $pending = 0; 1970 $_->{ready} or $pending++ for @subs; 1971 1972 # Look for immediate done 1973 if( !$pending ) { 1974 $self->{result} = [ map { @{ $_->{result} } } @subs ]; 1975 $self->_mark_ready( "needs_all" ); 1976 return $self; 1977 } 1978 1979 weaken( my $weakself = $self ); 1980 my $sub_on_ready = sub { 1981 return unless my $self = $weakself; 1982 return if $self->{result} or $self->{failure}; # don't recurse on child ->cancel 1983 1984 if( $_[0]->{cancelled} ) { 1985 $self->{failure} = [ "A component future was cancelled" ]; 1986 foreach my $sub ( @subs ) { 1987 $sub->cancel if !$sub->{ready}; 1988 } 1989 $self->_mark_ready( "needs_all" ); 1990 } 1991 elsif( $_[0]->{failure} ) { 1992 $self->{failure} = [ @{ $_[0]->{failure} } ]; 1993 foreach my $sub ( @subs ) { 1994 $sub->cancel if !$sub->{ready}; 1995 } 1996 $self->_mark_ready( "needs_all" ); 1997 } 1998 else { 1999 $pending--; 2000 $pending and return; 2001 2002 $self->{result} = [ map { @{ $_->{result} } } @subs ]; 2003 $self->_mark_ready( "needs_all" ); 2004 } 2005 }; 2006 2007 foreach my $sub ( @subs ) { 2008 $sub->{ready} or $sub->on_ready( $sub_on_ready ); 2009 } 2010 2011 return $self; 2012} 2013 2014=head2 needs_any 2015 2016 $future = Future->needs_any( @subfutures ) 2017 2018Returns a new C<Future> instance that will indicate it is ready once any of 2019the sub future objects given to it indicate that they have completed 2020successfully, or when all of them indicate that they have failed. If any sub 2021future succeeds, then this will succeed immediately, and the remaining subs 2022not yet ready will be cancelled. Any component futures that are cancelled are 2023ignored, apart from the final component left; at which point the result will 2024be a failure. 2025 2026If successful, its result will be that of the first component future that 2027succeeded. If it fails, its failure will be that of the last component future 2028to fail. To access the other failures, use C<failed_futures>. 2029 2030Normally when this future completes successfully, only one of its component 2031futures will be done. If it is constructed with multiple that are already done 2032however, then all of these will be returned from C<done_futures>. Users should 2033be careful to still check all the results from C<done_futures> in that case. 2034 2035When given an empty list this constructor returns an immediately-failed 2036future. 2037 2038This constructor would primarily be used by users of asynchronous interfaces. 2039 2040=cut 2041 2042sub needs_any 2043{ 2044 my $class = shift; 2045 my @subs = @_; 2046 2047 unless( @subs ) { 2048 my $self = $class->fail( "Cannot ->needs_any with no subfutures" ); 2049 $self->{subs} = []; 2050 return $self; 2051 } 2052 2053 my $self = Future->_new_convergent( \@subs ); 2054 2055 # Look for immediate done 2056 my $immediate_done; 2057 my $pending = 0; 2058 foreach my $sub ( @subs ) { 2059 $sub->{ready} and !$sub->{failure} and $immediate_done = $sub, last; 2060 $sub->{ready} or $pending++; 2061 } 2062 2063 if( $immediate_done ) { 2064 foreach my $sub ( @subs ) { 2065 $sub->{ready} ? $sub->{reported} = 1 : $sub->cancel; 2066 } 2067 2068 $self->{result} = [ @{ $immediate_done->{result} } ]; 2069 $self->_mark_ready( "needs_any" ); 2070 return $self; 2071 } 2072 2073 # Look for immediate fail 2074 my $immediate_fail = 1; 2075 foreach my $sub ( @subs ) { 2076 $sub->{ready} or $immediate_fail = 0, last; 2077 } 2078 2079 if( $immediate_fail ) { 2080 $_->{reported} = 1 for @subs; 2081 # For consistency we'll pick the last one for the failure 2082 $self->{failure} = [ $subs[-1]->{failure} ]; 2083 $self->_mark_ready( "needs_any" ); 2084 return $self; 2085 } 2086 2087 weaken( my $weakself = $self ); 2088 my $sub_on_ready = sub { 2089 return unless my $self = $weakself; 2090 return if $self->{result} or $self->{failure}; # don't recurse on child ->cancel 2091 2092 return if --$pending and $_[0]->{cancelled}; 2093 2094 if( $_[0]->{cancelled} ) { 2095 $self->{failure} = [ "All component futures were cancelled" ]; 2096 $self->_mark_ready( "needs_any" ); 2097 } 2098 elsif( $_[0]->{failure} ) { 2099 $pending and return; 2100 2101 $self->{failure} = [ @{ $_[0]->{failure} } ]; 2102 $self->_mark_ready( "needs_any" ); 2103 } 2104 else { 2105 $self->{result} = [ @{ $_[0]->{result} } ]; 2106 foreach my $sub ( @subs ) { 2107 $sub->cancel if !$sub->{ready}; 2108 } 2109 $self->_mark_ready( "needs_any" ); 2110 } 2111 }; 2112 2113 foreach my $sub ( @subs ) { 2114 $sub->{ready} or $sub->on_ready( $sub_on_ready ); 2115 } 2116 2117 return $self; 2118} 2119 2120=head1 METHODS ON CONVERGENT FUTURES 2121 2122The following methods apply to convergent (i.e. non-leaf) futures, to access 2123the component futures stored by it. 2124 2125=cut 2126 2127=head2 pending_futures 2128 2129 @f = $future->pending_futures 2130 2131=head2 ready_futures 2132 2133 @f = $future->ready_futures 2134 2135=head2 done_futures 2136 2137 @f = $future->done_futures 2138 2139=head2 failed_futures 2140 2141 @f = $future->failed_futures 2142 2143=head2 cancelled_futures 2144 2145 @f = $future->cancelled_futures 2146 2147Return a list of all the pending, ready, done, failed, or cancelled 2148component futures. In scalar context, each will yield the number of such 2149component futures. 2150 2151=cut 2152 2153sub pending_futures 2154{ 2155 my $self = shift; 2156 $self->{subs} or Carp::croak "Cannot call ->pending_futures on a non-convergent Future"; 2157 return grep { not $_->{ready} } @{ $self->{subs} }; 2158} 2159 2160sub ready_futures 2161{ 2162 my $self = shift; 2163 $self->{subs} or Carp::croak "Cannot call ->ready_futures on a non-convergent Future"; 2164 return grep { $_->{ready} } @{ $self->{subs} }; 2165} 2166 2167sub done_futures 2168{ 2169 my $self = shift; 2170 $self->{subs} or Carp::croak "Cannot call ->done_futures on a non-convergent Future"; 2171 return grep { $_->{ready} and not $_->{failure} and not $_->{cancelled} } @{ $self->{subs} }; 2172} 2173 2174sub failed_futures 2175{ 2176 my $self = shift; 2177 $self->{subs} or Carp::croak "Cannot call ->failed_futures on a non-convergent Future"; 2178 return grep { $_->{ready} and $_->{failure} } @{ $self->{subs} }; 2179} 2180 2181sub cancelled_futures 2182{ 2183 my $self = shift; 2184 $self->{subs} or Carp::croak "Cannot call ->cancelled_futures on a non-convergent Future"; 2185 return grep { $_->{ready} and $_->{cancelled} } @{ $self->{subs} }; 2186} 2187 2188=head1 TRACING METHODS 2189 2190=head2 set_label 2191 2192=head2 label 2193 2194 $future = $future->set_label( $label ) 2195 2196 $label = $future->label 2197 2198I<Since version 0.28.> 2199 2200Chaining mutator and accessor for the label of the C<Future>. This should be a 2201plain string value, whose value will be stored by the future instance for use 2202in debugging messages or other tooling, or similar purposes. 2203 2204=cut 2205 2206sub set_label 2207{ 2208 my $self = shift; 2209 ( $self->{label} ) = @_; 2210 return $self; 2211} 2212 2213sub label 2214{ 2215 my $self = shift; 2216 return $self->{label}; 2217} 2218 2219sub __selfstr 2220{ 2221 my $self = shift; 2222 return "$self" unless defined $self->{label}; 2223 return "$self (\"$self->{label}\")"; 2224} 2225 2226=head2 btime 2227 2228=head2 rtime 2229 2230 [ $sec, $usec ] = $future->btime 2231 2232 [ $sec, $usec ] = $future->rtime 2233 2234I<Since version 0.28.> 2235 2236Accessors that return the tracing timestamps from the instance. These give the 2237time the instance was constructed ("birth" time, C<btime>) and the time the 2238result was determined (the "ready" time, C<rtime>). Each result is returned as 2239a two-element ARRAY ref, containing the epoch time in seconds and 2240microseconds, as given by C<Time::HiRes::gettimeofday>. 2241 2242In order for these times to be captured, they have to be enabled by setting 2243C<$Future::TIMES> to a true value. This is initialised true at the time the 2244module is loaded if either C<PERL_FUTURE_DEBUG> or C<PERL_FUTURE_TIMES> are 2245set in the environment. 2246 2247=cut 2248 2249sub btime 2250{ 2251 my $self = shift; 2252 return $self->{btime}; 2253} 2254 2255sub rtime 2256{ 2257 my $self = shift; 2258 return $self->{rtime}; 2259} 2260 2261=head2 elapsed 2262 2263 $sec = $future->elapsed 2264 2265I<Since version 0.28.> 2266 2267If both tracing timestamps are defined, returns the number of seconds of 2268elapsed time between them as a floating-point number. If not, returns 2269C<undef>. 2270 2271=cut 2272 2273sub elapsed 2274{ 2275 my $self = shift; 2276 return undef unless defined $self->{btime} and defined $self->{rtime}; 2277 return $self->{elapsed} ||= tv_interval( $self->{btime}, $self->{rtime} ); 2278} 2279 2280=head2 wrap_cb 2281 2282 $cb = $future->wrap_cb( $operation_name, $cb ) 2283 2284I<Since version 0.31.> 2285 2286I<Note: This method is experimental and may be changed or removed in a later 2287version.> 2288 2289This method is invoked internally by various methods that are about to save a 2290callback CODE reference supplied by the user, to be invoked later. The default 2291implementation simply returns the callback argument as-is; the method is 2292provided to allow users to provide extra behaviour. This can be done by 2293applying a method modifier of the C<around> kind, so in effect add a chain of 2294wrappers. Each wrapper can then perform its own wrapping logic of the 2295callback. C<$operation_name> is a string giving the reason for which the 2296callback is being saved; currently one of C<on_ready>, C<on_done>, C<on_fail> 2297or C<sequence>; the latter being used for all the sequence-returning methods. 2298 2299This method is intentionally invoked only for CODE references that are being 2300saved on a pending C<Future> instance to be invoked at some later point. It 2301does not run for callbacks to be invoked on an already-complete instance. This 2302is for performance reasons, where the intended behaviour is that the wrapper 2303can provide some amount of context save and restore, to return the operating 2304environment for the callback back to what it was at the time it was saved. 2305 2306For example, the following wrapper saves the value of a package variable at 2307the time the callback was saved, and restores that value at invocation time 2308later on. This could be useful for preserving context during logging in a 2309Future-based program. 2310 2311 our $LOGGING_CTX; 2312 2313 no warnings 'redefine'; 2314 2315 my $orig = Future->can( "wrap_cb" ); 2316 *Future::wrap_cb = sub { 2317 my $cb = $orig->( @_ ); 2318 2319 my $saved_logging_ctx = $LOGGING_CTX; 2320 2321 return sub { 2322 local $LOGGING_CTX = $saved_logging_ctx; 2323 $cb->( @_ ); 2324 }; 2325 }; 2326 2327At this point, any code deferred into a C<Future> by any of its callbacks will 2328observe the C<$LOGGING_CTX> variable as having the value it held at the time 2329the callback was saved, even if it is invoked later on when that value is 2330different. 2331 2332Remember when writing such a wrapper, that it still needs to invoke the 2333previous version of the method, so that it plays nicely in combination with 2334others (see the C<< $orig->( @_ ) >> part). 2335 2336=cut 2337 2338sub wrap_cb 2339{ 2340 my $self = shift; 2341 my ( $op, $cb ) = @_; 2342 return $cb; 2343} 2344 2345=head1 EXAMPLES 2346 2347The following examples all demonstrate possible uses of a C<Future> 2348object to provide a fictional asynchronous API. 2349 2350For more examples, comparing the use of C<Future> with regular call/return 2351style Perl code, see also L<Future::Phrasebook>. 2352 2353=head2 Providing Results 2354 2355By returning a new C<Future> object each time the asynchronous function is 2356called, it provides a placeholder for its eventual result, and a way to 2357indicate when it is complete. 2358 2359 sub foperation 2360 { 2361 my %args = @_; 2362 2363 my $future = Future->new; 2364 2365 do_something_async( 2366 foo => $args{foo}, 2367 on_done => sub { $future->done( @_ ); }, 2368 ); 2369 2370 return $future; 2371 } 2372 2373In most cases, the C<done> method will simply be invoked with the entire 2374result list as its arguments. In that case, it is convenient to use the 2375L<curry> module to form a C<CODE> reference that would invoke the C<done> 2376method. 2377 2378 my $future = Future->new; 2379 2380 do_something_async( 2381 foo => $args{foo}, 2382 on_done => $future->curry::done, 2383 ); 2384 2385The caller may then use this future to wait for a result using the C<on_ready> 2386method, and obtain the result using C<get>. 2387 2388 my $f = foperation( foo => "something" ); 2389 2390 $f->on_ready( sub { 2391 my $f = shift; 2392 say "The operation returned: ", $f->result; 2393 } ); 2394 2395=head2 Indicating Success or Failure 2396 2397Because the stored exception value of a failed future may not be false, the 2398C<failure> method can be used in a conditional statement to detect success or 2399failure. 2400 2401 my $f = foperation( foo => "something" ); 2402 2403 $f->on_ready( sub { 2404 my $f = shift; 2405 if( not my $e = $f->failure ) { 2406 say "The operation succeeded with: ", $f->result; 2407 } 2408 else { 2409 say "The operation failed with: ", $e; 2410 } 2411 } ); 2412 2413By using C<not> in the condition, the order of the C<if> blocks can be 2414arranged to put the successful case first, similar to a C<try>/C<catch> block. 2415 2416Because the C<get> method re-raises the passed exception if the future failed, 2417it can be used to control a C<try>/C<catch> block directly. (This is sometimes 2418called I<Exception Hoisting>). 2419 2420 use Syntax::Keyword::Try; 2421 2422 $f->on_ready( sub { 2423 my $f = shift; 2424 try { 2425 say "The operation succeeded with: ", $f->result; 2426 } 2427 catch { 2428 say "The operation failed with: ", $_; 2429 } 2430 } ); 2431 2432Even neater still may be the separate use of the C<on_done> and C<on_fail> 2433methods. 2434 2435 $f->on_done( sub { 2436 my @result = @_; 2437 say "The operation succeeded with: ", @result; 2438 } ); 2439 $f->on_fail( sub { 2440 my ( $failure ) = @_; 2441 say "The operation failed with: $failure"; 2442 } ); 2443 2444=head2 Immediate Futures 2445 2446Because the C<done> method returns the future object itself, it can be used to 2447generate a C<Future> that is immediately ready with a result. This can also be 2448used as a class method. 2449 2450 my $f = Future->done( $value ); 2451 2452Similarly, the C<fail> and C<die> methods can be used to generate a C<Future> 2453that is immediately failed. 2454 2455 my $f = Future->die( "This is never going to work" ); 2456 2457This could be considered similarly to a C<die> call. 2458 2459An C<eval{}> block can be used to turn a C<Future>-returning function that 2460might throw an exception, into a C<Future> that would indicate this failure. 2461 2462 my $f = eval { function() } || Future->fail( $@ ); 2463 2464This is neater handled by the C<call> class method, which wraps the call in 2465an C<eval{}> block and tests the result: 2466 2467 my $f = Future->call( \&function ); 2468 2469=head2 Sequencing 2470 2471The C<then> method can be used to create simple chains of dependent tasks, 2472each one executing and returning a C<Future> when the previous operation 2473succeeds. 2474 2475 my $f = do_first() 2476 ->then( sub { 2477 return do_second(); 2478 }) 2479 ->then( sub { 2480 return do_third(); 2481 }); 2482 2483The result of the C<$f> future itself will be the result of the future 2484returned by the final function, if none of them failed. If any of them fails 2485it will fail with the same failure. This can be considered similar to normal 2486exception handling in synchronous code; the first time a function call throws 2487an exception, the subsequent calls are not made. 2488 2489=head2 Merging Control Flow 2490 2491A C<wait_all> future may be used to resynchronise control flow, while waiting 2492for multiple concurrent operations to finish. 2493 2494 my $f1 = foperation( foo => "something" ); 2495 my $f2 = foperation( bar => "something else" ); 2496 2497 my $f = Future->wait_all( $f1, $f2 ); 2498 2499 $f->on_ready( sub { 2500 say "Operations are ready:"; 2501 say " foo: ", $f1->result; 2502 say " bar: ", $f2->result; 2503 } ); 2504 2505This provides an ability somewhat similar to C<CPS::kpar()> or 2506L<Async::MergePoint>. 2507 2508=cut 2509 2510=head1 KNOWN ISSUES 2511 2512=head2 Cancellation of Non-Final Sequence Futures 2513 2514The behaviour of future cancellation still has some unanswered questions 2515regarding how to handle the situation where a future is cancelled that has a 2516sequence future constructed from it. 2517 2518In particular, it is unclear in each of the following examples what the 2519behaviour of C<$f2> should be, were C<$f1> to be cancelled: 2520 2521 $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ... 2522 2523 $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ... 2524 2525 $f2 = $f1->followed_by( sub { ... } ); 2526 2527In the C<then>-style case it is likely that this situation should be treated 2528as if C<$f1> had failed, perhaps with some special message. The C<else>-style 2529case is more complex, because it may be that the entire operation should still 2530fail, or it may be that the cancellation of C<$f1> should again be treated 2531simply as a special kind of failure, and the C<else> logic run as normal. 2532 2533To be specific; in each case it is unclear what happens if the first future is 2534cancelled, while the second one is still waiting on it. The semantics for 2535"normal" top-down cancellation of C<$f2> and how it affects C<$f1> are already 2536clear and defined. 2537 2538=head2 Cancellation of Divergent Flow 2539 2540A further complication of cancellation comes from the case where a given 2541future is reused multiple times for multiple sequences or convergent trees. 2542 2543In particular, it is in clear in each of the following examples what the 2544behaviour of C<$f2> should be, were C<$f1> to be cancelled: 2545 2546 my $f_initial = Future->new; ... 2547 my $f1 = $f_initial->then( ... ); 2548 my $f2 = $f_initial->then( ... ); 2549 2550 my $f1 = Future->needs_all( $f_initial ); 2551 my $f2 = Future->needs_all( $f_initial ); 2552 2553The point of cancellation propagation is to trace backwards through stages of 2554some larger sequence of operations that now no longer need to happen, because 2555the final result is no longer required. But in each of these cases, just 2556because C<$f1> has been cancelled, the initial future C<$f_initial> is still 2557required because there is another future (C<$f2>) that will still require its 2558result. 2559 2560Initially it would appear that some kind of reference-counting mechanism could 2561solve this question, though that itself is further complicated by the 2562C<on_ready> handler and its variants. 2563 2564It may simply be that a comprehensive useful set of cancellation semantics 2565can't be universally provided to cover all cases; and that some use-cases at 2566least would require the application logic to give extra information to its 2567C<Future> objects on how they should wire up the cancel propagation logic. 2568 2569Both of these cancellation issues are still under active design consideration; 2570see the discussion on RT96685 for more information 2571(L<https://rt.cpan.org/Ticket/Display.html?id=96685>). 2572 2573=cut 2574 2575=head1 SEE ALSO 2576 2577=over 4 2578 2579=item * 2580 2581L<Future::AsyncAwait> - deferred subroutine syntax for futures 2582 2583Provides a neat syntax extension for writing future-based code. 2584 2585=item * 2586 2587L<Future::IO> - Future-returning IO methods 2588 2589Provides methods similar to core IO functions, which yield results by Futures. 2590 2591=item * 2592 2593L<Promises> - an implementation of the "Promise/A+" pattern for asynchronous 2594programming 2595 2596A different alternative implementation of a similar idea. 2597 2598=item * 2599 2600L<curry> - Create automatic curried method call closures for any class or 2601object 2602 2603=item * 2604 2605"The Past, The Present and The Future" - slides from a talk given at the 2606London Perl Workshop, 2012. 2607 2608L<https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit> 2609 2610=item * 2611 2612"Futures advent calendar 2013" 2613 2614L<http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html> 2615 2616=item * 2617 2618"Asynchronous Programming with Futures" - YAPC::EU 2014 2619 2620L<https://www.youtube.com/watch?v=u9dZgFM6FtE> 2621 2622=back 2623 2624=cut 2625 2626=head1 TODO 2627 2628=over 4 2629 2630=item * 2631 2632Consider the ability to pass the constructor a C<block> CODEref, instead of 2633needing to use a subclass. This might simplify async/etc.. implementations, 2634and allows the reuse of the idea of subclassing to extend the abilities of 2635C<Future> itself - for example to allow a kind of Future that can report 2636incremental progress. 2637 2638=back 2639 2640=cut 2641 2642=head1 AUTHOR 2643 2644Paul Evans <leonerd@leonerd.org.uk> 2645 2646=cut 2647 26480x55AA; 2649