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', $mitem->get_document);
73 $kw->{flagged} = 1 if $flagged;
74 # we keep the empty 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 ];
81 my ($self, $mitem) = @_;
82 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
83 my $nshard = $self->{nshard};
84 my $docid = $mitem->get_docid;
85 my $shard = ($docid - 1) % $nshard;
86 my $num = int(($docid - 1) / $nshard) + 1;
87 my $ibx = $self->{shard2ibx}->[$shard];
88 my $smsg = $ibx->over->get_art($num);
89 return if $smsg->{bytes} == 0;
90 mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
95 my ($self, $qstr, $opt) = @_;
97 $opt->{relevance} //= -2;
98 $self->mset($qstr //= 'z:1..', $opt);
103 sub _mset_more ($$) {
104 my ($mset, $mo) = @_;
105 my $size = $mset->size;
106 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
109 # $startq will EOF when do_augment is done augmenting and allow
110 # query_mset and query_thread_mset to proceed.
111 sub wait_startq ($) {
113 my $startq = delete $lei->{startq} or return;
115 my $n = sysread($startq, my $do_augment_done, 1);
117 return if $n == 0; # no MUA
118 if ($do_augment_done eq 'q') {
119 $lei->{opt}->{quiet} = 1;
120 delete $lei->{opt}->{verbose};
121 delete $lei->{-progress};
123 $lei->fail("$$ WTF `$do_augment_done'");
127 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
133 return if $lei->{early_mua} || !$lei->{-progress};
134 if ($lei->{pkt_op_p}) {
135 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
136 } else { # single lei-daemon consumer
137 my ($desc, $mset_size, $mset_total_est) = @_;
138 $lei->{-mset_total} += $mset_size;
139 $lei->qerr("# $desc $mset_size/$mset_total_est");
143 sub query_thread_mset { # for --threads
144 my ($self, $ibxish) = @_;
145 local $0 = "$0 query_thread_mset";
146 my $lei = $self->{lei};
147 my ($srch, $over) = ($ibxish->search, $ibxish->over);
148 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
149 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
150 my $mo = { %{$lei->{mset_opt}} };
152 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
153 my $can_kw = !!$ibxish->can('msg_keywords');
154 my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
156 $mset = $srch->mset($mo->{qstr}, $mo);
157 mset_progress($lei, $desc, $mset->size,
158 $mset->get_matches_estimated);
159 my $ids = $srch->mset_to_artnums($mset, $mo);
160 my $ctx = { ids => $ids };
162 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
163 while ($over->expand_thread($ctx)) {
164 for my $n (@{$ctx->{xids}}) {
165 my $smsg = $over->get_art($n) or next;
166 my $mitem = delete $n2item{$smsg->{num}};
167 next if $smsg->{bytes} == 0;
168 wait_startq($lei); # wait for keyword updates
171 mitem_kw($smsg, $mitem, $fl);
173 $smsg->{lei_q_tt_flagged} = 1;
176 $each_smsg->($smsg, $mitem);
178 @{$ctx->{xids}} = ();
180 } while (_mset_more($mset, $mo));
181 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
182 $lei->{ovv}->ovv_atexit_child($lei);
185 sub query_mset { # non-parallel for non-"--threads" users
187 local $0 = "$0 query_mset";
188 my $lei = $self->{lei};
189 my $mo = { %{$lei->{mset_opt}} };
191 for my $loc (locals($self)) {
192 attach_external($self, $loc);
194 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
196 $mset = $self->mset($mo->{qstr}, $mo);
197 mset_progress($lei, 'xsearch', $mset->size,
198 $mset->size, $mset->get_matches_estimated);
199 for my $mitem ($mset->items) {
200 my $smsg = smsg_for($self, $mitem) or next;
202 $each_smsg->($smsg, $mitem);
204 } while (_mset_more($mset, $mo));
205 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
206 $lei->{ovv}->ovv_atexit_child($lei);
209 sub each_remote_eml { # callback for MboxReader->mboxrd
210 my ($eml, $self, $lei, $each_smsg) = @_;
211 my $xoids = $lei->{ale}->xoids_for($eml, 1);
212 if ($self->{import_sto} && !$xoids) {
213 $self->{import_sto}->ipc_do('add_eml', $eml);
215 my $smsg = bless {}, 'PublicInbox::Smsg';
216 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
217 : git_sha(1, $eml)->hexdigest;
218 $smsg->populate($eml);
219 $smsg->parse_references($eml, mids($eml));
220 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
221 delete @$smsg{qw(From Subject -ds -ts)};
223 if ($lei->{-progress}) {
224 ++$lei->{-nr_remote_eml};
226 my $next = $lei->{-next_progress} //= ($now + 1);
228 $lei->{-next_progress} = $now + 1;
229 my $nr = $lei->{-nr_remote_eml};
230 $lei->err("# $lei->{-current_url} $nr/?");
233 $each_smsg->($smsg, undef, $eml);
236 sub query_remote_mboxrd {
237 my ($self, $uris) = @_;
238 local $0 = "$0 query_remote_mboxrd";
239 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
240 my $lei = $self->{lei};
241 my $opt = $lei->{opt};
242 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
243 push(@qform, t => 1) if $opt->{threads};
244 my $verbose = $opt->{verbose};
245 my ($reap_tail, $reap_curl);
246 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
247 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
248 my $rdr = { 2 => $cerr, pgid => 0 };
249 my $sigint_reap = $lei->can('sigint_reap');
251 # spawn a process to force line-buffering, otherwise curl
252 # will write 1 character at-a-time and parallel outputs
253 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
254 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
255 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
256 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
258 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
259 push @$curl, '-s', '-d', '';
260 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
261 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
262 for my $uri (@$uris) {
263 $lei->{-current_url} = $uri->as_string;
264 $lei->{-nr_remote_eml} = 0;
265 $uri->query_form(@qform);
266 my $cmd = $curl->for_uri($lei, $uri);
267 $lei->qerr("# $cmd");
268 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
269 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
270 $fh = IO::Uncompress::Gunzip->new($fh);
271 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
273 my $err = waitpid($pid, 0) == $pid ? undef
274 : "BUG: waitpid($cmd): $!";
275 @$reap_curl = (); # cancel OnDestroy
277 my $nr = $lei->{-nr_remote_eml};
278 if ($nr && $lei->{sto}) {
279 my $wait = $lei->{sto}->ipc_do('done');
282 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
287 seek($cerr, 0, SEEK_SET) or
288 $lei->err("seek($cmd stderr): $!");
289 $err = do { local $/; <$cerr> } //
290 "read($cmd stderr): $!";
291 truncate($cerr, 0) or
292 $lei->err("truncate($cmd stderr): $!");
294 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
295 $uri->query_form(q => $lei->{mset_opt}->{qstr});
296 $lei->child_error($?, "E: <$uri> $err");
299 $lei->{ovv}->ovv_atexit_child($lei);
302 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
304 sub xsearch_done_wait { # dwaitpid callback
305 my ($arg, $pid) = @_;
306 my ($wq, $lei) = @$arg;
307 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
310 sub query_done { # EOF callback for main daemon
312 my $l2m = delete $lei->{l2m};
313 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
314 if (my $lxs = delete $lei->{lxs}) {
315 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
317 $lei->{ovv}->ovv_end($lei);
318 if ($l2m) { # close() calls LeiToMail reap_compress
319 if (my $out = delete $lei->{old_1}) {
320 if (my $mbout = $lei->{1}) {
321 close($mbout) or return $lei->fail(<<"");
322 Error closing $lei->{ovv}->{dst}: $!
327 if ($l2m->lock_free) {
330 } else { # mbox users
331 delete $l2m->{mbl}; # drop dotlock
335 $lei->{-progress} and
336 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
340 sub do_post_augment {
342 my $l2m = $lei->{l2m} or return; # client disconnected
344 eval { $l2m->post_augment($lei) };
347 if (my $lxs = delete $lei->{lxs}) {
349 $lxs->wq_close(0, undef, $lei);
353 if (!$err && delete $lei->{early_mua}) { # non-augment case
356 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
359 sub incr_post_augment { # called whenever an l2m shard finishes augment
361 my $l2m = $lei->{l2m} or return; # client disconnected
362 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
363 do_post_augment($lei);
366 my $MAX_PER_HOST = 4;
369 my ($self, $opt) = @_;
370 my $nl = $opt->{threads} ? locals($self) : 1;
371 my $nr = remotes($self);
372 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
376 sub start_query { # always runs in main (lei-daemon) process
378 if ($self->{threads}) {
379 for my $ibxish (locals($self)) {
380 $self->wq_io_do('query_thread_mset', [], $ibxish);
382 } elsif (locals($self)) {
383 $self->wq_io_do('query_mset', []);
387 for my $uri (remotes($self)) {
388 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
391 $self->wq_io_do('query_remote_mboxrd', [], $uris);
393 $self->wq_close(1); # lei_xsearch workers stop when done
396 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
397 my ($self, $l2m) = @_;
398 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
402 sub ipc_atfork_child {
404 $self->{lei}->lei_atfork_child;
405 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
406 $self->SUPER::ipc_atfork_child;
409 sub delete_pkt_op { # OnDestroy callback
410 my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
411 close $unclosed_after_die;
415 my ($self, $lei) = @_;
416 my $l2m = $lei->{l2m};
418 '|' => [ $lei->can('sigpipe_handler'), $lei ],
419 '!' => [ $lei->can('fail_handler'), $lei ],
420 '.' => [ \&do_post_augment, $lei ],
421 '+' => [ \&incr_post_augment, $lei ],
422 '' => [ \&query_done, $lei ],
423 'mset_progress' => [ \&mset_progress, $lei ],
424 'x_it' => [ $lei->can('x_it'), $lei ],
425 'child_error' => [ $lei->can('child_error'), $lei ],
426 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
428 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
429 my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
430 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
431 $lei->{1}->autoflush(1);
432 $lei->start_pager if delete $lei->{need_pager};
433 $lei->{ovv}->ovv_begin($lei);
435 $l2m->pre_augment($lei);
436 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
439 $l2m->wq_workers_start('lei2mail', undef,
440 $lei->oldset, { lei => $lei });
441 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
443 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
445 $self->wq_workers_start('lei_xsearch', undef,
446 $lei->oldset, { lei => $lei });
447 my $op = delete $lei->{pkt_op_c};
448 delete $lei->{pkt_op_p};
449 $self->{threads} = $lei->{opt}->{threads};
451 $l2m->net_merge_complete unless $lei->{auth};
455 $lei->event_step_init; # wait for shutdowns
456 if ($lei->{oneshot}) {
457 while ($op->{sock}) { $op->event_step }
462 my ($self, $uri) = @_;
463 if (my $curl = $self->{curl} //= which('curl') // 0) {
464 require PublicInbox::MboxReader;
465 require IO::Uncompress::Gunzip;
466 require PublicInbox::LeiCurl;
467 push @{$self->{remotes}}, $uri;
469 warn "curl missing, ignoring $uri\n";
473 sub prepare_external {
474 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
475 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
476 return add_uri($self, $loc) if $loc->can('scheme');
477 } elsif ($loc =~ m!\Ahttps?://!) {
479 return add_uri($self, URI->new($loc));
480 } elsif (-f "$loc/ei.lock") {
481 require PublicInbox::ExtSearch;
482 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
483 $loc = PublicInbox::ExtSearch->new($loc);
484 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
485 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
486 require PublicInbox::Inbox; # v2, v1
487 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
489 warn "W: ignoring $loc, unable to determine type\n";
492 push @{$self->{locals}}, $loc;