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