]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiQuery.pm
ds: inline set_cloexec
[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" command and provides internals for
5 # several other sub-commands (up, lcat, ...)
6 package PublicInbox::LeiQuery;
7 use strict;
8 use v5.10.1;
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 _start_query { # used by "lei q" and "lei up"
16         my ($self) = @_;
17         require PublicInbox::LeiOverview;
18         PublicInbox::LeiOverview->new($self) or return;
19         my $opt = $self->{opt};
20         my ($xj, $mj) = split(/,/, $opt->{jobs} // '');
21         if (defined($xj) && $xj ne '' && $xj !~ /\A[1-9][0-9]*\z/) {
22                 return $self->fail("`$xj' search jobs must be >= 1");
23         }
24         my $lxs = $self->{lxs};
25         $xj ||= $lxs->concurrency($opt); # allow: "--jobs ,$WRITER_ONLY"
26         my $nproc = $lxs->detect_nproc || 1; # don't memoize, schedtool(1) exists
27         $xj = $nproc if $xj > $nproc;
28         $lxs->{-wq_nr_workers} = $xj;
29         if (defined($mj) && $mj !~ /\A[1-9][0-9]*\z/) {
30                 return $self->fail("`$mj' writer jobs must be >= 1");
31         }
32         my $l2m = $self->{l2m};
33         # we use \1 (a ref) to distinguish between default vs. user-supplied
34         if ($l2m && grep { $opt->{$_} //= \1 } (qw(mail-sync import-remote
35                                                         import-before))) {
36                 $self->_lei_store(1)->write_prepare($self);
37         }
38         $l2m and $l2m->{-wq_nr_workers} = $mj // do {
39                 $mj = int($nproc * 0.75 + 0.5); # keep some CPU for git
40         };
41
42         # descending docid order is cheapest, MUA controls sorting order
43         $self->{mset_opt}->{relevance} //= -2 if $l2m || $opt->{threads};
44
45         my $tot = $self->{mset_opt}->{total} //= $self->{opt}->{limit} // 10000;
46         $self->{mset_opt}->{limit} = $tot > 10000 ? 10000 : $tot;
47         $self->{mset_opt}->{offset} //= 0;
48         $self->{mset_opt}->{threads} //= $opt->{threads};
49
50         if ($self->{net}) {
51                 require PublicInbox::LeiAuth;
52                 $self->{auth} = PublicInbox::LeiAuth->new
53         }
54         $lxs->do_query($self);
55 }
56
57 sub qstr_add { # PublicInbox::InputPipe::consume callback for --stdin
58         my ($self) = @_; # $_[1] = $rbuf
59         if (defined($_[1])) {
60                 $_[1] eq '' and return eval {
61                         $self->fchdir or return;
62                         $self->{mset_opt}->{q_raw} = $self->{mset_opt}->{qstr};
63                         $self->{lse}->query_approxidate($self->{lse}->git,
64                                                 $self->{mset_opt}->{qstr});
65                         _start_query($self);
66                 };
67                 $self->{mset_opt}->{qstr} .= $_[1];
68         } else {
69                 $self->fail("error reading stdin: $!");
70         }
71 }
72
73 sub lxs_prepare {
74         my ($self) = @_;
75         require PublicInbox::LeiXSearch;
76         # prepare any number of LeiXSearch || LeiSearch || Inbox || URL
77         my $lxs = $self->{lxs} = PublicInbox::LeiXSearch->new;
78         my $opt = $self->{opt};
79         my @only = @{$opt->{only} // []};
80         # --local is enabled by default unless --only is used
81         # we'll allow "--only $LOCATION --local"
82         my $sto = $self->_lei_store(1);
83         $self->{lse} = $sto->search;
84         if ($opt->{'local'} //= scalar(@only) ? 0 : 1) {
85                 $lxs->prepare_external($self->{lse});
86         }
87         if (@only) {
88                 for my $loc (@only) {
89                         my @loc = $self->get_externals($loc) or return;
90                         $lxs->prepare_external($_) for @loc;
91                 }
92         } else {
93                 my (@ilocals, @iremotes);
94                 for my $loc (@{$opt->{include} // []}) {
95                         my @loc = $self->get_externals($loc) or return;
96                         $lxs->prepare_external($_) for @loc;
97                         @ilocals = @{$lxs->{locals} // []};
98                         @iremotes = @{$lxs->{remotes} // []};
99                 }
100                 # --external is enabled by default, but allow --no-external
101                 if ($opt->{external} //= 1) {
102                         my %x;
103                         for my $loc (@{$opt->{exclude} // []}) {
104                                 my @l = $self->get_externals($loc, 1) or return;
105                                 $x{$_} = 1 for @l;
106                         }
107                         my $ne = $self->externals_each(\&prep_ext, $lxs, \%x);
108                         $opt->{remote} //= !($lxs->locals - $opt->{'local'});
109                         if ($opt->{'local'}) {
110                                 $lxs->{remotes} = \@iremotes if !$opt->{remote};
111                         } else {
112                                 $lxs->{locals} = \@ilocals;
113                         }
114                 }
115         }
116         ($lxs->locals || $lxs->remotes) ? ($self->{lxs} = $lxs) :
117                 $self->fail('no local or remote inboxes to search');
118 }
119
120 # the main "lei q SEARCH_TERMS" method
121 sub lei_q {
122         my ($self, @argv) = @_;
123         PublicInbox::Config->json; # preload before forking
124         my $lxs = lxs_prepare($self) or return;
125         $self->ale->refresh_externals($lxs, $self);
126         my $opt = $self->{opt};
127         my %mset_opt;
128         $mset_opt{asc} = $opt->{'reverse'} ? 1 : 0;
129         if (defined(my $sort = $opt->{'sort'})) {
130                 if ($sort eq 'relevance') {
131                         $mset_opt{relevance} = 1;
132                 } elsif ($sort eq 'docid') {
133                         $mset_opt{relevance} = $mset_opt{asc} ? -1 : -2;
134                 } elsif ($sort =~ /\Areceived(?:-?[aA]t)?\z/) {
135                         # the default
136                 } else {
137                         die "unrecognized --sort=$sort\n";
138                 }
139                 $opt->{save} and return
140                         $self->fail('--save and --sort are incompatible');
141         }
142         $self->{mset_opt} = \%mset_opt;
143
144         if ($opt->{stdin}) {
145                 return $self->fail(<<'') if @argv;
146 no query allowed on command-line with --stdin
147
148                 require PublicInbox::InputPipe;
149                 PublicInbox::InputPipe::consume($self->{0}, \&qstr_add, $self);
150                 return;
151         }
152         $mset_opt{q_raw} = [ @argv ]; # copy
153         $mset_opt{qstr} =
154                 $self->{lse}->query_argv_to_string($self->{lse}->git, \@argv);
155         _start_query($self);
156 }
157
158 # shell completion helper called by lei__complete
159 sub _complete_q {
160         my ($self, @argv) = @_;
161         my @cur;
162         my $cb = $self->lazy_cb(qw(forget-external _complete_));
163         while (@argv) {
164                 if ($argv[-1] =~ /\A(?:-I|(?:--(?:include|exclude|only)))\z/) {
165                         my @c = $cb->($self, @cur);
166                         # try basename match:
167                         if (scalar(@cur) == 1 && index($cur[0], '/') < 0) {
168                                 my $all = $self->externals_each;
169                                 my %bn;
170                                 for my $loc (keys %$all) {
171                                         my $bn = (split(m!/!, $loc))[-1];
172                                         ++$bn{$bn};
173                                 }
174                                 push @c, grep {
175                                         $bn{$_} == 1 && /\A\Q$cur[0]/
176                                 } keys %bn;
177                         }
178                         return @c if @c;
179                 }
180                 unshift(@cur, pop @argv);
181         }
182         ();
183 }
184
185 # Stuff we may pass through to curl (as of 7.64.0), see curl manpage for
186 # details, so most options which make sense for HTTP/HTTPS (including proxy
187 # support for Tor and other methods of getting past weird networks).
188 # Most of these are untested by us, some may not make sense for our use case
189 # and typos below are likely.
190 # n.b. some short options (-$NUMBER) are not supported since they conflict
191 # with other "lei q" switches.
192 # FIXME: Getopt::Long doesn't easily let us support support options with
193 # '.' in them (e.g. --http1.1)
194 # TODO: should we depend on "-c http.*" options for things which have
195 # analogues in git(1)? that would reduce likelyhood of conflicts with
196 # our other CLI options
197 # Note: some names are renamed to avoid potential conflicts,
198 # see %lei2curl in lib/PublicInbox/LeiCurl.pm
199 sub curl_opt { qw(
200         curl-config=s@
201         abstract-unix-socket=s anyauth basic cacert=s capath=s
202         cert-status cert-type cert=s ciphers=s
203         connect-timeout=s connect-to=s cookie-jar=s cookie=s crlfile=s
204         digest disable dns-interface=s dns-ipv4-addr=s dns-ipv6-addr=s
205         dns-servers=s doh-url=s egd-file=s engine=s false-start
206         happy-eyeballs-timeout-ms=s haproxy-protocol header=s@
207         http2-prior-knowledge http2 insecure
208         interface=s ipv4 ipv6 junk-session-cookies
209         key-type=s key=s limit-rate=s local-port=s location-trusted location
210         max-redirs=i max-time=s negotiate netrc-file=s netrc-optional netrc
211         no-alpn no-buffer no-npn no-sessionid noproxy=s ntlm-wb ntlm
212         pass=s pinnedpubkey=s post301 post302 post303 preproxy=s
213         proxy-anyauth proxy-basic proxy-cacert=s proxy-capath=s
214         proxy-cert-type=s proxy-cert=s proxy-ciphers=s proxy-crlfile=s
215         proxy-digest proxy-header=s@ proxy-insecure
216         proxy-key-type=s proxy-key proxy-negotiate proxy-ntlm proxy-pass=s
217         proxy-pinnedpubkey=s proxy-service-name=s proxy-ssl-allow-beast
218         proxy-tls13-ciphers=s proxy-tlsauthtype=s proxy-tlspassword=s
219         proxy-tlsuser=s proxy-tlsv1 proxy-user=s proxy=s
220         proxytunnel=s pubkey=s random-file=s referer=s resolve=s
221         retry-connrefused retry-delay=s retry-max-time=s retry=i
222         sasl-ir service-name=s socks4=s socks4a=s socks5-basic
223         socks5-gssapi-service-name=s socks5-gssapi socks5-hostname=s socks5=s
224         speed-limit speed-type ssl-allow-beast sslv2 sslv3
225         suppress-connect-headers tcp-fastopen tls-max=s
226         tls13-ciphers=s tlsauthtype=s tlspassword=s tlsuser=s
227         tlsv1 trace-ascii=s trace-time trace=s
228         unix-socket=s user-agent=s user=s
229 )
230 }
231
232 1;