fix some non-blocking behavior but it's not right yet; log some signals
[scpubgit/Object-Remote.git] / lib / Object / Remote / Role / Connector.pm
CommitLineData
47c83a13 1package Object::Remote::Role::Connector;
2
84b04178 3use Module::Runtime qw(use_module);
12fb4a80 4use Object::Remote::Future;
5d59cb98 5use Object::Remote::Logging qw(:log :dlog );
47c83a13 6use Moo::Role;
7
8requires '_open2_for';
9
cc670b30 10has timeout => (is => 'ro', default => sub { { after => 10 } });
498c4ad5 11
47c83a13 12sub connect {
13 my $self = shift;
b7a853b3 14 Dlog_debug { "Preparing to create connection with args of: $_" } @_;
12fb4a80 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 {
5d59cb98 20 log_trace { "Initializing connection for child pid '$child_pid'" };
12fb4a80 21 my $f = shift;
22 $channel->on_line_call(sub {
23 if ($_[0] eq "Shere") {
5d59cb98 24 log_trace { "Received 'Shere' from child pid '$child_pid'; setting done handler to create connection" };
12fb4a80 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 {
5d59cb98 33 log_warn { "'Shere' was not found in connection data for child pid '$child_pid'" };
12fb4a80 34 $f->fail("Expected Shere from remote but received: $_[0]");
35 }
36 undef($channel);
37 });
38 $channel->on_close_call(sub {
f8080c1c 39 log_trace { "Connection has been closed" };
12fb4a80 40 $f->fail("Channel closed without seeing Shere: $_[0]");
41 undef($channel);
42 });
5d59cb98 43 log_trace { "initialized events on channel for child pid '$child_pid'; creating timeout" };
12fb4a80 44 Object::Remote->current_loop
45 ->watch_time(
498c4ad5 46 %{$self->timeout},
12fb4a80 47 code => sub {
5d59cb98 48 Dlog_trace { "Connection timeout timer has fired for child pid '$child_pid'; is_ready: $_" } $f->is_ready;
49 unless($f->is_ready) {
50 log_warn { "Connection with child pid '$child_pid' has timed out" };
9031635d 51 $f->fail("Connection timed out") unless $f->is_ready;
5d59cb98 52 }
12fb4a80 53 undef($channel);
9031635d 54
12fb4a80 55 }
56 );
5d59cb98 57 log_trace { "connection for child pid '$child_pid' has been initialized" };
12fb4a80 58 $f;
59 }
47c83a13 60}
61
621;