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;
2d81cf18 9use Object::Remote::Logging qw (:log :dlog);
b51a8453 10use Object::Remote::Tied;
9e72f0cf 11use Object::Remote;
ed5a8a8e 12use Symbol;
9e72f0cf 13use IO::Handle;
14use Module::Runtime qw(use_module);
8ed52376 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};
07105aca 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,
90a3a7f2 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) = @_;
8ed52376 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(@_) });
8ed52376 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
8ed52376 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 => (
8ed52376 61 is => 'rw', default => sub { CPS::Future->new },
07105aca 62 trigger => sub {
12fb4a80 63 my ($self, $f) = @_;
07105aca 64 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
12fb4a80 65 weaken($self);
66 $f->on_done(sub {
8ed52376 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) = @_;
07105aca 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) = @_;
07105aca 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 }
b51a8453 137 )->filter_json_single_key_object(
138 __remote_tied_hash__ => sub {
139 my %tied_hash;
140 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
141 return \%tied_hash;
142 }
143 )->filter_json_single_key_object(
144 __remote_tied_array__ => sub {
145 my @tied_array;
146 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
147 return \@tied_array;
148 }
149 );
9e72f0cf 150}
151
84b04178 152BEGIN {
153 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
154 eval { require Object::Remote::Connector::Local };
a9fdb55e 155 eval { require Object::Remote::Connector::LocalSudo };
84b04178 156 eval { require Object::Remote::Connector::SSH };
1d26d6f9 157 eval { require Object::Remote::Connector::UNIX };
84b04178 158}
159
160sub new_from_spec {
161 my ($class, $spec) = @_;
e144d525 162 return $spec if blessed $spec;
07105aca 163 Dlog_debug { "creating a new connection from spec" };
84b04178 164 foreach my $poss (do { our @Guess }) {
fbd3b8ec 165 if (my $conn = $poss->($spec)) {
166 return $conn->maybe::start::connect;
167 }
84b04178 168 }
169 die "Couldn't figure out what to do with ${spec}";
170}
171
11dbd4a0 172sub remote_object {
e144d525 173 my ($self, @args) = @_;
174 Object::Remote::Handle->new(
175 connection => $self, @args
176 )->proxy;
177}
178
4c17fea5 179sub connect {
180 my ($self, $to) = @_;
07105aca 181 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
deb77aaf 182 return await_future(
183 $self->send_class_call(0, 'Object::Remote', connect => $to)
184 );
4c17fea5 185}
186
11dbd4a0 187sub remote_sub {
c6fe6fbd 188 my ($self, $sub) = @_;
189 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
07105aca 190 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
deb77aaf 191 return await_future($self->send_class_call(0, $pkg, can => $name));
192}
193
194sub send_class_call {
195 my ($self, $ctx, @call) = @_;
07105aca 196 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
deb77aaf 197 $self->send(call => class_call_handler => $ctx => call => @call);
198}
199
200sub register_class_call_handler {
201 my ($self) = @_;
3687a42d 202 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 203 my $o = $self->new_class_call_handler;
3687a42d 204 $self->_local_object_to_id($o);
205 $o;
206 };
c6fe6fbd 207}
208
c5736e1c 209sub new_class_call_handler {
210 Object::Remote::CodeContainer->new(
211 code => sub {
212 my ($class, $method) = (shift, shift);
213 use_module($class)->$method(@_);
214 }
215 );
216}
217
9e72f0cf 218sub register_remote {
219 my ($self, $remote) = @_;
07105aca 220 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
9e72f0cf 221 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
222 return $remote;
223}
224
225sub send_free {
226 my ($self, $id) = @_;
b51a8453 227 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
9e72f0cf 228 delete $self->remote_objects_by_id->{$id};
229 $self->_send([ free => $id ]);
230}
231
232sub send {
233 my ($self, $type, @call) = @_;
234
deb77aaf 235 my $future = CPS::Future->new;
a2d43709 236 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 237
238 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 239
a980b0b8 240 my $outstanding = $self->outstanding_futures;
241 $outstanding->{$future} = $future;
a2d43709 242 $future->on_ready(sub {
243 undef($remote);
244 delete $outstanding->{$future}
245 });
a980b0b8 246
9e72f0cf 247 $self->_send(\@call);
248
249 return $future;
250}
251
9d804009 252sub send_discard {
253 my ($self, $type, @call) = @_;
254
deb77aaf 255 unshift @call, $type => 'NULL';
9d804009 256
257 $self->_send(\@call);
258}
259
9e72f0cf 260sub _send {
261 my ($self, $to_send) = @_;
2d81cf18 262 my $fh = $self->send_to_fh;
07105aca 263 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
2d81cf18 264 my $serialized = $self->_serialize($to_send)."\n";
5953edf6 265 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
2d81cf18 266 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
b51a8453 267 #logic it could easily do short-writes to the remote side - how about taking this entire buffer
268 #and having the run loop send it to the file handle so this doesn't block while the sending
269 #is happening?
8ed52376 270 my $ret;
271 eval {
272 local($SIG{PIPE}) = 'IGNORE';
273 die "filehandle is not open" unless openhandle($fh);
274 log_trace { "file handle has passed openhandle() test; printing to it" };
275 $ret = print $fh $serialized;
276 die "print was not successful: $!" unless defined $ret
277 };
278
279 if ($@) {
280 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
281 my $error = $@; chomp($error);
282 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
283 return;
284 }
285
2d81cf18 286 return $ret;
9e72f0cf 287}
288
289sub _serialize {
290 my ($self, $data) = @_;
3687a42d 291 local our @New_Ids = (-1);
9d804009 292 return eval {
ad4f54b2 293 my $flat = $self->_encode($self->_deobjectify($data));
294 warn "$$ >>> ${flat}\n" if $DEBUG;
295 $flat;
70a578ac 296 } || do {
9d804009 297 my $err = $@; # won't get here if the eval doesn't die
298 # don't keep refs to new things
299 delete @{$self->local_objects_by_id}{@New_Ids};
300 die "Error serializing: $err";
301 };
9e72f0cf 302}
303
a76f2f60 304sub _local_object_to_id {
305 my ($self, $object) = @_;
306 my $id = refaddr($object);
307 $self->local_objects_by_id->{$id} ||= do {
3687a42d 308 push our(@New_Ids), $id if @New_Ids;
a76f2f60 309 $object;
310 };
311 return $id;
312}
313
9e72f0cf 314sub _deobjectify {
315 my ($self, $data) = @_;
316 if (blessed($data)) {
a76f2f60 317 return +{ __remote_object__ => $self->_local_object_to_id($data) };
9e72f0cf 318 } elsif (my $ref = ref($data)) {
319 if ($ref eq 'HASH') {
b51a8453 320 my $tied_to = tied(%$data);
321 if(defined($tied_to)) {
322 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
323 } else {
324 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
325 }
9e72f0cf 326 } elsif ($ref eq 'ARRAY') {
b51a8453 327 my $tied_to = tied(@$data);
328 if (defined($tied_to)) {
329 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
330 } else {
331 return [ map $self->_deobjectify($_), @$data ];
332 }
fe6c9a7f 333 } elsif ($ref eq 'CODE') {
334 my $id = $self->_local_object_to_id(
335 Object::Remote::CodeContainer->new(code => $data)
336 );
337 return +{ __remote_code__ => $id };
6ed5d580 338 } elsif ($ref eq 'SCALAR') {
339 return +{ __scalar_ref__ => $$data };
ed5a8a8e 340 } elsif ($ref eq 'GLOB') {
341 return +{ __glob_ref__ => $self->_local_object_to_id(
342 Object::Remote::GlobContainer->new(handle => $data)
343 ) };
9e72f0cf 344 } else {
345 die "Can't collapse reftype $ref";
346 }
347 }
348 return $data; # plain scalar
349}
350
9e72f0cf 351sub _receive {
ad4f54b2 352 my ($self, $flat) = @_;
353 warn "$$ <<< $flat\n" if $DEBUG;
07105aca 354 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
ad4f54b2 355 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
356 or do { warn "Deserialize failed for ${flat}: $@"; return };
07105aca 357 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
9e72f0cf 358 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 359 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 360 return;
361}
362
363sub receive_free {
364 my ($self, $id) = @_;
07105aca 365 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
9d804009 366 delete $self->local_objects_by_id->{$id}
367 or warn "Free: no such object $id";
9e72f0cf 368 return;
369}
370
371sub receive_call {
deb77aaf 372 my ($self, $future_id, $id, @rest) = @_;
07105aca 373 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
deb77aaf 374 my $future = $self->_id_to_remote_object($future_id);
8131a88a 375 $future->{method} = 'call_discard_free';
9e72f0cf 376 my $local = $self->local_objects_by_id->{$id}
377 or do { $future->fail("No such object $id"); return };
378 $self->_invoke($future, $local, @rest);
379}
380
8131a88a 381sub receive_call_free {
382 my ($self, $future, $id, @rest) = @_;
07105aca 383 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
84b04178 384 $self->receive_call($future, $id, undef, @rest);
8131a88a 385 $self->receive_free($id);
386}
387
9e72f0cf 388sub _invoke {
84b04178 389 my ($self, $future, $local, $ctx, $method, @args) = @_;
07105aca 390 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
dc28afe8 391 if ($method =~ /^start::/) {
392 my $f = $local->$method(@args);
393 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 394 return unless $f;
dc28afe8 395 $f->on_fail(sub { undef($f); $future->fail(@_) });
396 return;
397 }
84b04178 398 my $do = sub { $local->$method(@args) };
399 eval {
400 $future->done(
401 defined($ctx)
402 ? ($ctx ? $do->() : scalar($do->()))
403 : do { $do->(); () }
404 );
405 1;
406 } or do { $future->fail($@); return; };
9e72f0cf 407 return;
408}
409
9e72f0cf 4101;
b9a9982d 411
412=head1 NAME
413
414Object::Remote::Connection - An underlying connection for L<Object::Remote>
415
416=head1 LAME
417
418Shipping prioritised over writing this part up. Blame mst.
419
420=cut