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