experimental move to non-blocking reads in ReadChannel; fix log bugs; annotate fixes...
[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;
9d64d2d9 9use Object::Remote::Logging qw (:log :dlog);
9e72f0cf 10use Object::Remote;
ed5a8a8e 11use Symbol;
9e72f0cf 12use IO::Handle;
13use Module::Runtime qw(use_module);
14use Scalar::Util qw(weaken blessed refaddr);
15use JSON::PP qw(encode_json);
16use Moo;
17
6db5156c 18our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
9031635d 19#numbering each connection allows it to be
20#tracked along with file handles in
21#the logs
22BEGIN { our $NEXT_CONNECTION_ID = 0 }
23has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
ad4f54b2 24
9e72f0cf 25has send_to_fh => (
26 is => 'ro', required => 1,
90115979 27 trigger => sub {
28 my $self = $_[0];
29 $_[1]->autoflush(1);
30 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
31 },
9e72f0cf 32);
33
12fb4a80 34has read_channel => (
9e72f0cf 35 is => 'ro', required => 1,
36 trigger => sub {
12fb4a80 37 my ($self, $ch) = @_;
90115979 38 Dlog_trace { my $id = $self->_id; "trigger for read_channel has been invoked for connection $id; file handle is " } $ch->fh;
9e72f0cf 39 weaken($self);
12fb4a80 40 $ch->on_line_call(sub { $self->_receive(@_) });
41 $ch->on_close_call(sub { $self->on_close->done(@_) });
9e72f0cf 42 },
43);
44
12fb4a80 45has on_close => (
46 is => 'ro', default => sub { CPS::Future->new },
9031635d 47 trigger => sub {
12fb4a80 48 my ($self, $f) = @_;
9031635d 49 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
12fb4a80 50 weaken($self);
51 $f->on_done(sub {
52 $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
53 });
54 }
55);
ad4f54b2 56
47c83a13 57has child_pid => (is => 'ro');
58
11dbd4a0 59has local_objects_by_id => (
60 is => 'ro', default => sub { {} },
61 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
62);
9e72f0cf 63
11dbd4a0 64has remote_objects_by_id => (
65 is => 'ro', default => sub { {} },
66 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
67);
9e72f0cf 68
a980b0b8 69has outstanding_futures => (is => 'ro', default => sub { {} });
70
12fb4a80 71sub _fail_outstanding {
72 my ($self, $error) = @_;
9031635d 73 Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
12fb4a80 74 my $outstanding = $self->outstanding_futures;
75 $_->fail($error) for values %$outstanding;
76 %$outstanding = ();
77 return;
78}
79
9e72f0cf 80has _json => (
81 is => 'lazy',
82 handles => {
83 _deserialize => 'decode',
84 _encode => 'encode',
85 },
86);
87
fe6c9a7f 88sub _id_to_remote_object {
89 my ($self, $id) = @_;
9031635d 90 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
fe6c9a7f 91 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
92 (
93 $self->remote_objects_by_id->{$id}
94 or Object::Remote::Handle->new(connection => $self, id => $id)
95 )->proxy;
96}
97
9e72f0cf 98sub _build__json {
99 weaken(my $self = shift);
9e72f0cf 100 JSON::PP->new->filter_json_single_key_object(
101 __remote_object__ => sub {
fe6c9a7f 102 $self->_id_to_remote_object(@_);
103 }
104 )->filter_json_single_key_object(
105 __remote_code__ => sub {
106 my $code_container = $self->_id_to_remote_object(@_);
107 sub { $code_container->call(@_) };
9e72f0cf 108 }
6ed5d580 109 )->filter_json_single_key_object(
110 __scalar_ref__ => sub {
111 my $value = shift;
112 return \$value;
113 }
ed5a8a8e 114 )->filter_json_single_key_object(
115 __glob_ref__ => sub {
116 my $glob_container = $self->_id_to_remote_object(@_);
117 my $handle = Symbol::gensym;
118 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
119 return $handle;
120 }
6163a5aa 121 )->filter_json_single_key_object(
122 __local_object__ => sub {
123 $self->local_objects_by_id->{$_[0]}
124 }
9e72f0cf 125 );
126}
127
84b04178 128BEGIN {
129 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
130 eval { require Object::Remote::Connector::Local };
a9fdb55e 131 eval { require Object::Remote::Connector::LocalSudo };
84b04178 132 eval { require Object::Remote::Connector::SSH };
1d26d6f9 133 eval { require Object::Remote::Connector::UNIX };
84b04178 134}
135
136sub new_from_spec {
137 my ($class, $spec) = @_;
e144d525 138 return $spec if blessed $spec;
9031635d 139 Dlog_debug { "creating a new connection from spec" };
84b04178 140 foreach my $poss (do { our @Guess }) {
fbd3b8ec 141 if (my $conn = $poss->($spec)) {
9031635d 142 #Dlog_debug { my $id = $conn->_id; "created connection $id for spec $_" } $spec;
fbd3b8ec 143 return $conn->maybe::start::connect;
144 }
84b04178 145 }
146 die "Couldn't figure out what to do with ${spec}";
147}
148
11dbd4a0 149sub remote_object {
e144d525 150 my ($self, @args) = @_;
151 Object::Remote::Handle->new(
152 connection => $self, @args
153 )->proxy;
154}
155
4c17fea5 156sub connect {
157 my ($self, $to) = @_;
9031635d 158 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
deb77aaf 159 return await_future(
160 $self->send_class_call(0, 'Object::Remote', connect => $to)
161 );
4c17fea5 162}
163
11dbd4a0 164sub remote_sub {
c6fe6fbd 165 my ($self, $sub) = @_;
166 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
9031635d 167 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
deb77aaf 168 return await_future($self->send_class_call(0, $pkg, can => $name));
169}
170
171sub send_class_call {
172 my ($self, $ctx, @call) = @_;
9031635d 173 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
deb77aaf 174 $self->send(call => class_call_handler => $ctx => call => @call);
175}
176
177sub register_class_call_handler {
178 my ($self) = @_;
3687a42d 179 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 180 my $o = $self->new_class_call_handler;
3687a42d 181 $self->_local_object_to_id($o);
182 $o;
183 };
c6fe6fbd 184}
185
c5736e1c 186sub new_class_call_handler {
187 Object::Remote::CodeContainer->new(
188 code => sub {
189 my ($class, $method) = (shift, shift);
190 use_module($class)->$method(@_);
191 }
192 );
193}
194
9e72f0cf 195sub register_remote {
196 my ($self, $remote) = @_;
9031635d 197 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
9e72f0cf 198 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
199 return $remote;
200}
201
202sub send_free {
203 my ($self, $id) = @_;
9031635d 204 Dlog_debug { "sending request to free object '$id' for connection $_" } $self->_id;
9e72f0cf 205 delete $self->remote_objects_by_id->{$id};
206 $self->_send([ free => $id ]);
207}
208
209sub send {
210 my ($self, $type, @call) = @_;
211
deb77aaf 212 my $future = CPS::Future->new;
a2d43709 213 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 214
215 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 216
a980b0b8 217 my $outstanding = $self->outstanding_futures;
218 $outstanding->{$future} = $future;
a2d43709 219 $future->on_ready(sub {
220 undef($remote);
221 delete $outstanding->{$future}
222 });
a980b0b8 223
9e72f0cf 224 $self->_send(\@call);
225
226 return $future;
227}
228
9d804009 229sub send_discard {
230 my ($self, $type, @call) = @_;
231
deb77aaf 232 unshift @call, $type => 'NULL';
9d804009 233
234 $self->_send(\@call);
235}
236
9e72f0cf 237sub _send {
238 my ($self, $to_send) = @_;
9d64d2d9 239 my $fh = $self->send_to_fh;
9031635d 240 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
9d64d2d9 241 my $serialized = $self->_serialize($to_send)."\n";
9031635d 242 Dlog_debug { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
9d64d2d9 243 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
244 #logic it could easily do short-writes to the remote side
245 my $ret = print $fh $serialized;
246 Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
247 #TODO hrm reason print's return value was ignored?
248 die "could not write to filehandle: $!" unless $ret;
249 return $ret;
9e72f0cf 250}
251
252sub _serialize {
253 my ($self, $data) = @_;
3687a42d 254 local our @New_Ids = (-1);
9031635d 255 Dlog_debug { "starting to serialize data for connection $_" } $self->_id;
9d804009 256 return eval {
ad4f54b2 257 my $flat = $self->_encode($self->_deobjectify($data));
258 warn "$$ >>> ${flat}\n" if $DEBUG;
259 $flat;
70a578ac 260 } || do {
9d804009 261 my $err = $@; # won't get here if the eval doesn't die
262 # don't keep refs to new things
263 delete @{$self->local_objects_by_id}{@New_Ids};
264 die "Error serializing: $err";
265 };
9e72f0cf 266}
267
a76f2f60 268sub _local_object_to_id {
269 my ($self, $object) = @_;
270 my $id = refaddr($object);
271 $self->local_objects_by_id->{$id} ||= do {
3687a42d 272 push our(@New_Ids), $id if @New_Ids;
a76f2f60 273 $object;
274 };
275 return $id;
276}
277
9e72f0cf 278sub _deobjectify {
279 my ($self, $data) = @_;
280 if (blessed($data)) {
6163a5aa 281 if (
282 $data->isa('Object::Remote::Proxy')
283 and $data->{remote}->connection == $self
284 ) {
285 return +{ __local_object__ => $data->{remote}->id };
286 } else {
287 return +{ __remote_object__ => $self->_local_object_to_id($data) };
288 }
9e72f0cf 289 } elsif (my $ref = ref($data)) {
290 if ($ref eq 'HASH') {
291 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
292 } elsif ($ref eq 'ARRAY') {
293 return [ map $self->_deobjectify($_), @$data ];
fe6c9a7f 294 } elsif ($ref eq 'CODE') {
295 my $id = $self->_local_object_to_id(
296 Object::Remote::CodeContainer->new(code => $data)
297 );
298 return +{ __remote_code__ => $id };
6ed5d580 299 } elsif ($ref eq 'SCALAR') {
300 return +{ __scalar_ref__ => $$data };
ed5a8a8e 301 } elsif ($ref eq 'GLOB') {
302 return +{ __glob_ref__ => $self->_local_object_to_id(
303 Object::Remote::GlobContainer->new(handle => $data)
304 ) };
9e72f0cf 305 } else {
306 die "Can't collapse reftype $ref";
307 }
308 }
309 return $data; # plain scalar
310}
311
9e72f0cf 312sub _receive {
ad4f54b2 313 my ($self, $flat) = @_;
314 warn "$$ <<< $flat\n" if $DEBUG;
9031635d 315 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
ad4f54b2 316 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
317 or do { warn "Deserialize failed for ${flat}: $@"; return };
9031635d 318 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
9e72f0cf 319 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 320 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 321 return;
322}
323
324sub receive_free {
325 my ($self, $id) = @_;
9031635d 326 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
9d804009 327 delete $self->local_objects_by_id->{$id}
328 or warn "Free: no such object $id";
9e72f0cf 329 return;
330}
331
332sub receive_call {
deb77aaf 333 my ($self, $future_id, $id, @rest) = @_;
9031635d 334 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
deb77aaf 335 my $future = $self->_id_to_remote_object($future_id);
8131a88a 336 $future->{method} = 'call_discard_free';
9e72f0cf 337 my $local = $self->local_objects_by_id->{$id}
338 or do { $future->fail("No such object $id"); return };
339 $self->_invoke($future, $local, @rest);
340}
341
8131a88a 342sub receive_call_free {
343 my ($self, $future, $id, @rest) = @_;
9031635d 344 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
84b04178 345 $self->receive_call($future, $id, undef, @rest);
8131a88a 346 $self->receive_free($id);
347}
348
9e72f0cf 349sub _invoke {
84b04178 350 my ($self, $future, $local, $ctx, $method, @args) = @_;
9031635d 351 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
dc28afe8 352 if ($method =~ /^start::/) {
353 my $f = $local->$method(@args);
354 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 355 return unless $f;
dc28afe8 356 $f->on_fail(sub { undef($f); $future->fail(@_) });
357 return;
358 }
84b04178 359 my $do = sub { $local->$method(@args) };
360 eval {
361 $future->done(
362 defined($ctx)
363 ? ($ctx ? $do->() : scalar($do->()))
364 : do { $do->(); () }
365 );
366 1;
367 } or do { $future->fail($@); return; };
9e72f0cf 368 return;
369}
370
9e72f0cf 3711;
b9a9982d 372
373=head1 NAME
374
375Object::Remote::Connection - An underlying connection for L<Object::Remote>
376
377=head1 LAME
378
379Shipping prioritised over writing this part up. Blame mst.
380
381=cut