add ability to do discard sends and make things basically work
[scpubgit/Object-Remote.git] / lib / Object / Remote.pm
1 package Object::Remote;
2
3 use Object::Remote::MiniLoop;
4 use Object::Remote::Proxy;
5 use Scalar::Util qw(weaken);
6 use Moo;
7
8 has connection => (is => 'ro', required => 1);
9
10 has id => (is => 'rwp');
11
12 sub proxy {
13   bless({ remote => $_[0], method => 'call' }, 'Object::Remote::Proxy');
14 }
15
16 sub BUILD {
17   my ($self, $args) = @_;
18   unless ($self->id) {
19     die "No id supplied and no class either" unless $args->{class};
20     $self->_set_id(
21       $self->_await(
22         $self->connection->send(
23           class_call => $args->{class},
24           $args->{constructor}||'new', @{$args->{args}||[]}
25         )
26       )
27     );
28   }
29   $self->connection->register_remote($self);
30 }
31
32 sub current_loop {
33   our $Current_Loop ||= Object::Remote::MiniLoop->new
34 }
35
36 sub call {
37   my ($self, $method, @args) = @_;
38   $self->_await($self->connection->send(call => $self->id, $method, @args));
39 }
40
41 sub call_discard {
42   my ($self, $method, @args) = @_;
43   $self->connection->send_discard(call => $self->id, $method, @args);
44 }
45
46 sub _await {
47   my ($self, $future) = @_;
48   my $loop = $self->current_loop;
49   $future->on_ready(sub { $loop->stop });
50   $loop->run;
51   $future->get;
52 }
53
54 sub DEMOLISH {
55   my ($self, $gd) = @_;
56   return if $gd;
57   $self->connection->send_free($self->id);
58 }
59
60 1;