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);
13 use Module::Runtime qw(use_module);
14 use Scalar::Util qw(weaken blessed refaddr);
15 use JSON::PP qw(encode_json);
18 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
19 #numbering each connection allows it to be
20 #tracked along with file handles in
22 BEGIN { our $NEXT_CONNECTION_ID = 0 }
23 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
26 is => 'ro', required => 1,
30 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
35 is => 'ro', required => 1,
38 Dlog_trace { my $id = $self->_id; "trigger for read_channel has been invoked for connection $id; file handle is " } $ch->fh;
40 $ch->on_line_call(sub { $self->_receive(@_) });
41 $ch->on_close_call(sub { $self->on_close->done(@_) });
46 is => 'ro', default => sub { CPS::Future->new },
49 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
52 $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
57 has child_pid => (is => 'ro');
59 has local_objects_by_id => (
60 is => 'ro', default => sub { {} },
61 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
64 has remote_objects_by_id => (
65 is => 'ro', default => sub { {} },
66 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
69 has outstanding_futures => (is => 'ro', default => sub { {} });
71 sub _fail_outstanding {
72 my ($self, $error) = @_;
73 Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
74 my $outstanding = $self->outstanding_futures;
75 $_->fail($error) for values %$outstanding;
83 _deserialize => 'decode',
88 sub _id_to_remote_object {
90 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
91 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
93 $self->remote_objects_by_id->{$id}
94 or Object::Remote::Handle->new(connection => $self, id => $id)
99 weaken(my $self = shift);
100 JSON::PP->new->filter_json_single_key_object(
101 __remote_object__ => sub {
102 $self->_id_to_remote_object(@_);
104 )->filter_json_single_key_object(
105 __remote_code__ => sub {
106 my $code_container = $self->_id_to_remote_object(@_);
107 sub { $code_container->call(@_) };
109 )->filter_json_single_key_object(
110 __scalar_ref__ => sub {
114 )->filter_json_single_key_object(
115 __glob_ref__ => sub {
116 my $glob_container = $self->_id_to_remote_object(@_);
117 my $handle = Symbol::gensym;
118 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
121 )->filter_json_single_key_object(
122 __local_object__ => sub {
123 $self->local_objects_by_id->{$_[0]}
129 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
130 eval { require Object::Remote::Connector::Local };
131 eval { require Object::Remote::Connector::LocalSudo };
132 eval { require Object::Remote::Connector::SSH };
133 eval { require Object::Remote::Connector::UNIX };
137 my ($class, $spec) = @_;
138 return $spec if blessed $spec;
139 Dlog_debug { "creating a new connection from spec" };
140 foreach my $poss (do { our @Guess }) {
141 if (my $conn = $poss->($spec)) {
142 #Dlog_debug { my $id = $conn->_id; "created connection $id for spec $_" } $spec;
143 return $conn->maybe::start::connect;
146 die "Couldn't figure out what to do with ${spec}";
150 my ($self, @args) = @_;
151 Object::Remote::Handle->new(
152 connection => $self, @args
157 my ($self, $to) = @_;
158 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
160 $self->send_class_call(0, 'Object::Remote', connect => $to)
165 my ($self, $sub) = @_;
166 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
167 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
168 return await_future($self->send_class_call(0, $pkg, can => $name));
171 sub send_class_call {
172 my ($self, $ctx, @call) = @_;
173 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
174 $self->send(call => class_call_handler => $ctx => call => @call);
177 sub register_class_call_handler {
179 $self->local_objects_by_id->{'class_call_handler'} ||= do {
180 my $o = $self->new_class_call_handler;
181 $self->_local_object_to_id($o);
186 sub new_class_call_handler {
187 Object::Remote::CodeContainer->new(
189 my ($class, $method) = (shift, shift);
190 use_module($class)->$method(@_);
195 sub register_remote {
196 my ($self, $remote) = @_;
197 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
198 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
203 my ($self, $id) = @_;
204 Dlog_debug { "sending request to free object '$id' for connection $_" } $self->_id;
205 delete $self->remote_objects_by_id->{$id};
206 $self->_send([ free => $id ]);
210 my ($self, $type, @call) = @_;
212 my $future = CPS::Future->new;
213 my $remote = $self->remote_objects_by_id->{$call[0]};
215 unshift @call, $type => $self->_local_object_to_id($future);
217 my $outstanding = $self->outstanding_futures;
218 $outstanding->{$future} = $future;
219 $future->on_ready(sub {
221 delete $outstanding->{$future}
224 $self->_send(\@call);
230 my ($self, $type, @call) = @_;
232 unshift @call, $type => 'NULL';
234 $self->_send(\@call);
238 my ($self, $to_send) = @_;
239 my $fh = $self->send_to_fh;
240 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
241 my $serialized = $self->_serialize($to_send)."\n";
242 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
243 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
244 #logic it could easily do short-writes to the remote side
245 my $ret = print $fh $serialized;
246 Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
247 #TODO hrm reason print's return value was ignored?
248 die "could not write to filehandle: $!" unless $ret;
253 my ($self, $data) = @_;
254 local our @New_Ids = (-1);
256 my $flat = $self->_encode($self->_deobjectify($data));
257 warn "$$ >>> ${flat}\n" if $DEBUG;
260 my $err = $@; # won't get here if the eval doesn't die
261 # don't keep refs to new things
262 delete @{$self->local_objects_by_id}{@New_Ids};
263 die "Error serializing: $err";
267 sub _local_object_to_id {
268 my ($self, $object) = @_;
269 my $id = refaddr($object);
270 $self->local_objects_by_id->{$id} ||= do {
271 push our(@New_Ids), $id if @New_Ids;
278 my ($self, $data) = @_;
279 if (blessed($data)) {
281 $data->isa('Object::Remote::Proxy')
282 and $data->{remote}->connection == $self
284 return +{ __local_object__ => $data->{remote}->id };
286 return +{ __remote_object__ => $self->_local_object_to_id($data) };
288 } elsif (my $ref = ref($data)) {
289 if ($ref eq 'HASH') {
290 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
291 } elsif ($ref eq 'ARRAY') {
292 return [ map $self->_deobjectify($_), @$data ];
293 } elsif ($ref eq 'CODE') {
294 my $id = $self->_local_object_to_id(
295 Object::Remote::CodeContainer->new(code => $data)
297 return +{ __remote_code__ => $id };
298 } elsif ($ref eq 'SCALAR') {
299 return +{ __scalar_ref__ => $$data };
300 } elsif ($ref eq 'GLOB') {
301 return +{ __glob_ref__ => $self->_local_object_to_id(
302 Object::Remote::GlobContainer->new(handle => $data)
305 die "Can't collapse reftype $ref";
308 return $data; # plain scalar
312 my ($self, $flat) = @_;
313 warn "$$ <<< $flat\n" if $DEBUG;
314 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
315 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
316 or do { warn "Deserialize failed for ${flat}: $@"; return };
317 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
318 eval { $self->${\"receive_${type}"}(@rest); 1 }
319 or do { warn "Receive failed for ${flat}: $@"; return };
324 my ($self, $id) = @_;
325 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
326 delete $self->local_objects_by_id->{$id}
327 or warn "Free: no such object $id";
332 my ($self, $future_id, $id, @rest) = @_;
333 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
334 my $future = $self->_id_to_remote_object($future_id);
335 $future->{method} = 'call_discard_free';
336 my $local = $self->local_objects_by_id->{$id}
337 or do { $future->fail("No such object $id"); return };
338 $self->_invoke($future, $local, @rest);
341 sub receive_call_free {
342 my ($self, $future, $id, @rest) = @_;
343 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
344 $self->receive_call($future, $id, undef, @rest);
345 $self->receive_free($id);
349 my ($self, $future, $local, $ctx, $method, @args) = @_;
350 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
351 if ($method =~ /^start::/) {
352 my $f = $local->$method(@args);
353 $f->on_done(sub { undef($f); $future->done(@_) });
355 $f->on_fail(sub { undef($f); $future->fail(@_) });
358 my $do = sub { $local->$method(@args) };
362 ? ($ctx ? $do->() : scalar($do->()))
366 } or do { $future->fail($@); return; };
374 Object::Remote::Connection - An underlying connection for L<Object::Remote>
378 Shipping prioritised over writing this part up. Blame mst.