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 $smsg->{kw} = [ sort keys %$kw ];
78 my ($self, $mitem) = @_;
79 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
80 my $nshard = $self->{nshard};
81 my $docid = $mitem->get_docid;
82 my $shard = ($docid - 1) % $nshard;
83 my $num = int(($docid - 1) / $nshard) + 1;
84 my $ibx = $self->{shard2ibx}->[$shard];
85 my $smsg = $ibx->over->get_art($num);
86 mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
87 $smsg->{docid} = $docid;
92 my ($self, $qstr, $opt) = @_;
94 $opt->{relevance} //= -2;
95 $self->mset($qstr //= 'bytes:1..', $opt);
100 sub _mset_more ($$) {
101 my ($mset, $mo) = @_;
102 my $size = $mset->size;
103 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
106 # $startq will EOF when do_augment is done augmenting and allow
107 # query_mset and query_thread_mset to proceed.
108 sub wait_startq ($) {
110 my $startq = delete $lei->{startq} or return;
112 my $n = sysread($startq, my $do_augment_done, 1);
114 return if $n == 0; # no MUA
115 if ($do_augment_done eq 'q') {
116 $lei->{opt}->{quiet} = 1;
117 delete $lei->{opt}->{verbose};
118 delete $lei->{-progress};
120 $lei->fail("$$ WTF `$do_augment_done'");
124 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
130 return if $lei->{early_mua} || !$lei->{-progress};
131 if ($lei->{pkt_op_p}) {
132 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
133 } else { # single lei-daemon consumer
134 my ($desc, $mset_size, $mset_total_est) = @_;
135 $lei->{-mset_total} += $mset_size;
136 $lei->qerr("# $desc $mset_size/$mset_total_est");
140 sub query_thread_mset { # for --threads
141 my ($self, $ibxish) = @_;
142 local $0 = "$0 query_thread_mset";
143 my $lei = $self->{lei};
144 my ($srch, $over) = ($ibxish->search, $ibxish->over);
145 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
146 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
147 my $mo = { %{$lei->{mset_opt}} };
149 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
150 my $can_kw = !!$ibxish->can('msg_keywords');
151 my $fl = $lei->{opt}->{threads} > 1;
153 $mset = $srch->mset($mo->{qstr}, $mo);
154 mset_progress($lei, $desc, $mset->size,
155 $mset->get_matches_estimated);
156 my $ids = $srch->mset_to_artnums($mset, $mo);
157 my $ctx = { ids => $ids };
159 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
160 while ($over->expand_thread($ctx)) {
161 for my $n (@{$ctx->{xids}}) {
162 my $smsg = $over->get_art($n) or next;
164 my $mitem = delete $n2item{$smsg->{num}};
167 mitem_kw($smsg, $mitem, $fl);
169 $smsg->{kw} = [ 'flagged' ];
172 $each_smsg->($smsg, $mitem);
174 @{$ctx->{xids}} = ();
176 } while (_mset_more($mset, $mo));
177 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
178 $lei->{ovv}->ovv_atexit_child($lei);
181 sub query_mset { # non-parallel for non-"--threads" users
183 local $0 = "$0 query_mset";
184 my $lei = $self->{lei};
185 my $mo = { %{$lei->{mset_opt}} };
187 for my $loc (locals($self)) {
188 attach_external($self, $loc);
190 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
192 $mset = $self->mset($mo->{qstr}, $mo);
193 mset_progress($lei, 'xsearch', $mset->size,
194 $mset->size, $mset->get_matches_estimated);
195 for my $mitem ($mset->items) {
196 my $smsg = smsg_for($self, $mitem) or next;
198 $each_smsg->($smsg, $mitem);
200 } while (_mset_more($mset, $mo));
201 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
202 $lei->{ovv}->ovv_atexit_child($lei);
205 sub each_remote_eml { # callback for MboxReader->mboxrd
206 my ($eml, $self, $lei, $each_smsg) = @_;
207 $lei->{sto}->ipc_do('add_eml', $eml) if $lei->{opt}->{'import-remote'};
208 my $smsg = bless {}, 'PublicInbox::Smsg';
209 $smsg->populate($eml);
210 $smsg->parse_references($eml, mids($eml));
211 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
212 delete @$smsg{qw(From Subject -ds -ts)};
214 if ($lei->{-progress}) {
215 ++$lei->{-nr_remote_eml};
217 my $next = $lei->{-next_progress} //= ($now + 1);
219 $lei->{-next_progress} = $now + 1;
220 my $nr = $lei->{-nr_remote_eml};
221 $lei->err("# $lei->{-current_url} $nr/?");
224 $each_smsg->($smsg, undef, $eml);
227 sub query_remote_mboxrd {
228 my ($self, $uris) = @_;
229 local $0 = "$0 query_remote_mboxrd";
230 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
231 my $lei = $self->{lei};
232 my $opt = $lei->{opt};
233 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
234 push(@qform, t => 1) if $opt->{threads};
235 my $verbose = $opt->{verbose};
236 my ($reap_tail, $reap_curl);
237 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
238 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
239 my $rdr = { 2 => $cerr, pgid => 0 };
240 my $sigint_reap = $lei->can('sigint_reap');
242 # spawn a process to force line-buffering, otherwise curl
243 # will write 1 character at-a-time and parallel outputs
244 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
245 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
246 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
247 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
249 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
250 push @$curl, '-s', '-d', '';
251 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
252 for my $uri (@$uris) {
253 $lei->{-current_url} = $uri->as_string;
254 $lei->{-nr_remote_eml} = 0;
255 $uri->query_form(@qform);
256 my $cmd = $curl->for_uri($lei, $uri);
257 $lei->qerr("# $cmd");
258 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
259 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
260 $fh = IO::Uncompress::Gunzip->new($fh);
261 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
263 my $err = waitpid($pid, 0) == $pid ? undef
264 : "BUG: waitpid($cmd): $!";
265 @$reap_curl = (); # cancel OnDestroy
267 my $nr = $lei->{-nr_remote_eml};
268 if ($nr && $lei->{sto}) {
269 my $wait = $lei->{sto}->ipc_do('done');
272 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
277 seek($cerr, 0, SEEK_SET) or
278 $lei->err("seek($cmd stderr): $!");
279 $err = do { local $/; <$cerr> } //
280 "read($cmd stderr): $!";
281 truncate($cerr, 0) or
282 $lei->err("truncate($cmd stderr): $!");
284 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
285 $uri->query_form(q => $lei->{mset_opt}->{qstr});
286 $lei->child_error($?, "E: <$uri> $err");
289 $lei->{ovv}->ovv_atexit_child($lei);
292 # called by LeiOverview::each_smsg_cb
293 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
298 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
299 for my $ibxish (locals($self)) {
300 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
301 $seen{$d} //= push @dirs, "$d/objects\n"
303 my $git_dir = $tmp->dirname;
304 PublicInbox::Import::init_bare($git_dir);
305 my $f = "$git_dir/objects/info/alternates";
306 open my $alt, '>', $f or die "open($f): $!";
307 print $alt @dirs or die "print $f: $!";
308 close $alt or die "close $f: $!";
309 my $git = PublicInbox::Git->new($git_dir);
314 sub xsearch_done_wait { # dwaitpid callback
315 my ($arg, $pid) = @_;
316 my ($wq, $lei) = @$arg;
317 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
320 sub query_done { # EOF callback for main daemon
322 my $l2m = delete $lei->{l2m};
323 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
324 if (my $lxs = delete $lei->{lxs}) {
325 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
327 $lei->{ovv}->ovv_end($lei);
328 if ($l2m) { # close() calls LeiToMail reap_compress
329 if (my $out = delete $lei->{old_1}) {
330 if (my $mbout = $lei->{1}) {
331 close($mbout) or return $lei->fail(<<"");
332 Error closing $lei->{ovv}->{dst}: $!
337 if ($l2m->lock_free) {
340 } else { # mbox users
341 delete $l2m->{mbl}; # drop dotlock
345 $lei->{-progress} and
346 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
350 sub do_post_augment {
352 my $l2m = $lei->{l2m} or return; # client disconnected
354 eval { $l2m->post_augment($lei) };
357 if (my $lxs = delete $lei->{lxs}) {
359 $lxs->wq_close(0, undef, $lei);
363 if (!$err && delete $lei->{early_mua}) { # non-augment case
366 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
369 sub incr_post_augment { # called whenever an l2m shard finishes augment
371 my $l2m = $lei->{l2m} or return; # client disconnected
372 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
373 do_post_augment($lei);
376 my $MAX_PER_HOST = 4;
379 my ($self, $opt) = @_;
380 my $nl = $opt->{threads} ? locals($self) : 1;
381 my $nr = remotes($self);
382 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
386 sub start_query { # always runs in main (lei-daemon) process
388 if ($self->{threads}) {
389 for my $ibxish (locals($self)) {
390 $self->wq_io_do('query_thread_mset', [], $ibxish);
392 } elsif (locals($self)) {
393 $self->wq_io_do('query_mset', []);
397 for my $uri (remotes($self)) {
398 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
401 $self->wq_io_do('query_remote_mboxrd', [], $uris);
403 $self->wq_close(1); # lei_xsearch workers stop when done
406 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
407 my ($self, $l2m) = @_;
408 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
412 sub ipc_atfork_child {
414 $self->{lei}->lei_atfork_child;
415 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
416 $self->SUPER::ipc_atfork_child;
419 sub delete_pkt_op { # OnDestroy callback
420 my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
421 close $unclosed_after_die;
425 my ($self, $lei) = @_;
426 my $l2m = $lei->{l2m};
428 '|' => [ $lei->can('sigpipe_handler'), $lei ],
429 '!' => [ $lei->can('fail_handler'), $lei ],
430 '.' => [ \&do_post_augment, $lei ],
431 '+' => [ \&incr_post_augment, $lei ],
432 '' => [ \&query_done, $lei ],
433 'mset_progress' => [ \&mset_progress, $lei ],
434 'x_it' => [ $lei->can('x_it'), $lei ],
435 'child_error' => [ $lei->can('child_error'), $lei ],
436 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
438 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
439 my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
440 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
441 $lei->{1}->autoflush(1);
442 $lei->start_pager if delete $lei->{need_pager};
443 $lei->{ovv}->ovv_begin($lei);
445 $l2m->pre_augment($lei);
446 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
449 $l2m->wq_workers_start('lei2mail', undef,
450 $lei->oldset, { lei => $lei });
451 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
453 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
455 if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
456 # lei->{git_tmp} is set for wq_wait_old so we don't
457 # delete until all lei2mail + lei_xsearch workers are reaped
458 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
460 $self->wq_workers_start('lei_xsearch', undef,
461 $lei->oldset, { lei => $lei });
462 my $op = delete $lei->{pkt_op_c};
463 delete $lei->{pkt_op_p};
464 $self->{threads} = $lei->{opt}->{threads};
466 $l2m->net_merge_complete unless $lei->{auth};
470 $lei->event_step_init; # wait for shutdowns
471 if ($lei->{oneshot}) {
472 while ($op->{sock}) { $op->event_step }
477 my ($self, $uri) = @_;
478 if (my $curl = $self->{curl} //= which('curl') // 0) {
479 require PublicInbox::MboxReader;
480 require IO::Uncompress::Gunzip;
481 require PublicInbox::LeiCurl;
482 push @{$self->{remotes}}, $uri;
484 warn "curl missing, ignoring $uri\n";
488 sub prepare_external {
489 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
490 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
491 return add_uri($self, $loc) if $loc->can('scheme');
492 } elsif ($loc =~ m!\Ahttps?://!) {
494 return add_uri($self, URI->new($loc));
495 } elsif (-f "$loc/ei.lock") {
496 require PublicInbox::ExtSearch;
497 $loc = PublicInbox::ExtSearch->new($loc);
498 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
499 require PublicInbox::Inbox; # v2, v1
500 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
502 warn "W: ignoring $loc, unable to determine type\n";
505 push @{$self->{locals}}, $loc;