1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Combine any combination of PublicInbox::Search,
5 # PublicInbox::ExtSearch, and PublicInbox::LeiSearch objects
7 package PublicInbox::LeiXSearch;
10 use parent qw(PublicInbox::LeiSearch PublicInbox::IPC);
11 use PublicInbox::DS qw(dwaitpid);
12 use PublicInbox::OpPipe;
13 use PublicInbox::Import;
14 use File::Temp 0.19 (); # 0.19 for ->newdir
16 use PublicInbox::Search qw(xap_terms);
17 use PublicInbox::Spawn qw(popen_rd);
18 use PublicInbox::MID qw(mids);
22 PublicInbox::Search::load_xapian();
24 qp_flags => $PublicInbox::Search::QP_FLAGS |
25 PublicInbox::Search::FLAG_PURE_NOT(),
30 my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
31 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
32 my $srch = $ibxish->search or
33 return warn("$desc not indexed for Xapian\n");
34 my @shards = $srch->xdb_shards_flat or
35 return warn("$desc has no Xapian shardsXapian\n");
37 if (delete $self->{xdb}) { # XXX: do we need this?
38 # clobber existing {xdb} if amending
39 my $expect = delete $self->{nshard};
40 my $shards = delete $self->{shards_flat};
41 scalar(@$shards) == $expect or die
42 "BUG: {nshard}$expect != shards=".scalar(@$shards);
45 for my $old_ibxish (@{$self->{shard2ibx}}) {
46 next if $prev == $old_ibxish;
48 my @shards = $old_ibxish->search->xdb_shards_flat;
49 push @{$self->{shards_flat}}, @shards;
51 my $nr = scalar(@{$self->{shards_flat}});
53 "BUG: reloaded $nr shards, expected $expect"
55 push @{$self->{shards_flat}}, @shards;
56 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
59 # returns a list of local inboxes (or count in scalar context)
60 sub locals { @{$_[0]->{locals} // []} }
62 sub remotes { @{$_[0]->{remotes} // []} }
64 # called by PublicInbox::Search::xdb
65 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
69 my ($self, $mitem) = @_;
70 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
71 my $nshard = $self->{nshard};
72 my $docid = $mitem->get_docid;
73 my $shard = ($docid - 1) % $nshard;
74 my $num = int(($docid - 1) / $nshard) + 1;
75 my $ibx = $self->{shard2ibx}->[$shard];
76 my $smsg = $ibx->over->get_art($num);
77 if (ref($ibx->can('msg_keywords'))) {
78 my $kw = xap_terms('K', $mitem->get_document);
79 $smsg->{kw} = [ sort keys %$kw ];
81 $smsg->{docid} = $docid;
86 my ($self, $qstr, $opt) = @_;
88 $opt->{relevance} //= -2;
89 $self->mset($qstr //= 'bytes:1..', $opt);
96 my $size = $mset->size;
97 $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
100 # $startq will EOF when query_prepare is done augmenting and allow
101 # query_mset and query_thread_mset to proceed.
102 sub wait_startq ($) {
105 read($startq, my $query_prepare_done, 1);
108 sub query_thread_mset { # for --thread
109 my ($self, $lei, $ibxish) = @_;
110 local $0 = "$0 query_thread_mset";
111 my $startq = delete $self->{5};
112 my %sig = $lei->atfork_child_wq($self);
113 local @SIG{keys %sig} = values %sig;
115 my ($srch, $over) = ($ibxish->search, $ibxish->over);
116 unless ($srch && $over) {
117 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
118 warn "$desc not indexed by Xapian\n";
121 my $mo = { %{$lei->{mset_opt}} };
123 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
125 $mset = $srch->mset($mo->{qstr}, $mo);
126 my $ids = $srch->mset_to_artnums($mset, $mo);
127 my $ctx = { ids => $ids };
129 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
130 while ($over->expand_thread($ctx)) {
131 for my $n (@{$ctx->{xids}}) {
132 my $smsg = $over->get_art($n) or next;
133 wait_startq($startq) if $startq;
134 my $mitem = delete $n2item{$smsg->{num}};
135 $each_smsg->($smsg, $mitem);
137 @{$ctx->{xids}} = ();
139 } while (_mset_more($mset, $mo));
140 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
141 $lei->{ovv}->ovv_atexit_child($lei);
144 sub query_mset { # non-parallel for non-"--thread" users
145 my ($self, $lei) = @_;
146 local $0 = "$0 query_mset";
147 my $startq = delete $self->{5};
148 my %sig = $lei->atfork_child_wq($self);
149 local @SIG{keys %sig} = values %sig;
150 my $mo = { %{$lei->{mset_opt}} };
152 for my $loc (locals($self)) {
153 attach_external($self, $loc);
155 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
157 $mset = $self->mset($mo->{qstr}, $mo);
158 for my $mitem ($mset->items) {
159 my $smsg = smsg_for($self, $mitem) or next;
160 wait_startq($startq) if $startq;
161 $each_smsg->($smsg, $mitem);
163 } while (_mset_more($mset, $mo));
164 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
165 $lei->{ovv}->ovv_atexit_child($lei);
168 sub each_eml { # callback for MboxReader->mboxrd
169 my ($eml, $self, $lei, $each_smsg) = @_;
170 my $smsg = bless {}, 'PublicInbox::Smsg';
171 $smsg->populate($eml);
172 PublicInbox::OverIdx::parse_references($smsg, $eml, mids($eml));
173 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
174 delete @$smsg{qw(From Subject -ds -ts)};
175 if (my $startq = delete($self->{5})) { wait_startq($startq) }
176 $each_smsg->($smsg, undef, $eml);
179 sub query_remote_mboxrd {
180 my ($self, $lei, $uris) = @_;
181 local $0 = "$0 query_remote_mboxrd";
182 my %sig = $lei->atfork_child_wq($self); # keep $self->{5} startq
183 local @SIG{keys %sig} = values %sig;
184 my ($opt, $env) = @$lei{qw(opt env)};
185 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
186 push(@qform, t => 1) if $opt->{thread};
187 my @cmd = (qw(curl -sSf -d), '');
188 my $verbose = $opt->{verbose};
189 push @cmd, '-v' if $verbose;
190 for my $o ($lei->curl_opt) {
191 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
192 if ($o =~ s/=[is]@\z//) {
193 my $ary = $opt->{$o} or next;
194 push @cmd, map { ("--$o", $_) } @$ary;
195 } elsif ($o =~ s/=[is]\z//) {
196 my $val = $opt->{$o} // next;
197 push @cmd, "--$o", $val;
198 } elsif ($opt->{$o}) {
202 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
203 my $tor = $opt->{torsocks} //= 'auto';
204 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
205 for my $uri (@$uris) {
206 $uri->query_form(@qform);
207 my $cmd = [ @cmd, $uri->as_string ];
208 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
209 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
210 unshift @$cmd, 'torsocks';
211 } elsif (PublicInbox::Config::git_bool($tor)) {
212 unshift @$cmd, 'torsocks';
214 $lei->err("# @$cmd") if $verbose;
216 my $fh = popen_rd($cmd, $env, { 2 => $lei->{2} });
217 $fh = IO::Uncompress::Gunzip->new($fh);
219 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
222 return $lei->fail("E: @$cmd: $@") if $@;
223 if (($? >> 8) == 22) { # HTTP 404 from curl(1)
224 $uri->query_form(q => $lei->{mset_opt}->{qstr});
225 $lei->err('# no results from '.$uri->as_string);
227 $uri->query_form(q => $lei->{mset_opt}->{qstr});
228 $lei->err('E: '.$uri->as_string);
229 $lei->child_error($?);
233 $lei->{ovv}->ovv_atexit_child($lei);
239 my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
240 for my $ibx (@{$self->{shard2ibx} // []}) {
241 my $d = File::Spec->canonpath($ibx->git->{git_dir});
242 $seen{$d} //= push @dirs, "$d/objects\n"
244 my $git_dir = $tmp->dirname;
245 PublicInbox::Import::init_bare($git_dir);
246 my $f = "$git_dir/objects/info/alternates";
247 open my $alt, '>', $f or die "open($f): $!";
248 print $alt @dirs or die "print $f: $!";
249 close $alt or die "close $f: $!";
250 my $git = PublicInbox::Git->new($git_dir);
255 sub query_done { # EOF callback
257 my $has_l2m = exists $lei->{l2m};
258 for my $f (qw(lxs l2m)) {
259 my $wq = delete $lei->{$f} or next;
262 $lei->{ovv}->ovv_end($lei);
263 if ($has_l2m) { # close() calls LeiToMail reap_compress
264 if (my $out = delete $lei->{old_1}) {
265 if (my $mbout = $lei->{1}) {
266 close($mbout) or return $lei->fail(<<"");
267 Error closing $lei->{ovv}->{dst}: $!
277 sub do_post_augment {
278 my ($lei, $zpipe, $au_done) = @_;
279 my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
280 eval { $l2m->post_augment($lei, $zpipe) };
282 if (my $lxs = delete $lei->{lxs}) {
288 close $au_done; # triggers wait_startq
291 my $MAX_PER_HOST = 4;
292 sub MAX_PER_HOST { $MAX_PER_HOST }
295 my ($self, $opt) = @_;
296 my $nl = $opt->{thread} ? locals($self) : 1;
297 my $nr = remotes($self);
298 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
302 sub start_query { # always runs in main (lei-daemon) process
303 my ($self, $io, $lei) = @_;
304 if ($lei->{opt}->{thread}) {
305 for my $ibxish (locals($self)) {
306 $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
308 } elsif (locals($self)) {
309 $self->wq_do('query_mset', $io, $lei);
313 for my $uri (remotes($self)) {
314 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
317 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
322 sub query_prepare { # called by wq_do
323 my ($self, $lei) = @_;
324 local $0 = "$0 query_prepare";
325 my %sig = $lei->atfork_child_wq($self);
326 -p $lei->{0} or die "BUG: \$done pipe expected";
327 local @SIG{keys %sig} = values %sig;
328 eval { $lei->{l2m}->do_augment($lei) };
329 $lei->fail($@) if $@;
330 syswrite($lei->{0}, '.') == 1 or die "do_post_augment trigger: $!";
333 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
335 my $lxs = delete $lei->{lxs};
336 if ($lxs && $lxs->wq_kill_old) {
340 close(delete $lei->{1}) if $lei->{1};
344 my ($self, $lei_orig) = @_;
345 my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
347 pipe(my $done, $io[0]) or die "pipe $!";
348 $lei_orig->{1}->autoflush(1);
350 $lei_orig->event_step_init; # wait for shutdowns
352 '' => [ \&query_done, $lei_orig ],
353 '!' => [ \&sigpipe_handler, $lei_orig ]
355 my $in_loop = exists $lei_orig->{sock};
356 $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
357 my $l2m = $lei->{l2m};
359 # may redirect $lei->{1} for mbox
360 my $zpipe = $l2m->pre_augment($lei_orig);
361 $io[1] = $lei_orig->{1};
362 pipe(my ($startq, $au_done)) or die "pipe: $!";
363 $done_op->{'.'} = [ \&do_post_augment, $lei_orig,
365 local $io[4] = *STDERR{GLOB}; # don't send l2m->{-wq_s1}
366 die "BUG: unexpected \$io[5]: $io[5]" if $io[5];
367 $self->wq_do('query_prepare', \@io, $lei);
368 fcntl($startq, 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
370 $io[1] = $zpipe->[1] if $zpipe;
372 start_query($self, \@io, $lei);
375 # for the $lei->atfork_child_wq PIPE handler:
376 while ($done->{sock}) { $done->event_step }
380 sub ipc_atfork_prepare {
382 if (exists $self->{remotes}) {
383 require PublicInbox::MboxReader;
384 require PublicInbox::OverIdx; # parse_references
385 require IO::Uncompress::Gunzip;
387 # FDS: (0: done_wr, 1: stdout|mbox, 2: stderr,
388 # 3: sock, 4: $l2m->{-wq_s1}, 5: $startq)
389 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
392 sub prepare_external {
393 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
394 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
395 return push(@{$self->{remotes}}, $loc) if $loc->can('scheme');
396 } elsif ($loc =~ m!\Ahttps?://!) {
398 return push(@{$self->{remotes}}, URI->new($loc));
399 } elsif (-f "$loc/ei.lock") {
400 require PublicInbox::ExtSearch;
401 $loc = PublicInbox::ExtSearch->new($loc);
402 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
403 require PublicInbox::Inbox; # v2, v1
404 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
406 warn "W: ignoring $loc, unable to determine type\n";
409 push @{$self->{locals}}, $loc;