1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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;
11 use parent qw(PublicInbox::DS Exporter);
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 our @EXPORT_OK = qw(pkt_do);
20 my $self = bless { sock => $r }, $cls;
22 $self->SUPER::new($r, EPOLLIN|EPOLLET);
25 # returns a blessed object as the consumer, and a GLOB/IO for the producer
29 socketpair($c, $p, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
33 sub pkt_do { # for the producer to trigger event_step in consumer
34 my ($producer, $cmd, @args) = @_;
35 send($producer, @args ? "$cmd\0".ipc_freeze(\@args) : $cmd, MSG_EOR);
40 my $c = $self->{sock};
43 my $n = recv($c, $msg, 4096, 0);
45 return if $! == EAGAIN;
51 if (index($msg, "\0") > 0) {
52 ($cmd, my $pargs) = split(/\0/, $msg, 2);
53 @pargs = @{ipc_thaw($pargs)};
55 # for compatibility with the script/lei in client mode,
56 # it doesn't load Sereal||Storable for startup speed
57 ($cmd, @pargs) = split(/ /, $msg);
59 my $op = $self->{ops}->{$cmd //= $msg};
60 die "BUG: unknown message: `$cmd'" unless $op;
61 my ($sub, @args) = @$op;
62 $sub->(@args, @pargs);
63 return $self->close if $msg eq ''; # close on EOF
67 # call this when we're ready to wait on events
69 my ($self, $ops) = @_;