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