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;
9 use Module::Runtime qw(use_module);
10 use Scalar::Util qw(weaken blessed refaddr);
11 use JSON::PP qw(encode_json);
14 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
17 is => 'ro', required => 1,
18 trigger => sub { $_[1]->autoflush(1) },
21 has receive_from_fh => (
22 is => 'ro', required => 1,
26 Object::Remote->current_loop
29 on_read_ready => sub { $self->_receive_data_from($fh) }
34 has on_close => (is => 'rw', default => sub { CPS::Future->new });
36 has child_pid => (is => 'ro');
38 has ready_future => (is => 'lazy');
40 sub _build_ready_future { CPS::Future->new }
42 has _receive_data_buffer => (is => 'ro', default => sub { my $x = ''; \$x });
44 has local_objects_by_id => (
45 is => 'ro', default => sub { {} },
46 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
49 has remote_objects_by_id => (
50 is => 'ro', default => sub { {} },
51 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
54 has outstanding_futures => (is => 'ro', default => sub { {} });
59 _deserialize => 'decode',
64 sub _id_to_remote_object {
66 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
68 $self->remote_objects_by_id->{$id}
69 or Object::Remote::Handle->new(connection => $self, id => $id)
74 weaken(my $self = shift);
75 JSON::PP->new->filter_json_single_key_object(
76 __remote_object__ => sub {
77 $self->_id_to_remote_object(@_);
79 )->filter_json_single_key_object(
80 __remote_code__ => sub {
81 my $code_container = $self->_id_to_remote_object(@_);
82 sub { $code_container->call(@_) };
88 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
89 eval { require Object::Remote::Connector::Local };
90 eval { require Object::Remote::Connector::LocalSudo };
91 eval { require Object::Remote::Connector::SSH };
92 eval { require Object::Remote::Connector::UNIX };
96 my ($class, $spec) = @_;
97 return $spec if blessed $spec;
98 foreach my $poss (do { our @Guess }) {
99 if (my $obj = $poss->($spec)) { return $obj }
101 die "Couldn't figure out what to do with ${spec}";
105 my ($self, @args) = @_;
106 Object::Remote::Handle->new(
107 connection => $self, @args
112 my ($self, $to) = @_;
114 $self->send_class_call(0, 'Object::Remote', connect => $to)
119 my ($self, $sub) = @_;
120 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
121 return await_future($self->send_class_call(0, $pkg, can => $name));
124 sub send_class_call {
125 my ($self, $ctx, @call) = @_;
126 $self->send(call => class_call_handler => $ctx => call => @call);
129 sub register_class_call_handler {
131 $self->local_objects_by_id->{'class_call_handler'}
132 = Object::Remote::CodeContainer->new(
134 my ($class, $method) = (shift, shift);
135 use_module($class)->$method(@_);
140 sub register_remote {
141 my ($self, $remote) = @_;
142 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
148 await_future($self->ready_future);
152 my ($self, $id) = @_;
153 delete $self->remote_objects_by_id->{$id};
154 $self->_send([ free => $id ]);
158 my ($self, $type, @call) = @_;
160 my $future = CPS::Future->new;
162 unshift @call, $type => $self->_local_object_to_id($future);
164 my $outstanding = $self->outstanding_futures;
165 $outstanding->{$future} = $future;
166 $future->on_ready(sub { delete $outstanding->{$future} });
168 $self->_send(\@call);
174 my ($self, $type, @call) = @_;
176 unshift @call, $type => 'NULL';
178 $self->_send(\@call);
182 my ($self, $to_send) = @_;
186 print { $self->send_to_fh } $self->_serialize($to_send)."\n";
190 my ($self, $data) = @_;
193 my $flat = $self->_encode($self->_deobjectify($data));
194 warn "$$ >>> ${flat}\n" if $DEBUG;
197 my $err = $@; # won't get here if the eval doesn't die
198 # don't keep refs to new things
199 delete @{$self->local_objects_by_id}{@New_Ids};
200 die "Error serializing: $err";
204 sub _local_object_to_id {
205 my ($self, $object) = @_;
206 my $id = refaddr($object);
207 $self->local_objects_by_id->{$id} ||= do {
208 push our(@New_Ids), $id;
215 my ($self, $data) = @_;
216 if (blessed($data)) {
217 return +{ __remote_object__ => $self->_local_object_to_id($data) };
218 } elsif (my $ref = ref($data)) {
219 if ($ref eq 'HASH') {
220 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
221 } elsif ($ref eq 'ARRAY') {
222 return [ map $self->_deobjectify($_), @$data ];
223 } elsif ($ref eq 'CODE') {
224 my $id = $self->_local_object_to_id(
225 Object::Remote::CodeContainer->new(code => $data)
227 return +{ __remote_code__ => $id };
229 die "Can't collapse reftype $ref";
232 return $data; # plain scalar
235 sub _receive_data_from {
236 my ($self, $fh) = @_;
237 my $rb = $self->_receive_data_buffer;
238 my $ready = $self->ready_future->is_ready;
239 my $len = sysread($fh, $$rb, 1024, length($$rb));
240 my $err = defined($len) ? '' : ": $!";
241 if (defined($len) and $len > 0) {
242 while ($$rb =~ s/^(.*)\n//) {
247 die "New remote container did not send Shere - got ${line}"
248 unless $line eq "Shere";
249 $self->ready_future->done;
253 Object::Remote->current_loop
255 handle => $self->receive_from_fh,
258 my $outstanding = $self->outstanding_futures;
259 $_->fail("Connection lost${err}") for values %$outstanding;
261 $self->on_close->done();
266 my ($self, $flat) = @_;
267 warn "$$ <<< $flat\n" if $DEBUG;
268 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
269 or do { warn "Deserialize failed for ${flat}: $@"; return };
270 eval { $self->${\"receive_${type}"}(@rest); 1 }
271 or do { warn "Receive failed for ${flat}: $@"; return };
276 my ($self, $id) = @_;
277 delete $self->local_objects_by_id->{$id}
278 or warn "Free: no such object $id";
283 my ($self, $future_id, $id, @rest) = @_;
284 my $future = $self->_id_to_remote_object($future_id);
285 $future->{method} = 'call_discard_free';
286 my $local = $self->local_objects_by_id->{$id}
287 or do { $future->fail("No such object $id"); return };
288 $self->_invoke($future, $local, @rest);
291 sub receive_call_free {
292 my ($self, $future, $id, @rest) = @_;
293 $self->receive_call($future, $id, undef, @rest);
294 $self->receive_free($id);
297 sub receive_class_call {
298 my ($self, $future_id, $class, @rest) = @_;
299 my $future = $self->_id_to_remote_object($future_id);
300 $future->{method} = 'call_discard_free';
301 eval { use_module($class) }
302 or do { $future->fail("Error loading ${class}: $@"); return };
303 $self->_invoke($future, $class, @rest);
307 my ($self, $future, $local, $ctx, $method, @args) = @_;
308 if ($method =~ /^start::/) {
309 my $f = $local->$method(@args);
310 $f->on_done(sub { undef($f); $future->done(@_) });
312 $f->on_fail(sub { undef($f); $future->fail(@_) });
315 my $do = sub { $local->$method(@args) };
319 ? ($ctx ? $do->() : scalar($do->()))
323 } or do { $future->fail($@); return; };
328 my ($self, $gd) = @_;
330 Object::Remote->current_loop
332 handle => $self->receive_from_fh,