]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/PktOp.pm
d5b95a73d7f57671e862b606d3032adaa9181502
[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);
13 use Errno qw(EAGAIN EINTR);
14 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
15 use Socket qw(AF_UNIX MSG_EOR SOCK_SEQPACKET);
16
17 sub new {
18         my ($cls, $r, $ops, $in_loop) = @_;
19         my $self = bless { sock => $r, ops => $ops, re => [] }, $cls;
20         if (ref($ops) eq 'ARRAY') {
21                 my %ops;
22                 for my $op (@$ops) {
23                         if (ref($op->[0])) {
24                                 push @{$self->{re}}, $op;
25                         } else {
26                                 $ops{$op->[0]} = $op->[1];
27                         }
28                 }
29                 $self->{ops} = \%ops;
30         }
31         if ($in_loop) { # iff using DS->EventLoop
32                 $r->blocking(0);
33                 $self->SUPER::new($r, EPOLLIN|EPOLLET);
34         }
35         $self;
36 }
37
38 # returns a blessed object as the consumer, and a GLOB/IO for the producer
39 sub pair {
40         my ($cls, $ops, $in_loop) = @_;
41         my ($c, $p);
42         socketpair($c, $p, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
43         (new($cls, $c, $ops, $in_loop), $p);
44 }
45
46 sub close {
47         my ($self) = @_;
48         my $c = $self->{sock} or return;
49         $c->blocking ? delete($self->{sock}) : $self->SUPER::close;
50 }
51
52 sub event_step {
53         my ($self) = @_;
54         my $c = $self->{sock};
55         my $msg;
56         do {
57                 my $n = recv($c, $msg, 128, 0);
58                 unless (defined $n) {
59                         return if $! == EAGAIN;
60                         next if $! == EINTR;
61                         $self->close;
62                         die "recv: $!";
63                 }
64                 my $op = $self->{ops}->{$msg};
65                 unless ($op) {
66                         for my $re_op (@{$self->{re}}) {
67                                 $msg =~ $re_op->[0] or next;
68                                 $op = $re_op->[1];
69                                 last;
70                         }
71                 }
72                 die "BUG: unknown message: `$msg'" unless $op;
73                 my ($sub, @args) = @$op;
74                 $sub->(@args);
75                 return $self->close if $msg eq ''; # close on EOF
76         } while (1);
77 }
78
79 1;