680197e91915566eb5df26b41d0b26d4c30889de
[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   $method = "start::${method}" if (caller(0)||'') eq 'start';
63   future {
64     $self->connection->send(call => $self->id, $w, $method, @args)
65   };
66 }
67
68 sub call_discard {
69   my ($self, $method, @args) = @_;
70   $self->connection->send_discard(call => $self->id, $method, @args);
71 }
72
73 sub call_discard_free {
74   my ($self, $method, @args) = @_;
75   $self->disarm_free;
76   $self->connection->send_discard(call_free => $self->id, $method, @args);
77 }
78
79 sub DEMOLISH {
80   my ($self, $gd) = @_;
81   return if $gd or $self->disarmed_free;
82   $self->connection->send_free($self->id);
83 }
84
85 1;