found location of hang; make annotations; added more log lines
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
1 package Object::Remote::Connection;
2
3 use Object::Remote::Future;
4 use Object::Remote::Null;
5 use Object::Remote::Handle;
6 use Object::Remote::CodeContainer;
7 use Object::Remote::GlobProxy;
8 use Object::Remote::GlobContainer;
9 use Object::Remote::Logging qw (:log :dlog);
10 use Object::Remote;
11 use Symbol;
12 use IO::Handle;
13 use Module::Runtime qw(use_module);
14 use Scalar::Util qw(weaken blessed refaddr);
15 use JSON::PP qw(encode_json);
16 use Moo;
17
18 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
19
20 has send_to_fh => (
21   is => 'ro', required => 1,
22   trigger => sub { $_[1]->autoflush(1) },
23 );
24
25 has read_channel => (
26   is => 'ro', required => 1,
27   trigger => sub {
28     my ($self, $ch) = @_;
29     weaken($self);
30     $ch->on_line_call(sub { $self->_receive(@_) });
31     $ch->on_close_call(sub { $self->on_close->done(@_) });
32   },
33 );
34
35 has on_close => (
36   is => 'ro', default => sub { CPS::Future->new },
37   trigger => sub { 
38     my ($self, $f) = @_;
39     weaken($self);
40     $f->on_done(sub {
41       $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
42     });
43   }
44 );
45
46 has child_pid => (is => 'ro');
47
48 has local_objects_by_id => (
49   is => 'ro', default => sub { {} },
50   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
51 );
52
53 has remote_objects_by_id => (
54   is => 'ro', default => sub { {} },
55   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
56 );
57
58 has outstanding_futures => (is => 'ro', default => sub { {} });
59
60 sub _fail_outstanding {
61   my ($self, $error) = @_;
62   my $outstanding = $self->outstanding_futures;
63   $_->fail($error) for values %$outstanding;
64   %$outstanding = ();
65   return;
66 }
67
68 has _json => (
69   is => 'lazy',
70   handles => {
71     _deserialize => 'decode',
72     _encode => 'encode',
73   },
74 );
75
76 sub _id_to_remote_object {
77   my ($self, $id) = @_;
78   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
79   (
80     $self->remote_objects_by_id->{$id}
81     or Object::Remote::Handle->new(connection => $self, id => $id)
82   )->proxy;
83 }
84
85 sub _build__json {
86   weaken(my $self = shift);
87   JSON::PP->new->filter_json_single_key_object(
88     __remote_object__ => sub {
89       $self->_id_to_remote_object(@_);
90     }
91   )->filter_json_single_key_object(
92     __remote_code__ => sub {
93       my $code_container = $self->_id_to_remote_object(@_);
94       sub { $code_container->call(@_) };
95     }
96   )->filter_json_single_key_object(
97     __scalar_ref__ => sub {
98       my $value = shift;
99       return \$value;
100     }
101   )->filter_json_single_key_object(
102     __glob_ref__ => sub {
103       my $glob_container = $self->_id_to_remote_object(@_);
104       my $handle = Symbol::gensym;
105       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
106       return $handle;
107     }
108   );
109 }
110
111 BEGIN {
112   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
113   eval { require Object::Remote::Connector::Local };
114   eval { require Object::Remote::Connector::LocalSudo };
115   eval { require Object::Remote::Connector::SSH };
116   eval { require Object::Remote::Connector::UNIX };
117 }
118
119 sub new_from_spec {
120   my ($class, $spec) = @_;
121   return $spec if blessed $spec;
122   foreach my $poss (do { our @Guess }) {
123     if (my $conn = $poss->($spec)) {
124       return $conn->maybe::start::connect;
125     }
126   }
127   die "Couldn't figure out what to do with ${spec}";
128 }
129
130 sub remote_object {
131   my ($self, @args) = @_;
132   Object::Remote::Handle->new(
133     connection => $self, @args
134   )->proxy;
135 }
136
137 sub connect {
138   my ($self, $to) = @_;
139   Dlog_debug { "Creating connection to remote node $_" } $to;
140   return await_future(
141     $self->send_class_call(0, 'Object::Remote', connect => $to)
142   );
143 }
144
145 sub remote_sub {
146   my ($self, $sub) = @_;
147   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
148   log_debug { "Invoking remote sub '$sub'" };
149   return await_future($self->send_class_call(0, $pkg, can => $name));
150 }
151
152 sub send_class_call {
153   my ($self, $ctx, @call) = @_;
154   log_trace { "Sending a non-blocking class call" };
155   $self->send(call => class_call_handler => $ctx => call => @call);
156 }
157
158 sub register_class_call_handler {
159   my ($self) = @_;
160   $self->local_objects_by_id->{'class_call_handler'} ||= do {
161     my $o = $self->new_class_call_handler;
162     $self->_local_object_to_id($o);
163     $o;
164   };
165 }
166
167 sub new_class_call_handler {
168   Object::Remote::CodeContainer->new(
169     code => sub {
170       my ($class, $method) = (shift, shift);
171       use_module($class)->$method(@_);
172     }
173   );
174 }
175
176 sub register_remote {
177   my ($self, $remote) = @_;
178   log_trace { my $i = $remote->id; "Registered a remote object with id of '$i'" };
179   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
180   return $remote;
181 }
182
183 sub send_free {
184   my ($self, $id) = @_;
185   log_debug { "sending request to free object '$id'" };
186   delete $self->remote_objects_by_id->{$id};
187   $self->_send([ free => $id ]);
188 }
189
190 sub send {
191   my ($self, $type, @call) = @_;
192
193   my $future = CPS::Future->new;
194   my $remote = $self->remote_objects_by_id->{$call[0]};
195
196   unshift @call, $type => $self->_local_object_to_id($future);
197
198   my $outstanding = $self->outstanding_futures;
199   $outstanding->{$future} = $future;
200   $future->on_ready(sub {
201     undef($remote);
202     delete $outstanding->{$future}
203   });
204
205   $self->_send(\@call);
206
207   return $future;
208 }
209
210 sub send_discard {
211   my ($self, $type, @call) = @_;
212
213   unshift @call, $type => 'NULL';
214
215   $self->_send(\@call);
216 }
217
218 sub _send {
219   my ($self, $to_send) = @_;
220   my $fh = $self->send_to_fh;
221   my $serialized = $self->_serialize($to_send)."\n";
222   Dlog_debug { my $l = length($serialized); "Sending '$l' characters of serialized data to $_" } $fh;
223   #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
224   #logic it could easily do short-writes to the remote side
225   my $ret = print $fh $serialized;
226   Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
227   #TODO hrm reason print's return value was ignored?
228   die "could not write to filehandle: $!" unless $ret;
229   return $ret; 
230 }
231
232 sub _serialize {
233   my ($self, $data) = @_;
234   local our @New_Ids = (-1);
235   return eval {
236     my $flat = $self->_encode($self->_deobjectify($data));
237     warn "$$ >>> ${flat}\n" if $DEBUG;
238     $flat;
239   } || do {
240     my $err = $@; # won't get here if the eval doesn't die
241     # don't keep refs to new things
242     delete @{$self->local_objects_by_id}{@New_Ids};
243     die "Error serializing: $err";
244   };
245 }
246
247 sub _local_object_to_id {
248   my ($self, $object) = @_;
249   my $id = refaddr($object);
250   $self->local_objects_by_id->{$id} ||= do {
251     push our(@New_Ids), $id if @New_Ids;
252     $object;
253   };
254   return $id;
255 }
256
257 sub _deobjectify {
258   my ($self, $data) = @_;
259   if (blessed($data)) {
260     return +{ __remote_object__ => $self->_local_object_to_id($data) };
261   } elsif (my $ref = ref($data)) {
262     if ($ref eq 'HASH') {
263       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
264     } elsif ($ref eq 'ARRAY') {
265       return [ map $self->_deobjectify($_), @$data ];
266     } elsif ($ref eq 'CODE') {
267       my $id = $self->_local_object_to_id(
268                  Object::Remote::CodeContainer->new(code => $data)
269                );
270       return +{ __remote_code__ => $id };
271     } elsif ($ref eq 'SCALAR') {
272       return +{ __scalar_ref__ => $$data };
273     } elsif ($ref eq 'GLOB') {
274       return +{ __glob_ref__ => $self->_local_object_to_id(
275         Object::Remote::GlobContainer->new(handle => $data)
276       ) };
277     } else {
278       die "Can't collapse reftype $ref";
279     }
280   }
281   return $data; # plain scalar
282 }
283
284 sub _receive {
285   my ($self, $flat) = @_;
286   warn "$$ <<< $flat\n" if $DEBUG;
287   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
288     or do { warn "Deserialize failed for ${flat}: $@"; return };
289   eval { $self->${\"receive_${type}"}(@rest); 1 }
290     or do { warn "Receive failed for ${flat}: $@"; return };
291   return;
292 }
293
294 sub receive_free {
295   my ($self, $id) = @_;
296   delete $self->local_objects_by_id->{$id}
297     or warn "Free: no such object $id";
298   return;
299 }
300
301 sub receive_call {
302   my ($self, $future_id, $id, @rest) = @_;
303   my $future = $self->_id_to_remote_object($future_id);
304   $future->{method} = 'call_discard_free';
305   my $local = $self->local_objects_by_id->{$id}
306     or do { $future->fail("No such object $id"); return };
307   $self->_invoke($future, $local, @rest);
308 }
309
310 sub receive_call_free {
311   my ($self, $future, $id, @rest) = @_;
312   $self->receive_call($future, $id, undef, @rest);
313   $self->receive_free($id);
314 }
315
316 sub _invoke {
317   my ($self, $future, $local, $ctx, $method, @args) = @_;
318   if ($method =~ /^start::/) {
319     my $f = $local->$method(@args);
320     $f->on_done(sub { undef($f); $future->done(@_) });
321     return unless $f;
322     $f->on_fail(sub { undef($f); $future->fail(@_) });
323     return;
324   }
325   my $do = sub { $local->$method(@args) };
326   eval {
327     $future->done(
328       defined($ctx)
329         ? ($ctx ? $do->() : scalar($do->()))
330         : do { $do->(); () }
331     );
332     1;
333   } or do { $future->fail($@); return; };
334   return;
335 }
336
337 1;
338
339 =head1 NAME
340
341 Object::Remote::Connection - An underlying connection for L<Object::Remote>
342
343 =head1 LAME
344
345 Shipping prioritised over writing this part up. Blame mst.
346
347 =cut