allow scalar refs 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;
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   )->filter_json_single_key_object(
85     __scalar_ref__ => sub {
86       my $value = shift;
87       return \$value;
88     }
89   );
90 }
91
92 BEGIN {
93   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
94   eval { require Object::Remote::Connector::Local };
95   eval { require Object::Remote::Connector::LocalSudo };
96   eval { require Object::Remote::Connector::SSH };
97   eval { require Object::Remote::Connector::UNIX };
98 }
99
100 sub new_from_spec {
101   my ($class, $spec) = @_;
102   return $spec if blessed $spec;
103   foreach my $poss (do { our @Guess }) {
104     if (my $obj = $poss->($spec)) { return $obj }
105   }
106   die "Couldn't figure out what to do with ${spec}";
107 }
108
109 sub remote_object {
110   my ($self, @args) = @_;
111   Object::Remote::Handle->new(
112     connection => $self, @args
113   )->proxy;
114 }
115
116 sub connect {
117   my ($self, $to) = @_;
118   return await_future(
119     $self->send_class_call(0, 'Object::Remote', connect => $to)
120   );
121 }
122
123 sub remote_sub {
124   my ($self, $sub) = @_;
125   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
126   return await_future($self->send_class_call(0, $pkg, can => $name));
127 }
128
129 sub send_class_call {
130   my ($self, $ctx, @call) = @_;
131   $self->send(call => class_call_handler => $ctx => call => @call);
132 }
133
134 sub register_class_call_handler {
135   my ($self) = @_;
136   $self->local_objects_by_id->{'class_call_handler'} ||= do {
137     my $o = $self->new_class_call_handler;
138     $self->_local_object_to_id($o);
139     $o;
140   };
141 }
142
143 sub new_class_call_handler {
144   Object::Remote::CodeContainer->new(
145     code => sub {
146       my ($class, $method) = (shift, shift);
147       use_module($class)->$method(@_);
148     }
149   );
150 }
151
152 sub register_remote {
153   my ($self, $remote) = @_;
154   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
155   return $remote;
156 }
157
158 sub await_ready {
159   my ($self) = @_;
160   await_future($self->ready_future);
161 }
162
163 sub send_free {
164   my ($self, $id) = @_;
165   delete $self->remote_objects_by_id->{$id};
166   $self->_send([ free => $id ]);
167 }
168
169 sub send {
170   my ($self, $type, @call) = @_;
171
172   my $future = CPS::Future->new;
173   my $remote = $self->remote_objects_by_id->{$call[0]};
174
175   unshift @call, $type => $self->_local_object_to_id($future);
176
177   my $outstanding = $self->outstanding_futures;
178   $outstanding->{$future} = $future;
179   $future->on_ready(sub {
180     undef($remote);
181     delete $outstanding->{$future}
182   });
183
184   $self->_send(\@call);
185
186   return $future;
187 }
188
189 sub send_discard {
190   my ($self, $type, @call) = @_;
191
192   unshift @call, $type => 'NULL';
193
194   $self->_send(\@call);
195 }
196
197 sub _send {
198   my ($self, $to_send) = @_;
199
200   $self->await_ready;
201
202   print { $self->send_to_fh } $self->_serialize($to_send)."\n";
203 }
204
205 sub _serialize {
206   my ($self, $data) = @_;
207   local our @New_Ids = (-1);
208   return eval {
209     my $flat = $self->_encode($self->_deobjectify($data));
210     warn "$$ >>> ${flat}\n" if $DEBUG;
211     $flat;
212   } || do {
213     my $err = $@; # won't get here if the eval doesn't die
214     # don't keep refs to new things
215     delete @{$self->local_objects_by_id}{@New_Ids};
216     die "Error serializing: $err";
217   };
218 }
219
220 sub _local_object_to_id {
221   my ($self, $object) = @_;
222   my $id = refaddr($object);
223   $self->local_objects_by_id->{$id} ||= do {
224     push our(@New_Ids), $id if @New_Ids;
225     $object;
226   };
227   return $id;
228 }
229
230 sub _deobjectify {
231   my ($self, $data) = @_;
232   if (blessed($data)) {
233     return +{ __remote_object__ => $self->_local_object_to_id($data) };
234   } elsif (my $ref = ref($data)) {
235     if ($ref eq 'HASH') {
236       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
237     } elsif ($ref eq 'ARRAY') {
238       return [ map $self->_deobjectify($_), @$data ];
239     } elsif ($ref eq 'CODE') {
240       my $id = $self->_local_object_to_id(
241                  Object::Remote::CodeContainer->new(code => $data)
242                );
243       return +{ __remote_code__ => $id };
244     } elsif ($ref eq 'SCALAR') {
245       return +{ __scalar_ref__ => $$data };
246     } else {
247       die "Can't collapse reftype $ref";
248     }
249   }
250   return $data; # plain scalar
251 }
252
253 sub _receive_data_from {
254   my ($self, $fh) = @_;
255   my $rb = $self->_receive_data_buffer;
256   my $ready = $self->ready_future->is_ready;
257   my $len = sysread($fh, $$rb, 1024, length($$rb));
258   my $err = defined($len) ? '' : ": $!";
259   if (defined($len) and $len > 0) {
260     while ($$rb =~ s/^(.*)\n//) {
261       if ($ready) {
262         $self->_receive($1);
263       } else {
264         my $line = $1;
265         die "New remote container did not send Shere - got ${line}"
266           unless $line eq "Shere";
267         $self->ready_future->done;
268       }
269     }
270   } else {
271     Object::Remote->current_loop
272                   ->unwatch_io(
273                       handle => $self->receive_from_fh,
274                       on_read_ready => 1
275                     );
276     my $outstanding = $self->outstanding_futures;
277     $_->fail("Connection lost${err}") for values %$outstanding;
278     %$outstanding = ();
279     $self->on_close->done();
280   }
281 }
282
283 sub _receive {
284   my ($self, $flat) = @_;
285   warn "$$ <<< $flat\n" if $DEBUG;
286   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
287     or do { warn "Deserialize failed for ${flat}: $@"; return };
288   eval { $self->${\"receive_${type}"}(@rest); 1 }
289     or do { warn "Receive failed for ${flat}: $@"; return };
290   return;
291 }
292
293 sub receive_free {
294   my ($self, $id) = @_;
295   delete $self->local_objects_by_id->{$id}
296     or warn "Free: no such object $id";
297   return;
298 }
299
300 sub receive_call {
301   my ($self, $future_id, $id, @rest) = @_;
302   my $future = $self->_id_to_remote_object($future_id);
303   $future->{method} = 'call_discard_free';
304   my $local = $self->local_objects_by_id->{$id}
305     or do { $future->fail("No such object $id"); return };
306   $self->_invoke($future, $local, @rest);
307 }
308
309 sub receive_call_free {
310   my ($self, $future, $id, @rest) = @_;
311   $self->receive_call($future, $id, undef, @rest);
312   $self->receive_free($id);
313 }
314
315 sub _invoke {
316   my ($self, $future, $local, $ctx, $method, @args) = @_;
317   if ($method =~ /^start::/) {
318     my $f = $local->$method(@args);
319     $f->on_done(sub { undef($f); $future->done(@_) });
320     return unless $f;
321     $f->on_fail(sub { undef($f); $future->fail(@_) });
322     return;
323   }
324   my $do = sub { $local->$method(@args) };
325   eval {
326     $future->done(
327       defined($ctx)
328         ? ($ctx ? $do->() : scalar($do->()))
329         : do { $do->(); () }
330     );
331     1;
332   } or do { $future->fail($@); return; };
333   return;
334 }
335
336 sub DEMOLISH {
337   my ($self, $gd) = @_;
338   return if $gd;
339   Object::Remote->current_loop
340                 ->unwatch_io(
341                     handle => $self->receive_from_fh,
342                     on_read_ready => 1
343                   );
344 }
345
346 1;
347
348 =head1 NAME
349
350 Object::Remote::Connection - An underlying connection for L<Object::Remote>
351
352 =head1 LAME
353
354 Shipping prioritised over writing this part up. Blame mst.
355
356 =cut