fixup start, add then::
[scpubgit/Object-Remote.git] / lib / Object / Remote / Future.pm
1 package Object::Remote::Future;
2
3 use strict;
4 use warnings;
5 use base qw(Exporter);
6
7 use CPS::Future;
8
9 our @EXPORT = qw(future await_future await_all);
10
11 sub future (&) {
12   my $f = $_[0]->(CPS::Future->new);
13   return $f if ((caller(1)||'') eq 'start');
14   await_future($f);
15 }
16
17 sub await_future {
18   my $f = shift;
19   return $f if $f->is_ready;
20   require Object::Remote;
21   my $loop = Object::Remote->current_loop;
22   $f->on_ready(sub { $loop->stop });
23   $loop->run;
24   return wantarray ? $f->get : ($f->get)[0];
25 }
26
27 sub await_all {
28   await_future(CPS::Future->needs_all(@_));
29   map $_->get, @_;
30 }
31
32 package start;
33
34 sub AUTOLOAD {
35   my $invocant = shift;
36   my ($method) = our $AUTOLOAD =~ /^start::(.+)$/;
37   my $res;
38   unless (eval { $res = $invocant->$method(@_); 1 }) {
39     my $f = CPS::Future->new;
40     $f->fail($@);
41     return $f;
42   }
43   unless (Scalar::Util::blessed($res) and $res->isa('CPS::Future')) {
44     my $f = CPS::Future->new;
45     $f->done($res);
46     return $f;
47   }
48   return $res;
49 }
50
51 package then;
52
53 sub AUTOLOAD {
54   my $invocant = shift;
55   my ($method) = our $AUTOLOAD =~ /^then::(.+)$/;
56   my @args = @_;
57   # Need two copies since if we're called on an already complete future
58   # $f will be freed immediately
59   my $ret = my $f = CPS::Future->new;
60   $invocant->on_fail(sub { $f->fail(@_); undef($f); });
61   $invocant->on_done(sub {
62     my ($obj) = @_;
63     my $next = $obj->${\"start::${method}"}(@args);
64     $next->on_done(sub { $f->done(@_); undef($f); });
65     $next->on_fail(sub { $f->fail(@_); undef($f); });
66   });
67   return $ret;
68 }
69
70 1;
71
72 =head1 NAME
73
74 Object::Remote::Future - Asynchronous calling for L<Object::Remote>
75
76 =head1 LAME
77
78 Shipping prioritised over writing this part up. Blame mst.
79
80 =cut