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 # we keep the empty array here to prevent expensive work in
74 # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
75 $smsg->{kw} = [ sort keys %$kw ];
80 my ($self, $mitem) = @_;
81 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
82 my $nshard = $self->{nshard};
83 my $docid = $mitem->get_docid;
84 my $shard = ($docid - 1) % $nshard;
85 my $num = int(($docid - 1) / $nshard) + 1;
86 my $ibx = $self->{shard2ibx}->[$shard];
87 my $smsg = $ibx->over->get_art($num);
88 return if $smsg->{bytes} == 0;
89 mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
94 my ($self, $qstr, $opt) = @_;
96 $opt->{relevance} //= -2;
97 $self->mset($qstr //= 'z:1..', $opt);
102 sub _mset_more ($$) {
103 my ($mset, $mo) = @_;
104 my $size = $mset->size;
105 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
108 # $startq will EOF when do_augment is done augmenting and allow
109 # query_mset and query_thread_mset to proceed.
110 sub wait_startq ($) {
112 my $startq = delete $lei->{startq} or return;
114 my $n = sysread($startq, my $do_augment_done, 1);
116 return if $n == 0; # no MUA
117 if ($do_augment_done eq 'q') {
118 $lei->{opt}->{quiet} = 1;
119 delete $lei->{opt}->{verbose};
120 delete $lei->{-progress};
122 $lei->fail("$$ WTF `$do_augment_done'");
126 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
132 return if $lei->{early_mua} || !$lei->{-progress};
133 if ($lei->{pkt_op_p}) {
134 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
135 } else { # single lei-daemon consumer
136 my ($desc, $mset_size, $mset_total_est) = @_;
137 $lei->{-mset_total} += $mset_size;
138 $lei->qerr("# $desc $mset_size/$mset_total_est");
142 sub query_thread_mset { # for --threads
143 my ($self, $ibxish) = @_;
144 local $0 = "$0 query_thread_mset";
145 my $lei = $self->{lei};
146 my ($srch, $over) = ($ibxish->search, $ibxish->over);
147 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
148 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
149 my $mo = { %{$lei->{mset_opt}} };
151 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
152 my $can_kw = !!$ibxish->can('msg_keywords');
153 my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
155 $mset = $srch->mset($mo->{qstr}, $mo);
156 mset_progress($lei, $desc, $mset->size,
157 $mset->get_matches_estimated);
158 my $ids = $srch->mset_to_artnums($mset, $mo);
159 my $ctx = { ids => $ids };
161 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
162 while ($over->expand_thread($ctx)) {
163 for my $n (@{$ctx->{xids}}) {
164 my $smsg = $over->get_art($n) or next;
165 my $mitem = delete $n2item{$smsg->{num}};
166 next if $smsg->{bytes} == 0;
167 wait_startq($lei); # wait for keyword updates
170 mitem_kw($smsg, $mitem, $fl);
172 $smsg->{lei_q_tt_flagged} = 1;
175 $each_smsg->($smsg, $mitem);
177 @{$ctx->{xids}} = ();
179 } while (_mset_more($mset, $mo));
180 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
181 $lei->{ovv}->ovv_atexit_child($lei);
184 sub query_mset { # non-parallel for non-"--threads" users
186 local $0 = "$0 query_mset";
187 my $lei = $self->{lei};
188 my $mo = { %{$lei->{mset_opt}} };
190 for my $loc (locals($self)) {
191 attach_external($self, $loc);
193 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
195 $mset = $self->mset($mo->{qstr}, $mo);
196 mset_progress($lei, 'xsearch', $mset->size,
197 $mset->size, $mset->get_matches_estimated);
198 for my $mitem ($mset->items) {
199 my $smsg = smsg_for($self, $mitem) or next;
201 $each_smsg->($smsg, $mitem);
203 } while (_mset_more($mset, $mo));
204 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
205 $lei->{ovv}->ovv_atexit_child($lei);
208 sub each_remote_eml { # callback for MboxReader->mboxrd
209 my ($eml, $self, $lei, $each_smsg) = @_;
210 if ($self->{import_sto} && !$lei->{ale}->xoids_for($eml, 1)) {
211 $self->{import_sto}->ipc_do('add_eml', $eml);
213 my $smsg = bless {}, 'PublicInbox::Smsg';
214 $smsg->populate($eml);
215 $smsg->parse_references($eml, mids($eml));
216 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
217 delete @$smsg{qw(From Subject -ds -ts)};
219 if ($lei->{-progress}) {
220 ++$lei->{-nr_remote_eml};
222 my $next = $lei->{-next_progress} //= ($now + 1);
224 $lei->{-next_progress} = $now + 1;
225 my $nr = $lei->{-nr_remote_eml};
226 $lei->err("# $lei->{-current_url} $nr/?");
229 $each_smsg->($smsg, undef, $eml);
232 sub query_remote_mboxrd {
233 my ($self, $uris) = @_;
234 local $0 = "$0 query_remote_mboxrd";
235 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
236 my $lei = $self->{lei};
237 my $opt = $lei->{opt};
238 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
239 push(@qform, t => 1) if $opt->{threads};
240 my $verbose = $opt->{verbose};
241 my ($reap_tail, $reap_curl);
242 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
243 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
244 my $rdr = { 2 => $cerr, pgid => 0 };
245 my $sigint_reap = $lei->can('sigint_reap');
247 # spawn a process to force line-buffering, otherwise curl
248 # will write 1 character at-a-time and parallel outputs
249 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
250 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
251 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
252 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
254 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
255 push @$curl, '-s', '-d', '';
256 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
257 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
258 for my $uri (@$uris) {
259 $lei->{-current_url} = $uri->as_string;
260 $lei->{-nr_remote_eml} = 0;
261 $uri->query_form(@qform);
262 my $cmd = $curl->for_uri($lei, $uri);
263 $lei->qerr("# $cmd");
264 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
265 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
266 $fh = IO::Uncompress::Gunzip->new($fh);
267 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
269 my $err = waitpid($pid, 0) == $pid ? undef
270 : "BUG: waitpid($cmd): $!";
271 @$reap_curl = (); # cancel OnDestroy
273 my $nr = $lei->{-nr_remote_eml};
274 if ($nr && $lei->{sto}) {
275 my $wait = $lei->{sto}->ipc_do('done');
278 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
283 seek($cerr, 0, SEEK_SET) or
284 $lei->err("seek($cmd stderr): $!");
285 $err = do { local $/; <$cerr> } //
286 "read($cmd stderr): $!";
287 truncate($cerr, 0) or
288 $lei->err("truncate($cmd stderr): $!");
290 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
291 $uri->query_form(q => $lei->{mset_opt}->{qstr});
292 $lei->child_error($?, "E: <$uri> $err");
295 $lei->{ovv}->ovv_atexit_child($lei);
298 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
300 sub xsearch_done_wait { # dwaitpid callback
301 my ($arg, $pid) = @_;
302 my ($wq, $lei) = @$arg;
303 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
306 sub query_done { # EOF callback for main daemon
308 my $l2m = delete $lei->{l2m};
309 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
310 if (my $lxs = delete $lei->{lxs}) {
311 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
313 $lei->{ovv}->ovv_end($lei);
314 if ($l2m) { # close() calls LeiToMail reap_compress
315 if (my $out = delete $lei->{old_1}) {
316 if (my $mbout = $lei->{1}) {
317 close($mbout) or return $lei->fail(<<"");
318 Error closing $lei->{ovv}->{dst}: $!
323 if ($l2m->lock_free) {
326 } else { # mbox users
327 delete $l2m->{mbl}; # drop dotlock
331 $lei->{-progress} and
332 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
336 sub do_post_augment {
338 my $l2m = $lei->{l2m} or return; # client disconnected
340 eval { $l2m->post_augment($lei) };
343 if (my $lxs = delete $lei->{lxs}) {
345 $lxs->wq_close(0, undef, $lei);
349 if (!$err && delete $lei->{early_mua}) { # non-augment case
352 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
355 sub incr_post_augment { # called whenever an l2m shard finishes augment
357 my $l2m = $lei->{l2m} or return; # client disconnected
358 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
359 do_post_augment($lei);
362 my $MAX_PER_HOST = 4;
365 my ($self, $opt) = @_;
366 my $nl = $opt->{threads} ? locals($self) : 1;
367 my $nr = remotes($self);
368 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
372 sub start_query { # always runs in main (lei-daemon) process
374 if ($self->{threads}) {
375 for my $ibxish (locals($self)) {
376 $self->wq_io_do('query_thread_mset', [], $ibxish);
378 } elsif (locals($self)) {
379 $self->wq_io_do('query_mset', []);
383 for my $uri (remotes($self)) {
384 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
387 $self->wq_io_do('query_remote_mboxrd', [], $uris);
389 $self->wq_close(1); # lei_xsearch workers stop when done
392 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
393 my ($self, $l2m) = @_;
394 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
398 sub ipc_atfork_child {
400 $self->{lei}->lei_atfork_child;
401 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
402 $self->SUPER::ipc_atfork_child;
405 sub delete_pkt_op { # OnDestroy callback
406 my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
407 close $unclosed_after_die;
411 my ($self, $lei) = @_;
412 my $l2m = $lei->{l2m};
414 '|' => [ $lei->can('sigpipe_handler'), $lei ],
415 '!' => [ $lei->can('fail_handler'), $lei ],
416 '.' => [ \&do_post_augment, $lei ],
417 '+' => [ \&incr_post_augment, $lei ],
418 '' => [ \&query_done, $lei ],
419 'mset_progress' => [ \&mset_progress, $lei ],
420 'x_it' => [ $lei->can('x_it'), $lei ],
421 'child_error' => [ $lei->can('child_error'), $lei ],
422 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
424 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
425 my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
426 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
427 $lei->{1}->autoflush(1);
428 $lei->start_pager if delete $lei->{need_pager};
429 $lei->{ovv}->ovv_begin($lei);
431 $l2m->pre_augment($lei);
432 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
435 $l2m->wq_workers_start('lei2mail', undef,
436 $lei->oldset, { lei => $lei });
437 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
439 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
441 $self->wq_workers_start('lei_xsearch', undef,
442 $lei->oldset, { lei => $lei });
443 my $op = delete $lei->{pkt_op_c};
444 delete $lei->{pkt_op_p};
445 $self->{threads} = $lei->{opt}->{threads};
447 $l2m->net_merge_complete unless $lei->{auth};
451 $lei->event_step_init; # wait for shutdowns
452 if ($lei->{oneshot}) {
453 while ($op->{sock}) { $op->event_step }
458 my ($self, $uri) = @_;
459 if (my $curl = $self->{curl} //= which('curl') // 0) {
460 require PublicInbox::MboxReader;
461 require IO::Uncompress::Gunzip;
462 require PublicInbox::LeiCurl;
463 push @{$self->{remotes}}, $uri;
465 warn "curl missing, ignoring $uri\n";
469 sub prepare_external {
470 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
471 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
472 return add_uri($self, $loc) if $loc->can('scheme');
473 } elsif ($loc =~ m!\Ahttps?://!) {
475 return add_uri($self, URI->new($loc));
476 } elsif (-f "$loc/ei.lock") {
477 require PublicInbox::ExtSearch;
478 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
479 $loc = PublicInbox::ExtSearch->new($loc);
480 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
481 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
482 require PublicInbox::Inbox; # v2, v1
483 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
485 warn "W: ignoring $loc, unable to determine type\n";
488 push @{$self->{locals}}, $loc;