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 each_remote_eml { # callback for MboxReader->mboxrd
260 my ($eml, $self, $lei, $each_smsg) = @_;
261 my $xoids = $lei->{ale}->xoids_for($eml, 1);
262 if ($self->{import_sto} && !$xoids) {
263 $self->{import_sto}->ipc_do('add_eml', $eml);
265 my $smsg = bless {}, 'PublicInbox::Smsg';
266 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
267 : git_sha(1, $eml)->hexdigest;
268 $smsg->populate($eml);
269 $smsg->parse_references($eml, mids($eml));
270 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
271 delete @$smsg{qw(From Subject -ds -ts)};
273 if ($lei->{-progress}) {
274 ++$lei->{-nr_remote_eml};
276 my $next = $lei->{-next_progress} //= ($now + 1);
278 $lei->{-next_progress} = $now + 1;
279 my $nr = $lei->{-nr_remote_eml};
280 mset_progress($lei, $lei->{-current_url}, $nr, '?');
283 $each_smsg->($smsg, undef, $eml);
286 sub query_remote_mboxrd {
287 my ($self, $uris) = @_;
288 local $0 = "$0 query_remote_mboxrd";
289 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
290 my $lei = $self->{lei};
291 my $opt = $lei->{opt};
292 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
293 push(@qform, t => 1) if $opt->{threads};
294 my $verbose = $opt->{verbose};
295 my ($reap_tail, $reap_curl);
296 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
297 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
298 my $rdr = { 2 => $cerr, pgid => 0 };
299 my $sigint_reap = $lei->can('sigint_reap');
301 # spawn a process to force line-buffering, otherwise curl
302 # will write 1 character at-a-time and parallel outputs
303 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
304 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
305 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
306 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
308 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
309 push @$curl, '-s', '-d', '';
310 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
311 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
312 for my $uri (@$uris) {
313 $lei->{-current_url} = $uri->as_string;
314 $lei->{-nr_remote_eml} = 0;
315 $uri->query_form(@qform);
316 my $cmd = $curl->for_uri($lei, $uri);
317 $lei->qerr("# $cmd");
318 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
319 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
320 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
321 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
323 my $err = waitpid($pid, 0) == $pid ? undef
324 : "BUG: waitpid($cmd): $!";
325 @$reap_curl = (); # cancel OnDestroy
327 my $nr = $lei->{-nr_remote_eml};
328 if ($nr && $lei->{sto}) {
329 my $wait = $lei->{sto}->ipc_do('done');
332 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
337 seek($cerr, 0, SEEK_SET) or
338 $lei->err("seek($cmd stderr): $!");
339 $err = do { local $/; <$cerr> } //
340 "read($cmd stderr): $!";
341 truncate($cerr, 0) or
342 $lei->err("truncate($cmd stderr): $!");
344 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
345 $uri->query_form(q => $lei->{mset_opt}->{qstr});
346 $lei->child_error($?, "E: <$uri> $err");
349 $lei->{ovv}->ovv_atexit_child($lei);
352 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
354 sub xsearch_done_wait { # dwaitpid callback
355 my ($arg, $pid) = @_;
356 my ($wq, $lei) = @$arg;
357 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
360 sub query_done { # EOF callback for main daemon
362 my $l2m = delete $lei->{l2m};
363 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
364 if (my $lxs = delete $lei->{lxs}) {
365 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
367 if ($lei->{opt}->{'mail-sync'} && !$lei->{sto}) {
368 warn "BUG: {sto} missing with --mail-sync";
370 my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
371 $lei->{ovv}->ovv_end($lei);
373 if ($l2m) { # close() calls LeiToMail reap_compress
374 if (my $out = delete $lei->{old_1}) {
375 if (my $mbout = $lei->{1}) {
376 close($mbout) or return $lei->fail(<<"");
377 Error closing $lei->{ovv}->{dst}: $!
382 if ($l2m->lock_free) {
385 } else { # mbox users
386 delete $l2m->{mbl}; # drop dotlock
390 if ($lei->{-progress}) {
391 my $tot = $lei->{-mset_total} // 0;
392 my $nr = $lei->{-nr_write} // 0;
394 "# $nr written to $lei->{ovv}->{dst} ($tot matches)" :
397 $lei->start_mua if $start_mua;
401 sub do_post_augment {
403 my $l2m = $lei->{l2m} or return; # client disconnected
404 $lei->fchdir or return;
406 eval { $l2m->post_augment($lei) };
409 if (my $lxs = delete $lei->{lxs}) {
411 $lxs->wq_close(0, undef, $lei);
415 if (!$err && delete $lei->{early_mua}) { # non-augment case
418 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
421 sub incr_post_augment { # called whenever an l2m shard finishes augment
423 my $l2m = $lei->{l2m} or return; # client disconnected
424 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
425 do_post_augment($lei);
428 my $MAX_PER_HOST = 4;
431 my ($self, $opt) = @_;
432 my $nl = $opt->{threads} ? locals($self) : 1;
433 my $nr = remotes($self);
434 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
438 sub start_query ($;$) { # always runs in main (lei-daemon) process
439 my ($self, $l2m) = @_;
440 if ($self->{opt_threads} || ($l2m && !$self->{opt_sort})) {
441 for my $ibxish (locals($self)) {
442 $self->wq_io_do('query_one_mset', [], $ibxish);
444 } elsif (locals($self)) {
445 $self->wq_io_do('query_combined_mset', []);
449 for my $uri (remotes($self)) {
450 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
453 $self->wq_io_do('query_remote_mboxrd', [], $uris);
455 $self->wq_close(1); # lei_xsearch workers stop when done
458 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
459 my ($self, $l2m) = @_;
460 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
461 start_query($self, $l2m);
464 sub ipc_atfork_child {
466 $self->{lei}->_lei_atfork_child;
467 $self->SUPER::ipc_atfork_child;
471 my ($self, $lei) = @_;
472 my $l2m = $lei->{l2m};
474 '|' => [ $lei->can('sigpipe_handler'), $lei ],
475 '!' => [ $lei->can('fail_handler'), $lei ],
476 '.' => [ \&do_post_augment, $lei ],
477 '+' => [ \&incr_post_augment, $lei ],
478 '' => [ \&query_done, $lei ],
479 'mset_progress' => [ \&mset_progress, $lei ],
480 'l2m_progress' => [ \&l2m_progress, $lei ],
481 'x_it' => [ $lei->can('x_it'), $lei ],
482 'child_error' => [ $lei->can('child_error'), $lei ],
483 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
485 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
486 my $end = $lei->pkt_op_pair;
487 $lei->{1}->autoflush(1);
488 $lei->start_pager if delete $lei->{need_pager};
489 $lei->{ovv}->ovv_begin($lei);
490 die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
492 $l2m->pre_augment($lei);
493 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
496 my $F_SETPIPE_SZ = $^O eq 'linux' ? 1031 : undef;
497 if ($l2m->{-wq_nr_workers} > 1 &&
498 $l2m->{base_type} =~ /\A(?:maildir|mbox)\z/) {
499 # setup two barriers to coordinate dedupe_nr
500 # between l2m workers
501 pipe(my ($a_r, $a_w)) or die "pipe: $!";
502 fcntl($a_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
503 pipe(my ($b_r, $b_w)) or die "pipe: $!";
504 fcntl($b_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
505 $l2m->{au_peers} = [ $a_r, $a_w, $b_r, $b_w ];
507 $l2m->wq_workers_start('lei2mail', undef,
508 $lei->oldset, { lei => $lei });
509 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
510 fcntl($lei->{startq}, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
511 delete $l2m->{au_peers};
513 $self->wq_workers_start('lei_xsearch', undef,
514 $lei->oldset, { lei => $lei });
515 my $op_c = delete $lei->{pkt_op_c};
516 delete $lei->{pkt_op_p};
518 $self->{opt_threads} = $lei->{opt}->{threads};
519 $self->{opt_sort} = $lei->{opt}->{'sort'};
521 $l2m->net_merge_all_done unless $lei->{auth};
525 $lei->event_step_init; # wait for shutdowns
526 $op_c->op_wait_event($ops);
530 my ($self, $uri) = @_;
531 if (my $curl = $self->{curl} //= which('curl') // 0) {
532 require PublicInbox::MboxReader;
533 require IO::Uncompress::Gunzip;
534 require PublicInbox::LeiCurl;
535 push @{$self->{remotes}}, $uri;
537 warn "curl missing, ignoring $uri\n";
541 sub prepare_external {
542 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
543 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
544 return add_uri($self, $loc) if $loc->can('scheme');
545 } elsif ($loc =~ m!\Ahttps?://!) {
547 return add_uri($self, URI->new($loc));
548 } elsif (-f "$loc/ei.lock") {
549 require PublicInbox::ExtSearch;
550 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
551 $loc = PublicInbox::ExtSearch->new($loc);
552 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
553 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
554 require PublicInbox::Inbox; # v2, v1
555 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
557 warn "W: ignoring $loc, unable to determine type\n";
560 push @{$self->{locals}}, $loc;