parti8al conversion to future based system; start still being weird
[scpubgit/Object-Remote.git] / lib / Object / Remote.pm
CommitLineData
9e72f0cf 1package Object::Remote;
2
3use Object::Remote::MiniLoop;
4use Object::Remote::Proxy;
84b04178 5use Scalar::Util qw(weaken blessed);
dc28afe8 6use Object::Remote::Future;
84b04178 7use Module::Runtime qw(use_module);
9e72f0cf 8use Moo;
9
84b04178 10sub new::on {
11 my ($class, $on, @args) = @_;
12 __PACKAGE__->new(
13 connection => $on,
14 class => $class,
15 args => \@args
16 )->proxy;
17}
18
19has connection => (
20 is => 'ro', required => 1,
21 coerce => sub {
22 blessed($_[0])
23 ? $_[0]
24 : use_module('Object::Remote::Connection')->new_from_spec($_[0])
25 },
26);
9e72f0cf 27
28has id => (is => 'rwp');
29
ad4f54b2 30has disarmed_free => (is => 'rwp');
31
32sub disarm_free { $_[0]->_set_disarmed_free(1); $_[0] }
33
2065b08b 34sub proxy {
35 bless({ remote => $_[0], method => 'call' }, 'Object::Remote::Proxy');
9e72f0cf 36}
37
38sub BUILD {
39 my ($self, $args) = @_;
40 unless ($self->id) {
41 die "No id supplied and no class either" unless $args->{class};
542d5b5c 42 ref($_) eq 'HASH' and $_ = [ %$_ ] for $args->{args};
9e72f0cf 43 $self->_set_id(
dc28afe8 44 await_future(
9e72f0cf 45 $self->connection->send(
84b04178 46 class_call => $args->{class}, 0,
9e72f0cf 47 $args->{constructor}||'new', @{$args->{args}||[]}
48 )
ad4f54b2 49 )->{remote}->disarm_free->id
9e72f0cf 50 );
51 }
52 $self->connection->register_remote($self);
53}
54
55sub current_loop {
56 our $Current_Loop ||= Object::Remote::MiniLoop->new
57}
58
59sub call {
9d804009 60 my ($self, $method, @args) = @_;
dc28afe8 61 my $w = wantarray;
62 future {
63 $self->connection->send(call => $self->id, $w, $method, @args)
64 };
9e72f0cf 65}
66
2065b08b 67sub call_discard {
68 my ($self, $method, @args) = @_;
69 $self->connection->send_discard(call => $self->id, $method, @args);
70}
71
8131a88a 72sub call_discard_free {
73 my ($self, $method, @args) = @_;
74 $self->disarm_free;
75 $self->connection->send_discard(call_free => $self->id, $method, @args);
76}
77
9e72f0cf 78sub DEMOLISH {
79 my ($self, $gd) = @_;
ad4f54b2 80 return if $gd or $self->disarmed_free;
9e72f0cf 81 $self->connection->send_free($self->id);
82}
83
841;