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