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