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(now);
12 use PublicInbox::PktOp qw(pkt_do);
13 use File::Temp 0.19 (); # 0.19 for ->newdir
15 use PublicInbox::Search qw(xap_terms);
16 use PublicInbox::Spawn qw(popen_rd spawn which);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::Smsg;
20 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
24 PublicInbox::Search::load_xapian();
26 qp_flags => $PublicInbox::Search::QP_FLAGS |
27 PublicInbox::Search::FLAG_PURE_NOT(),
32 my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
33 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
34 my $srch = $ibxish->search or
35 return warn("$desc not indexed for Xapian\n");
36 my @shards = $srch->xdb_shards_flat or
37 return warn("$desc has no Xapian shards\n");
39 if (delete $self->{xdb}) { # XXX: do we need this?
40 # clobber existing {xdb} if amending
41 my $expect = delete $self->{nshard};
42 my $shards = delete $self->{shards_flat};
43 scalar(@$shards) == $expect or die
44 "BUG: {nshard}$expect != shards=".scalar(@$shards);
47 for my $old_ibxish (@{$self->{shard2ibx}}) {
48 next if $prev == $old_ibxish;
50 my @shards = $old_ibxish->search->xdb_shards_flat;
51 push @{$self->{shards_flat}}, @shards;
53 my $nr = scalar(@{$self->{shards_flat}});
55 "BUG: reloaded $nr shards, expected $expect"
57 push @{$self->{shards_flat}}, @shards;
58 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
61 # returns a list of local inboxes (or count in scalar context)
62 sub locals { @{$_[0]->{locals} // []} }
64 sub remotes { @{$_[0]->{remotes} // []} }
66 # called by PublicInbox::Search::xdb (usually via ->mset)
67 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
70 my ($smsg, $mitem, $flagged) = @_;
71 my $kw = xap_terms('K', $mitem->get_document);
72 $kw->{flagged} = 1 if $flagged;
73 $smsg->{kw} = [ sort keys %$kw ];
78 my ($self, $mitem) = @_;
79 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
80 my $nshard = $self->{nshard};
81 my $docid = $mitem->get_docid;
82 my $shard = ($docid - 1) % $nshard;
83 my $num = int(($docid - 1) / $nshard) + 1;
84 my $ibx = $self->{shard2ibx}->[$shard];
85 my $smsg = $ibx->over->get_art($num);
86 mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
87 $smsg->{docid} = $docid;
92 my ($self, $qstr, $opt) = @_;
94 $opt->{relevance} //= -2;
95 $self->mset($qstr //= 'z:1..', $opt);
100 sub overs_all { # for xids_for
102 grep(defined, map { $_->over } locals($self))
105 sub _mset_more ($$) {
106 my ($mset, $mo) = @_;
107 my $size = $mset->size;
108 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
111 # $startq will EOF when do_augment is done augmenting and allow
112 # query_mset and query_thread_mset to proceed.
113 sub wait_startq ($) {
115 my $startq = delete $lei->{startq} or return;
117 my $n = sysread($startq, my $do_augment_done, 1);
119 return if $n == 0; # no MUA
120 if ($do_augment_done eq 'q') {
121 $lei->{opt}->{quiet} = 1;
122 delete $lei->{opt}->{verbose};
123 delete $lei->{-progress};
125 $lei->fail("$$ WTF `$do_augment_done'");
129 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
135 return if $lei->{early_mua} || !$lei->{-progress};
136 if ($lei->{pkt_op_p}) {
137 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
138 } else { # single lei-daemon consumer
139 my ($desc, $mset_size, $mset_total_est) = @_;
140 $lei->{-mset_total} += $mset_size;
141 $lei->qerr("# $desc $mset_size/$mset_total_est");
145 sub query_thread_mset { # for --threads
146 my ($self, $ibxish) = @_;
147 local $0 = "$0 query_thread_mset";
148 my $lei = $self->{lei};
149 my ($srch, $over) = ($ibxish->search, $ibxish->over);
150 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
151 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
152 my $mo = { %{$lei->{mset_opt}} };
154 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
155 my $can_kw = !!$ibxish->can('msg_keywords');
156 my $fl = $lei->{opt}->{threads} > 1 ? [ 'flagged' ] : undef;
158 $mset = $srch->mset($mo->{qstr}, $mo);
159 mset_progress($lei, $desc, $mset->size,
160 $mset->get_matches_estimated);
161 my $ids = $srch->mset_to_artnums($mset, $mo);
162 my $ctx = { ids => $ids };
164 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
165 while ($over->expand_thread($ctx)) {
166 for my $n (@{$ctx->{xids}}) {
167 my $smsg = $over->get_art($n) or next;
169 my $mitem = delete $n2item{$smsg->{num}};
172 mitem_kw($smsg, $mitem, $fl);
177 $each_smsg->($smsg, $mitem);
179 @{$ctx->{xids}} = ();
181 } while (_mset_more($mset, $mo));
182 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
183 $lei->{ovv}->ovv_atexit_child($lei);
186 sub query_mset { # non-parallel for non-"--threads" users
188 local $0 = "$0 query_mset";
189 my $lei = $self->{lei};
190 my $mo = { %{$lei->{mset_opt}} };
192 for my $loc (locals($self)) {
193 attach_external($self, $loc);
195 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
197 $mset = $self->mset($mo->{qstr}, $mo);
198 mset_progress($lei, 'xsearch', $mset->size,
199 $mset->size, $mset->get_matches_estimated);
200 for my $mitem ($mset->items) {
201 my $smsg = smsg_for($self, $mitem) or next;
203 $each_smsg->($smsg, $mitem);
205 } while (_mset_more($mset, $mo));
206 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
207 $lei->{ovv}->ovv_atexit_child($lei);
210 sub each_remote_eml { # callback for MboxReader->mboxrd
211 my ($eml, $self, $lei, $each_smsg) = @_;
212 if (my $sto = $self->{import_sto}) {
213 $sto->ipc_do('add_eml_maybe', $eml);
215 my $smsg = bless {}, 'PublicInbox::Smsg';
216 $smsg->populate($eml);
217 $smsg->parse_references($eml, mids($eml));
218 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
219 delete @$smsg{qw(From Subject -ds -ts)};
221 if ($lei->{-progress}) {
222 ++$lei->{-nr_remote_eml};
224 my $next = $lei->{-next_progress} //= ($now + 1);
226 $lei->{-next_progress} = $now + 1;
227 my $nr = $lei->{-nr_remote_eml};
228 $lei->err("# $lei->{-current_url} $nr/?");
231 $each_smsg->($smsg, undef, $eml);
234 sub query_remote_mboxrd {
235 my ($self, $uris) = @_;
236 local $0 = "$0 query_remote_mboxrd";
237 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
238 my $lei = $self->{lei};
239 my $opt = $lei->{opt};
240 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
241 push(@qform, t => 1) if $opt->{threads};
242 my $verbose = $opt->{verbose};
243 my ($reap_tail, $reap_curl);
244 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
245 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
246 my $rdr = { 2 => $cerr, pgid => 0 };
247 my $sigint_reap = $lei->can('sigint_reap');
249 # spawn a process to force line-buffering, otherwise curl
250 # will write 1 character at-a-time and parallel outputs
251 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
252 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
253 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
254 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
256 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
257 push @$curl, '-s', '-d', '';
258 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
259 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
260 for my $uri (@$uris) {
261 $lei->{-current_url} = $uri->as_string;
262 $lei->{-nr_remote_eml} = 0;
263 $uri->query_form(@qform);
264 my $cmd = $curl->for_uri($lei, $uri);
265 $lei->qerr("# $cmd");
266 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
267 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
268 $fh = IO::Uncompress::Gunzip->new($fh);
269 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
271 my $err = waitpid($pid, 0) == $pid ? undef
272 : "BUG: waitpid($cmd): $!";
273 @$reap_curl = (); # cancel OnDestroy
275 my $nr = $lei->{-nr_remote_eml};
276 if ($nr && $lei->{sto}) {
277 my $wait = $lei->{sto}->ipc_do('done');
280 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
285 seek($cerr, 0, SEEK_SET) or
286 $lei->err("seek($cmd stderr): $!");
287 $err = do { local $/; <$cerr> } //
288 "read($cmd stderr): $!";
289 truncate($cerr, 0) or
290 $lei->err("truncate($cmd stderr): $!");
292 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
293 $uri->query_form(q => $lei->{mset_opt}->{qstr});
294 $lei->child_error($?, "E: <$uri> $err");
297 $lei->{ovv}->ovv_atexit_child($lei);
300 # called by LeiOverview::each_smsg_cb
301 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
306 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
307 for my $ibxish (locals($self)) {
308 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
309 $seen{$d} //= push @dirs, "$d/objects\n"
311 my $git_dir = $tmp->dirname;
312 PublicInbox::Import::init_bare($git_dir);
313 my $f = "$git_dir/objects/info/alternates";
314 open my $alt, '>', $f or die "open($f): $!";
315 print $alt @dirs or die "print $f: $!";
316 close $alt or die "close $f: $!";
317 my $git = PublicInbox::Git->new($git_dir);
322 sub xsearch_done_wait { # dwaitpid callback
323 my ($arg, $pid) = @_;
324 my ($wq, $lei) = @$arg;
325 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
328 sub query_done { # EOF callback for main daemon
330 my $l2m = delete $lei->{l2m};
331 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
332 if (my $lxs = delete $lei->{lxs}) {
333 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
335 $lei->{ovv}->ovv_end($lei);
336 if ($l2m) { # close() calls LeiToMail reap_compress
337 if (my $out = delete $lei->{old_1}) {
338 if (my $mbout = $lei->{1}) {
339 close($mbout) or return $lei->fail(<<"");
340 Error closing $lei->{ovv}->{dst}: $!
345 if ($l2m->lock_free) {
348 } else { # mbox users
349 delete $l2m->{mbl}; # drop dotlock
353 $lei->{-progress} and
354 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
358 sub do_post_augment {
360 my $l2m = $lei->{l2m} or return; # client disconnected
362 eval { $l2m->post_augment($lei) };
365 if (my $lxs = delete $lei->{lxs}) {
367 $lxs->wq_close(0, undef, $lei);
371 if (!$err && delete $lei->{early_mua}) { # non-augment case
374 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
377 sub incr_post_augment { # called whenever an l2m shard finishes augment
379 my $l2m = $lei->{l2m} or return; # client disconnected
380 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
381 do_post_augment($lei);
384 my $MAX_PER_HOST = 4;
387 my ($self, $opt) = @_;
388 my $nl = $opt->{threads} ? locals($self) : 1;
389 my $nr = remotes($self);
390 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
394 sub start_query { # always runs in main (lei-daemon) process
396 if ($self->{threads}) {
397 for my $ibxish (locals($self)) {
398 $self->wq_io_do('query_thread_mset', [], $ibxish);
400 } elsif (locals($self)) {
401 $self->wq_io_do('query_mset', []);
405 for my $uri (remotes($self)) {
406 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
409 $self->wq_io_do('query_remote_mboxrd', [], $uris);
411 $self->wq_close(1); # lei_xsearch workers stop when done
414 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
415 my ($self, $l2m) = @_;
416 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
420 sub ipc_atfork_child {
422 $self->{lei}->lei_atfork_child;
423 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
424 $self->SUPER::ipc_atfork_child;
427 sub delete_pkt_op { # OnDestroy callback
428 my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
429 close $unclosed_after_die;
433 my ($self, $lei) = @_;
434 my $l2m = $lei->{l2m};
436 '|' => [ $lei->can('sigpipe_handler'), $lei ],
437 '!' => [ $lei->can('fail_handler'), $lei ],
438 '.' => [ \&do_post_augment, $lei ],
439 '+' => [ \&incr_post_augment, $lei ],
440 '' => [ \&query_done, $lei ],
441 'mset_progress' => [ \&mset_progress, $lei ],
442 'x_it' => [ $lei->can('x_it'), $lei ],
443 'child_error' => [ $lei->can('child_error'), $lei ],
444 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
446 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
447 my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
448 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
449 $lei->{1}->autoflush(1);
450 $lei->start_pager if delete $lei->{need_pager};
451 $lei->{ovv}->ovv_begin($lei);
453 $l2m->pre_augment($lei);
454 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
457 $l2m->wq_workers_start('lei2mail', undef,
458 $lei->oldset, { lei => $lei });
459 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
461 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
463 if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
464 # lei->{git_tmp} is set for wq_wait_old so we don't
465 # delete until all lei2mail + lei_xsearch workers are reaped
466 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
468 $self->wq_workers_start('lei_xsearch', undef,
469 $lei->oldset, { lei => $lei });
470 my $op = delete $lei->{pkt_op_c};
471 delete $lei->{pkt_op_p};
472 $self->{threads} = $lei->{opt}->{threads};
474 $l2m->net_merge_complete unless $lei->{auth};
478 $lei->event_step_init; # wait for shutdowns
479 if ($lei->{oneshot}) {
480 while ($op->{sock}) { $op->event_step }
485 my ($self, $uri) = @_;
486 if (my $curl = $self->{curl} //= which('curl') // 0) {
487 require PublicInbox::MboxReader;
488 require IO::Uncompress::Gunzip;
489 require PublicInbox::LeiCurl;
490 push @{$self->{remotes}}, $uri;
492 warn "curl missing, ignoring $uri\n";
496 sub prepare_external {
497 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
498 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
499 return add_uri($self, $loc) if $loc->can('scheme');
500 } elsif ($loc =~ m!\Ahttps?://!) {
502 return add_uri($self, URI->new($loc));
503 } elsif (-f "$loc/ei.lock") {
504 require PublicInbox::ExtSearch;
505 $loc = PublicInbox::ExtSearch->new($loc);
506 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
507 require PublicInbox::Inbox; # v2, v1
508 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
510 warn "W: ignoring $loc, unable to determine type\n";
513 push @{$self->{locals}}, $loc;