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;
2d81cf18 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};
07105aca 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,
90a3a7f2 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) = @_;
90a3a7f2 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 },
07105aca 47 trigger => sub {
12fb4a80 48 my ($self, $f) = @_;
07105aca 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) = @_;
07105aca 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) = @_;
07105aca 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 }
9e72f0cf 121 );
122}
123
84b04178 124BEGIN {
125 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
126 eval { require Object::Remote::Connector::Local };
a9fdb55e 127 eval { require Object::Remote::Connector::LocalSudo };
84b04178 128 eval { require Object::Remote::Connector::SSH };
1d26d6f9 129 eval { require Object::Remote::Connector::UNIX };
84b04178 130}
131
132sub new_from_spec {
133 my ($class, $spec) = @_;
e144d525 134 return $spec if blessed $spec;
07105aca 135 Dlog_debug { "creating a new connection from spec" };
84b04178 136 foreach my $poss (do { our @Guess }) {
fbd3b8ec 137 if (my $conn = $poss->($spec)) {
07105aca 138 #Dlog_debug { my $id = $conn->_id; "created connection $id for spec $_" } $spec;
fbd3b8ec 139 return $conn->maybe::start::connect;
140 }
84b04178 141 }
142 die "Couldn't figure out what to do with ${spec}";
143}
144
11dbd4a0 145sub remote_object {
e144d525 146 my ($self, @args) = @_;
147 Object::Remote::Handle->new(
148 connection => $self, @args
149 )->proxy;
150}
151
4c17fea5 152sub connect {
153 my ($self, $to) = @_;
07105aca 154 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
deb77aaf 155 return await_future(
156 $self->send_class_call(0, 'Object::Remote', connect => $to)
157 );
4c17fea5 158}
159
11dbd4a0 160sub remote_sub {
c6fe6fbd 161 my ($self, $sub) = @_;
162 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
07105aca 163 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
deb77aaf 164 return await_future($self->send_class_call(0, $pkg, can => $name));
165}
166
167sub send_class_call {
168 my ($self, $ctx, @call) = @_;
07105aca 169 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
deb77aaf 170 $self->send(call => class_call_handler => $ctx => call => @call);
171}
172
173sub register_class_call_handler {
174 my ($self) = @_;
3687a42d 175 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 176 my $o = $self->new_class_call_handler;
3687a42d 177 $self->_local_object_to_id($o);
178 $o;
179 };
c6fe6fbd 180}
181
c5736e1c 182sub new_class_call_handler {
183 Object::Remote::CodeContainer->new(
184 code => sub {
185 my ($class, $method) = (shift, shift);
186 use_module($class)->$method(@_);
187 }
188 );
189}
190
9e72f0cf 191sub register_remote {
192 my ($self, $remote) = @_;
07105aca 193 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
9e72f0cf 194 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
195 return $remote;
196}
197
198sub send_free {
199 my ($self, $id) = @_;
07105aca 200 Dlog_debug { "sending request to free object '$id' for connection $_" } $self->_id;
9e72f0cf 201 delete $self->remote_objects_by_id->{$id};
202 $self->_send([ free => $id ]);
203}
204
205sub send {
206 my ($self, $type, @call) = @_;
207
deb77aaf 208 my $future = CPS::Future->new;
a2d43709 209 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 210
211 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 212
a980b0b8 213 my $outstanding = $self->outstanding_futures;
214 $outstanding->{$future} = $future;
a2d43709 215 $future->on_ready(sub {
216 undef($remote);
217 delete $outstanding->{$future}
218 });
a980b0b8 219
9e72f0cf 220 $self->_send(\@call);
221
222 return $future;
223}
224
9d804009 225sub send_discard {
226 my ($self, $type, @call) = @_;
227
deb77aaf 228 unshift @call, $type => 'NULL';
9d804009 229
230 $self->_send(\@call);
231}
232
9e72f0cf 233sub _send {
234 my ($self, $to_send) = @_;
2d81cf18 235 my $fh = $self->send_to_fh;
07105aca 236 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
2d81cf18 237 my $serialized = $self->_serialize($to_send)."\n";
07105aca 238 Dlog_debug { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
2d81cf18 239 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
240 #logic it could easily do short-writes to the remote side
241 my $ret = print $fh $serialized;
242 Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
243 #TODO hrm reason print's return value was ignored?
244 die "could not write to filehandle: $!" unless $ret;
245 return $ret;
9e72f0cf 246}
247
248sub _serialize {
249 my ($self, $data) = @_;
3687a42d 250 local our @New_Ids = (-1);
07105aca 251 Dlog_debug { "starting to serialize data for connection $_" } $self->_id;
9d804009 252 return eval {
ad4f54b2 253 my $flat = $self->_encode($self->_deobjectify($data));
254 warn "$$ >>> ${flat}\n" if $DEBUG;
255 $flat;
70a578ac 256 } || do {
9d804009 257 my $err = $@; # won't get here if the eval doesn't die
258 # don't keep refs to new things
259 delete @{$self->local_objects_by_id}{@New_Ids};
260 die "Error serializing: $err";
261 };
9e72f0cf 262}
263
a76f2f60 264sub _local_object_to_id {
265 my ($self, $object) = @_;
266 my $id = refaddr($object);
267 $self->local_objects_by_id->{$id} ||= do {
3687a42d 268 push our(@New_Ids), $id if @New_Ids;
a76f2f60 269 $object;
270 };
271 return $id;
272}
273
9e72f0cf 274sub _deobjectify {
275 my ($self, $data) = @_;
276 if (blessed($data)) {
a76f2f60 277 return +{ __remote_object__ => $self->_local_object_to_id($data) };
9e72f0cf 278 } elsif (my $ref = ref($data)) {
279 if ($ref eq 'HASH') {
280 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
281 } elsif ($ref eq 'ARRAY') {
282 return [ map $self->_deobjectify($_), @$data ];
fe6c9a7f 283 } elsif ($ref eq 'CODE') {
284 my $id = $self->_local_object_to_id(
285 Object::Remote::CodeContainer->new(code => $data)
286 );
287 return +{ __remote_code__ => $id };
6ed5d580 288 } elsif ($ref eq 'SCALAR') {
289 return +{ __scalar_ref__ => $$data };
ed5a8a8e 290 } elsif ($ref eq 'GLOB') {
291 return +{ __glob_ref__ => $self->_local_object_to_id(
292 Object::Remote::GlobContainer->new(handle => $data)
293 ) };
9e72f0cf 294 } else {
295 die "Can't collapse reftype $ref";
296 }
297 }
298 return $data; # plain scalar
299}
300
9e72f0cf 301sub _receive {
ad4f54b2 302 my ($self, $flat) = @_;
303 warn "$$ <<< $flat\n" if $DEBUG;
07105aca 304 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
ad4f54b2 305 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
306 or do { warn "Deserialize failed for ${flat}: $@"; return };
07105aca 307 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
9e72f0cf 308 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 309 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 310 return;
311}
312
313sub receive_free {
314 my ($self, $id) = @_;
07105aca 315 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
9d804009 316 delete $self->local_objects_by_id->{$id}
317 or warn "Free: no such object $id";
9e72f0cf 318 return;
319}
320
321sub receive_call {
deb77aaf 322 my ($self, $future_id, $id, @rest) = @_;
07105aca 323 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
deb77aaf 324 my $future = $self->_id_to_remote_object($future_id);
8131a88a 325 $future->{method} = 'call_discard_free';
9e72f0cf 326 my $local = $self->local_objects_by_id->{$id}
327 or do { $future->fail("No such object $id"); return };
328 $self->_invoke($future, $local, @rest);
329}
330
8131a88a 331sub receive_call_free {
332 my ($self, $future, $id, @rest) = @_;
07105aca 333 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
84b04178 334 $self->receive_call($future, $id, undef, @rest);
8131a88a 335 $self->receive_free($id);
336}
337
9e72f0cf 338sub _invoke {
84b04178 339 my ($self, $future, $local, $ctx, $method, @args) = @_;
07105aca 340 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
dc28afe8 341 if ($method =~ /^start::/) {
342 my $f = $local->$method(@args);
343 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 344 return unless $f;
dc28afe8 345 $f->on_fail(sub { undef($f); $future->fail(@_) });
346 return;
347 }
84b04178 348 my $do = sub { $local->$method(@args) };
349 eval {
350 $future->done(
351 defined($ctx)
352 ? ($ctx ? $do->() : scalar($do->()))
353 : do { $do->(); () }
354 );
355 1;
356 } or do { $future->fail($@); return; };
9e72f0cf 357 return;
358}
359
9e72f0cf 3601;
b9a9982d 361
362=head1 NAME
363
364Object::Remote::Connection - An underlying connection for L<Object::Remote>
365
366=head1 LAME
367
368Shipping prioritised over writing this part up. Blame mst.
369
370=cut