create ReadChannel object to allow moving Shere logic into connect
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
CommitLineData
9e72f0cf 1package Object::Remote::Connection;
2
dc28afe8 3use Object::Remote::Future;
9d804009 4use Object::Remote::Null;
676438a1 5use Object::Remote::Handle;
fe6c9a7f 6use Object::Remote::CodeContainer;
ed5a8a8e 7use Object::Remote::GlobProxy;
8use Object::Remote::GlobContainer;
9e72f0cf 9use Object::Remote;
ed5a8a8e 10use Symbol;
9e72f0cf 11use IO::Handle;
12use Module::Runtime qw(use_module);
13use Scalar::Util qw(weaken blessed refaddr);
14use JSON::PP qw(encode_json);
15use Moo;
16
6db5156c 17our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
ad4f54b2 18
9e72f0cf 19has send_to_fh => (
20 is => 'ro', required => 1,
21 trigger => sub { $_[1]->autoflush(1) },
22);
23
12fb4a80 24has read_channel => (
9e72f0cf 25 is => 'ro', required => 1,
26 trigger => sub {
12fb4a80 27 my ($self, $ch) = @_;
9e72f0cf 28 weaken($self);
12fb4a80 29 $ch->on_line_call(sub { $self->_receive(@_) });
30 $ch->on_close_call(sub { $self->on_close->done(@_) });
9e72f0cf 31 },
32);
33
12fb4a80 34has on_close => (
35 is => 'ro', default => sub { CPS::Future->new },
36 trigger => sub {
37 my ($self, $f) = @_;
38 weaken($self);
39 $f->on_done(sub {
40 $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
41 });
42 }
43);
ad4f54b2 44
47c83a13 45has child_pid => (is => 'ro');
46
11dbd4a0 47has local_objects_by_id => (
48 is => 'ro', default => sub { {} },
49 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
50);
9e72f0cf 51
11dbd4a0 52has remote_objects_by_id => (
53 is => 'ro', default => sub { {} },
54 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
55);
9e72f0cf 56
a980b0b8 57has outstanding_futures => (is => 'ro', default => sub { {} });
58
12fb4a80 59sub _fail_outstanding {
60 my ($self, $error) = @_;
61 my $outstanding = $self->outstanding_futures;
62 $_->fail($error) for values %$outstanding;
63 %$outstanding = ();
64 return;
65}
66
9e72f0cf 67has _json => (
68 is => 'lazy',
69 handles => {
70 _deserialize => 'decode',
71 _encode => 'encode',
72 },
73);
74
fe6c9a7f 75sub _id_to_remote_object {
76 my ($self, $id) = @_;
77 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
78 (
79 $self->remote_objects_by_id->{$id}
80 or Object::Remote::Handle->new(connection => $self, id => $id)
81 )->proxy;
82}
83
9e72f0cf 84sub _build__json {
85 weaken(my $self = shift);
9e72f0cf 86 JSON::PP->new->filter_json_single_key_object(
87 __remote_object__ => sub {
fe6c9a7f 88 $self->_id_to_remote_object(@_);
89 }
90 )->filter_json_single_key_object(
91 __remote_code__ => sub {
92 my $code_container = $self->_id_to_remote_object(@_);
93 sub { $code_container->call(@_) };
9e72f0cf 94 }
6ed5d580 95 )->filter_json_single_key_object(
96 __scalar_ref__ => sub {
97 my $value = shift;
98 return \$value;
99 }
ed5a8a8e 100 )->filter_json_single_key_object(
101 __glob_ref__ => sub {
102 my $glob_container = $self->_id_to_remote_object(@_);
103 my $handle = Symbol::gensym;
104 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
105 return $handle;
106 }
9e72f0cf 107 );
108}
109
84b04178 110BEGIN {
111 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
112 eval { require Object::Remote::Connector::Local };
a9fdb55e 113 eval { require Object::Remote::Connector::LocalSudo };
84b04178 114 eval { require Object::Remote::Connector::SSH };
1d26d6f9 115 eval { require Object::Remote::Connector::UNIX };
84b04178 116}
117
118sub new_from_spec {
119 my ($class, $spec) = @_;
e144d525 120 return $spec if blessed $spec;
84b04178 121 foreach my $poss (do { our @Guess }) {
122 if (my $obj = $poss->($spec)) { return $obj }
123 }
124 die "Couldn't figure out what to do with ${spec}";
125}
126
11dbd4a0 127sub remote_object {
e144d525 128 my ($self, @args) = @_;
129 Object::Remote::Handle->new(
130 connection => $self, @args
131 )->proxy;
132}
133
4c17fea5 134sub connect {
135 my ($self, $to) = @_;
deb77aaf 136 return await_future(
137 $self->send_class_call(0, 'Object::Remote', connect => $to)
138 );
4c17fea5 139}
140
11dbd4a0 141sub remote_sub {
c6fe6fbd 142 my ($self, $sub) = @_;
143 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
deb77aaf 144 return await_future($self->send_class_call(0, $pkg, can => $name));
145}
146
147sub send_class_call {
148 my ($self, $ctx, @call) = @_;
149 $self->send(call => class_call_handler => $ctx => call => @call);
150}
151
152sub register_class_call_handler {
153 my ($self) = @_;
3687a42d 154 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 155 my $o = $self->new_class_call_handler;
3687a42d 156 $self->_local_object_to_id($o);
157 $o;
158 };
c6fe6fbd 159}
160
c5736e1c 161sub new_class_call_handler {
162 Object::Remote::CodeContainer->new(
163 code => sub {
164 my ($class, $method) = (shift, shift);
165 use_module($class)->$method(@_);
166 }
167 );
168}
169
9e72f0cf 170sub register_remote {
171 my ($self, $remote) = @_;
172 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
173 return $remote;
174}
175
176sub send_free {
177 my ($self, $id) = @_;
178 delete $self->remote_objects_by_id->{$id};
179 $self->_send([ free => $id ]);
180}
181
182sub send {
183 my ($self, $type, @call) = @_;
184
deb77aaf 185 my $future = CPS::Future->new;
a2d43709 186 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 187
188 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 189
a980b0b8 190 my $outstanding = $self->outstanding_futures;
191 $outstanding->{$future} = $future;
a2d43709 192 $future->on_ready(sub {
193 undef($remote);
194 delete $outstanding->{$future}
195 });
a980b0b8 196
9e72f0cf 197 $self->_send(\@call);
198
199 return $future;
200}
201
9d804009 202sub send_discard {
203 my ($self, $type, @call) = @_;
204
deb77aaf 205 unshift @call, $type => 'NULL';
9d804009 206
207 $self->_send(\@call);
208}
209
9e72f0cf 210sub _send {
211 my ($self, $to_send) = @_;
212
9d804009 213 print { $self->send_to_fh } $self->_serialize($to_send)."\n";
9e72f0cf 214}
215
216sub _serialize {
217 my ($self, $data) = @_;
3687a42d 218 local our @New_Ids = (-1);
9d804009 219 return eval {
ad4f54b2 220 my $flat = $self->_encode($self->_deobjectify($data));
221 warn "$$ >>> ${flat}\n" if $DEBUG;
222 $flat;
70a578ac 223 } || do {
9d804009 224 my $err = $@; # won't get here if the eval doesn't die
225 # don't keep refs to new things
226 delete @{$self->local_objects_by_id}{@New_Ids};
227 die "Error serializing: $err";
228 };
9e72f0cf 229}
230
a76f2f60 231sub _local_object_to_id {
232 my ($self, $object) = @_;
233 my $id = refaddr($object);
234 $self->local_objects_by_id->{$id} ||= do {
3687a42d 235 push our(@New_Ids), $id if @New_Ids;
a76f2f60 236 $object;
237 };
238 return $id;
239}
240
9e72f0cf 241sub _deobjectify {
242 my ($self, $data) = @_;
243 if (blessed($data)) {
a76f2f60 244 return +{ __remote_object__ => $self->_local_object_to_id($data) };
9e72f0cf 245 } elsif (my $ref = ref($data)) {
246 if ($ref eq 'HASH') {
247 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
248 } elsif ($ref eq 'ARRAY') {
249 return [ map $self->_deobjectify($_), @$data ];
fe6c9a7f 250 } elsif ($ref eq 'CODE') {
251 my $id = $self->_local_object_to_id(
252 Object::Remote::CodeContainer->new(code => $data)
253 );
254 return +{ __remote_code__ => $id };
6ed5d580 255 } elsif ($ref eq 'SCALAR') {
256 return +{ __scalar_ref__ => $$data };
ed5a8a8e 257 } elsif ($ref eq 'GLOB') {
258 return +{ __glob_ref__ => $self->_local_object_to_id(
259 Object::Remote::GlobContainer->new(handle => $data)
260 ) };
9e72f0cf 261 } else {
262 die "Can't collapse reftype $ref";
263 }
264 }
265 return $data; # plain scalar
266}
267
9e72f0cf 268sub _receive {
ad4f54b2 269 my ($self, $flat) = @_;
270 warn "$$ <<< $flat\n" if $DEBUG;
271 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
272 or do { warn "Deserialize failed for ${flat}: $@"; return };
9e72f0cf 273 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 274 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 275 return;
276}
277
278sub receive_free {
279 my ($self, $id) = @_;
9d804009 280 delete $self->local_objects_by_id->{$id}
281 or warn "Free: no such object $id";
9e72f0cf 282 return;
283}
284
285sub receive_call {
deb77aaf 286 my ($self, $future_id, $id, @rest) = @_;
287 my $future = $self->_id_to_remote_object($future_id);
8131a88a 288 $future->{method} = 'call_discard_free';
9e72f0cf 289 my $local = $self->local_objects_by_id->{$id}
290 or do { $future->fail("No such object $id"); return };
291 $self->_invoke($future, $local, @rest);
292}
293
8131a88a 294sub receive_call_free {
295 my ($self, $future, $id, @rest) = @_;
84b04178 296 $self->receive_call($future, $id, undef, @rest);
8131a88a 297 $self->receive_free($id);
298}
299
9e72f0cf 300sub _invoke {
84b04178 301 my ($self, $future, $local, $ctx, $method, @args) = @_;
dc28afe8 302 if ($method =~ /^start::/) {
303 my $f = $local->$method(@args);
304 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 305 return unless $f;
dc28afe8 306 $f->on_fail(sub { undef($f); $future->fail(@_) });
307 return;
308 }
84b04178 309 my $do = sub { $local->$method(@args) };
310 eval {
311 $future->done(
312 defined($ctx)
313 ? ($ctx ? $do->() : scalar($do->()))
314 : do { $do->(); () }
315 );
316 1;
317 } or do { $future->fail($@); return; };
9e72f0cf 318 return;
319}
320
9e72f0cf 3211;
b9a9982d 322
323=head1 NAME
324
325Object::Remote::Connection - An underlying connection for L<Object::Remote>
326
327=head1 LAME
328
329Shipping prioritised over writing this part up. Blame mst.
330
331=cut