File: Server.pm

package info (click to toggle)
libmr-tarantool-perl 0.0.24-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 416 kB
  • sloc: perl: 3,662; makefile: 2
file content (122 lines) | stat: -rw-r--r-- 2,242 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package MR::IProto::Server;

=head1 NAME

MR::IProto::Server - server

=head1 DESCRIPTION

=cut

use Mouse;
use AnyEvent::Handle;
use AnyEvent::Socket;
use Scalar::Util qw/weaken/;
use MR::IProto::Server::Connection;

with 'MR::IProto::Role::Debuggable';

has prefix => (
    is  => 'ro',
    isa => 'Str',
    default => sub { ref shift },
);

has host => (
    is  => 'ro',
    isa => 'Str',
    default => '0.0.0.0',
);

has port => (
    is  => 'ro',
    isa => 'Int',
    required => 1,
);

has handler => (
    is  => 'ro',
    isa => 'CodeRef',
    required => 1,
);

has on_accept => (
    is  => 'ro',
    isa => 'CodeRef',
);

has on_close => (
    is  => 'ro',
    isa => 'CodeRef',
);

has on_error => (
    is  => 'ro',
    isa => 'CodeRef',
);

has _guard => (
    is  => 'ro',
    lazy_build => 1,
);

has _connections => (
    is  => 'ro',
    isa => 'HashRef',
    default => sub { {} },
);

has _recv_payload => (
    is  => 'ro',
    isa => 'CodeRef',
    lazy_build => 1,
);

sub run {
    my ($self) = @_;
    $self->_guard;
    return;
}

sub _build_debug_cb {
    my ($self) = @_;
    my $prefix = $self->prefix;
    return sub {
        my ($msg) = @_;
        chomp $msg;
        warn sprintf "%s: %s\n", $prefix, $msg;
        return;
    };
}

sub _build__guard {
    my ($self) = @_;
    weaken($self);
    return tcp_server $self->host, $self->port, sub {
        my ($fh, $host, $port) = @_;
        my $connection = MR::IProto::Server::Connection->new(
            fh        => $fh,
            host      => $host,
            port      => $port,
            handler   => $self->handler,
            on_accept => $self->on_accept,
            on_close  => sub {
                my ($connection) = @_;
                my $key = sprintf "%s:%d", $connection->host, $connection->port;
                delete $self->_connections->{$key};
                $self->on_close->($connection) if $self->on_close;
                return;
            },
            on_error  => $self->on_error,
            debug     => $self->debug,
            debug_cb  => $self->debug_cb,
        );
        $self->_connections->{"$host:$port"} = $connection;
        return;
    };
}

no Mouse;
__PACKAGE__->meta->make_immutable();

1;