Propagate errors from FatNode code
[scpubgit/Object-Remote.git] / lib / Object / Remote / Role / Connector.pm
1 package Object::Remote::Role::Connector;
2
3 use Module::Runtime qw(use_module);
4 use Object::Remote::Future;
5 use Moo::Role;
6
7 requires '_open2_for';
8
9 has timeout => (is => 'ro', default => sub { { after => 10 } });
10
11 sub connect {
12   my $self = shift;
13   my ($send_to_fh, $receive_from_fh, $child_pid) = $self->_open2_for(@_);
14   my $channel = use_module('Object::Remote::ReadChannel')->new(
15     fh => $receive_from_fh
16   );
17   return future {
18     my $f = shift;
19     $channel->on_line_call(sub {
20       if ($_[0] eq "Shere") {
21         $f->done(
22           use_module('Object::Remote::Connection')->new(
23             send_to_fh => $send_to_fh,
24             read_channel => $channel,
25             child_pid => $child_pid,
26           )
27         );
28       } else {
29         $f->fail("Expected Shere from remote but received: $_[0]");
30       }
31       undef($channel);
32     });
33     $channel->on_close_call(sub {
34       $f->fail("Channel closed without seeing Shere: $_[0]");
35       undef($channel);
36     });
37     Object::Remote->current_loop
38                   ->watch_time(
39                       %{$self->timeout},
40                       code => sub {
41                         $f->fail("Connection timed out") unless $f->is_ready;
42                         undef($channel);
43                       }
44                     );
45     $f;
46   }
47 }
48
49 1;