working module sending
[scpubgit/Object-Remote.git] / lib / Object / Remote.pm
CommitLineData
9e72f0cf 1package Object::Remote;
2
3use Object::Remote::MiniLoop;
4use Object::Remote::Proxy;
5use Scalar::Util qw(weaken);
6use Moo;
7
8has connection => (is => 'ro', required => 1);
9
10has id => (is => 'rwp');
11
ad4f54b2 12has disarmed_free => (is => 'rwp');
13
14sub disarm_free { $_[0]->_set_disarmed_free(1); $_[0] }
15
2065b08b 16sub proxy {
17 bless({ remote => $_[0], method => 'call' }, 'Object::Remote::Proxy');
9e72f0cf 18}
19
20sub BUILD {
21 my ($self, $args) = @_;
22 unless ($self->id) {
23 die "No id supplied and no class either" unless $args->{class};
542d5b5c 24 ref($_) eq 'HASH' and $_ = [ %$_ ] for $args->{args};
9e72f0cf 25 $self->_set_id(
26 $self->_await(
27 $self->connection->send(
28 class_call => $args->{class},
29 $args->{constructor}||'new', @{$args->{args}||[]}
30 )
ad4f54b2 31 )->{remote}->disarm_free->id
9e72f0cf 32 );
33 }
34 $self->connection->register_remote($self);
35}
36
37sub current_loop {
38 our $Current_Loop ||= Object::Remote::MiniLoop->new
39}
40
41sub call {
9d804009 42 my ($self, $method, @args) = @_;
9e72f0cf 43 $self->_await($self->connection->send(call => $self->id, $method, @args));
44}
45
2065b08b 46sub call_discard {
47 my ($self, $method, @args) = @_;
48 $self->connection->send_discard(call => $self->id, $method, @args);
49}
50
8131a88a 51sub 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
9e72f0cf 57sub _await {
58 my ($self, $future) = @_;
59 my $loop = $self->current_loop;
60 $future->on_ready(sub { $loop->stop });
61 $loop->run;
ad4f54b2 62 ($future->get)[0];
9e72f0cf 63}
64
65sub DEMOLISH {
66 my ($self, $gd) = @_;
ad4f54b2 67 return if $gd or $self->disarmed_free;
9e72f0cf 68 $self->connection->send_free($self->id);
69}
70
711;