| 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 router); | ||
| 6 | use Moo::Role; | ||
| 7 | |||
| 8 | requires '_open2_for'; | ||
| 9 | |||
| 10 | my $timeout_factor = $ENV{PERL_TEST_TIME_OUT_FACTOR} || 1; | ||
| 11 | $timeout_factor = 1 if $timeout_factor < 1; | ||
| 12 | |||
| 13 | has timeout => (is => 'ro', default => sub { 10 * $timeout_factor }); | ||
| 14 | |||
| 15 | BEGIN { router()->exclude_forwarding; } | ||
| 16 | |||
| 17 | sub connect { | ||
| 18 | my $self = shift; | ||
| 19 | Dlog_debug { "Preparing to create connection with args of: $_" } @_; | ||
| 20 | my ($send_to_fh, $receive_from_fh, $child_pid) = $self->_open2_for(@_); | ||
| 21 | my $channel = use_module('Object::Remote::ReadChannel')->new( | ||
| 22 | fh => $receive_from_fh | ||
| 23 | ); | ||
| 24 | return future { | ||
| 25 | log_trace { "Initializing connection for child pid '$child_pid'" }; | ||
| 26 | my $f = shift; | ||
| 27 | $channel->on_line_call(sub { | ||
| 28 | if ($_[0] eq "Shere") { | ||
| 29 | log_trace { "Received 'Shere' from child pid '$child_pid'; setting done handler to create connection" }; | ||
| 30 | $f->done( | ||
| 31 | use_module('Object::Remote::Connection')->new( | ||
| 32 | send_to_fh => $send_to_fh, | ||
| 33 | read_channel => $channel, | ||
| 34 | child_pid => $child_pid, | ||
| 35 | ) | ||
| 36 | ); | ||
| 37 | } else { | ||
| 38 | log_warn { "'Shere' was not found in connection data for child pid '$child_pid'" }; | ||
| 39 | $f->fail("Expected Shere from remote but received: $_[0]"); | ||
| 40 | } | ||
| 41 | undef($channel); | ||
| 42 | }); | ||
| 43 | $f->on_fail(sub { | ||
| 44 | # when the future doesn't fail, the connection takes ownership of the child process | ||
| 45 | kill('TERM', $child_pid); | ||
| 46 | waitpid $child_pid, 0; | ||
| 47 | }); | ||
| 48 | $channel->on_close_call(sub { | ||
| 49 | log_trace { "Connection has been closed" }; | ||
| 50 | $f->fail("Channel closed without seeing Shere: $_[0]"); | ||
| 51 | undef($channel); | ||
| 52 | }); | ||
| 53 | log_trace { "initialized events on channel for child pid '$child_pid'; creating timeout" }; | ||
| 54 | Object::Remote->current_loop | ||
| 55 | ->watch_time( | ||
| 56 | after => $self->timeout, | ||
| 57 | code => sub { | ||
| 58 | Dlog_trace {"Connection timeout timer has fired for child pid '$child_pid'; is_ready: $_" } $f->is_ready; | ||
| 59 | unless($f->is_ready) { | ||
| 60 | log_warn { "Connection with child pid '$child_pid' has timed out" }; | ||
| 61 | $f->fail("Connection timed out") unless $f->is_ready; | ||
| 62 | } | ||
| 63 | undef($channel); | ||
| 64 | |||
| 65 | } | ||
| 66 | ); | ||
| 67 | log_trace { "connection for child pid '$child_pid' has been initialized" }; | ||
| 68 | $f; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | 1; |