eliminate is_ready attr in favour of ready_future
[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 => (is => 'ro', default => sub { {} });
45
46 has remote_objects_by_id => (is => 'ro', default => sub { {} });
47
48 has outstanding_futures => (is => 'ro', default => sub { {} });
49
50 has _json => (
51   is => 'lazy',
52   handles => {
53     _deserialize => 'decode',
54     _encode => 'encode',
55   },
56 );
57
58 sub _id_to_remote_object {
59   my ($self, $id) = @_;
60   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
61   (
62     $self->remote_objects_by_id->{$id}
63     or Object::Remote::Handle->new(connection => $self, id => $id)
64   )->proxy;
65 }
66
67 sub _build__json {
68   weaken(my $self = shift);
69   JSON::PP->new->filter_json_single_key_object(
70     __remote_object__ => sub {
71       $self->_id_to_remote_object(@_);
72     }
73   )->filter_json_single_key_object(
74     __remote_code__ => sub {
75       my $code_container = $self->_id_to_remote_object(@_);
76       sub { $code_container->call(@_) };
77     }
78   );
79 }
80
81 BEGIN {
82   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
83   eval { require Object::Remote::Connector::Local };
84   eval { require Object::Remote::Connector::LocalSudo };
85   eval { require Object::Remote::Connector::SSH };
86 }
87
88 sub new_from_spec {
89   my ($class, $spec) = @_;
90   return $spec if blessed $spec;
91   foreach my $poss (do { our @Guess }) {
92     if (my $obj = $poss->($spec)) { return $obj }
93   }
94   die "Couldn't figure out what to do with ${spec}";
95 }
96
97 sub new_remote {
98   my ($self, @args) = @_;
99   Object::Remote::Handle->new(
100     connection => $self, @args
101   )->proxy;
102 }
103
104 sub connect {
105   my ($self, $to) = @_;
106   return await_future($self->send(
107     class_call => 'Object::Remote', 0, connect => $to
108   ));
109 }
110
111 sub get_remote_sub {
112   my ($self, $sub) = @_;
113   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
114   return await_future($self->send(class_call => $pkg, 0, can => $name));
115 }
116
117 sub register_remote {
118   my ($self, $remote) = @_;
119   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
120   return $remote;
121 }
122
123 sub await_ready {
124   my ($self) = @_;
125   await_future($self->ready_future);
126 }
127
128 sub send_free {
129   my ($self, $id) = @_;
130   delete $self->remote_objects_by_id->{$id};
131   $self->_send([ free => $id ]);
132 }
133
134 sub send {
135   my ($self, $type, @call) = @_;
136
137   unshift @call, $type => my $future = CPS::Future->new;
138
139   my $outstanding = $self->outstanding_futures;
140   $outstanding->{$future} = $future;
141   $future->on_ready(sub { delete $outstanding->{$future} });
142
143   $self->_send(\@call);
144
145   return $future;
146 }
147
148 sub send_discard {
149   my ($self, $type, @call) = @_;
150
151   unshift @call, $type => { __remote_object__ => 'NULL' };
152
153   $self->_send(\@call);
154 }
155
156 sub _send {
157   my ($self, $to_send) = @_;
158
159   $self->await_ready;
160
161   print { $self->send_to_fh } $self->_serialize($to_send)."\n";
162 }
163
164 sub _serialize {
165   my ($self, $data) = @_;
166   local our @New_Ids;
167   return eval {
168     my $flat = $self->_encode($self->_deobjectify($data));
169     warn "$$ >>> ${flat}\n" if $DEBUG;
170     $flat;
171   } || do {
172     my $err = $@; # won't get here if the eval doesn't die
173     # don't keep refs to new things
174     delete @{$self->local_objects_by_id}{@New_Ids};
175     die "Error serializing: $err";
176   };
177 }
178
179 sub _local_object_to_id {
180   my ($self, $object) = @_;
181   my $id = refaddr($object);
182   $self->local_objects_by_id->{$id} ||= do {
183     push our(@New_Ids), $id;
184     $object;
185   };
186   return $id;
187 }
188
189 sub _deobjectify {
190   my ($self, $data) = @_;
191   if (blessed($data)) {
192     return +{ __remote_object__ => $self->_local_object_to_id($data) };
193   } elsif (my $ref = ref($data)) {
194     if ($ref eq 'HASH') {
195       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
196     } elsif ($ref eq 'ARRAY') {
197       return [ map $self->_deobjectify($_), @$data ];
198     } elsif ($ref eq 'CODE') {
199       my $id = $self->_local_object_to_id(
200                  Object::Remote::CodeContainer->new(code => $data)
201                );
202       return +{ __remote_code__ => $id };
203     } else {
204       die "Can't collapse reftype $ref";
205     }
206   }
207   return $data; # plain scalar
208 }
209
210 sub _receive_data_from {
211   my ($self, $fh) = @_;
212   my $rb = $self->_receive_data_buffer;
213   my $ready = $self->ready_future->is_ready;
214   if (sysread($fh, $$rb, 1024, length($$rb)) > 0) {
215     while ($$rb =~ s/^(.*)\n//) {
216       if ($ready) {
217         $self->_receive($1);
218       } else {
219         my $line = $1;
220         die "New remote container did not send Shere - got ${line}"
221           unless $line eq "Shere";
222         $self->ready_future->done;
223       }
224     }
225   } else {
226     Object::Remote->current_loop
227                   ->unwatch_io(
228                       handle => $self->receive_from_fh,
229                       on_read_ready => 1
230                     );
231     my $outstanding = $self->outstanding_futures;
232     $_->fail("Connection lost") for values %$outstanding;
233     %$outstanding = ();
234     $self->on_close->done();
235   }
236 }
237
238 sub _receive {
239   my ($self, $flat) = @_;
240   warn "$$ <<< $flat\n" if $DEBUG;
241   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
242     or do { warn "Deserialize failed for ${flat}: $@"; return };
243   eval { $self->${\"receive_${type}"}(@rest); 1 }
244     or do { warn "Receive failed for ${flat}: $@"; return };
245   return;
246 }
247
248 sub receive_free {
249   my ($self, $id) = @_;
250   delete $self->local_objects_by_id->{$id}
251     or warn "Free: no such object $id";
252   return;
253 }
254
255 sub receive_call {
256   my ($self, $future, $id, @rest) = @_;
257   $future->{method} = 'call_discard_free';
258   my $local = $self->local_objects_by_id->{$id}
259     or do { $future->fail("No such object $id"); return };
260   $self->_invoke($future, $local, @rest);
261 }
262
263 sub receive_call_free {
264   my ($self, $future, $id, @rest) = @_;
265   $self->receive_call($future, $id, undef, @rest);
266   $self->receive_free($id);
267 }
268
269 sub receive_class_call {
270   my ($self, $future, $class, @rest) = @_;
271   $future->{method} = 'call_discard_free';
272   eval { use_module($class) }
273     or do { $future->fail("Error loading ${class}: $@"); return };
274   $self->_invoke($future, $class, @rest);
275 }
276
277 sub _invoke {
278   my ($self, $future, $local, $ctx, $method, @args) = @_;
279   if ($method =~ /^start::/) {
280     my $f = $local->$method(@args);
281     $f->on_done(sub { undef($f); $future->done(@_) });
282     return unless $f;
283     $f->on_fail(sub { undef($f); $future->fail(@_) });
284     return;
285   }
286   my $do = sub { $local->$method(@args) };
287   eval {
288     $future->done(
289       defined($ctx)
290         ? ($ctx ? $do->() : scalar($do->()))
291         : do { $do->(); () }
292     );
293     1;
294   } or do { $future->fail($@); return; };
295   return;
296 }
297
298 sub DEMOLISH {
299   my ($self, $gd) = @_;
300   return if $gd;
301   Object::Remote->current_loop
302                 ->unwatch_io(
303                     handle => $self->receive_from_fh,
304                     on_read_ready => 1
305                   );
306 }
307
308 1;