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} // []} }
71 my ($smsg, $mitem, $flagged) = @_;
72 my $kw = xap_terms('K', my $doc = $mitem->get_document);
73 $kw->{flagged} = 1 if $flagged;
74 # we keep the empty {kw} array here to prevent expensive work in
75 # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
76 $smsg->{kw} = [ sort keys %$kw ];
77 my $L = xap_terms('L', $doc);
78 $smsg->{L} = [ sort keys %$L ] if scalar(keys %$L);
83 my ($self, $mitem) = @_;
84 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
85 my $nshard = $self->{nshard};
86 my $docid = $mitem->get_docid;
87 my $shard = ($docid - 1) % $nshard;
88 my $num = int(($docid - 1) / $nshard) + 1;
89 my $ibx = $self->{shard2ibx}->[$shard];
90 my $smsg = $ibx->over->get_art($num);
91 return if $smsg->{bytes} == 0; # external message
92 if ($ibx->can('msg_keywords')) {
93 mitem_kw($smsg, $mitem);
99 my ($self, $qstr, $opt) = @_;
101 $opt->{relevance} //= -2;
102 $self->mset($qstr //= 'z:1..', $opt);
107 sub _mset_more ($$) {
108 my ($mset, $mo) = @_;
109 my $size = $mset->size;
110 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
113 # $startq will EOF when do_augment is done augmenting and allow
114 # query_combined_mset and query_thread_mset to proceed.
115 sub wait_startq ($) {
117 my $startq = delete $lei->{startq} or return;
119 my $n = sysread($startq, my $do_augment_done, 1);
121 return if $n == 0; # no MUA
122 if ($do_augment_done eq 'q') {
123 $lei->{opt}->{quiet} = 1;
124 delete $lei->{opt}->{verbose};
125 delete $lei->{-progress};
127 $lei->fail("$$ WTF `$do_augment_done'");
131 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
137 return if $lei->{early_mua} || !$lei->{-progress};
138 if ($lei->{pkt_op_p}) {
139 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
140 } else { # single lei-daemon consumer
141 my ($desc, $mset_size, $mset_total_est) = @_;
142 $lei->{-mset_total} += $mset_size;
143 $lei->qerr("# $desc $mset_size/$mset_total_est");
149 $lei->{-nr_write} += $nr;
152 sub query_one_mset { # for --threads and l2m w/o sort
153 my ($self, $ibxish) = @_;
154 local $0 = "$0 query_one_mset";
155 my $lei = $self->{lei};
156 my ($srch, $over) = ($ibxish->search, $ibxish->over);
157 my $dir = $ibxish->{inboxdir} // $ibxish->{topdir};
158 return warn("$dir not indexed by Xapian\n") unless ($srch && $over);
159 my $mo = { %{$lei->{mset_opt}} }; # copy
161 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
162 my $can_kw = !!$ibxish->can('msg_keywords');
163 my $threads = $lei->{opt}->{threads} // 0;
164 my $fl = $threads > 1 ? 1 : undef;
165 my $lss = $lei->{dedupe};
166 $lss = undef unless $lss && $lss->can('cfg_set'); # saved search
167 my $maxk = "external.$dir.maxuid";
168 my $stop_at = $lss ? $lss->{-cfg}->{$maxk} : undef;
169 if (defined $stop_at) {
170 die "$maxk=$stop_at has multiple values" if ref $stop_at;
172 local $SIG{__WARN__} = sub { push @e, @_ };
174 return warn("$maxk=$stop_at: @e") if @e;
178 $mset = $srch->mset($mo->{qstr}, $mo);
179 mset_progress($lei, $dir, $mset->size,
180 $mset->get_matches_estimated);
181 wait_startq($lei); # wait for keyword updates
182 my $ids = $srch->mset_to_artnums($mset, $mo);
183 @$ids = grep { $_ > $stop_at } @$ids if defined($stop_at);
186 # copy $ids if $lss since over->expand_thread
187 # shifts @{$ctx->{ids}}
188 $first_ids = [ @$ids ] if $lss;
189 my $ctx = { ids => $ids };
190 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
191 while ($over->expand_thread($ctx)) {
192 for my $n (@{$ctx->{xids}}) {
193 my $smsg = $over->get_art($n) or next;
194 my $mitem = delete $n2item{$n};
195 next if $smsg->{bytes} == 0;
196 if ($mitem && $can_kw) {
197 mitem_kw($smsg, $mitem, $fl);
198 } elsif ($mitem && $fl) {
199 # call ->xsmsg_vmd, later
200 $smsg->{lei_q_tt_flagged} = 1;
202 $each_smsg->($smsg, $mitem);
204 @{$ctx->{xids}} = ();
208 my @items = $mset->items;
210 my $mitem = $items[$i++];
211 my $smsg = $over->get_art($n) or next;
212 next if $smsg->{bytes} == 0;
213 mitem_kw($smsg, $mitem, $fl) if $can_kw;
214 $each_smsg->($smsg, $mitem);
217 } while (_mset_more($mset, $mo));
218 if ($lss && scalar(@$first_ids)) {
220 my $max = $first_ids->[0];
221 $lss->cfg_set($maxk, $max);
224 undef $each_smsg; # may commit
225 $lei->{ovv}->ovv_atexit_child($lei);
228 sub query_combined_mset { # non-parallel for non-"--threads" users
230 local $0 = "$0 query_combined_mset";
231 my $lei = $self->{lei};
232 my $mo = { %{$lei->{mset_opt}} };
234 for my $loc (locals($self)) {
235 attach_external($self, $loc);
237 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
239 $mset = $self->mset($mo->{qstr}, $mo);
240 mset_progress($lei, 'xsearch', $mset->size,
241 $mset->size, $mset->get_matches_estimated);
242 wait_startq($lei); # wait for keyword updates
243 for my $mitem ($mset->items) {
244 my $smsg = smsg_for($self, $mitem) or next;
245 $each_smsg->($smsg, $mitem);
247 } while (_mset_more($mset, $mo));
248 undef $each_smsg; # may commit
249 $lei->{ovv}->ovv_atexit_child($lei);
252 sub each_remote_eml { # callback for MboxReader->mboxrd
253 my ($eml, $self, $lei, $each_smsg) = @_;
254 my $xoids = $lei->{ale}->xoids_for($eml, 1);
255 if ($self->{import_sto} && !$xoids) {
256 $self->{import_sto}->ipc_do('add_eml', $eml);
258 my $smsg = bless {}, 'PublicInbox::Smsg';
259 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
260 : git_sha(1, $eml)->hexdigest;
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)};
266 if ($lei->{-progress}) {
267 ++$lei->{-nr_remote_eml};
269 my $next = $lei->{-next_progress} //= ($now + 1);
271 $lei->{-next_progress} = $now + 1;
272 my $nr = $lei->{-nr_remote_eml};
273 mset_progress($lei, $lei->{-current_url}, $nr, '?');
276 $each_smsg->($smsg, undef, $eml);
279 sub query_remote_mboxrd {
280 my ($self, $uris) = @_;
281 local $0 = "$0 query_remote_mboxrd";
282 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
283 my $lei = $self->{lei};
284 my $opt = $lei->{opt};
285 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
286 push(@qform, t => 1) if $opt->{threads};
287 my $verbose = $opt->{verbose};
288 my ($reap_tail, $reap_curl);
289 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
290 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
291 my $rdr = { 2 => $cerr, pgid => 0 };
292 my $sigint_reap = $lei->can('sigint_reap');
294 # spawn a process to force line-buffering, otherwise curl
295 # will write 1 character at-a-time and parallel outputs
296 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
297 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
298 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
299 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
301 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
302 push @$curl, '-s', '-d', '';
303 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
304 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
305 for my $uri (@$uris) {
306 $lei->{-current_url} = $uri->as_string;
307 $lei->{-nr_remote_eml} = 0;
308 $uri->query_form(@qform);
309 my $cmd = $curl->for_uri($lei, $uri);
310 $lei->qerr("# $cmd");
311 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
312 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
313 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
314 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
316 my $err = waitpid($pid, 0) == $pid ? undef
317 : "BUG: waitpid($cmd): $!";
318 @$reap_curl = (); # cancel OnDestroy
320 my $nr = $lei->{-nr_remote_eml};
321 if ($nr && $lei->{sto}) {
322 my $wait = $lei->{sto}->ipc_do('done');
325 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
330 seek($cerr, 0, SEEK_SET) or
331 $lei->err("seek($cmd stderr): $!");
332 $err = do { local $/; <$cerr> } //
333 "read($cmd stderr): $!";
334 truncate($cerr, 0) or
335 $lei->err("truncate($cmd stderr): $!");
337 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
338 $uri->query_form(q => $lei->{mset_opt}->{qstr});
339 $lei->child_error($?, "E: <$uri> $err");
342 $lei->{ovv}->ovv_atexit_child($lei);
345 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
347 sub xsearch_done_wait { # dwaitpid callback
348 my ($arg, $pid) = @_;
349 my ($wq, $lei) = @$arg;
350 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
353 sub query_done { # EOF callback for main daemon
355 my $l2m = delete $lei->{l2m};
356 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
357 if (my $lxs = delete $lei->{lxs}) {
358 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
360 my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
361 $lei->{ovv}->ovv_end($lei);
363 if ($l2m) { # close() calls LeiToMail reap_compress
364 if (my $out = delete $lei->{old_1}) {
365 if (my $mbout = $lei->{1}) {
366 close($mbout) or return $lei->fail(<<"");
367 Error closing $lei->{ovv}->{dst}: $!
372 if ($l2m->lock_free) {
375 } else { # mbox users
376 delete $l2m->{mbl}; # drop dotlock
380 if ($lei->{-progress}) {
381 my $tot = $lei->{-mset_total} // 0;
382 my $nr = $lei->{-nr_write} // 0;
384 "# $nr written to $lei->{ovv}->{dst} ($tot matches)" :
387 $lei->start_mua if $start_mua;
391 sub do_post_augment {
393 my $l2m = $lei->{l2m} or return; # client disconnected
395 eval { $l2m->post_augment($lei) };
398 if (my $lxs = delete $lei->{lxs}) {
400 $lxs->wq_close(0, undef, $lei);
404 if (!$err && delete $lei->{early_mua}) { # non-augment case
407 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
410 sub incr_post_augment { # called whenever an l2m shard finishes augment
412 my $l2m = $lei->{l2m} or return; # client disconnected
413 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
414 do_post_augment($lei);
417 my $MAX_PER_HOST = 4;
420 my ($self, $opt) = @_;
421 my $nl = $opt->{threads} ? locals($self) : 1;
422 my $nr = remotes($self);
423 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
427 sub start_query ($;$) { # always runs in main (lei-daemon) process
428 my ($self, $l2m) = @_;
429 if ($self->{opt_threads} || ($l2m && !$self->{opt_sort})) {
430 for my $ibxish (locals($self)) {
431 $self->wq_io_do('query_one_mset', [], $ibxish);
433 } elsif (locals($self)) {
434 $self->wq_io_do('query_combined_mset', []);
438 for my $uri (remotes($self)) {
439 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
442 $self->wq_io_do('query_remote_mboxrd', [], $uris);
444 $self->wq_close(1); # lei_xsearch workers stop when done
447 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
448 my ($self, $l2m) = @_;
449 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
450 start_query($self, $l2m);
453 sub ipc_atfork_child {
455 $self->{lei}->_lei_atfork_child;
456 $self->SUPER::ipc_atfork_child;
460 my ($self, $lei) = @_;
461 my $l2m = $lei->{l2m};
463 '|' => [ $lei->can('sigpipe_handler'), $lei ],
464 '!' => [ $lei->can('fail_handler'), $lei ],
465 '.' => [ \&do_post_augment, $lei ],
466 '+' => [ \&incr_post_augment, $lei ],
467 '' => [ \&query_done, $lei ],
468 'mset_progress' => [ \&mset_progress, $lei ],
469 'l2m_progress' => [ \&l2m_progress, $lei ],
470 'x_it' => [ $lei->can('x_it'), $lei ],
471 'child_error' => [ $lei->can('child_error'), $lei ],
472 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
474 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
475 my $end = $lei->pkt_op_pair;
476 $lei->{1}->autoflush(1);
477 $lei->start_pager if delete $lei->{need_pager};
478 $lei->{ovv}->ovv_begin($lei);
479 die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
481 $l2m->pre_augment($lei);
482 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
485 $l2m->wq_workers_start('lei2mail', undef,
486 $lei->oldset, { lei => $lei });
487 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
489 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
491 $self->wq_workers_start('lei_xsearch', undef,
492 $lei->oldset, { lei => $lei });
493 my $op_c = delete $lei->{pkt_op_c};
494 delete $lei->{pkt_op_p};
496 $self->{opt_threads} = $lei->{opt}->{threads};
497 $self->{opt_sort} = $lei->{opt}->{'sort'};
499 $l2m->net_merge_all_done unless $lei->{auth};
503 $lei->event_step_init; # wait for shutdowns
504 $op_c->op_wait_event($ops);
508 my ($self, $uri) = @_;
509 if (my $curl = $self->{curl} //= which('curl') // 0) {
510 require PublicInbox::MboxReader;
511 require IO::Uncompress::Gunzip;
512 require PublicInbox::LeiCurl;
513 push @{$self->{remotes}}, $uri;
515 warn "curl missing, ignoring $uri\n";
519 sub prepare_external {
520 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
521 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
522 return add_uri($self, $loc) if $loc->can('scheme');
523 } elsif ($loc =~ m!\Ahttps?://!) {
525 return add_uri($self, URI->new($loc));
526 } elsif (-f "$loc/ei.lock") {
527 require PublicInbox::ExtSearch;
528 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
529 $loc = PublicInbox::ExtSearch->new($loc);
530 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
531 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
532 require PublicInbox::Inbox; # v2, v1
533 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
535 warn "W: ignoring $loc, unable to determine type\n";
538 push @{$self->{locals}}, $loc;