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;
112 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
113 eval { require Object::Remote::Connector::Local };
114 eval { require Object::Remote::Connector::LocalSudo };
115 eval { require Object::Remote::Connector::SSH };
116 eval { require Object::Remote::Connector::UNIX };
120 my ($class, $spec) = @_;
121 return $spec if blessed $spec;
122 foreach my $poss (do { our @Guess }) {
123 if (my $conn = $poss->($spec)) {
124 return $conn->maybe::start::connect;
127 die "Couldn't figure out what to do with ${spec}";
131 my ($self, @args) = @_;
132 Object::Remote::Handle->new(
133 connection => $self, @args
138 my ($self, $to) = @_;
139 Dlog_debug { "Creating connection to remote node $_" } $to;
141 $self->send_class_call(0, 'Object::Remote', connect => $to)
146 my ($self, $sub) = @_;
147 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
148 log_debug { "Invoking remote sub '$sub'" };
149 return await_future($self->send_class_call(0, $pkg, can => $name));
152 sub send_class_call {
153 my ($self, $ctx, @call) = @_;
154 log_trace { "Sending a non-blocking class call" };
155 $self->send(call => class_call_handler => $ctx => call => @call);
158 sub register_class_call_handler {
160 $self->local_objects_by_id->{'class_call_handler'} ||= do {
161 my $o = $self->new_class_call_handler;
162 $self->_local_object_to_id($o);
167 sub new_class_call_handler {
168 Object::Remote::CodeContainer->new(
170 my ($class, $method) = (shift, shift);
171 use_module($class)->$method(@_);
176 sub register_remote {
177 my ($self, $remote) = @_;
178 log_trace { my $i = $remote->id; "Registered a remote object with id of '$i'" };
179 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
184 my ($self, $id) = @_;
185 log_debug { "sending request to free object '$id'" };
186 delete $self->remote_objects_by_id->{$id};
187 $self->_send([ free => $id ]);
191 my ($self, $type, @call) = @_;
193 my $future = CPS::Future->new;
194 my $remote = $self->remote_objects_by_id->{$call[0]};
196 unshift @call, $type => $self->_local_object_to_id($future);
198 my $outstanding = $self->outstanding_futures;
199 $outstanding->{$future} = $future;
200 $future->on_ready(sub {
202 delete $outstanding->{$future}
205 $self->_send(\@call);
211 my ($self, $type, @call) = @_;
213 unshift @call, $type => 'NULL';
215 $self->_send(\@call);
219 my ($self, $to_send) = @_;
220 my $fh = $self->send_to_fh;
221 my $serialized = $self->_serialize($to_send)."\n";
222 Dlog_debug { my $l = length($serialized); "Sending '$l' characters of serialized data to $_" } $fh;
223 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
224 #logic it could easily do short-writes to the remote side
225 my $ret = print $fh $serialized;
226 Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
227 #TODO hrm reason print's return value was ignored?
228 die "could not write to filehandle: $!" unless $ret;
233 my ($self, $data) = @_;
234 local our @New_Ids = (-1);
236 my $flat = $self->_encode($self->_deobjectify($data));
237 warn "$$ >>> ${flat}\n" if $DEBUG;
240 my $err = $@; # won't get here if the eval doesn't die
241 # don't keep refs to new things
242 delete @{$self->local_objects_by_id}{@New_Ids};
243 die "Error serializing: $err";
247 sub _local_object_to_id {
248 my ($self, $object) = @_;
249 my $id = refaddr($object);
250 $self->local_objects_by_id->{$id} ||= do {
251 push our(@New_Ids), $id if @New_Ids;
258 my ($self, $data) = @_;
259 if (blessed($data)) {
260 return +{ __remote_object__ => $self->_local_object_to_id($data) };
261 } elsif (my $ref = ref($data)) {
262 if ($ref eq 'HASH') {
263 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
264 } elsif ($ref eq 'ARRAY') {
265 return [ map $self->_deobjectify($_), @$data ];
266 } elsif ($ref eq 'CODE') {
267 my $id = $self->_local_object_to_id(
268 Object::Remote::CodeContainer->new(code => $data)
270 return +{ __remote_code__ => $id };
271 } elsif ($ref eq 'SCALAR') {
272 return +{ __scalar_ref__ => $$data };
273 } elsif ($ref eq 'GLOB') {
274 return +{ __glob_ref__ => $self->_local_object_to_id(
275 Object::Remote::GlobContainer->new(handle => $data)
278 die "Can't collapse reftype $ref";
281 return $data; # plain scalar
285 my ($self, $flat) = @_;
286 warn "$$ <<< $flat\n" if $DEBUG;
287 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
288 or do { warn "Deserialize failed for ${flat}: $@"; return };
289 eval { $self->${\"receive_${type}"}(@rest); 1 }
290 or do { warn "Receive failed for ${flat}: $@"; return };
295 my ($self, $id) = @_;
296 delete $self->local_objects_by_id->{$id}
297 or warn "Free: no such object $id";
302 my ($self, $future_id, $id, @rest) = @_;
303 my $future = $self->_id_to_remote_object($future_id);
304 $future->{method} = 'call_discard_free';
305 my $local = $self->local_objects_by_id->{$id}
306 or do { $future->fail("No such object $id"); return };
307 $self->_invoke($future, $local, @rest);
310 sub receive_call_free {
311 my ($self, $future, $id, @rest) = @_;
312 $self->receive_call($future, $id, undef, @rest);
313 $self->receive_free($id);
317 my ($self, $future, $local, $ctx, $method, @args) = @_;
318 if ($method =~ /^start::/) {
319 my $f = $local->$method(@args);
320 $f->on_done(sub { undef($f); $future->done(@_) });
322 $f->on_fail(sub { undef($f); $future->fail(@_) });
325 my $do = sub { $local->$method(@args) };
329 ? ($ctx ? $do->() : scalar($do->()))
333 } or do { $future->fail($@); return; };
341 Object::Remote::Connection - An underlying connection for L<Object::Remote>
345 Shipping prioritised over writing this part up. Blame mst.