fix bug where dead connections would not execute cleanup code; add in repeating timer...
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
CommitLineData
9e72f0cf 1package Object::Remote::Connection;
2
dc28afe8 3use Object::Remote::Future;
9d804009 4use Object::Remote::Null;
676438a1 5use Object::Remote::Handle;
fe6c9a7f 6use Object::Remote::CodeContainer;
ed5a8a8e 7use Object::Remote::GlobProxy;
8use Object::Remote::GlobContainer;
9d64d2d9 9use Object::Remote::Logging qw (:log :dlog);
7790ca36 10use Object::Remote::Tied;
9e72f0cf 11use Object::Remote;
ed5a8a8e 12use Symbol;
9e72f0cf 13use IO::Handle;
14use Module::Runtime qw(use_module);
f8080c1c 15use Scalar::Util qw(weaken blessed refaddr openhandle);
9e72f0cf 16use JSON::PP qw(encode_json);
17use Moo;
18
6db5156c 19our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
9031635d 20#numbering each connection allows it to be
21#tracked along with file handles in
22#the logs
23BEGIN { our $NEXT_CONNECTION_ID = 0 }
24has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
ad4f54b2 25
9e72f0cf 26has send_to_fh => (
27 is => 'ro', required => 1,
90115979 28 trigger => sub {
29 my $self = $_[0];
30 $_[1]->autoflush(1);
31 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
32 },
9e72f0cf 33);
34
12fb4a80 35has read_channel => (
9e72f0cf 36 is => 'ro', required => 1,
37 trigger => sub {
12fb4a80 38 my ($self, $ch) = @_;
f8080c1c 39 my $id = $self->_id;
40 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
9e72f0cf 41 weaken($self);
12fb4a80 42 $ch->on_line_call(sub { $self->_receive(@_) });
f8080c1c 43 $ch->on_close_call(sub {
44 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
45 $self->on_close->done(@_);
46 });
9e72f0cf 47 },
48);
49
f8080c1c 50#TODO properly fix this bug -
51#trigger can't ever be invoked with a default
52#value and the on_close attribute is read only....
53#the future never gets the on_done handler
54#installed
55sub BUILD {
56 my ($self) = @_;
57 $self->on_close(CPS::Future->new);
58}
59
12fb4a80 60has on_close => (
f8080c1c 61 is => 'rw', default => sub { CPS::Future->new },
9031635d 62 trigger => sub {
12fb4a80 63 my ($self, $f) = @_;
9031635d 64 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
12fb4a80 65 weaken($self);
66 $f->on_done(sub {
f8080c1c 67 Dlog_trace { "failing all of the outstanding futures for connection $_" } $self->_id;
68 $self->_fail_outstanding("Connection lost: " . ($f->get)[0]);
12fb4a80 69 });
70 }
71);
ad4f54b2 72
47c83a13 73has child_pid => (is => 'ro');
74
11dbd4a0 75has local_objects_by_id => (
76 is => 'ro', default => sub { {} },
77 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
78);
9e72f0cf 79
11dbd4a0 80has remote_objects_by_id => (
81 is => 'ro', default => sub { {} },
82 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
83);
9e72f0cf 84
a980b0b8 85has outstanding_futures => (is => 'ro', default => sub { {} });
86
12fb4a80 87sub _fail_outstanding {
88 my ($self, $error) = @_;
9031635d 89 Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
12fb4a80 90 my $outstanding = $self->outstanding_futures;
91 $_->fail($error) for values %$outstanding;
92 %$outstanding = ();
93 return;
94}
95
9e72f0cf 96has _json => (
97 is => 'lazy',
98 handles => {
99 _deserialize => 'decode',
100 _encode => 'encode',
101 },
102);
103
fe6c9a7f 104sub _id_to_remote_object {
105 my ($self, $id) = @_;
9031635d 106 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
fe6c9a7f 107 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
108 (
109 $self->remote_objects_by_id->{$id}
110 or Object::Remote::Handle->new(connection => $self, id => $id)
111 )->proxy;
112}
113
9e72f0cf 114sub _build__json {
115 weaken(my $self = shift);
9e72f0cf 116 JSON::PP->new->filter_json_single_key_object(
117 __remote_object__ => sub {
fe6c9a7f 118 $self->_id_to_remote_object(@_);
119 }
120 )->filter_json_single_key_object(
121 __remote_code__ => sub {
122 my $code_container = $self->_id_to_remote_object(@_);
123 sub { $code_container->call(@_) };
9e72f0cf 124 }
6ed5d580 125 )->filter_json_single_key_object(
126 __scalar_ref__ => sub {
127 my $value = shift;
128 return \$value;
129 }
ed5a8a8e 130 )->filter_json_single_key_object(
131 __glob_ref__ => sub {
132 my $glob_container = $self->_id_to_remote_object(@_);
133 my $handle = Symbol::gensym;
134 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
135 return $handle;
136 }
6163a5aa 137 )->filter_json_single_key_object(
138 __local_object__ => sub {
139 $self->local_objects_by_id->{$_[0]}
140 }
7790ca36 141 )->filter_json_single_key_object(
142 __remote_tied_hash__ => sub {
143 my %tied_hash;
144 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
145 return \%tied_hash;
146 }
147 )->filter_json_single_key_object(
148 __remote_tied_array__ => sub {
149 my @tied_array;
150 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
151 return \@tied_array;
152 }
153 );
9e72f0cf 154}
155
84b04178 156BEGIN {
157 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
158 eval { require Object::Remote::Connector::Local };
a9fdb55e 159 eval { require Object::Remote::Connector::LocalSudo };
84b04178 160 eval { require Object::Remote::Connector::SSH };
1d26d6f9 161 eval { require Object::Remote::Connector::UNIX };
84b04178 162}
163
164sub new_from_spec {
165 my ($class, $spec) = @_;
e144d525 166 return $spec if blessed $spec;
9031635d 167 Dlog_debug { "creating a new connection from spec" };
84b04178 168 foreach my $poss (do { our @Guess }) {
fbd3b8ec 169 if (my $conn = $poss->($spec)) {
170 return $conn->maybe::start::connect;
171 }
84b04178 172 }
173 die "Couldn't figure out what to do with ${spec}";
174}
175
11dbd4a0 176sub remote_object {
e144d525 177 my ($self, @args) = @_;
178 Object::Remote::Handle->new(
179 connection => $self, @args
180 )->proxy;
181}
182
4c17fea5 183sub connect {
184 my ($self, $to) = @_;
9031635d 185 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
deb77aaf 186 return await_future(
187 $self->send_class_call(0, 'Object::Remote', connect => $to)
188 );
4c17fea5 189}
190
11dbd4a0 191sub remote_sub {
c6fe6fbd 192 my ($self, $sub) = @_;
193 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
9031635d 194 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
deb77aaf 195 return await_future($self->send_class_call(0, $pkg, can => $name));
196}
197
198sub send_class_call {
199 my ($self, $ctx, @call) = @_;
9031635d 200 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
deb77aaf 201 $self->send(call => class_call_handler => $ctx => call => @call);
202}
203
204sub register_class_call_handler {
205 my ($self) = @_;
3687a42d 206 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 207 my $o = $self->new_class_call_handler;
3687a42d 208 $self->_local_object_to_id($o);
209 $o;
210 };
c6fe6fbd 211}
212
c5736e1c 213sub new_class_call_handler {
214 Object::Remote::CodeContainer->new(
215 code => sub {
216 my ($class, $method) = (shift, shift);
217 use_module($class)->$method(@_);
218 }
219 );
220}
221
9e72f0cf 222sub register_remote {
223 my ($self, $remote) = @_;
9031635d 224 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
9e72f0cf 225 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
226 return $remote;
227}
228
229sub send_free {
230 my ($self, $id) = @_;
7790ca36 231 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
9e72f0cf 232 delete $self->remote_objects_by_id->{$id};
233 $self->_send([ free => $id ]);
234}
235
236sub send {
237 my ($self, $type, @call) = @_;
238
deb77aaf 239 my $future = CPS::Future->new;
a2d43709 240 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 241
242 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 243
a980b0b8 244 my $outstanding = $self->outstanding_futures;
245 $outstanding->{$future} = $future;
a2d43709 246 $future->on_ready(sub {
247 undef($remote);
248 delete $outstanding->{$future}
249 });
a980b0b8 250
9e72f0cf 251 $self->_send(\@call);
252
253 return $future;
254}
255
9d804009 256sub send_discard {
257 my ($self, $type, @call) = @_;
258
deb77aaf 259 unshift @call, $type => 'NULL';
9d804009 260
261 $self->_send(\@call);
262}
263
9e72f0cf 264sub _send {
265 my ($self, $to_send) = @_;
9d64d2d9 266 my $fh = $self->send_to_fh;
9031635d 267 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
9d64d2d9 268 my $serialized = $self->_serialize($to_send)."\n";
6b7b2732 269 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
9d64d2d9 270 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
7790ca36 271 #logic it could easily do short-writes to the remote side - how about taking this entire buffer
272 #and having the run loop send it to the file handle so this doesn't block while the sending
273 #is happening?
f8080c1c 274 my $ret;
275 eval {
276 local($SIG{PIPE}) = 'IGNORE';
277 die "filehandle is not open" unless openhandle($fh);
278 log_trace { "file handle has passed openhandle() test; printing to it" };
279 $ret = print $fh $serialized;
280 die "print was not successful: $!" unless defined $ret
281 };
282
283 if ($@) {
284 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
285 my $error = $@; chomp($error);
286 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
287 return;
288 }
289
9d64d2d9 290 return $ret;
9e72f0cf 291}
292
293sub _serialize {
294 my ($self, $data) = @_;
3687a42d 295 local our @New_Ids = (-1);
9d804009 296 return eval {
ad4f54b2 297 my $flat = $self->_encode($self->_deobjectify($data));
298 warn "$$ >>> ${flat}\n" if $DEBUG;
299 $flat;
70a578ac 300 } || do {
9d804009 301 my $err = $@; # won't get here if the eval doesn't die
302 # don't keep refs to new things
303 delete @{$self->local_objects_by_id}{@New_Ids};
304 die "Error serializing: $err";
305 };
9e72f0cf 306}
307
a76f2f60 308sub _local_object_to_id {
309 my ($self, $object) = @_;
310 my $id = refaddr($object);
311 $self->local_objects_by_id->{$id} ||= do {
3687a42d 312 push our(@New_Ids), $id if @New_Ids;
a76f2f60 313 $object;
314 };
315 return $id;
316}
317
9e72f0cf 318sub _deobjectify {
319 my ($self, $data) = @_;
320 if (blessed($data)) {
6163a5aa 321 if (
322 $data->isa('Object::Remote::Proxy')
323 and $data->{remote}->connection == $self
324 ) {
325 return +{ __local_object__ => $data->{remote}->id };
326 } else {
327 return +{ __remote_object__ => $self->_local_object_to_id($data) };
328 }
9e72f0cf 329 } elsif (my $ref = ref($data)) {
330 if ($ref eq 'HASH') {
7790ca36 331 my $tied_to = tied(%$data);
332 if(defined($tied_to)) {
333 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
334 } else {
335 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
336 }
9e72f0cf 337 } elsif ($ref eq 'ARRAY') {
7790ca36 338 my $tied_to = tied(@$data);
339 if (defined($tied_to)) {
340 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
341 } else {
342 return [ map $self->_deobjectify($_), @$data ];
343 }
fe6c9a7f 344 } elsif ($ref eq 'CODE') {
345 my $id = $self->_local_object_to_id(
346 Object::Remote::CodeContainer->new(code => $data)
347 );
348 return +{ __remote_code__ => $id };
6ed5d580 349 } elsif ($ref eq 'SCALAR') {
350 return +{ __scalar_ref__ => $$data };
ed5a8a8e 351 } elsif ($ref eq 'GLOB') {
352 return +{ __glob_ref__ => $self->_local_object_to_id(
353 Object::Remote::GlobContainer->new(handle => $data)
354 ) };
9e72f0cf 355 } else {
356 die "Can't collapse reftype $ref";
357 }
358 }
359 return $data; # plain scalar
360}
361
9e72f0cf 362sub _receive {
ad4f54b2 363 my ($self, $flat) = @_;
364 warn "$$ <<< $flat\n" if $DEBUG;
9031635d 365 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
ad4f54b2 366 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
367 or do { warn "Deserialize failed for ${flat}: $@"; return };
9031635d 368 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
9e72f0cf 369 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 370 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 371 return;
372}
373
374sub receive_free {
375 my ($self, $id) = @_;
9031635d 376 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
9d804009 377 delete $self->local_objects_by_id->{$id}
378 or warn "Free: no such object $id";
9e72f0cf 379 return;
380}
381
382sub receive_call {
deb77aaf 383 my ($self, $future_id, $id, @rest) = @_;
9031635d 384 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
deb77aaf 385 my $future = $self->_id_to_remote_object($future_id);
8131a88a 386 $future->{method} = 'call_discard_free';
9e72f0cf 387 my $local = $self->local_objects_by_id->{$id}
388 or do { $future->fail("No such object $id"); return };
389 $self->_invoke($future, $local, @rest);
390}
391
8131a88a 392sub receive_call_free {
393 my ($self, $future, $id, @rest) = @_;
9031635d 394 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
84b04178 395 $self->receive_call($future, $id, undef, @rest);
8131a88a 396 $self->receive_free($id);
397}
398
9e72f0cf 399sub _invoke {
84b04178 400 my ($self, $future, $local, $ctx, $method, @args) = @_;
9031635d 401 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
dc28afe8 402 if ($method =~ /^start::/) {
403 my $f = $local->$method(@args);
404 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 405 return unless $f;
dc28afe8 406 $f->on_fail(sub { undef($f); $future->fail(@_) });
407 return;
408 }
84b04178 409 my $do = sub { $local->$method(@args) };
410 eval {
411 $future->done(
412 defined($ctx)
413 ? ($ctx ? $do->() : scalar($do->()))
414 : do { $do->(); () }
415 );
416 1;
417 } or do { $future->fail($@); return; };
9e72f0cf 418 return;
419}
420
9e72f0cf 4211;
b9a9982d 422
423=head1 NAME
424
425Object::Remote::Connection - An underlying connection for L<Object::Remote>
426
427=head1 LAME
428
429Shipping prioritised over writing this part up. Blame mst.
430
431=cut