create ReadChannel object to allow moving Shere logic into connect
[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 sub connect {
10   my $self = shift;
11   my ($send_to_fh, $receive_from_fh, $child_pid) = $self->_open2_for(@_);
12   my $channel = use_module('Object::Remote::ReadChannel')->new(
13     fh => $receive_from_fh
14   );
15   return future {
16     my $f = shift;
17     $channel->on_line_call(sub {
18       if ($_[0] eq "Shere") {
19         $f->done(
20           use_module('Object::Remote::Connection')->new(
21             send_to_fh => $send_to_fh,
22             read_channel => $channel,
23             child_pid => $child_pid,
24           )
25         );
26       } else {
27         $f->fail("Expected Shere from remote but received: $_[0]");
28       }
29       undef($channel);
30     });
31     $channel->on_close_call(sub {
32       $f->fail("Channel closed without seeing Shere: $_[0]");
33       undef($channel);
34     });
35     Object::Remote->current_loop
36                   ->watch_time(
37                       after => 5,
38                       code => sub {
39                         $f->fail("Connection timed out") unless $f->is_ready;
40                         undef($channel);
41                       }
42                     );
43     $f;
44   }
45 }
46
47 1;