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 | |
ad4f54b2 |
12 | has disarmed_free => (is => 'rwp'); |
13 | |
14 | sub disarm_free { $_[0]->_set_disarmed_free(1); $_[0] } |
15 | |
2065b08b |
16 | sub proxy { |
17 | bless({ remote => $_[0], method => 'call' }, 'Object::Remote::Proxy'); |
9e72f0cf |
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}; |
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 | |
37 | sub current_loop { |
38 | our $Current_Loop ||= Object::Remote::MiniLoop->new |
39 | } |
40 | |
41 | sub call { |
9d804009 |
42 | my ($self, $method, @args) = @_; |
9e72f0cf |
43 | $self->_await($self->connection->send(call => $self->id, $method, @args)); |
44 | } |
45 | |
2065b08b |
46 | sub call_discard { |
47 | my ($self, $method, @args) = @_; |
48 | $self->connection->send_discard(call => $self->id, $method, @args); |
49 | } |
50 | |
8131a88a |
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 | |
9e72f0cf |
57 | sub _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 | |
65 | sub DEMOLISH { |
66 | my ($self, $gd) = @_; |
ad4f54b2 |
67 | return if $gd or $self->disarmed_free; |
9e72f0cf |
68 | $self->connection->send_free($self->id); |
69 | } |
70 | |
71 | 1; |