slightly improve things
[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
12has proxy => (is => 'lazy', weak_ref => 1);
13
14sub _build_proxy {
9d804009 15 bless({ remote => $_[0] }, 'Object::Remote::Proxy');
9e72f0cf 16}
17
18sub BUILD {
19 my ($self, $args) = @_;
20 unless ($self->id) {
21 die "No id supplied and no class either" unless $args->{class};
22 $self->_set_id(
23 $self->_await(
24 $self->connection->send(
25 class_call => $args->{class},
26 $args->{constructor}||'new', @{$args->{args}||[]}
27 )
28 )
29 );
30 }
31 $self->connection->register_remote($self);
32}
33
34sub current_loop {
35 our $Current_Loop ||= Object::Remote::MiniLoop->new
36}
37
38sub call {
9d804009 39 my ($self, $method, @args) = @_;
9e72f0cf 40 $self->_await($self->connection->send(call => $self->id, $method, @args));
41}
42
43sub _await {
44 my ($self, $future) = @_;
45 my $loop = $self->current_loop;
46 $future->on_ready(sub { $loop->stop });
47 $loop->run;
48 $future->get;
49}
50
51sub DEMOLISH {
52 my ($self, $gd) = @_;
53 return if $gd;
54 $self->connection->send_free($self->id);
55}
56
571;