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 return if $smsg->{bytes} == 0;
87 mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
88 $smsg->{docid} = $docid;
93 my ($self, $qstr, $opt) = @_;
95 $opt->{relevance} //= -2;
96 $self->mset($qstr //= 'z:1..', $opt);
101 sub _mset_more ($$) {
102 my ($mset, $mo) = @_;
103 my $size = $mset->size;
104 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
107 # $startq will EOF when do_augment is done augmenting and allow
108 # query_mset and query_thread_mset to proceed.
109 sub wait_startq ($) {
111 my $startq = delete $lei->{startq} or return;
113 my $n = sysread($startq, my $do_augment_done, 1);
115 return if $n == 0; # no MUA
116 if ($do_augment_done eq 'q') {
117 $lei->{opt}->{quiet} = 1;
118 delete $lei->{opt}->{verbose};
119 delete $lei->{-progress};
121 $lei->fail("$$ WTF `$do_augment_done'");
125 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
131 return if $lei->{early_mua} || !$lei->{-progress};
132 if ($lei->{pkt_op_p}) {
133 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
134 } else { # single lei-daemon consumer
135 my ($desc, $mset_size, $mset_total_est) = @_;
136 $lei->{-mset_total} += $mset_size;
137 $lei->qerr("# $desc $mset_size/$mset_total_est");
141 sub query_thread_mset { # for --threads
142 my ($self, $ibxish) = @_;
143 local $0 = "$0 query_thread_mset";
144 my $lei = $self->{lei};
145 my ($srch, $over) = ($ibxish->search, $ibxish->over);
146 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
147 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
148 my $mo = { %{$lei->{mset_opt}} };
150 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
151 my $can_kw = !!$ibxish->can('msg_keywords');
152 my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
154 $mset = $srch->mset($mo->{qstr}, $mo);
155 mset_progress($lei, $desc, $mset->size,
156 $mset->get_matches_estimated);
157 my $ids = $srch->mset_to_artnums($mset, $mo);
158 my $ctx = { ids => $ids };
160 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
161 while ($over->expand_thread($ctx)) {
162 for my $n (@{$ctx->{xids}}) {
163 my $smsg = $over->get_art($n) or next;
164 my $mitem = delete $n2item{$smsg->{num}};
165 next if $smsg->{bytes} == 0;
166 wait_startq($lei); # wait for keyword updates
169 mitem_kw($smsg, $mitem, $fl);
171 $smsg->{lei_q_tt_flagged} = 1;
174 $each_smsg->($smsg, $mitem);
176 @{$ctx->{xids}} = ();
178 } while (_mset_more($mset, $mo));
179 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
180 $lei->{ovv}->ovv_atexit_child($lei);
183 sub query_mset { # non-parallel for non-"--threads" users
185 local $0 = "$0 query_mset";
186 my $lei = $self->{lei};
187 my $mo = { %{$lei->{mset_opt}} };
189 for my $loc (locals($self)) {
190 attach_external($self, $loc);
192 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
194 $mset = $self->mset($mo->{qstr}, $mo);
195 mset_progress($lei, 'xsearch', $mset->size,
196 $mset->size, $mset->get_matches_estimated);
197 for my $mitem ($mset->items) {
198 my $smsg = smsg_for($self, $mitem) or next;
200 $each_smsg->($smsg, $mitem);
202 } while (_mset_more($mset, $mo));
203 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
204 $lei->{ovv}->ovv_atexit_child($lei);
207 sub each_remote_eml { # callback for MboxReader->mboxrd
208 my ($eml, $self, $lei, $each_smsg) = @_;
209 if ($self->{import_sto} && !$lei->{ale}->xoids_for($eml, 1)) {
210 $self->{import_sto}->ipc_do('add_eml', $eml);
212 my $smsg = bless {}, 'PublicInbox::Smsg';
213 $smsg->populate($eml);
214 $smsg->parse_references($eml, mids($eml));
215 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
216 delete @$smsg{qw(From Subject -ds -ts)};
218 if ($lei->{-progress}) {
219 ++$lei->{-nr_remote_eml};
221 my $next = $lei->{-next_progress} //= ($now + 1);
223 $lei->{-next_progress} = $now + 1;
224 my $nr = $lei->{-nr_remote_eml};
225 $lei->err("# $lei->{-current_url} $nr/?");
228 $each_smsg->($smsg, undef, $eml);
231 sub query_remote_mboxrd {
232 my ($self, $uris) = @_;
233 local $0 = "$0 query_remote_mboxrd";
234 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
235 my $lei = $self->{lei};
236 my $opt = $lei->{opt};
237 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
238 push(@qform, t => 1) if $opt->{threads};
239 my $verbose = $opt->{verbose};
240 my ($reap_tail, $reap_curl);
241 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
242 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
243 my $rdr = { 2 => $cerr, pgid => 0 };
244 my $sigint_reap = $lei->can('sigint_reap');
246 # spawn a process to force line-buffering, otherwise curl
247 # will write 1 character at-a-time and parallel outputs
248 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
249 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
250 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
251 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
253 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
254 push @$curl, '-s', '-d', '';
255 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
256 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
257 for my $uri (@$uris) {
258 $lei->{-current_url} = $uri->as_string;
259 $lei->{-nr_remote_eml} = 0;
260 $uri->query_form(@qform);
261 my $cmd = $curl->for_uri($lei, $uri);
262 $lei->qerr("# $cmd");
263 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
264 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
265 $fh = IO::Uncompress::Gunzip->new($fh);
266 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
268 my $err = waitpid($pid, 0) == $pid ? undef
269 : "BUG: waitpid($cmd): $!";
270 @$reap_curl = (); # cancel OnDestroy
272 my $nr = $lei->{-nr_remote_eml};
273 if ($nr && $lei->{sto}) {
274 my $wait = $lei->{sto}->ipc_do('done');
277 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
282 seek($cerr, 0, SEEK_SET) or
283 $lei->err("seek($cmd stderr): $!");
284 $err = do { local $/; <$cerr> } //
285 "read($cmd stderr): $!";
286 truncate($cerr, 0) or
287 $lei->err("truncate($cmd stderr): $!");
289 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
290 $uri->query_form(q => $lei->{mset_opt}->{qstr});
291 $lei->child_error($?, "E: <$uri> $err");
294 $lei->{ovv}->ovv_atexit_child($lei);
297 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
299 sub xsearch_done_wait { # dwaitpid callback
300 my ($arg, $pid) = @_;
301 my ($wq, $lei) = @$arg;
302 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
305 sub query_done { # EOF callback for main daemon
307 my $l2m = delete $lei->{l2m};
308 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
309 if (my $lxs = delete $lei->{lxs}) {
310 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
312 $lei->{ovv}->ovv_end($lei);
313 if ($l2m) { # close() calls LeiToMail reap_compress
314 if (my $out = delete $lei->{old_1}) {
315 if (my $mbout = $lei->{1}) {
316 close($mbout) or return $lei->fail(<<"");
317 Error closing $lei->{ovv}->{dst}: $!
322 if ($l2m->lock_free) {
325 } else { # mbox users
326 delete $l2m->{mbl}; # drop dotlock
330 $lei->{-progress} and
331 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
335 sub do_post_augment {
337 my $l2m = $lei->{l2m} or return; # client disconnected
339 eval { $l2m->post_augment($lei) };
342 if (my $lxs = delete $lei->{lxs}) {
344 $lxs->wq_close(0, undef, $lei);
348 if (!$err && delete $lei->{early_mua}) { # non-augment case
351 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
354 sub incr_post_augment { # called whenever an l2m shard finishes augment
356 my $l2m = $lei->{l2m} or return; # client disconnected
357 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
358 do_post_augment($lei);
361 my $MAX_PER_HOST = 4;
364 my ($self, $opt) = @_;
365 my $nl = $opt->{threads} ? locals($self) : 1;
366 my $nr = remotes($self);
367 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
371 sub start_query { # always runs in main (lei-daemon) process
373 if ($self->{threads}) {
374 for my $ibxish (locals($self)) {
375 $self->wq_io_do('query_thread_mset', [], $ibxish);
377 } elsif (locals($self)) {
378 $self->wq_io_do('query_mset', []);
382 for my $uri (remotes($self)) {
383 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
386 $self->wq_io_do('query_remote_mboxrd', [], $uris);
388 $self->wq_close(1); # lei_xsearch workers stop when done
391 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
392 my ($self, $l2m) = @_;
393 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
397 sub ipc_atfork_child {
399 $self->{lei}->lei_atfork_child;
400 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
401 $self->SUPER::ipc_atfork_child;
404 sub delete_pkt_op { # OnDestroy callback
405 my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
406 close $unclosed_after_die;
410 my ($self, $lei) = @_;
411 my $l2m = $lei->{l2m};
413 '|' => [ $lei->can('sigpipe_handler'), $lei ],
414 '!' => [ $lei->can('fail_handler'), $lei ],
415 '.' => [ \&do_post_augment, $lei ],
416 '+' => [ \&incr_post_augment, $lei ],
417 '' => [ \&query_done, $lei ],
418 'mset_progress' => [ \&mset_progress, $lei ],
419 'x_it' => [ $lei->can('x_it'), $lei ],
420 'child_error' => [ $lei->can('child_error'), $lei ],
421 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
423 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
424 my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
425 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
426 $lei->{1}->autoflush(1);
427 $lei->start_pager if delete $lei->{need_pager};
428 $lei->{ovv}->ovv_begin($lei);
430 $l2m->pre_augment($lei);
431 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
434 $l2m->wq_workers_start('lei2mail', undef,
435 $lei->oldset, { lei => $lei });
436 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
438 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
440 $self->wq_workers_start('lei_xsearch', undef,
441 $lei->oldset, { lei => $lei });
442 my $op = delete $lei->{pkt_op_c};
443 delete $lei->{pkt_op_p};
444 $self->{threads} = $lei->{opt}->{threads};
446 $l2m->net_merge_complete unless $lei->{auth};
450 $lei->event_step_init; # wait for shutdowns
451 if ($lei->{oneshot}) {
452 while ($op->{sock}) { $op->event_step }
457 my ($self, $uri) = @_;
458 if (my $curl = $self->{curl} //= which('curl') // 0) {
459 require PublicInbox::MboxReader;
460 require IO::Uncompress::Gunzip;
461 require PublicInbox::LeiCurl;
462 push @{$self->{remotes}}, $uri;
464 warn "curl missing, ignoring $uri\n";
468 sub prepare_external {
469 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
470 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
471 return add_uri($self, $loc) if $loc->can('scheme');
472 } elsif ($loc =~ m!\Ahttps?://!) {
474 return add_uri($self, URI->new($loc));
475 } elsif (-f "$loc/ei.lock") {
476 require PublicInbox::ExtSearch;
477 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
478 $loc = PublicInbox::ExtSearch->new($loc);
479 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
480 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
481 require PublicInbox::Inbox; # v2, v1
482 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
484 warn "W: ignoring $loc, unable to determine type\n";
487 push @{$self->{locals}}, $loc;