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