got all general logging done, start of adding ids to objects and incorporating ids...
[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::Logging qw (:log :dlog);
10 use Object::Remote;
11 use Symbol;
12 use IO::Handle;
13 use Module::Runtime qw(use_module);
14 use Scalar::Util qw(weaken blessed refaddr);
15 use JSON::PP qw(encode_json);
16 use Moo;
17
18 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
19 #numbering each connection allows it to be
20 #tracked along with file handles in
21 #the logs
22 BEGIN { our $NEXT_CONNECTION_ID = 0 }
23 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
24
25 has send_to_fh => (
26   is => 'ro', required => 1,
27   trigger => sub { $_[1]->autoflush(1) },
28 );
29
30 has read_channel => (
31   is => 'ro', required => 1,
32   trigger => sub {
33     my ($self, $ch) = @_;
34     Dlog_trace { "trigger for read_channel has been invoked for connection $_" } $self->_id;
35     weaken($self);
36     $ch->on_line_call(sub { $self->_receive(@_) });
37     $ch->on_close_call(sub { $self->on_close->done(@_) });
38   },
39 );
40
41 has on_close => (
42   is => 'ro', default => sub { CPS::Future->new },
43   trigger => sub {
44     my ($self, $f) = @_;
45     Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
46     weaken($self);
47     $f->on_done(sub {
48       $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
49     });
50   }
51 );
52
53 has child_pid => (is => 'ro');
54
55 has local_objects_by_id => (
56   is => 'ro', default => sub { {} },
57   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
58 );
59
60 has remote_objects_by_id => (
61   is => 'ro', default => sub { {} },
62   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
63 );
64
65 has outstanding_futures => (is => 'ro', default => sub { {} });
66
67 sub _fail_outstanding {
68   my ($self, $error) = @_;
69   Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
70   my $outstanding = $self->outstanding_futures;
71   $_->fail($error) for values %$outstanding;
72   %$outstanding = ();
73   return;
74 }
75
76 has _json => (
77   is => 'lazy',
78   handles => {
79     _deserialize => 'decode',
80     _encode => 'encode',
81   },
82 );
83
84 sub _id_to_remote_object {
85   my ($self, $id) = @_;
86   Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
87   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
88   (
89     $self->remote_objects_by_id->{$id}
90     or Object::Remote::Handle->new(connection => $self, id => $id)
91   )->proxy;
92 }
93
94 sub _build__json {
95   weaken(my $self = shift);
96   JSON::PP->new->filter_json_single_key_object(
97     __remote_object__ => sub {
98       $self->_id_to_remote_object(@_);
99     }
100   )->filter_json_single_key_object(
101     __remote_code__ => sub {
102       my $code_container = $self->_id_to_remote_object(@_);
103       sub { $code_container->call(@_) };
104     }
105   )->filter_json_single_key_object(
106     __scalar_ref__ => sub {
107       my $value = shift;
108       return \$value;
109     }
110   )->filter_json_single_key_object(
111     __glob_ref__ => sub {
112       my $glob_container = $self->_id_to_remote_object(@_);
113       my $handle = Symbol::gensym;
114       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
115       return $handle;
116     }
117   )->filter_json_single_key_object(
118     __local_object__ => sub {
119       $self->local_objects_by_id->{$_[0]}
120     }
121   );
122 }
123
124 BEGIN {
125   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
126   eval { require Object::Remote::Connector::Local };
127   eval { require Object::Remote::Connector::LocalSudo };
128   eval { require Object::Remote::Connector::SSH };
129   eval { require Object::Remote::Connector::UNIX };
130 }
131
132 sub new_from_spec {
133   my ($class, $spec) = @_;
134   return $spec if blessed $spec;
135   Dlog_debug { "creating a new connection from spec" };
136   foreach my $poss (do { our @Guess }) {
137     if (my $conn = $poss->($spec)) {
138       #Dlog_debug { my $id = $conn->_id; "created connection $id for spec $_" } $spec;
139       return $conn->maybe::start::connect;
140     }
141   }
142   die "Couldn't figure out what to do with ${spec}";
143 }
144
145 sub remote_object {
146   my ($self, @args) = @_;
147   Object::Remote::Handle->new(
148     connection => $self, @args
149   )->proxy;
150 }
151
152 sub connect {
153   my ($self, $to) = @_;
154   Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
155   return await_future(
156     $self->send_class_call(0, 'Object::Remote', connect => $to)
157   );
158 }
159
160 sub remote_sub {
161   my ($self, $sub) = @_;
162   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
163   Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
164   return await_future($self->send_class_call(0, $pkg, can => $name));
165 }
166
167 sub send_class_call {
168   my ($self, $ctx, @call) = @_;
169   Dlog_trace { "Sending a class call for connection $_" } $self->_id;
170   $self->send(call => class_call_handler => $ctx => call => @call);
171 }
172
173 sub register_class_call_handler {
174   my ($self) = @_;
175   $self->local_objects_by_id->{'class_call_handler'} ||= do {
176     my $o = $self->new_class_call_handler;
177     $self->_local_object_to_id($o);
178     $o;
179   };
180 }
181
182 sub new_class_call_handler {
183   Object::Remote::CodeContainer->new(
184     code => sub {
185       my ($class, $method) = (shift, shift);
186       use_module($class)->$method(@_);
187     }
188   );
189 }
190
191 sub register_remote {
192   my ($self, $remote) = @_;
193   Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
194   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
195   return $remote;
196 }
197
198 sub send_free {
199   my ($self, $id) = @_;
200   Dlog_debug { "sending request to free object '$id' for connection $_" } $self->_id;
201   delete $self->remote_objects_by_id->{$id};
202   $self->_send([ free => $id ]);
203 }
204
205 sub send {
206   my ($self, $type, @call) = @_;
207
208   my $future = CPS::Future->new;
209   my $remote = $self->remote_objects_by_id->{$call[0]};
210
211   unshift @call, $type => $self->_local_object_to_id($future);
212
213   my $outstanding = $self->outstanding_futures;
214   $outstanding->{$future} = $future;
215   $future->on_ready(sub {
216     undef($remote);
217     delete $outstanding->{$future}
218   });
219
220   $self->_send(\@call);
221
222   return $future;
223 }
224
225 sub send_discard {
226   my ($self, $type, @call) = @_;
227
228   unshift @call, $type => 'NULL';
229
230   $self->_send(\@call);
231 }
232
233 sub _send {
234   my ($self, $to_send) = @_;
235   my $fh = $self->send_to_fh;
236   Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
237   my $serialized = $self->_serialize($to_send)."\n";
238   Dlog_debug { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
239   #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
240   #logic it could easily do short-writes to the remote side
241   my $ret = print $fh $serialized;
242   Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
243   #TODO hrm reason print's return value was ignored?
244   die "could not write to filehandle: $!" unless $ret;
245   return $ret; 
246 }
247
248 sub _serialize {
249   my ($self, $data) = @_;
250   local our @New_Ids = (-1);
251   Dlog_debug { "starting to serialize data for connection $_" } $self->_id;
252   return eval {
253     my $flat = $self->_encode($self->_deobjectify($data));
254     warn "$$ >>> ${flat}\n" if $DEBUG;
255     $flat;
256   } || do {
257     my $err = $@; # won't get here if the eval doesn't die
258     # don't keep refs to new things
259     delete @{$self->local_objects_by_id}{@New_Ids};
260     die "Error serializing: $err";
261   };
262 }
263
264 sub _local_object_to_id {
265   my ($self, $object) = @_;
266   my $id = refaddr($object);
267   $self->local_objects_by_id->{$id} ||= do {
268     push our(@New_Ids), $id if @New_Ids;
269     $object;
270   };
271   return $id;
272 }
273
274 sub _deobjectify {
275   my ($self, $data) = @_;
276   if (blessed($data)) {
277     if (
278       $data->isa('Object::Remote::Proxy')
279       and $data->{remote}->connection == $self
280     ) {
281       return +{ __local_object__ => $data->{remote}->id };
282     } else {
283       return +{ __remote_object__ => $self->_local_object_to_id($data) };
284     }
285   } elsif (my $ref = ref($data)) {
286     if ($ref eq 'HASH') {
287       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
288     } elsif ($ref eq 'ARRAY') {
289       return [ map $self->_deobjectify($_), @$data ];
290     } elsif ($ref eq 'CODE') {
291       my $id = $self->_local_object_to_id(
292                  Object::Remote::CodeContainer->new(code => $data)
293                );
294       return +{ __remote_code__ => $id };
295     } elsif ($ref eq 'SCALAR') {
296       return +{ __scalar_ref__ => $$data };
297     } elsif ($ref eq 'GLOB') {
298       return +{ __glob_ref__ => $self->_local_object_to_id(
299         Object::Remote::GlobContainer->new(handle => $data)
300       ) };
301     } else {
302       die "Can't collapse reftype $ref";
303     }
304   }
305   return $data; # plain scalar
306 }
307
308 sub _receive {
309   my ($self, $flat) = @_;
310   warn "$$ <<< $flat\n" if $DEBUG;
311   Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
312   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
313     or do { warn "Deserialize failed for ${flat}: $@"; return };
314   Dlog_trace { "deserialization complete for connection $_" } $self->_id;
315   eval { $self->${\"receive_${type}"}(@rest); 1 }
316     or do { warn "Receive failed for ${flat}: $@"; return };
317   return;
318 }
319
320 sub receive_free {
321   my ($self, $id) = @_;
322   Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
323   delete $self->local_objects_by_id->{$id}
324     or warn "Free: no such object $id";
325   return;
326 }
327
328 sub receive_call {
329   my ($self, $future_id, $id, @rest) = @_;
330   Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
331   my $future = $self->_id_to_remote_object($future_id);
332   $future->{method} = 'call_discard_free';
333   my $local = $self->local_objects_by_id->{$id}
334     or do { $future->fail("No such object $id"); return };
335   $self->_invoke($future, $local, @rest);
336 }
337
338 sub receive_call_free {
339   my ($self, $future, $id, @rest) = @_;
340   Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
341   $self->receive_call($future, $id, undef, @rest);
342   $self->receive_free($id);
343 }
344
345 sub _invoke {
346   my ($self, $future, $local, $ctx, $method, @args) = @_;
347   Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
348   if ($method =~ /^start::/) {
349     my $f = $local->$method(@args);
350     $f->on_done(sub { undef($f); $future->done(@_) });
351     return unless $f;
352     $f->on_fail(sub { undef($f); $future->fail(@_) });
353     return;
354   }
355   my $do = sub { $local->$method(@args) };
356   eval {
357     $future->done(
358       defined($ctx)
359         ? ($ctx ? $do->() : scalar($do->()))
360         : do { $do->(); () }
361     );
362     1;
363   } or do { $future->fail($@); return; };
364   return;
365 }
366
367 1;
368
369 =head1 NAME
370
371 Object::Remote::Connection - An underlying connection for L<Object::Remote>
372
373 =head1 LAME
374
375 Shipping prioritised over writing this part up. Blame mst.
376
377 =cut