working module sending
[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 has disarmed_free => (is => 'rwp');
13
14 sub disarm_free { $_[0]->_set_disarmed_free(1); $_[0] }
15
16 sub proxy {
17   bless({ remote => $_[0], method => 'call' }, 'Object::Remote::Proxy');
18 }
19
20 sub BUILD {
21   my ($self, $args) = @_;
22   unless ($self->id) {
23     die "No id supplied and no class either" unless $args->{class};
24     ref($_) eq 'HASH' and $_ = [ %$_ ] for $args->{args};
25     $self->_set_id(
26       $self->_await(
27         $self->connection->send(
28           class_call => $args->{class},
29           $args->{constructor}||'new', @{$args->{args}||[]}
30         )
31       )->{remote}->disarm_free->id
32     );
33   }
34   $self->connection->register_remote($self);
35 }
36
37 sub current_loop {
38   our $Current_Loop ||= Object::Remote::MiniLoop->new
39 }
40
41 sub call {
42   my ($self, $method, @args) = @_;
43   $self->_await($self->connection->send(call => $self->id, $method, @args));
44 }
45
46 sub call_discard {
47   my ($self, $method, @args) = @_;
48   $self->connection->send_discard(call => $self->id, $method, @args);
49 }
50
51 sub call_discard_free {
52   my ($self, $method, @args) = @_;
53   $self->disarm_free;
54   $self->connection->send_discard(call_free => $self->id, $method, @args);
55 }
56
57 sub _await {
58   my ($self, $future) = @_;
59   my $loop = $self->current_loop;
60   $future->on_ready(sub { $loop->stop });
61   $loop->run;
62   ($future->get)[0];
63 }
64
65 sub DEMOLISH {
66   my ($self, $gd) = @_;
67   return if $gd or $self->disarmed_free;
68   $self->connection->send_free($self->id);
69 }
70
71 1;