clean up calling system
[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'}
132     = Object::Remote::CodeContainer->new(
133         code => sub {
134           my ($class, $method) = (shift, shift);
135           use_module($class)->$method(@_);
136         }
137       );
138 }
139
140 sub register_remote {
141   my ($self, $remote) = @_;
142   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
143   return $remote;
144 }
145
146 sub await_ready {
147   my ($self) = @_;
148   await_future($self->ready_future);
149 }
150
151 sub send_free {
152   my ($self, $id) = @_;
153   delete $self->remote_objects_by_id->{$id};
154   $self->_send([ free => $id ]);
155 }
156
157 sub send {
158   my ($self, $type, @call) = @_;
159
160   my $future = CPS::Future->new;
161
162   unshift @call, $type => $self->_local_object_to_id($future);
163
164   my $outstanding = $self->outstanding_futures;
165   $outstanding->{$future} = $future;
166   $future->on_ready(sub { delete $outstanding->{$future} });
167
168   $self->_send(\@call);
169
170   return $future;
171 }
172
173 sub send_discard {
174   my ($self, $type, @call) = @_;
175
176   unshift @call, $type => 'NULL';
177
178   $self->_send(\@call);
179 }
180
181 sub _send {
182   my ($self, $to_send) = @_;
183
184   $self->await_ready;
185
186   print { $self->send_to_fh } $self->_serialize($to_send)."\n";
187 }
188
189 sub _serialize {
190   my ($self, $data) = @_;
191   local our @New_Ids;
192   return eval {
193     my $flat = $self->_encode($self->_deobjectify($data));
194     warn "$$ >>> ${flat}\n" if $DEBUG;
195     $flat;
196   } || do {
197     my $err = $@; # won't get here if the eval doesn't die
198     # don't keep refs to new things
199     delete @{$self->local_objects_by_id}{@New_Ids};
200     die "Error serializing: $err";
201   };
202 }
203
204 sub _local_object_to_id {
205   my ($self, $object) = @_;
206   my $id = refaddr($object);
207   $self->local_objects_by_id->{$id} ||= do {
208     push our(@New_Ids), $id;
209     $object;
210   };
211   return $id;
212 }
213
214 sub _deobjectify {
215   my ($self, $data) = @_;
216   if (blessed($data)) {
217     return +{ __remote_object__ => $self->_local_object_to_id($data) };
218   } elsif (my $ref = ref($data)) {
219     if ($ref eq 'HASH') {
220       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
221     } elsif ($ref eq 'ARRAY') {
222       return [ map $self->_deobjectify($_), @$data ];
223     } elsif ($ref eq 'CODE') {
224       my $id = $self->_local_object_to_id(
225                  Object::Remote::CodeContainer->new(code => $data)
226                );
227       return +{ __remote_code__ => $id };
228     } else {
229       die "Can't collapse reftype $ref";
230     }
231   }
232   return $data; # plain scalar
233 }
234
235 sub _receive_data_from {
236   my ($self, $fh) = @_;
237   my $rb = $self->_receive_data_buffer;
238   my $ready = $self->ready_future->is_ready;
239   my $len = sysread($fh, $$rb, 1024, length($$rb));
240   my $err = defined($len) ? '' : ": $!";
241   if (defined($len) and $len > 0) {
242     while ($$rb =~ s/^(.*)\n//) {
243       if ($ready) {
244         $self->_receive($1);
245       } else {
246         my $line = $1;
247         die "New remote container did not send Shere - got ${line}"
248           unless $line eq "Shere";
249         $self->ready_future->done;
250       }
251     }
252   } else {
253     Object::Remote->current_loop
254                   ->unwatch_io(
255                       handle => $self->receive_from_fh,
256                       on_read_ready => 1
257                     );
258     my $outstanding = $self->outstanding_futures;
259     $_->fail("Connection lost${err}") for values %$outstanding;
260     %$outstanding = ();
261     $self->on_close->done();
262   }
263 }
264
265 sub _receive {
266   my ($self, $flat) = @_;
267   warn "$$ <<< $flat\n" if $DEBUG;
268   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
269     or do { warn "Deserialize failed for ${flat}: $@"; return };
270   eval { $self->${\"receive_${type}"}(@rest); 1 }
271     or do { warn "Receive failed for ${flat}: $@"; return };
272   return;
273 }
274
275 sub receive_free {
276   my ($self, $id) = @_;
277   delete $self->local_objects_by_id->{$id}
278     or warn "Free: no such object $id";
279   return;
280 }
281
282 sub receive_call {
283   my ($self, $future_id, $id, @rest) = @_;
284   my $future = $self->_id_to_remote_object($future_id);
285   $future->{method} = 'call_discard_free';
286   my $local = $self->local_objects_by_id->{$id}
287     or do { $future->fail("No such object $id"); return };
288   $self->_invoke($future, $local, @rest);
289 }
290
291 sub receive_call_free {
292   my ($self, $future, $id, @rest) = @_;
293   $self->receive_call($future, $id, undef, @rest);
294   $self->receive_free($id);
295 }
296
297 sub receive_class_call {
298   my ($self, $future_id, $class, @rest) = @_;
299   my $future = $self->_id_to_remote_object($future_id);
300   $future->{method} = 'call_discard_free';
301   eval { use_module($class) }
302     or do { $future->fail("Error loading ${class}: $@"); return };
303   $self->_invoke($future, $class, @rest);
304 }
305
306 sub _invoke {
307   my ($self, $future, $local, $ctx, $method, @args) = @_;
308   if ($method =~ /^start::/) {
309     my $f = $local->$method(@args);
310     $f->on_done(sub { undef($f); $future->done(@_) });
311     return unless $f;
312     $f->on_fail(sub { undef($f); $future->fail(@_) });
313     return;
314   }
315   my $do = sub { $local->$method(@args) };
316   eval {
317     $future->done(
318       defined($ctx)
319         ? ($ctx ? $do->() : scalar($do->()))
320         : do { $do->(); () }
321     );
322     1;
323   } or do { $future->fail($@); return; };
324   return;
325 }
326
327 sub DEMOLISH {
328   my ($self, $gd) = @_;
329   return if $gd;
330   Object::Remote->current_loop
331                 ->unwatch_io(
332                     handle => $self->receive_from_fh,
333                     on_read_ready => 1
334                   );
335 }
336
337 1;