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