add __local_object__
[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 read_channel => (
25   is => 'ro', required => 1,
26   trigger => sub {
27     my ($self, $ch) = @_;
28     weaken($self);
29     $ch->on_line_call(sub { $self->_receive(@_) });
30     $ch->on_close_call(sub { $self->on_close->done(@_) });
31   },
32 );
33
34 has on_close => (
35   is => 'ro', default => sub { CPS::Future->new },
36   trigger => sub { 
37     my ($self, $f) = @_;
38     weaken($self);
39     $f->on_done(sub {
40       $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
41     });
42   }
43 );
44
45 has child_pid => (is => 'ro');
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 sub _fail_outstanding {
60   my ($self, $error) = @_;
61   my $outstanding = $self->outstanding_futures;
62   $_->fail($error) for values %$outstanding;
63   %$outstanding = ();
64   return;
65 }
66
67 has _json => (
68   is => 'lazy',
69   handles => {
70     _deserialize => 'decode',
71     _encode => 'encode',
72   },
73 );
74
75 sub _id_to_remote_object {
76   my ($self, $id) = @_;
77   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
78   (
79     $self->remote_objects_by_id->{$id}
80     or Object::Remote::Handle->new(connection => $self, id => $id)
81   )->proxy;
82 }
83
84 sub _build__json {
85   weaken(my $self = shift);
86   JSON::PP->new->filter_json_single_key_object(
87     __remote_object__ => sub {
88       $self->_id_to_remote_object(@_);
89     }
90   )->filter_json_single_key_object(
91     __remote_code__ => sub {
92       my $code_container = $self->_id_to_remote_object(@_);
93       sub { $code_container->call(@_) };
94     }
95   )->filter_json_single_key_object(
96     __scalar_ref__ => sub {
97       my $value = shift;
98       return \$value;
99     }
100   )->filter_json_single_key_object(
101     __glob_ref__ => sub {
102       my $glob_container = $self->_id_to_remote_object(@_);
103       my $handle = Symbol::gensym;
104       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
105       return $handle;
106     }
107   )->filter_json_single_key_object(
108     __local_object__ => sub {
109       $self->local_objects_by_id->{$_[0]}
110     }
111   );
112 }
113
114 BEGIN {
115   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
116   eval { require Object::Remote::Connector::Local };
117   eval { require Object::Remote::Connector::LocalSudo };
118   eval { require Object::Remote::Connector::SSH };
119   eval { require Object::Remote::Connector::UNIX };
120 }
121
122 sub new_from_spec {
123   my ($class, $spec) = @_;
124   return $spec if blessed $spec;
125   foreach my $poss (do { our @Guess }) {
126     if (my $conn = $poss->($spec)) {
127       return $conn->maybe::start::connect;
128     }
129   }
130   die "Couldn't figure out what to do with ${spec}";
131 }
132
133 sub remote_object {
134   my ($self, @args) = @_;
135   Object::Remote::Handle->new(
136     connection => $self, @args
137   )->proxy;
138 }
139
140 sub connect {
141   my ($self, $to) = @_;
142   return await_future(
143     $self->send_class_call(0, 'Object::Remote', connect => $to)
144   );
145 }
146
147 sub remote_sub {
148   my ($self, $sub) = @_;
149   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
150   return await_future($self->send_class_call(0, $pkg, can => $name));
151 }
152
153 sub send_class_call {
154   my ($self, $ctx, @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   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
179   return $remote;
180 }
181
182 sub send_free {
183   my ($self, $id) = @_;
184   delete $self->remote_objects_by_id->{$id};
185   $self->_send([ free => $id ]);
186 }
187
188 sub send {
189   my ($self, $type, @call) = @_;
190
191   my $future = CPS::Future->new;
192   my $remote = $self->remote_objects_by_id->{$call[0]};
193
194   unshift @call, $type => $self->_local_object_to_id($future);
195
196   my $outstanding = $self->outstanding_futures;
197   $outstanding->{$future} = $future;
198   $future->on_ready(sub {
199     undef($remote);
200     delete $outstanding->{$future}
201   });
202
203   $self->_send(\@call);
204
205   return $future;
206 }
207
208 sub send_discard {
209   my ($self, $type, @call) = @_;
210
211   unshift @call, $type => 'NULL';
212
213   $self->_send(\@call);
214 }
215
216 sub _send {
217   my ($self, $to_send) = @_;
218
219   print { $self->send_to_fh } $self->_serialize($to_send)."\n";
220 }
221
222 sub _serialize {
223   my ($self, $data) = @_;
224   local our @New_Ids = (-1);
225   return eval {
226     my $flat = $self->_encode($self->_deobjectify($data));
227     warn "$$ >>> ${flat}\n" if $DEBUG;
228     $flat;
229   } || do {
230     my $err = $@; # won't get here if the eval doesn't die
231     # don't keep refs to new things
232     delete @{$self->local_objects_by_id}{@New_Ids};
233     die "Error serializing: $err";
234   };
235 }
236
237 sub _local_object_to_id {
238   my ($self, $object) = @_;
239   my $id = refaddr($object);
240   $self->local_objects_by_id->{$id} ||= do {
241     push our(@New_Ids), $id if @New_Ids;
242     $object;
243   };
244   return $id;
245 }
246
247 sub _deobjectify {
248   my ($self, $data) = @_;
249   if (blessed($data)) {
250     if (
251       $data->isa('Object::Remote::Proxy')
252       and $data->{remote}->connection == $self
253     ) {
254       return +{ __local_object__ => $data->{remote}->id };
255     } else {
256       return +{ __remote_object__ => $self->_local_object_to_id($data) };
257     }
258   } elsif (my $ref = ref($data)) {
259     if ($ref eq 'HASH') {
260       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
261     } elsif ($ref eq 'ARRAY') {
262       return [ map $self->_deobjectify($_), @$data ];
263     } elsif ($ref eq 'CODE') {
264       my $id = $self->_local_object_to_id(
265                  Object::Remote::CodeContainer->new(code => $data)
266                );
267       return +{ __remote_code__ => $id };
268     } elsif ($ref eq 'SCALAR') {
269       return +{ __scalar_ref__ => $$data };
270     } elsif ($ref eq 'GLOB') {
271       return +{ __glob_ref__ => $self->_local_object_to_id(
272         Object::Remote::GlobContainer->new(handle => $data)
273       ) };
274     } else {
275       die "Can't collapse reftype $ref";
276     }
277   }
278   return $data; # plain scalar
279 }
280
281 sub _receive {
282   my ($self, $flat) = @_;
283   warn "$$ <<< $flat\n" if $DEBUG;
284   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
285     or do { warn "Deserialize failed for ${flat}: $@"; return };
286   eval { $self->${\"receive_${type}"}(@rest); 1 }
287     or do { warn "Receive failed for ${flat}: $@"; return };
288   return;
289 }
290
291 sub receive_free {
292   my ($self, $id) = @_;
293   delete $self->local_objects_by_id->{$id}
294     or warn "Free: no such object $id";
295   return;
296 }
297
298 sub receive_call {
299   my ($self, $future_id, $id, @rest) = @_;
300   my $future = $self->_id_to_remote_object($future_id);
301   $future->{method} = 'call_discard_free';
302   my $local = $self->local_objects_by_id->{$id}
303     or do { $future->fail("No such object $id"); return };
304   $self->_invoke($future, $local, @rest);
305 }
306
307 sub receive_call_free {
308   my ($self, $future, $id, @rest) = @_;
309   $self->receive_call($future, $id, undef, @rest);
310   $self->receive_free($id);
311 }
312
313 sub _invoke {
314   my ($self, $future, $local, $ctx, $method, @args) = @_;
315   if ($method =~ /^start::/) {
316     my $f = $local->$method(@args);
317     $f->on_done(sub { undef($f); $future->done(@_) });
318     return unless $f;
319     $f->on_fail(sub { undef($f); $future->fail(@_) });
320     return;
321   }
322   my $do = sub { $local->$method(@args) };
323   eval {
324     $future->done(
325       defined($ctx)
326         ? ($ctx ? $do->() : scalar($do->()))
327         : do { $do->(); () }
328     );
329     1;
330   } or do { $future->fail($@); return; };
331   return;
332 }
333
334 1;
335
336 =head1 NAME
337
338 Object::Remote::Connection - An underlying connection for L<Object::Remote>
339
340 =head1 LAME
341
342 Shipping prioritised over writing this part up. Blame mst.
343
344 =cut