Commit | Line | Data |
9e72f0cf |
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 proxy => (is => 'lazy', weak_ref => 1); |
13 | |
14 | sub _build_proxy { |
15 | bless({ handle => $_[0] }, 'Object::Remote::Proxy'); |
16 | } |
17 | |
18 | sub 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 | |
34 | sub current_loop { |
35 | our $Current_Loop ||= Object::Remote::MiniLoop->new |
36 | } |
37 | |
38 | sub call { |
39 | my ($self, $id, $method, @args) = @_; |
40 | $self->_await($self->connection->send(call => $self->id, $method, @args)); |
41 | } |
42 | |
43 | sub _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 | |
51 | sub DEMOLISH { |
52 | my ($self, $gd) = @_; |
53 | return if $gd; |
54 | $self->connection->send_free($self->id); |
55 | } |
56 | |
57 | 1; |