]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiQuery.pm
lei q: support reading queries from stdin
[public-inbox.git] / lib / PublicInbox / LeiQuery.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 # handles lei <q|ls-query|rm-query|mv-query> commands
5 package PublicInbox::LeiQuery;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::DS qw(dwaitpid);
9
10 sub prep_ext { # externals_each callback
11         my ($lxs, $exclude, $loc) = @_;
12         $lxs->prepare_external($loc) unless $exclude->{$loc};
13 }
14
15 sub qstr_add { # for --stdin
16         my ($self) = @_; # $_[1] = $rbuf
17         if (defined($_[1])) {
18                 return eval { $self->{lxs}->do_query($self) } if $_[1] eq '';
19                 $self->{mset_opt}->{qstr} .= $_[1];
20         } else {
21                 $self->fail("error reading stdin: $!");
22         }
23 }
24
25 # the main "lei q SEARCH_TERMS" method
26 sub lei_q {
27         my ($self, @argv) = @_;
28         require PublicInbox::LeiXSearch;
29         require PublicInbox::LeiOverview;
30         require PublicInbox::V2Writable;
31         PublicInbox::Config->json; # preload before forking
32         my $opt = $self->{opt};
33         # prepare any number of LeiXSearch || LeiSearch || Inbox || URL
34         my $lxs = $self->{lxs} = PublicInbox::LeiXSearch->new;
35         my @only = @{$opt->{only} // []};
36         # --local is enabled by default unless --only is used
37         # we'll allow "--only $LOCATION --local"
38         if ($opt->{'local'} //= scalar(@only) ? 0 : 1) {
39                 my $sto = $self->_lei_store(1);
40                 $lxs->prepare_external($sto->search);
41         }
42         if (@only) {
43                 for my $loc (@only) {
44                         my @loc = $self->get_externals($loc) or return;
45                         $lxs->prepare_external($_) for @loc;
46                 }
47         } else {
48                 for my $loc (@{$opt->{include} // []}) {
49                         my @loc = $self->get_externals($loc) or return;
50                         $lxs->prepare_external($_) for @loc;
51                 }
52                 # --external is enabled by default, but allow --no-external
53                 if ($opt->{external} //= 1) {
54                         my %x;
55                         for my $loc (@{$opt->{exclude} // []}) {
56                                 my @l = $self->get_externals($loc, 1) or return;
57                                 $x{$_} = 1 for @l;
58                         }
59                         my $ne = $self->externals_each(\&prep_ext, $lxs, \%x);
60                         $opt->{remote} //= !($lxs->locals - $opt->{'local'});
61                         if ($opt->{'local'}) {
62                                 delete($lxs->{remotes}) if !$opt->{remote};
63                         } else {
64                                 delete($lxs->{locals});
65                         }
66                 }
67         }
68         unless ($lxs->locals || $lxs->remotes) {
69                 return $self->fail('no local or remote inboxes to search');
70         }
71         my ($xj, $mj) = split(/,/, $opt->{jobs} // '');
72         if (defined($xj) && $xj ne '' && $xj !~ /\A[1-9][0-9]*\z/) {
73                 return $self->fail("`$xj' search jobs must be >= 1");
74         }
75         $xj ||= $lxs->concurrency($opt); # allow: "--jobs ,$WRITER_ONLY"
76         my $nproc = $lxs->detect_nproc; # don't memoize, schedtool(1) exists
77         $xj = $nproc if $xj > $nproc;
78         PublicInbox::LeiOverview->new($self) or return;
79         $self->atfork_prepare_wq($lxs);
80         $lxs->wq_workers_start('lei_xsearch', $xj, $self->oldset);
81         delete $lxs->{-ipc_atfork_child_close};
82         if (my $l2m = $self->{l2m}) {
83                 if (defined($mj) && $mj !~ /\A[1-9][0-9]*\z/) {
84                         return $self->fail("`$mj' writer jobs must be >= 1");
85                 }
86                 $mj //= $nproc;
87                 $self->atfork_prepare_wq($l2m);
88                 $l2m->wq_workers_start('lei2mail', $mj, $self->oldset);
89                 delete $l2m->{-ipc_atfork_child_close};
90         }
91
92         # no forking workers after this
93
94         my %mset_opt = map { $_ => $opt->{$_} } qw(thread limit offset);
95         $mset_opt{asc} = $opt->{'reverse'} ? 1 : 0;
96         $mset_opt{limit} //= 10000;
97         if (defined(my $sort = $opt->{'sort'})) {
98                 if ($sort eq 'relevance') {
99                         $mset_opt{relevance} = 1;
100                 } elsif ($sort eq 'docid') {
101                         $mset_opt{relevance} = $mset_opt{asc} ? -1 : -2;
102                 } elsif ($sort =~ /\Areceived(?:-?[aA]t)?\z/) {
103                         # the default
104                 } else {
105                         die "unrecognized --sort=$sort\n";
106                 }
107         }
108         # descending docid order
109         $mset_opt{relevance} //= -2 if $opt->{thread};
110         $self->{mset_opt} = \%mset_opt;
111
112         if ($opt->{stdin}) {
113                 return $self->fail(<<'') if @argv;
114 no query allowed on command-line with --stdin
115
116                 require PublicInbox::InputPipe;
117                 PublicInbox::InputPipe::consume($self->{0}, \&qstr_add, $self);
118                 return;
119         }
120         # Consider spaces in argv to be for phrase search in Xapian.
121         # In other words, the users should need only care about
122         # normal shell quotes and not have to learn Xapian quoting.
123         $mset_opt{qstr} = join(' ', map {;
124                 /\s/ ? (s/\A(\w+:)// ? qq{$1"$_"} : qq{"$_"}) : $_
125         } @argv);
126         $lxs->do_query($self);
127 }
128
129 # shell completion helper called by lei__complete
130 sub _complete_q {
131         my ($self, @argv) = @_;
132         my $ext = qr/\A(?:-I|(?:--(?:include|exclude|only)))\z/;
133         my @cur;
134         while (@argv) {
135                 if ($argv[-1] =~ $ext) {
136                         my @c = $self->_complete_forget_external(@cur);
137                         # try basename match:
138                         if (scalar(@cur) == 1 && index($cur[0], '/') < 0) {
139                                 my $all = $self->externals_each;
140                                 my %bn;
141                                 for my $loc (keys %$all) {
142                                         my $bn = (split(m!/!, $loc))[-1];
143                                         ++$bn{$bn};
144                                 }
145                                 push @c, grep {
146                                         $bn{$_} == 1 && /\A\Q$cur[0]/
147                                 } keys %bn;
148                         }
149                         return @c if @c;
150                 }
151                 unshift(@cur, pop @argv);
152         }
153         ();
154 }
155
156 # Stuff we may pass through to curl (as of 7.64.0), see curl manpage for
157 # details, so most options which make sense for HTTP/HTTPS (including proxy
158 # support for Tor and other methods of getting past weird networks).
159 # Most of these are untested by us, some may not make sense for our use case
160 # and typos below are likely.
161 # n.b. some short options (-$NUMBER) are not supported since they conflict
162 # with other "lei q" switches.
163 # FIXME: Getopt::Long doesn't easily let us support support options with
164 # '.' in them (e.g. --http1.1)
165 sub curl_opt { qw(
166         abstract-unix-socket=s anyauth basic cacert=s capath=s
167         cert-status cert-type cert|E=s ciphers=s config|K=s@
168         connect-timeout=s connect-to=s cookie-jar|c=s cookie|b=s crlfile=s
169         digest disable dns-interface=s dns-ipv4-addr=s dns-ipv6-addr=s
170         dns-servers=s doh-url=s egd-file=s engine=s false-start
171         happy-eyeballs-timeout-ms=s haproxy-protocol header|H=s@
172         http2-prior-knowledge http2 insecure|k
173         interface=s ipv4 ipv6 junk-session-cookies
174         key-type=s key=s limit-rate=s local-port=s location-trusted location|L
175         max-redirs=i max-time=s negotiate netrc-file=s netrc-optional netrc
176         no-alpn no-buffer|N no-npn no-sessionid noproxy=s ntlm-wb ntlm
177         pass=s pinnedpubkey=s post301 post302 post303 preproxy=s
178         proxy-anyauth proxy-basic proxy-cacert=s proxy-capath=s
179         proxy-cert-type=s proxy-cert=s proxy-ciphers=s proxy-crlfile=s
180         proxy-digest proxy-header=s@ proxy-insecure
181         proxy-key-type=s proxy-key proxy-negotiate proxy-ntlm proxy-pass=s
182         proxy-pinnedpubkey=s proxy-service-name=s proxy-ssl-allow-beast
183         proxy-tls13-ciphers=s proxy-tlsauthtype=s proxy-tlspassword=s
184         proxy-tlsuser=s proxy-tlsv1 proxy-user|U=s proxy=s
185         proxytunnel=s pubkey=s random-file=s referer=s resolve=s
186         retry-connrefused retry-delay=s retry-max-time=s retry=i
187         sasl-ir service-name=s socks4=s socks4a=s socks5-basic
188         socks5-gssapi-service-name=s socks5-gssapi socks5-hostname=s socks5=s
189         speed-limit|Y speed-type|y ssl-allow-beast sslv2 sslv3
190         suppress-connect-headers tcp-fastopen tls-max=s
191         tls13-ciphers=s tlsauthtype=s tlspassword=s tlsuser=s
192         tlsv1 trace-ascii=s trace-time trace=s
193         unix-socket=s user-agent|A=s user|u=s
194 )
195 }
196
197 1;