]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/PktOp.pm
get rid of unnecessary bytes::length usage
[public-inbox.git] / lib / PublicInbox / PktOp.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # op dispatch socket, reads a message, runs a sub
5 # There may be multiple producers, but (for now) only one consumer
6 # Used for lei_xsearch and maybe other things
7 # "command" => [ $sub, @fixed_operands ]
8 package PublicInbox::PktOp;
9 use strict;
10 use v5.10.1;
11 use parent qw(PublicInbox::DS);
12 use Errno qw(EAGAIN EINTR);
13 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
14 use Socket qw(AF_UNIX MSG_EOR SOCK_SEQPACKET);
15 use PublicInbox::IPC qw(ipc_freeze ipc_thaw);
16
17 sub new {
18         my ($cls, $r) = @_;
19         my $self = bless { sock => $r }, $cls;
20         $r->blocking(0);
21         $self->SUPER::new($r, EPOLLIN|EPOLLET);
22 }
23
24 # returns a blessed objects as the consumer and producer
25 sub pair {
26         my ($cls) = @_;
27         my ($c, $p);
28         socketpair($c, $p, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
29         (new($cls, $c), bless { op_p => $p }, $cls);
30 }
31
32 sub pkt_do { # for the producer to trigger event_step in consumer
33         my ($self, $cmd, @args) = @_;
34         send($self->{op_p}, @args ? "$cmd\0".ipc_freeze(\@args) : $cmd, MSG_EOR)
35 }
36
37 sub event_step {
38         my ($self) = @_;
39         my $c = $self->{sock};
40         my $msg;
41         while (1) {
42                 my $n = recv($c, $msg, 4096, 0);
43                 unless (defined $n) {
44                         return if $! == EAGAIN;
45                         next if $! == EINTR;
46                         $self->close;
47                         die "recv: $!";
48                 }
49                 my ($cmd, @pargs);
50                 if (index($msg, "\0") > 0) {
51                         ($cmd, my $pargs) = split(/\0/, $msg, 2);
52                         @pargs = @{ipc_thaw($pargs)};
53                 } else {
54                         # for compatibility with the script/lei in client mode,
55                         # it doesn't load Sereal||Storable for startup speed
56                         ($cmd, @pargs) = split(/ /, $msg);
57                 }
58                 my $op = $self->{ops}->{$cmd //= $msg};
59                 if ($op) {
60                         my ($sub, @args) = @$op;
61                         $sub->(@args, @pargs);
62                 } elsif ($msg ne '') {
63                         die "BUG: unknown message: `$cmd'";
64                 }
65                 return $self->close if $msg eq ''; # close on EOF
66         }
67 }
68
69 1;