]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/PktOp.pm
lei q: emit progress and counting via PktOp
[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 # "literal" => [ sub, @operands ]
8 # /regexp/ => [ sub, @operands ]
9 package PublicInbox::PktOp;
10 use strict;
11 use v5.10.1;
12 use parent qw(PublicInbox::DS Exporter);
13 use Errno qw(EAGAIN EINTR);
14 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
15 use Socket qw(AF_UNIX MSG_EOR SOCK_SEQPACKET);
16 use PublicInbox::IPC qw(ipc_freeze ipc_thaw);
17 our @EXPORT_OK = qw(pkt_do);
18
19 sub new {
20         my ($cls, $r, $ops, $in_loop) = @_;
21         my $self = bless { sock => $r, ops => $ops, re => [] }, $cls;
22         if ($in_loop) { # iff using DS->EventLoop
23                 $r->blocking(0);
24                 $self->SUPER::new($r, EPOLLIN|EPOLLET);
25         }
26         $self;
27 }
28
29 # returns a blessed object as the consumer, and a GLOB/IO for the producer
30 sub pair {
31         my ($cls, $ops, $in_loop) = @_;
32         my ($c, $p);
33         socketpair($c, $p, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
34         (new($cls, $c, $ops, $in_loop), $p);
35 }
36
37 sub pkt_do { # for the producer to trigger event_step in consumer
38         my ($producer, $cmd, @args) = @_;
39         send($producer, @args ? "$cmd\0".ipc_freeze(\@args) : $cmd, MSG_EOR);
40 }
41
42 sub close {
43         my ($self) = @_;
44         my $c = $self->{sock} or return;
45         $c->blocking ? delete($self->{sock}) : $self->SUPER::close;
46 }
47
48 sub event_step {
49         my ($self) = @_;
50         my $c = $self->{sock};
51         my $msg;
52         do {
53                 my $n = recv($c, $msg, 4096, 0);
54                 unless (defined $n) {
55                         return if $! == EAGAIN;
56                         next if $! == EINTR;
57                         $self->close;
58                         die "recv: $!";
59                 }
60                 my ($cmd, $pargs) = split(/\0/, $msg, 2);
61                 my $op = $self->{ops}->{$cmd // $msg};
62                 die "BUG: unknown message: `$cmd'" unless $op;
63                 my ($sub, @args) = @$op;
64                 $sub->(@args, $pargs ? ipc_thaw($pargs) : ());
65                 return $self->close if $msg eq ''; # close on EOF
66         } while (1);
67 }
68
69 1;