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};
21 is => 'ro', required => 1,
22 trigger => sub { $_[1]->autoflush(1) },
26 is => 'ro', required => 1,
30 $ch->on_line_call(sub { $self->_receive(@_) });
31 $ch->on_close_call(sub { $self->on_close->done(@_) });
36 is => 'ro', default => sub { CPS::Future->new },
41 $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
46 has child_pid => (is => 'ro');
48 has local_objects_by_id => (
49 is => 'ro', default => sub { {} },
50 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
53 has remote_objects_by_id => (
54 is => 'ro', default => sub { {} },
55 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
58 has outstanding_futures => (is => 'ro', default => sub { {} });
60 sub _fail_outstanding {
61 my ($self, $error) = @_;
62 my $outstanding = $self->outstanding_futures;
63 $_->fail($error) for values %$outstanding;
71 _deserialize => 'decode',
76 sub _id_to_remote_object {
78 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
80 $self->remote_objects_by_id->{$id}
81 or Object::Remote::Handle->new(connection => $self, id => $id)
86 weaken(my $self = shift);
87 JSON::PP->new->filter_json_single_key_object(
88 __remote_object__ => sub {
89 $self->_id_to_remote_object(@_);
91 )->filter_json_single_key_object(
92 __remote_code__ => sub {
93 my $code_container = $self->_id_to_remote_object(@_);
94 sub { $code_container->call(@_) };
96 )->filter_json_single_key_object(
97 __scalar_ref__ => sub {
101 )->filter_json_single_key_object(
102 __glob_ref__ => sub {
103 my $glob_container = $self->_id_to_remote_object(@_);
104 my $handle = Symbol::gensym;
105 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
108 )->filter_json_single_key_object(
109 __local_object__ => sub {
110 $self->local_objects_by_id->{$_[0]}
116 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
117 eval { require Object::Remote::Connector::Local };
118 eval { require Object::Remote::Connector::LocalSudo };
119 eval { require Object::Remote::Connector::SSH };
120 eval { require Object::Remote::Connector::UNIX };
124 my ($class, $spec) = @_;
125 return $spec if blessed $spec;
126 foreach my $poss (do { our @Guess }) {
127 if (my $conn = $poss->($spec)) {
128 return $conn->maybe::start::connect;
131 die "Couldn't figure out what to do with ${spec}";
135 my ($self, @args) = @_;
136 Object::Remote::Handle->new(
137 connection => $self, @args
142 my ($self, $to) = @_;
143 Dlog_debug { "Creating connection to remote node $_" } $to;
145 $self->send_class_call(0, 'Object::Remote', connect => $to)
150 my ($self, $sub) = @_;
151 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
152 log_debug { "Invoking remote sub '$sub'" };
153 return await_future($self->send_class_call(0, $pkg, can => $name));
156 sub send_class_call {
157 my ($self, $ctx, @call) = @_;
158 log_trace { "Sending a non-blocking class call" };
159 $self->send(call => class_call_handler => $ctx => call => @call);
162 sub register_class_call_handler {
164 $self->local_objects_by_id->{'class_call_handler'} ||= do {
165 my $o = $self->new_class_call_handler;
166 $self->_local_object_to_id($o);
171 sub new_class_call_handler {
172 Object::Remote::CodeContainer->new(
174 my ($class, $method) = (shift, shift);
175 use_module($class)->$method(@_);
180 sub register_remote {
181 my ($self, $remote) = @_;
182 log_trace { my $i = $remote->id; "Registered a remote object with id of '$i'" };
183 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
188 my ($self, $id) = @_;
189 log_debug { "sending request to free object '$id'" };
190 delete $self->remote_objects_by_id->{$id};
191 $self->_send([ free => $id ]);
195 my ($self, $type, @call) = @_;
197 my $future = CPS::Future->new;
198 my $remote = $self->remote_objects_by_id->{$call[0]};
200 unshift @call, $type => $self->_local_object_to_id($future);
202 my $outstanding = $self->outstanding_futures;
203 $outstanding->{$future} = $future;
204 $future->on_ready(sub {
206 delete $outstanding->{$future}
209 $self->_send(\@call);
215 my ($self, $type, @call) = @_;
217 unshift @call, $type => 'NULL';
219 $self->_send(\@call);
223 my ($self, $to_send) = @_;
224 my $fh = $self->send_to_fh;
225 my $serialized = $self->_serialize($to_send)."\n";
226 Dlog_debug { my $l = length($serialized); "Sending '$l' characters of serialized data to $_" } $fh;
227 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
228 #logic it could easily do short-writes to the remote side
229 my $ret = print $fh $serialized;
230 Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
231 #TODO hrm reason print's return value was ignored?
232 die "could not write to filehandle: $!" unless $ret;
237 my ($self, $data) = @_;
238 local our @New_Ids = (-1);
240 my $flat = $self->_encode($self->_deobjectify($data));
241 warn "$$ >>> ${flat}\n" if $DEBUG;
244 my $err = $@; # won't get here if the eval doesn't die
245 # don't keep refs to new things
246 delete @{$self->local_objects_by_id}{@New_Ids};
247 die "Error serializing: $err";
251 sub _local_object_to_id {
252 my ($self, $object) = @_;
253 my $id = refaddr($object);
254 $self->local_objects_by_id->{$id} ||= do {
255 push our(@New_Ids), $id if @New_Ids;
262 my ($self, $data) = @_;
263 if (blessed($data)) {
265 $data->isa('Object::Remote::Proxy')
266 and $data->{remote}->connection == $self
268 return +{ __local_object__ => $data->{remote}->id };
270 return +{ __remote_object__ => $self->_local_object_to_id($data) };
272 } elsif (my $ref = ref($data)) {
273 if ($ref eq 'HASH') {
274 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
275 } elsif ($ref eq 'ARRAY') {
276 return [ map $self->_deobjectify($_), @$data ];
277 } elsif ($ref eq 'CODE') {
278 my $id = $self->_local_object_to_id(
279 Object::Remote::CodeContainer->new(code => $data)
281 return +{ __remote_code__ => $id };
282 } elsif ($ref eq 'SCALAR') {
283 return +{ __scalar_ref__ => $$data };
284 } elsif ($ref eq 'GLOB') {
285 return +{ __glob_ref__ => $self->_local_object_to_id(
286 Object::Remote::GlobContainer->new(handle => $data)
289 die "Can't collapse reftype $ref";
292 return $data; # plain scalar
296 my ($self, $flat) = @_;
297 warn "$$ <<< $flat\n" if $DEBUG;
298 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
299 or do { warn "Deserialize failed for ${flat}: $@"; return };
300 eval { $self->${\"receive_${type}"}(@rest); 1 }
301 or do { warn "Receive failed for ${flat}: $@"; return };
306 my ($self, $id) = @_;
307 delete $self->local_objects_by_id->{$id}
308 or warn "Free: no such object $id";
313 my ($self, $future_id, $id, @rest) = @_;
314 my $future = $self->_id_to_remote_object($future_id);
315 $future->{method} = 'call_discard_free';
316 my $local = $self->local_objects_by_id->{$id}
317 or do { $future->fail("No such object $id"); return };
318 $self->_invoke($future, $local, @rest);
321 sub receive_call_free {
322 my ($self, $future, $id, @rest) = @_;
323 $self->receive_call($future, $id, undef, @rest);
324 $self->receive_free($id);
328 my ($self, $future, $local, $ctx, $method, @args) = @_;
329 if ($method =~ /^start::/) {
330 my $f = $local->$method(@args);
331 $f->on_done(sub { undef($f); $future->done(@_) });
333 $f->on_fail(sub { undef($f); $future->fail(@_) });
336 my $do = sub { $local->$method(@args) };
340 ? ($ctx ? $do->() : scalar($do->()))
344 } or do { $future->fail($@); return; };
352 Object::Remote::Connection - An underlying connection for L<Object::Remote>
356 Shipping prioritised over writing this part up. Blame mst.