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