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'} ||= do {
132 my $o = $self->new_class_call_handler;
133 $self->_local_object_to_id($o);
138 sub new_class_call_handler {
139 Object::Remote::CodeContainer->new(
141 my ($class, $method) = (shift, shift);
142 use_module($class)->$method(@_);
147 sub register_remote {
148 my ($self, $remote) = @_;
149 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
155 await_future($self->ready_future);
159 my ($self, $id) = @_;
160 delete $self->remote_objects_by_id->{$id};
161 $self->_send([ free => $id ]);
165 my ($self, $type, @call) = @_;
167 my $future = CPS::Future->new;
168 my $remote = $self->remote_objects_by_id->{$call[0]};
170 unshift @call, $type => $self->_local_object_to_id($future);
172 my $outstanding = $self->outstanding_futures;
173 $outstanding->{$future} = $future;
174 $future->on_ready(sub {
176 delete $outstanding->{$future}
179 $self->_send(\@call);
185 my ($self, $type, @call) = @_;
187 unshift @call, $type => 'NULL';
189 $self->_send(\@call);
193 my ($self, $to_send) = @_;
197 print { $self->send_to_fh } $self->_serialize($to_send)."\n";
201 my ($self, $data) = @_;
202 local our @New_Ids = (-1);
204 my $flat = $self->_encode($self->_deobjectify($data));
205 warn "$$ >>> ${flat}\n" if $DEBUG;
208 my $err = $@; # won't get here if the eval doesn't die
209 # don't keep refs to new things
210 delete @{$self->local_objects_by_id}{@New_Ids};
211 die "Error serializing: $err";
215 sub _local_object_to_id {
216 my ($self, $object) = @_;
217 my $id = refaddr($object);
218 $self->local_objects_by_id->{$id} ||= do {
219 push our(@New_Ids), $id if @New_Ids;
226 my ($self, $data) = @_;
227 if (blessed($data)) {
228 return +{ __remote_object__ => $self->_local_object_to_id($data) };
229 } elsif (my $ref = ref($data)) {
230 if ($ref eq 'HASH') {
231 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
232 } elsif ($ref eq 'ARRAY') {
233 return [ map $self->_deobjectify($_), @$data ];
234 } elsif ($ref eq 'CODE') {
235 my $id = $self->_local_object_to_id(
236 Object::Remote::CodeContainer->new(code => $data)
238 return +{ __remote_code__ => $id };
240 die "Can't collapse reftype $ref";
243 return $data; # plain scalar
246 sub _receive_data_from {
247 my ($self, $fh) = @_;
248 my $rb = $self->_receive_data_buffer;
249 my $ready = $self->ready_future->is_ready;
250 my $len = sysread($fh, $$rb, 1024, length($$rb));
251 my $err = defined($len) ? '' : ": $!";
252 if (defined($len) and $len > 0) {
253 while ($$rb =~ s/^(.*)\n//) {
258 die "New remote container did not send Shere - got ${line}"
259 unless $line eq "Shere";
260 $self->ready_future->done;
264 Object::Remote->current_loop
266 handle => $self->receive_from_fh,
269 my $outstanding = $self->outstanding_futures;
270 $_->fail("Connection lost${err}") for values %$outstanding;
272 $self->on_close->done();
277 my ($self, $flat) = @_;
278 warn "$$ <<< $flat\n" if $DEBUG;
279 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
280 or do { warn "Deserialize failed for ${flat}: $@"; return };
281 eval { $self->${\"receive_${type}"}(@rest); 1 }
282 or do { warn "Receive failed for ${flat}: $@"; return };
287 my ($self, $id) = @_;
288 delete $self->local_objects_by_id->{$id}
289 or warn "Free: no such object $id";
294 my ($self, $future_id, $id, @rest) = @_;
295 my $future = $self->_id_to_remote_object($future_id);
296 $future->{method} = 'call_discard_free';
297 my $local = $self->local_objects_by_id->{$id}
298 or do { $future->fail("No such object $id"); return };
299 $self->_invoke($future, $local, @rest);
302 sub receive_call_free {
303 my ($self, $future, $id, @rest) = @_;
304 $self->receive_call($future, $id, undef, @rest);
305 $self->receive_free($id);
309 my ($self, $future, $local, $ctx, $method, @args) = @_;
310 if ($method =~ /^start::/) {
311 my $f = $local->$method(@args);
312 $f->on_done(sub { undef($f); $future->done(@_) });
314 $f->on_fail(sub { undef($f); $future->fail(@_) });
317 my $do = sub { $local->$method(@args) };
321 ? ($ctx ? $do->() : scalar($do->()))
325 } or do { $future->fail($@); return; };
330 my ($self, $gd) = @_;
332 Object::Remote->current_loop
334 handle => $self->receive_from_fh,