1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # handles lei <q|ls-query|rm-query|mv-query> commands
5 package PublicInbox::LeiQuery;
8 use PublicInbox::DS qw(dwaitpid);
10 sub _vivify_external { # _externals_each callback
12 if (-f "$dir/ei.lock") {
13 require PublicInbox::ExtSearch;
14 push @$src, PublicInbox::ExtSearch->new($dir);
15 } elsif (-f "$dir/inbox.lock" || -d "$dir/public-inbox") { # v2, v1
16 require PublicInbox::Inbox;
17 push @$src, bless { inboxdir => $dir }, 'PublicInbox::Inbox';
19 warn "W: ignoring $dir, unable to determine type\n";
23 # the main "lei q SEARCH_TERMS" method
25 my ($self, @argv) = @_;
26 require PublicInbox::LeiXSearch;
27 require PublicInbox::LeiOverview;
28 PublicInbox::Config->json; # preload before forking
29 my $opt = $self->{opt};
30 my @srcs; # any number of LeiXSearch || LeiSearch || Inbox
31 if ($opt->{'local'} //= 1) { # --local is enabled by default
32 my $sto = $self->_lei_store(1);
33 push @srcs, $sto->search;
36 my $lxs = $self->{lxs} = PublicInbox::LeiXSearch->new;
37 # --external is enabled by default, but allow --no-external
38 if ($opt->{external} //= 1) {
39 $self->_externals_each(\&_vivify_external, \@srcs);
41 my $xj = $opt->{jobs} // (scalar(@srcs) > 3 ? 3 : scalar(@srcs));
42 $xj = 1 if !$opt->{thread};
43 my $ovv = PublicInbox::LeiOverview->new($self) or return;
44 $self->atfork_prepare_wq($lxs);
45 $lxs->wq_workers_start('lei_xsearch', $xj, $self->oldset);
46 delete $lxs->{-ipc_atfork_child_close};
47 if (my $l2m = $self->{l2m}) {
48 my $mj = 4; # TODO: configurable
49 $self->atfork_prepare_wq($l2m);
50 $l2m->wq_workers_start('lei2mail', $mj, $self->oldset);
51 delete $l2m->{-ipc_atfork_child_close};
54 # no forking workers after this
56 my %mset_opt = map { $_ => $opt->{$_} } qw(thread limit offset);
57 $mset_opt{asc} = $opt->{'reverse'} ? 1 : 0;
58 $mset_opt{qstr} = join(' ', map {;
59 # Consider spaces in argv to be for phrase search in Xapian.
60 # In other words, the users should need only care about
61 # normal shell quotes and not have to learn Xapian quoting.
62 /\s/ ? (s/\A(\w+:)// ? qq{$1"$_"} : qq{"$_"}) : $_
64 if (defined(my $sort = $opt->{'sort'})) {
65 if ($sort eq 'relevance') {
66 $mset_opt{relevance} = 1;
67 } elsif ($sort eq 'docid') {
68 $mset_opt{relevance} = $mset_opt{asc} ? -1 : -2;
69 } elsif ($sort =~ /\Areceived(?:-?[aA]t)?\z/) {
72 die "unrecognized --sort=$sort\n";
75 # descending docid order
76 $mset_opt{relevance} //= -2 if $opt->{thread};
77 $self->{mset_opt} = \%mset_opt;
78 $ovv->ovv_begin($self);
79 $lxs->do_query($self, \@srcs);