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