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