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);
21 use PublicInbox::ContentHash qw(git_sha);
25 PublicInbox::Search::load_xapian();
27 qp_flags => $PublicInbox::Search::QP_FLAGS |
28 PublicInbox::Search::FLAG_PURE_NOT(),
33 my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
34 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
35 my $srch = $ibxish->search or
36 return warn("$desc not indexed for Xapian\n");
37 my @shards = $srch->xdb_shards_flat or
38 return warn("$desc has no Xapian shards\n");
40 if (delete $self->{xdb}) { # XXX: do we need this?
41 # clobber existing {xdb} if amending
42 my $expect = delete $self->{nshard};
43 my $shards = delete $self->{shards_flat};
44 scalar(@$shards) == $expect or die
45 "BUG: {nshard}$expect != shards=".scalar(@$shards);
48 for my $old_ibxish (@{$self->{shard2ibx}}) {
49 next if $prev == $old_ibxish;
51 my @shards = $old_ibxish->search->xdb_shards_flat;
52 push @{$self->{shards_flat}}, @shards;
54 my $nr = scalar(@{$self->{shards_flat}});
56 "BUG: reloaded $nr shards, expected $expect"
58 push @{$self->{shards_flat}}, @shards;
59 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
62 # returns a list of local inboxes (or count in scalar context)
63 sub locals { @{$_[0]->{locals} // []} }
65 sub remotes { @{$_[0]->{remotes} // []} }
67 # called by PublicInbox::Search::xdb (usually via ->mset)
68 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
70 sub _mitem_kw { # retry_reopen callback
71 my ($srch, $smsg, $mitem, $flagged) = @_;
72 my $doc = $mitem->get_document;
73 my $kw = xap_terms('K', $doc);
74 $kw->{flagged} = 1 if $flagged;
75 my $L = xap_terms('L', $doc);
76 # we keep the empty {kw} array here to prevent expensive work in
77 # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
78 $smsg->{kw} = [ sort keys %$kw ];
79 $smsg->{L} = [ sort keys %$L ] if scalar(keys %$L);
82 sub mitem_kw ($$$;$) {
83 my ($srch, $smsg, $mitem, $flagged) = @_;
84 $srch->retry_reopen(\&_mitem_kw, $smsg, $mitem, $flagged);
89 my ($self, $mitem) = @_;
90 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
91 my $nshard = $self->{nshard};
92 my $docid = $mitem->get_docid;
93 my $shard = ($docid - 1) % $nshard;
94 my $num = int(($docid - 1) / $nshard) + 1;
95 my $ibx = $self->{shard2ibx}->[$shard];
96 my $smsg = $ibx->over->get_art($num);
97 return if $smsg->{bytes} == 0; # external message
98 if ($ibx->can('msg_keywords')) {
99 mitem_kw($self, $smsg, $mitem);
105 my ($self, $qstr, $opt) = @_;
107 $opt->{relevance} //= -2;
108 $self->mset($qstr //= 'z:1..', $opt);
113 sub _mset_more ($$) {
114 my ($mset, $mo) = @_;
115 my $size = $mset->size;
116 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
119 # $startq will EOF when do_augment is done augmenting and allow
120 # query_combined_mset and query_thread_mset to proceed.
121 sub wait_startq ($) {
123 my $startq = delete $lei->{startq} or return;
125 my $n = sysread($startq, my $do_augment_done, 1);
127 return if $n == 0; # no MUA
128 if ($do_augment_done eq 'q') {
129 $lei->{opt}->{quiet} = 1;
130 delete $lei->{opt}->{verbose};
131 delete $lei->{-progress};
133 $lei->fail("$$ WTF `$do_augment_done'");
137 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
143 return if $lei->{early_mua} || !$lei->{-progress};
144 if ($lei->{pkt_op_p}) {
145 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
146 } else { # single lei-daemon consumer
147 my ($desc, $mset_size, $mset_total_est) = @_;
148 $lei->{-mset_total} += $mset_size if $mset_total_est ne '?';
149 $lei->qerr("# $desc $mset_size/$mset_total_est");
155 $lei->{-nr_write} += $nr;
158 sub query_one_mset { # for --threads and l2m w/o sort
159 my ($self, $ibxish) = @_;
160 local $0 = "$0 query_one_mset";
161 my $lei = $self->{lei};
162 my ($srch, $over) = ($ibxish->search, $ibxish->over);
163 my $dir = $ibxish->{inboxdir} // $ibxish->{topdir};
164 return warn("$dir not indexed by Xapian\n") unless ($srch && $over);
165 my $mo = { %{$lei->{mset_opt}} }; # copy
167 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
168 my $can_kw = !!$ibxish->can('msg_keywords');
169 my $threads = $lei->{opt}->{threads} // 0;
170 my $fl = $threads > 1 ? 1 : undef;
171 my $lss = $lei->{dedupe};
172 $lss = undef unless $lss && $lss->can('cfg_set'); # saved search
173 my $maxk = "external.$dir.maxuid";
174 my $stop_at = $lss ? $lss->{-cfg}->{$maxk} : undef;
175 if (defined $stop_at) {
176 die "$maxk=$stop_at has multiple values" if ref $stop_at;
178 local $SIG{__WARN__} = sub { push @e, @_ };
180 return warn("$maxk=$stop_at: @e") if @e;
184 $mset = $srch->mset($mo->{qstr}, $mo);
185 mset_progress($lei, $dir, $mset->size,
186 $mset->get_matches_estimated);
187 wait_startq($lei); # wait for keyword updates
188 my $ids = $srch->mset_to_artnums($mset, $mo);
189 @$ids = grep { $_ > $stop_at } @$ids if defined($stop_at);
192 # copy $ids if $lss since over->expand_thread
193 # shifts @{$ctx->{ids}}
194 $first_ids = [ @$ids ] if $lss;
195 my $ctx = { ids => $ids };
196 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
197 while ($over->expand_thread($ctx)) {
198 for my $n (@{$ctx->{xids}}) {
199 my $smsg = $over->get_art($n) or next;
200 my $mitem = delete $n2item{$n};
201 next if $smsg->{bytes} == 0;
202 if ($mitem && $can_kw) {
203 mitem_kw($srch, $smsg, $mitem,
205 } elsif ($mitem && $fl) {
206 # call ->xsmsg_vmd, later
207 $smsg->{lei_q_tt_flagged} = 1;
209 $each_smsg->($smsg, $mitem);
211 @{$ctx->{xids}} = ();
215 my @items = $mset->items;
217 my $mitem = $items[$i++];
218 my $smsg = $over->get_art($n) or next;
219 next if $smsg->{bytes} == 0;
220 mitem_kw($srch, $smsg, $mitem, $fl) if $can_kw;
221 $each_smsg->($smsg, $mitem);
224 } while (_mset_more($mset, $mo));
225 if ($lss && scalar(@$first_ids)) {
227 my $max = $first_ids->[0];
228 $lss->cfg_set($maxk, $max);
231 undef $each_smsg; # may commit
232 $lei->{ovv}->ovv_atexit_child($lei);
235 sub query_combined_mset { # non-parallel for non-"--threads" users
237 local $0 = "$0 query_combined_mset";
238 my $lei = $self->{lei};
239 my $mo = { %{$lei->{mset_opt}} };
241 for my $loc (locals($self)) {
242 attach_external($self, $loc);
244 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
246 $mset = $self->mset($mo->{qstr}, $mo);
247 mset_progress($lei, 'xsearch', $mset->size,
248 $mset->get_matches_estimated);
249 wait_startq($lei); # wait for keyword updates
250 for my $mitem ($mset->items) {
251 my $smsg = smsg_for($self, $mitem) or next;
252 $each_smsg->($smsg, $mitem);
254 } while (_mset_more($mset, $mo));
255 undef $each_smsg; # may commit
256 $lei->{ovv}->ovv_atexit_child($lei);
259 sub _smsg_fill ($$) {
260 my ($smsg, $eml) = @_;
261 $smsg->populate($eml);
262 $smsg->parse_references($eml, mids($eml));
263 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
264 delete @$smsg{qw(From Subject -ds -ts)};
267 sub each_remote_eml { # callback for MboxReader->mboxrd
268 my ($eml, $self, $lei, $each_smsg) = @_;
269 my $xoids = $lei->{ale}->xoids_for($eml, 1);
270 if ($self->{import_sto} && !$xoids) {
271 $self->{import_sto}->ipc_do('add_eml', $eml);
273 my $smsg = bless {}, 'PublicInbox::Smsg';
274 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
275 : git_sha(1, $eml)->hexdigest;
276 _smsg_fill($smsg, $eml);
278 if ($lei->{-progress}) {
279 ++$lei->{-nr_remote_eml};
281 my $next = $lei->{-next_progress} //= ($now + 1);
283 $lei->{-next_progress} = $now + 1;
284 my $nr = $lei->{-nr_remote_eml};
285 mset_progress($lei, $lei->{-current_url}, $nr, '?');
288 $each_smsg->($smsg, undef, $eml);
291 sub query_remote_mboxrd {
292 my ($self, $uris) = @_;
293 local $0 = "$0 query_remote_mboxrd";
294 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
295 my $lei = $self->{lei};
296 my $opt = $lei->{opt};
297 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
298 push(@qform, t => 1) if $opt->{threads};
299 my $verbose = $opt->{verbose};
300 my ($reap_tail, $reap_curl);
301 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
302 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
303 my $rdr = { 2 => $cerr, pgid => 0 };
304 my $sigint_reap = $lei->can('sigint_reap');
306 # spawn a process to force line-buffering, otherwise curl
307 # will write 1 character at-a-time and parallel outputs
308 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
309 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
310 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
311 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
313 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
314 push @$curl, '-s', '-d', '';
315 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
316 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
317 for my $uri (@$uris) {
318 $lei->{-current_url} = $uri->as_string;
319 $lei->{-nr_remote_eml} = 0;
320 $uri->query_form(@qform);
321 my $cmd = $curl->for_uri($lei, $uri);
322 $lei->qerr("# $cmd");
323 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
324 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
325 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
326 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
328 my $err = waitpid($pid, 0) == $pid ? undef
329 : "BUG: waitpid($cmd): $!";
330 @$reap_curl = (); # cancel OnDestroy
332 my $nr = $lei->{-nr_remote_eml};
333 if ($nr && $lei->{sto}) {
334 my $wait = $lei->{sto}->ipc_do('done');
337 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
342 seek($cerr, 0, SEEK_SET) or
343 $lei->err("seek($cmd stderr): $!");
344 $err = do { local $/; <$cerr> } //
345 "read($cmd stderr): $!";
346 truncate($cerr, 0) or
347 $lei->err("truncate($cmd stderr): $!");
349 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
350 $uri->query_form(q => $lei->{mset_opt}->{qstr});
351 $lei->child_error($?, "E: <$uri> $err");
354 $lei->{ovv}->ovv_atexit_child($lei);
357 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
359 sub xsearch_done_wait { # dwaitpid callback
360 my ($arg, $pid) = @_;
361 my ($wq, $lei) = @$arg;
362 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
365 sub query_done { # EOF callback for main daemon
367 my $l2m = delete $lei->{l2m};
368 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
369 if (my $lxs = delete $lei->{lxs}) {
370 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
372 if ($lei->{opt}->{'mail-sync'} && !$lei->{sto}) {
373 warn "BUG: {sto} missing with --mail-sync";
375 my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
376 $wait = $lei->{v2w} ? $lei->{v2w}->ipc_do('done') : undef;
377 $lei->{ovv}->ovv_end($lei);
379 if ($l2m) { # close() calls LeiToMail reap_compress
380 if (my $out = delete $lei->{old_1}) {
381 if (my $mbout = $lei->{1}) {
382 close($mbout) or return $lei->fail(<<"");
383 Error closing $lei->{ovv}->{dst}: $!
388 if ($l2m->lock_free) {
391 } else { # mbox users
392 delete $l2m->{mbl}; # drop dotlock
396 if ($lei->{-progress}) {
397 my $tot = $lei->{-mset_total} // 0;
398 my $nr = $lei->{-nr_write} // 0;
400 "# $nr written to $lei->{ovv}->{dst} ($tot matches)" :
403 $lei->start_mua if $start_mua;
407 sub do_post_augment {
409 my $l2m = $lei->{l2m} or return; # client disconnected
410 $lei->fchdir or return;
412 eval { $l2m->post_augment($lei) };
415 if (my $lxs = delete $lei->{lxs}) {
417 $lxs->wq_close(0, undef, $lei);
421 if (!$err && delete $lei->{early_mua}) { # non-augment case
424 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
427 sub incr_post_augment { # called whenever an l2m shard finishes augment
429 my $l2m = $lei->{l2m} or return; # client disconnected
430 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
431 do_post_augment($lei);
434 my $MAX_PER_HOST = 4;
437 my ($self, $opt) = @_;
438 my $nl = $opt->{threads} ? locals($self) : 1;
439 my $nr = remotes($self);
440 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
444 sub start_query ($;$) { # always runs in main (lei-daemon) process
445 my ($self, $l2m) = @_;
446 if ($self->{opt_threads} || ($l2m && !$self->{opt_sort})) {
447 for my $ibxish (locals($self)) {
448 $self->wq_io_do('query_one_mset', [], $ibxish);
450 } elsif (locals($self)) {
451 $self->wq_io_do('query_combined_mset', []);
455 for my $uri (remotes($self)) {
456 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
459 $self->wq_io_do('query_remote_mboxrd', [], $uris);
461 if ($self->{-do_lcat}) {
462 $self->wq_io_do('lcat_dump', []);
464 $self->wq_close(1); # lei_xsearch workers stop when done
467 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
468 my ($self, $l2m) = @_;
469 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
470 start_query($self, $l2m);
473 sub ipc_atfork_child {
475 $self->{lei}->_lei_atfork_child;
476 $self->SUPER::ipc_atfork_child;
480 my ($self, $lei) = @_;
481 my $l2m = $lei->{l2m};
483 '|' => [ $lei->can('sigpipe_handler'), $lei ],
484 '!' => [ $lei->can('fail_handler'), $lei ],
485 '.' => [ \&do_post_augment, $lei ],
486 '+' => [ \&incr_post_augment, $lei ],
487 '' => [ \&query_done, $lei ],
488 'mset_progress' => [ \&mset_progress, $lei ],
489 'l2m_progress' => [ \&l2m_progress, $lei ],
490 'x_it' => [ $lei->can('x_it'), $lei ],
491 'child_error' => [ $lei->can('child_error'), $lei ],
492 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
494 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
495 my $end = $lei->pkt_op_pair;
496 $lei->{1}->autoflush(1);
497 $lei->start_pager if delete $lei->{need_pager};
498 $lei->{ovv}->ovv_begin($lei);
499 die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
501 $l2m->pre_augment($lei);
502 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
505 my $F_SETPIPE_SZ = $^O eq 'linux' ? 1031 : undef;
506 if ($l2m->{-wq_nr_workers} > 1 &&
507 $l2m->{base_type} =~ /\A(?:maildir|mbox)\z/) {
508 # setup two barriers to coordinate dedupe_nr
509 # between l2m workers
510 pipe(my ($a_r, $a_w)) or die "pipe: $!";
511 fcntl($a_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
512 pipe(my ($b_r, $b_w)) or die "pipe: $!";
513 fcntl($b_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
514 $l2m->{au_peers} = [ $a_r, $a_w, $b_r, $b_w ];
516 $l2m->wq_workers_start('lei2mail', undef,
517 $lei->oldset, { lei => $lei });
518 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
519 fcntl($lei->{startq}, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
520 delete $l2m->{au_peers};
522 $self->wq_workers_start('lei_xsearch', undef,
523 $lei->oldset, { lei => $lei });
524 my $op_c = delete $lei->{pkt_op_c};
525 delete $lei->{pkt_op_p};
527 $self->{opt_threads} = $lei->{opt}->{threads};
528 $self->{opt_sort} = $lei->{opt}->{'sort'};
529 $self->{-do_lcat} = $lei->{lcat_blob} // $lei->{lcat_fid};
531 $l2m->net_merge_all_done unless $lei->{auth};
535 $lei->event_step_init; # wait for shutdowns
536 $op_c->op_wait_event($ops);
540 my ($self, $uri) = @_;
541 if (my $curl = $self->{curl} //= which('curl') // 0) {
542 require PublicInbox::MboxReader;
543 require IO::Uncompress::Gunzip;
544 require PublicInbox::LeiCurl;
545 push @{$self->{remotes}}, $uri;
547 warn "curl missing, ignoring $uri\n";
551 sub prepare_external {
552 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
553 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
554 return add_uri($self, $loc) if $loc->can('scheme');
555 } elsif ($loc =~ m!\Ahttps?://!) {
557 return add_uri($self, URI->new($loc));
558 } elsif (-f "$loc/ei.lock") {
559 require PublicInbox::ExtSearch;
560 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
561 $loc = PublicInbox::ExtSearch->new($loc);
562 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
563 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
564 require PublicInbox::Inbox; # v2, v1
565 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
567 warn "W: ignoring $loc, unable to determine type\n";
570 push @{$self->{locals}}, $loc;
573 sub _lcat_i { # LeiMailSync->each_src iterator callback
574 my ($oidbin, $id, $each_smsg) = @_;
575 $each_smsg->({blob => unpack('H*', $oidbin), pct => 100});
578 sub _lcat2smsg { # git->cat_async callback
579 my ($bref, $oid, $type, $size, $smsg) = @_;
581 my $eml = PublicInbox::Eml->new($bref);
582 my $json_dump = delete $smsg->{-json_dump};
583 bless $smsg, 'PublicInbox::Smsg';
584 _smsg_fill($smsg, $eml);
585 $json_dump->($smsg, undef, $eml);
591 my $lei = $self->{lei};
592 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
593 my $git = $lei->{ale}->git;
595 my $json_dump = $each_smsg;
599 $smsg->{-json_dump} = $json_dump;
600 $git->cat_async($smsg->{blob}, \&_lcat2smsg, $smsg);
603 for my $oid (@{$lei->{lcat_blob} // []}) {
604 $each_smsg->({ blob => $oid, pct => 100 });
606 if (my $fids = delete $lei->{lcat_fid}) {
607 my $lms = $lei->{lse}->lms;
608 for my $fid (@$fids) {
609 $lms->each_src({fid => $fid}, \&_lcat_i, $each_smsg);
612 $git->async_wait_all;
613 undef $each_smsg; # may commit
614 $lei->{ovv}->ovv_atexit_child($lei);