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