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");
147 sub query_one_mset { # for --threads and l2m w/o sort
148 my ($self, $ibxish) = @_;
149 local $0 = "$0 query_one_mset";
150 my $lei = $self->{lei};
151 my ($srch, $over) = ($ibxish->search, $ibxish->over);
152 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
153 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
154 my $mo = { %{$lei->{mset_opt}} };
156 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
157 my $can_kw = !!$ibxish->can('msg_keywords');
158 my $threads = $lei->{opt}->{threads} // 0;
159 my $fl = $threads > 1 ? 1 : undef;
161 $mset = $srch->mset($mo->{qstr}, $mo);
162 mset_progress($lei, $desc, $mset->size,
163 $mset->get_matches_estimated);
164 wait_startq($lei); # wait for keyword updates
165 my $ids = $srch->mset_to_artnums($mset, $mo);
168 my $ctx = { ids => $ids };
169 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
170 while ($over->expand_thread($ctx)) {
171 for my $n (@{$ctx->{xids}}) {
172 my $smsg = $over->get_art($n) or next;
173 my $mitem = delete $n2item{$n};
174 next if $smsg->{bytes} == 0;
175 if ($mitem && $can_kw) {
176 mitem_kw($smsg, $mitem, $fl);
177 } elsif ($mitem && $fl) {
178 # call ->xsmsg_vmd, later
179 $smsg->{lei_q_tt_flagged} = 1;
181 $each_smsg->($smsg, $mitem);
183 @{$ctx->{xids}} = ();
186 my @items = $mset->items;
188 my $mitem = $items[$i++];
189 my $smsg = $over->get_art($n) or next;
190 next if $smsg->{bytes} == 0;
191 mitem_kw($smsg, $mitem, $fl) if $can_kw;
192 $each_smsg->($smsg, $mitem);
195 } while (_mset_more($mset, $mo));
196 undef $each_smsg; # may commit
197 $lei->{ovv}->ovv_atexit_child($lei);
200 sub query_combined_mset { # non-parallel for non-"--threads" users
202 local $0 = "$0 query_combined_mset";
203 my $lei = $self->{lei};
204 my $mo = { %{$lei->{mset_opt}} };
206 for my $loc (locals($self)) {
207 attach_external($self, $loc);
209 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
211 $mset = $self->mset($mo->{qstr}, $mo);
212 mset_progress($lei, 'xsearch', $mset->size,
213 $mset->size, $mset->get_matches_estimated);
214 wait_startq($lei); # wait for keyword updates
215 for my $mitem ($mset->items) {
216 my $smsg = smsg_for($self, $mitem) or next;
217 $each_smsg->($smsg, $mitem);
219 } while (_mset_more($mset, $mo));
220 undef $each_smsg; # may commit
221 $lei->{ovv}->ovv_atexit_child($lei);
224 sub each_remote_eml { # callback for MboxReader->mboxrd
225 my ($eml, $self, $lei, $each_smsg) = @_;
226 my $xoids = $lei->{ale}->xoids_for($eml, 1);
227 if ($self->{import_sto} && !$xoids) {
228 $self->{import_sto}->ipc_do('add_eml', $eml);
230 my $smsg = bless {}, 'PublicInbox::Smsg';
231 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
232 : git_sha(1, $eml)->hexdigest;
233 $smsg->populate($eml);
234 $smsg->parse_references($eml, mids($eml));
235 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
236 delete @$smsg{qw(From Subject -ds -ts)};
238 if ($lei->{-progress}) {
239 ++$lei->{-nr_remote_eml};
241 my $next = $lei->{-next_progress} //= ($now + 1);
243 $lei->{-next_progress} = $now + 1;
244 my $nr = $lei->{-nr_remote_eml};
245 mset_progress($lei, $lei->{-current_url}, $nr, '?');
248 $each_smsg->($smsg, undef, $eml);
251 sub query_remote_mboxrd {
252 my ($self, $uris) = @_;
253 local $0 = "$0 query_remote_mboxrd";
254 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
255 my $lei = $self->{lei};
256 my $opt = $lei->{opt};
257 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
258 push(@qform, t => 1) if $opt->{threads};
259 my $verbose = $opt->{verbose};
260 my ($reap_tail, $reap_curl);
261 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
262 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
263 my $rdr = { 2 => $cerr, pgid => 0 };
264 my $sigint_reap = $lei->can('sigint_reap');
266 # spawn a process to force line-buffering, otherwise curl
267 # will write 1 character at-a-time and parallel outputs
268 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
269 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
270 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
271 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
273 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
274 push @$curl, '-s', '-d', '';
275 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
276 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
277 for my $uri (@$uris) {
278 $lei->{-current_url} = $uri->as_string;
279 $lei->{-nr_remote_eml} = 0;
280 $uri->query_form(@qform);
281 my $cmd = $curl->for_uri($lei, $uri);
282 $lei->qerr("# $cmd");
283 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
284 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
285 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
286 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
288 my $err = waitpid($pid, 0) == $pid ? undef
289 : "BUG: waitpid($cmd): $!";
290 @$reap_curl = (); # cancel OnDestroy
292 my $nr = $lei->{-nr_remote_eml};
293 if ($nr && $lei->{sto}) {
294 my $wait = $lei->{sto}->ipc_do('done');
297 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
302 seek($cerr, 0, SEEK_SET) or
303 $lei->err("seek($cmd stderr): $!");
304 $err = do { local $/; <$cerr> } //
305 "read($cmd stderr): $!";
306 truncate($cerr, 0) or
307 $lei->err("truncate($cmd stderr): $!");
309 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
310 $uri->query_form(q => $lei->{mset_opt}->{qstr});
311 $lei->child_error($?, "E: <$uri> $err");
314 $lei->{ovv}->ovv_atexit_child($lei);
317 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
319 sub xsearch_done_wait { # dwaitpid callback
320 my ($arg, $pid) = @_;
321 my ($wq, $lei) = @$arg;
322 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
325 sub query_done { # EOF callback for main daemon
327 my $l2m = delete $lei->{l2m};
328 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
329 if (my $lxs = delete $lei->{lxs}) {
330 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
332 my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
333 $lei->{ovv}->ovv_end($lei);
334 if ($l2m) { # close() calls LeiToMail reap_compress
335 if (my $out = delete $lei->{old_1}) {
336 if (my $mbout = $lei->{1}) {
337 close($mbout) or return $lei->fail(<<"");
338 Error closing $lei->{ovv}->{dst}: $!
343 if ($l2m->lock_free) {
346 } else { # mbox users
347 delete $l2m->{mbl}; # drop dotlock
351 $lei->{-progress} and
352 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
356 sub do_post_augment {
358 my $l2m = $lei->{l2m} or return; # client disconnected
360 eval { $l2m->post_augment($lei) };
363 if (my $lxs = delete $lei->{lxs}) {
365 $lxs->wq_close(0, undef, $lei);
369 if (!$err && delete $lei->{early_mua}) { # non-augment case
372 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
375 sub incr_post_augment { # called whenever an l2m shard finishes augment
377 my $l2m = $lei->{l2m} or return; # client disconnected
378 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
379 do_post_augment($lei);
382 my $MAX_PER_HOST = 4;
385 my ($self, $opt) = @_;
386 my $nl = $opt->{threads} ? locals($self) : 1;
387 my $nr = remotes($self);
388 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
392 sub start_query ($;$) { # always runs in main (lei-daemon) process
393 my ($self, $l2m) = @_;
394 if ($self->{opt_threads} || ($l2m && !$self->{opt_sort})) {
395 for my $ibxish (locals($self)) {
396 $self->wq_io_do('query_one_mset', [], $ibxish);
398 } elsif (locals($self)) {
399 $self->wq_io_do('query_combined_mset', []);
403 for my $uri (remotes($self)) {
404 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
407 $self->wq_io_do('query_remote_mboxrd', [], $uris);
409 $self->wq_close(1); # lei_xsearch workers stop when done
412 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
413 my ($self, $l2m) = @_;
414 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
415 start_query($self, $l2m);
418 sub ipc_atfork_child {
420 $self->{lei}->_lei_atfork_child;
421 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
422 $self->SUPER::ipc_atfork_child;
426 my ($self, $lei) = @_;
427 my $l2m = $lei->{l2m};
429 '|' => [ $lei->can('sigpipe_handler'), $lei ],
430 '!' => [ $lei->can('fail_handler'), $lei ],
431 '.' => [ \&do_post_augment, $lei ],
432 '+' => [ \&incr_post_augment, $lei ],
433 '' => [ \&query_done, $lei ],
434 'mset_progress' => [ \&mset_progress, $lei ],
435 'x_it' => [ $lei->can('x_it'), $lei ],
436 'child_error' => [ $lei->can('child_error'), $lei ],
437 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
439 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
440 my $end = $lei->pkt_op_pair;
441 $lei->{1}->autoflush(1);
442 $lei->start_pager if delete $lei->{need_pager};
443 $lei->{ovv}->ovv_begin($lei);
444 die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
446 $l2m->pre_augment($lei);
447 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
450 $l2m->wq_workers_start('lei2mail', undef,
451 $lei->oldset, { lei => $lei });
452 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
454 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
456 $self->wq_workers_start('lei_xsearch', undef,
457 $lei->oldset, { lei => $lei });
458 my $op_c = delete $lei->{pkt_op_c};
459 delete $lei->{pkt_op_p};
461 $self->{opt_threads} = $lei->{opt}->{threads};
462 $self->{opt_sort} = $lei->{opt}->{'sort'};
464 $l2m->net_merge_complete unless $lei->{auth};
468 $lei->event_step_init; # wait for shutdowns
469 $op_c->op_wait_event($ops);
473 my ($self, $uri) = @_;
474 if (my $curl = $self->{curl} //= which('curl') // 0) {
475 require PublicInbox::MboxReader;
476 require IO::Uncompress::Gunzip;
477 require PublicInbox::LeiCurl;
478 push @{$self->{remotes}}, $uri;
480 warn "curl missing, ignoring $uri\n";
484 sub prepare_external {
485 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
486 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
487 return add_uri($self, $loc) if $loc->can('scheme');
488 } elsif ($loc =~ m!\Ahttps?://!) {
490 return add_uri($self, URI->new($loc));
491 } elsif (-f "$loc/ei.lock") {
492 require PublicInbox::ExtSearch;
493 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
494 $loc = PublicInbox::ExtSearch->new($loc);
495 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
496 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
497 require PublicInbox::Inbox; # v2, v1
498 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
500 warn "W: ignoring $loc, unable to determine type\n";
503 push @{$self->{locals}}, $loc;