create ReadChannel object to allow moving Shere logic into 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::GlobProxy;
8 use Object::Remote::GlobContainer;
9 use Object::Remote;
10 use Symbol;
11 use IO::Handle;
12 use Module::Runtime qw(use_module);
13 use Scalar::Util qw(weaken blessed refaddr);
14 use JSON::PP qw(encode_json);
15 use Moo;
16
17 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
18
19 has send_to_fh => (
20   is => 'ro', required => 1,
21   trigger => sub { $_[1]->autoflush(1) },
22 );
23
24 has read_channel => (
25   is => 'ro', required => 1,
26   trigger => sub {
27     my ($self, $ch) = @_;
28     weaken($self);
29     $ch->on_line_call(sub { $self->_receive(@_) });
30     $ch->on_close_call(sub { $self->on_close->done(@_) });
31   },
32 );
33
34 has on_close => (
35   is => 'ro', default => sub { CPS::Future->new },
36   trigger => sub { 
37     my ($self, $f) = @_;
38     weaken($self);
39     $f->on_done(sub {
40       $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
41     });
42   }
43 );
44
45 has child_pid => (is => 'ro');
46
47 has local_objects_by_id => (
48   is => 'ro', default => sub { {} },
49   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
50 );
51
52 has remote_objects_by_id => (
53   is => 'ro', default => sub { {} },
54   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
55 );
56
57 has outstanding_futures => (is => 'ro', default => sub { {} });
58
59 sub _fail_outstanding {
60   my ($self, $error) = @_;
61   my $outstanding = $self->outstanding_futures;
62   $_->fail($error) for values %$outstanding;
63   %$outstanding = ();
64   return;
65 }
66
67 has _json => (
68   is => 'lazy',
69   handles => {
70     _deserialize => 'decode',
71     _encode => 'encode',
72   },
73 );
74
75 sub _id_to_remote_object {
76   my ($self, $id) = @_;
77   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
78   (
79     $self->remote_objects_by_id->{$id}
80     or Object::Remote::Handle->new(connection => $self, id => $id)
81   )->proxy;
82 }
83
84 sub _build__json {
85   weaken(my $self = shift);
86   JSON::PP->new->filter_json_single_key_object(
87     __remote_object__ => sub {
88       $self->_id_to_remote_object(@_);
89     }
90   )->filter_json_single_key_object(
91     __remote_code__ => sub {
92       my $code_container = $self->_id_to_remote_object(@_);
93       sub { $code_container->call(@_) };
94     }
95   )->filter_json_single_key_object(
96     __scalar_ref__ => sub {
97       my $value = shift;
98       return \$value;
99     }
100   )->filter_json_single_key_object(
101     __glob_ref__ => sub {
102       my $glob_container = $self->_id_to_remote_object(@_);
103       my $handle = Symbol::gensym;
104       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
105       return $handle;
106     }
107   );
108 }
109
110 BEGIN {
111   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
112   eval { require Object::Remote::Connector::Local };
113   eval { require Object::Remote::Connector::LocalSudo };
114   eval { require Object::Remote::Connector::SSH };
115   eval { require Object::Remote::Connector::UNIX };
116 }
117
118 sub new_from_spec {
119   my ($class, $spec) = @_;
120   return $spec if blessed $spec;
121   foreach my $poss (do { our @Guess }) {
122     if (my $obj = $poss->($spec)) { return $obj }
123   }
124   die "Couldn't figure out what to do with ${spec}";
125 }
126
127 sub remote_object {
128   my ($self, @args) = @_;
129   Object::Remote::Handle->new(
130     connection => $self, @args
131   )->proxy;
132 }
133
134 sub connect {
135   my ($self, $to) = @_;
136   return await_future(
137     $self->send_class_call(0, 'Object::Remote', connect => $to)
138   );
139 }
140
141 sub remote_sub {
142   my ($self, $sub) = @_;
143   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
144   return await_future($self->send_class_call(0, $pkg, can => $name));
145 }
146
147 sub send_class_call {
148   my ($self, $ctx, @call) = @_;
149   $self->send(call => class_call_handler => $ctx => call => @call);
150 }
151
152 sub register_class_call_handler {
153   my ($self) = @_;
154   $self->local_objects_by_id->{'class_call_handler'} ||= do {
155     my $o = $self->new_class_call_handler;
156     $self->_local_object_to_id($o);
157     $o;
158   };
159 }
160
161 sub new_class_call_handler {
162   Object::Remote::CodeContainer->new(
163     code => sub {
164       my ($class, $method) = (shift, shift);
165       use_module($class)->$method(@_);
166     }
167   );
168 }
169
170 sub register_remote {
171   my ($self, $remote) = @_;
172   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
173   return $remote;
174 }
175
176 sub send_free {
177   my ($self, $id) = @_;
178   delete $self->remote_objects_by_id->{$id};
179   $self->_send([ free => $id ]);
180 }
181
182 sub send {
183   my ($self, $type, @call) = @_;
184
185   my $future = CPS::Future->new;
186   my $remote = $self->remote_objects_by_id->{$call[0]};
187
188   unshift @call, $type => $self->_local_object_to_id($future);
189
190   my $outstanding = $self->outstanding_futures;
191   $outstanding->{$future} = $future;
192   $future->on_ready(sub {
193     undef($remote);
194     delete $outstanding->{$future}
195   });
196
197   $self->_send(\@call);
198
199   return $future;
200 }
201
202 sub send_discard {
203   my ($self, $type, @call) = @_;
204
205   unshift @call, $type => 'NULL';
206
207   $self->_send(\@call);
208 }
209
210 sub _send {
211   my ($self, $to_send) = @_;
212
213   print { $self->send_to_fh } $self->_serialize($to_send)."\n";
214 }
215
216 sub _serialize {
217   my ($self, $data) = @_;
218   local our @New_Ids = (-1);
219   return eval {
220     my $flat = $self->_encode($self->_deobjectify($data));
221     warn "$$ >>> ${flat}\n" if $DEBUG;
222     $flat;
223   } || do {
224     my $err = $@; # won't get here if the eval doesn't die
225     # don't keep refs to new things
226     delete @{$self->local_objects_by_id}{@New_Ids};
227     die "Error serializing: $err";
228   };
229 }
230
231 sub _local_object_to_id {
232   my ($self, $object) = @_;
233   my $id = refaddr($object);
234   $self->local_objects_by_id->{$id} ||= do {
235     push our(@New_Ids), $id if @New_Ids;
236     $object;
237   };
238   return $id;
239 }
240
241 sub _deobjectify {
242   my ($self, $data) = @_;
243   if (blessed($data)) {
244     return +{ __remote_object__ => $self->_local_object_to_id($data) };
245   } elsif (my $ref = ref($data)) {
246     if ($ref eq 'HASH') {
247       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
248     } elsif ($ref eq 'ARRAY') {
249       return [ map $self->_deobjectify($_), @$data ];
250     } elsif ($ref eq 'CODE') {
251       my $id = $self->_local_object_to_id(
252                  Object::Remote::CodeContainer->new(code => $data)
253                );
254       return +{ __remote_code__ => $id };
255     } elsif ($ref eq 'SCALAR') {
256       return +{ __scalar_ref__ => $$data };
257     } elsif ($ref eq 'GLOB') {
258       return +{ __glob_ref__ => $self->_local_object_to_id(
259         Object::Remote::GlobContainer->new(handle => $data)
260       ) };
261     } else {
262       die "Can't collapse reftype $ref";
263     }
264   }
265   return $data; # plain scalar
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 1;
322
323 =head1 NAME
324
325 Object::Remote::Connection - An underlying connection for L<Object::Remote>
326
327 =head1 LAME
328
329 Shipping prioritised over writing this part up. Blame mst.
330
331 =cut