]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/PktOp.pm
imap+nntp: share COMPRESS implementation
[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 ECONNRESET);
13 use PublicInbox::Syscall qw(EPOLLIN);
14 use Socket qw(AF_UNIX MSG_EOR SOCK_SEQPACKET);
15 use PublicInbox::IPC qw(ipc_freeze ipc_thaw);
16 use Scalar::Util qw(blessed);
17
18 sub new {
19         my ($cls, $r) = @_;
20         my $self = bless { sock => $r }, $cls;
21         $r->blocking(0);
22         $self->SUPER::new($r, EPOLLIN);
23 }
24
25 # returns a blessed objects as the consumer and producer
26 sub pair {
27         my ($cls) = @_;
28         my ($c, $p);
29         socketpair($c, $p, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
30         (new($cls, $c), bless { op_p => $p }, $cls);
31 }
32
33 sub pkt_do { # for the producer to trigger event_step in consumer
34         my ($self, $cmd, @args) = @_;
35         send($self->{op_p}, @args ? "$cmd\0".ipc_freeze(\@args) : $cmd, MSG_EOR)
36 }
37
38 sub event_step {
39         my ($self) = @_;
40         my $c = $self->{sock};
41         my $n = recv($c, my $msg, 4096, 0);
42         unless (defined $n) {
43                 return if $! == EAGAIN;
44                 die "recv: $!" if $! != ECONNRESET; # we may be bidirectional
45         }
46         my ($cmd, @pargs);
47         if (index($msg, "\0") > 0) {
48                 ($cmd, my $pargs) = split(/\0/, $msg, 2);
49                 @pargs = @{ipc_thaw($pargs)};
50         } else {
51                 # for compatibility with the script/lei in client mode,
52                 # it doesn't load Sereal||Storable for startup speed
53                 ($cmd, @pargs) = split(/ /, $msg);
54         }
55         my $op = $self->{ops}->{$cmd //= $msg};
56         if ($op) {
57                 my ($obj, @args) = (@$op, @pargs);
58                 blessed($obj) ? $obj->$cmd(@args) : $obj->(@args);
59         } elsif ($msg ne '') {
60                 die "BUG: unknown message: `$cmd'";
61         }
62         $self->close if $msg eq ''; # close on EOF
63 }
64
65 1;