more log lines - found deadlock where controller blocks on read seemingly outside...
[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 Object::Remote::Logging qw(:log :dlog );
6 use Moo::Role;
7
8 requires '_open2_for';
9
10 has timeout => (is => 'ro', default => sub { { after => 10 } });
11
12 sub connect {
13   my $self = shift;
14   Dlog_debug { "Perparing to create connection with args of: $_" } @_;
15   my ($send_to_fh, $receive_from_fh, $child_pid) = $self->_open2_for(@_);
16   my $channel = use_module('Object::Remote::ReadChannel')->new(
17     fh => $receive_from_fh
18   );
19   return future {
20     log_trace { "Initializing connection for child pid '$child_pid'" };
21     my $f = shift;
22     $channel->on_line_call(sub {
23       if ($_[0] eq "Shere") {
24         log_trace { "Received 'Shere' from child pid '$child_pid'; setting done handler to create connection" };
25         $f->done(
26           use_module('Object::Remote::Connection')->new(
27             send_to_fh => $send_to_fh,
28             read_channel => $channel,
29             child_pid => $child_pid,
30           )
31         );
32       } else {
33         log_warn { "'Shere' was not found in connection data for child pid '$child_pid'" };
34         $f->fail("Expected Shere from remote but received: $_[0]");
35       }
36       undef($channel);
37     });
38     $channel->on_close_call(sub {
39       $f->fail("Channel closed without seeing Shere: $_[0]");
40       undef($channel);
41     });
42     log_trace { "initialized events on channel for child pid '$child_pid'; creating timeout" };
43     Object::Remote->current_loop
44                   ->watch_time(
45                       %{$self->timeout},
46                       code => sub {
47 #                        log_warn { "Connection timed out for child pid '$child_pid'" };
48 #                        $f->fail("Connection timed out") unless $f->is_ready;
49 #                        undef($channel);
50                         Dlog_trace { "Connection timeout timer has fired for child pid '$child_pid'; is_ready: $_" } $f->is_ready;
51                         unless($f->is_ready) {
52                             log_warn { "Connection with child pid '$child_pid' has timed out" };
53                             $f->fail("Connection timed out") unless $f->is_ready;                    
54                         }
55                         #TODO hrm was this supposed to be conditional on the is_ready ? 
56                         #a connection is only good for timeout seconds?
57                         undef($channel);
58                       }
59                     );
60     log_trace { "connection for child pid '$child_pid' has been initialized" }; 
61     $f;
62   }
63 }
64
65 1;