start adding logs and add support for routed logs and logging to stderr
[scpubgit/Object-Remote.git] / lib / Object / Remote / Future.pm
CommitLineData
dc28afe8 1package Object::Remote::Future;
2
3use strict;
4use warnings;
5use base qw(Exporter);
6
4a9fa1a5 7use Object::Remote::Logging qw( :log );
8
dc28afe8 9use CPS::Future;
10
3f1f1e66 11our @EXPORT = qw(future await_future await_all);
dc28afe8 12
fbd3b8ec 13sub future (&;$) {
dc28afe8 14 my $f = $_[0]->(CPS::Future->new);
fbd3b8ec 15 return $f if ((caller(1+($_[1]||0))||'') eq 'start');
dc28afe8 16 await_future($f);
17}
18
fbd3b8ec 19our @await;
20
dc28afe8 21sub await_future {
22 my $f = shift;
23 return $f if $f->is_ready;
24 require Object::Remote;
25 my $loop = Object::Remote->current_loop;
fbd3b8ec 26 {
27 local @await = (@await, $f);
28 $f->on_ready(sub {
29 $loop->stop if $f == $await[-1]
30 });
31 $loop->run;
32 }
33 if (@await and $await[-1]->is_ready) {
34 $loop->stop;
35 }
dc28afe8 36 return wantarray ? $f->get : ($f->get)[0];
37}
38
3f1f1e66 39sub await_all {
f6888810 40 await_future(CPS::Future->wait_all(@_));
3f1f1e66 41 map $_->get, @_;
42}
43
dc28afe8 44package start;
45
fbd3b8ec 46our $start = sub { my ($obj, $call) = (shift, shift); $obj->$call(@_); };
47
dc28afe8 48sub AUTOLOAD {
49 my $invocant = shift;
8ba4f2e3 50 my ($method) = our $AUTOLOAD =~ /^start::(.+)$/;
dc28afe8 51 my $res;
52 unless (eval { $res = $invocant->$method(@_); 1 }) {
53 my $f = CPS::Future->new;
54 $f->fail($@);
55 return $f;
56 }
57 unless (Scalar::Util::blessed($res) and $res->isa('CPS::Future')) {
58 my $f = CPS::Future->new;
59 $f->done($res);
60 return $f;
61 }
62 return $res;
63}
64
fbd3b8ec 65package maybe;
66
67sub start {
68 my ($obj, $call) = (shift, shift);
69 if ((caller(1)||'') eq 'start') {
70 $obj->$start::start($call => @_);
71 } else {
72 $obj->$call(@_);
73 }
74}
75
9822fc76 76package maybe::start;
77
78sub AUTOLOAD {
79 my $invocant = shift;
80 my ($method) = our $AUTOLOAD =~ /^maybe::start::(.+)$/;
81 $method = "start::${method}" if ((caller(1)||'') eq 'start');
82 $invocant->$method(@_);
83}
84
11e7c8a5 85package then;
86
87sub AUTOLOAD {
88 my $invocant = shift;
89 my ($method) = our $AUTOLOAD =~ /^then::(.+)$/;
90 my @args = @_;
91 # Need two copies since if we're called on an already complete future
92 # $f will be freed immediately
93 my $ret = my $f = CPS::Future->new;
94 $invocant->on_fail(sub { $f->fail(@_); undef($f); });
95 $invocant->on_done(sub {
96 my ($obj) = @_;
97 my $next = $obj->${\"start::${method}"}(@args);
98 $next->on_done(sub { $f->done(@_); undef($f); });
99 $next->on_fail(sub { $f->fail(@_); undef($f); });
100 });
101 return $ret;
102}
103
dc28afe8 1041;
b9a9982d 105
106=head1 NAME
107
108Object::Remote::Future - Asynchronous calling for L<Object::Remote>
109
110=head1 LAME
111
112Shipping prioritised over writing this part up. Blame mst.
113
114=cut