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