1 package Object::Remote::Connection;
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::Tied;
14 use Module::Runtime qw(use_module);
15 use Scalar::Util qw(weaken blessed refaddr openhandle);
16 use JSON::PP qw(encode_json);
19 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
20 #numbering each connection allows it to be
21 #tracked along with file handles in
23 BEGIN { our $NEXT_CONNECTION_ID = 0 }
24 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
27 is => 'ro', required => 1,
31 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
36 is => 'ro', required => 1,
40 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
42 $ch->on_line_call(sub { $self->_receive(@_) });
43 $ch->on_close_call(sub {
44 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
45 $self->on_close->done(@_);
50 #TODO properly fix this bug -
51 #trigger can't ever be invoked with a default
52 #value and the on_close attribute is read only....
53 #the future never gets the on_done handler
57 $self->on_close(CPS::Future->new);
61 is => 'rw', default => sub { CPS::Future->new },
64 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
67 Dlog_trace { "failing all of the outstanding futures for connection $_" } $self->_id;
68 $self->_fail_outstanding("Connection lost: " . ($f->get)[0]);
73 has child_pid => (is => 'ro');
75 has local_objects_by_id => (
76 is => 'ro', default => sub { {} },
77 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
80 has remote_objects_by_id => (
81 is => 'ro', default => sub { {} },
82 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
85 has outstanding_futures => (is => 'ro', default => sub { {} });
87 sub _fail_outstanding {
88 my ($self, $error) = @_;
89 Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
90 my $outstanding = $self->outstanding_futures;
91 $_->fail($error) for values %$outstanding;
99 _deserialize => 'decode',
104 sub _id_to_remote_object {
105 my ($self, $id) = @_;
106 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
107 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
109 $self->remote_objects_by_id->{$id}
110 or Object::Remote::Handle->new(connection => $self, id => $id)
115 weaken(my $self = shift);
116 JSON::PP->new->filter_json_single_key_object(
117 __remote_object__ => sub {
118 $self->_id_to_remote_object(@_);
120 )->filter_json_single_key_object(
121 __remote_code__ => sub {
122 my $code_container = $self->_id_to_remote_object(@_);
123 sub { $code_container->call(@_) };
125 )->filter_json_single_key_object(
126 __scalar_ref__ => sub {
130 )->filter_json_single_key_object(
131 __glob_ref__ => sub {
132 my $glob_container = $self->_id_to_remote_object(@_);
133 my $handle = Symbol::gensym;
134 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
137 )->filter_json_single_key_object(
138 __remote_tied_hash__ => sub {
140 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
143 )->filter_json_single_key_object(
144 __remote_tied_array__ => sub {
146 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
153 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
154 eval { require Object::Remote::Connector::Local };
155 eval { require Object::Remote::Connector::LocalSudo };
156 eval { require Object::Remote::Connector::SSH };
157 eval { require Object::Remote::Connector::UNIX };
161 my ($class, $spec) = @_;
162 return $spec if blessed $spec;
163 Dlog_debug { "creating a new connection from spec" };
164 foreach my $poss (do { our @Guess }) {
165 if (my $conn = $poss->($spec)) {
166 return $conn->maybe::start::connect;
169 die "Couldn't figure out what to do with ${spec}";
173 my ($self, @args) = @_;
174 Object::Remote::Handle->new(
175 connection => $self, @args
180 my ($self, $to) = @_;
181 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
183 $self->send_class_call(0, 'Object::Remote', connect => $to)
188 my ($self, $sub) = @_;
189 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
190 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
191 return await_future($self->send_class_call(0, $pkg, can => $name));
194 sub send_class_call {
195 my ($self, $ctx, @call) = @_;
196 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
197 $self->send(call => class_call_handler => $ctx => call => @call);
200 sub register_class_call_handler {
202 $self->local_objects_by_id->{'class_call_handler'} ||= do {
203 my $o = $self->new_class_call_handler;
204 $self->_local_object_to_id($o);
209 sub new_class_call_handler {
210 Object::Remote::CodeContainer->new(
212 my ($class, $method) = (shift, shift);
213 use_module($class)->$method(@_);
218 sub register_remote {
219 my ($self, $remote) = @_;
220 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
221 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
226 my ($self, $id) = @_;
227 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
228 delete $self->remote_objects_by_id->{$id};
229 $self->_send([ free => $id ]);
233 my ($self, $type, @call) = @_;
235 my $future = CPS::Future->new;
236 my $remote = $self->remote_objects_by_id->{$call[0]};
238 unshift @call, $type => $self->_local_object_to_id($future);
240 my $outstanding = $self->outstanding_futures;
241 $outstanding->{$future} = $future;
242 $future->on_ready(sub {
244 delete $outstanding->{$future}
247 $self->_send(\@call);
253 my ($self, $type, @call) = @_;
255 unshift @call, $type => 'NULL';
257 $self->_send(\@call);
261 my ($self, $to_send) = @_;
262 my $fh = $self->send_to_fh;
263 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
264 my $serialized = $self->_serialize($to_send)."\n";
265 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
266 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
267 #logic it could easily do short-writes to the remote side - how about taking this entire buffer
268 #and having the run loop send it to the file handle so this doesn't block while the sending
272 local($SIG{PIPE}) = 'IGNORE';
273 die "filehandle is not open" unless openhandle($fh);
274 log_trace { "file handle has passed openhandle() test; printing to it" };
275 $ret = print $fh $serialized;
276 die "print was not successful: $!" unless defined $ret
280 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
281 my $error = $@; chomp($error);
282 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
290 my ($self, $data) = @_;
291 local our @New_Ids = (-1);
293 my $flat = $self->_encode($self->_deobjectify($data));
294 warn "$$ >>> ${flat}\n" if $DEBUG;
297 my $err = $@; # won't get here if the eval doesn't die
298 # don't keep refs to new things
299 delete @{$self->local_objects_by_id}{@New_Ids};
300 die "Error serializing: $err";
304 sub _local_object_to_id {
305 my ($self, $object) = @_;
306 my $id = refaddr($object);
307 $self->local_objects_by_id->{$id} ||= do {
308 push our(@New_Ids), $id if @New_Ids;
315 my ($self, $data) = @_;
316 if (blessed($data)) {
317 return +{ __remote_object__ => $self->_local_object_to_id($data) };
318 } elsif (my $ref = ref($data)) {
319 if ($ref eq 'HASH') {
320 my $tied_to = tied(%$data);
321 if(defined($tied_to)) {
322 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
324 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
326 } elsif ($ref eq 'ARRAY') {
327 my $tied_to = tied(@$data);
328 if (defined($tied_to)) {
329 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
331 return [ map $self->_deobjectify($_), @$data ];
333 } elsif ($ref eq 'CODE') {
334 my $id = $self->_local_object_to_id(
335 Object::Remote::CodeContainer->new(code => $data)
337 return +{ __remote_code__ => $id };
338 } elsif ($ref eq 'SCALAR') {
339 return +{ __scalar_ref__ => $$data };
340 } elsif ($ref eq 'GLOB') {
341 return +{ __glob_ref__ => $self->_local_object_to_id(
342 Object::Remote::GlobContainer->new(handle => $data)
345 die "Can't collapse reftype $ref";
348 return $data; # plain scalar
352 my ($self, $flat) = @_;
353 warn "$$ <<< $flat\n" if $DEBUG;
354 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
355 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
356 or do { warn "Deserialize failed for ${flat}: $@"; return };
357 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
358 eval { $self->${\"receive_${type}"}(@rest); 1 }
359 or do { warn "Receive failed for ${flat}: $@"; return };
364 my ($self, $id) = @_;
365 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
366 delete $self->local_objects_by_id->{$id}
367 or warn "Free: no such object $id";
372 my ($self, $future_id, $id, @rest) = @_;
373 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
374 my $future = $self->_id_to_remote_object($future_id);
375 $future->{method} = 'call_discard_free';
376 my $local = $self->local_objects_by_id->{$id}
377 or do { $future->fail("No such object $id"); return };
378 $self->_invoke($future, $local, @rest);
381 sub receive_call_free {
382 my ($self, $future, $id, @rest) = @_;
383 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
384 $self->receive_call($future, $id, undef, @rest);
385 $self->receive_free($id);
389 my ($self, $future, $local, $ctx, $method, @args) = @_;
390 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
391 if ($method =~ /^start::/) {
392 my $f = $local->$method(@args);
393 $f->on_done(sub { undef($f); $future->done(@_) });
395 $f->on_fail(sub { undef($f); $future->fail(@_) });
398 my $do = sub { $local->$method(@args) };
402 ? ($ctx ? $do->() : scalar($do->()))
406 } or do { $future->fail($@); return; };
414 Object::Remote::Connection - An underlying connection for L<Object::Remote>
418 Shipping prioritised over writing this part up. Blame mst.