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_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_thread_mset { # for --threads
148 my ($self, $ibxish) = @_;
149 local $0 = "$0 query_thread_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, $ibxish);
157 my $can_kw = !!$ibxish->can('msg_keywords');
158 my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
160 $mset = $srch->mset($mo->{qstr}, $mo);
161 mset_progress($lei, $desc, $mset->size,
162 $mset->get_matches_estimated);
163 wait_startq($lei); # wait for keyword updates
164 my $ids = $srch->mset_to_artnums($mset, $mo);
165 my $ctx = { ids => $ids };
167 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
168 while ($over->expand_thread($ctx)) {
169 for my $n (@{$ctx->{xids}}) {
170 my $smsg = $over->get_art($n) or next;
171 my $mitem = delete $n2item{$smsg->{num}};
172 next if $smsg->{bytes} == 0;
175 mitem_kw($smsg, $mitem, $fl);
177 # call ->xsmsg_vmd, later
178 $smsg->{lei_q_tt_flagged} = 1;
181 $each_smsg->($smsg, $mitem);
183 @{$ctx->{xids}} = ();
185 } while (_mset_more($mset, $mo));
186 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
187 $lei->{ovv}->ovv_atexit_child($lei);
190 sub query_mset { # non-parallel for non-"--threads" users
192 local $0 = "$0 query_mset";
193 my $lei = $self->{lei};
194 my $mo = { %{$lei->{mset_opt}} };
196 for my $loc (locals($self)) {
197 attach_external($self, $loc);
199 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
201 $mset = $self->mset($mo->{qstr}, $mo);
202 mset_progress($lei, 'xsearch', $mset->size,
203 $mset->size, $mset->get_matches_estimated);
204 wait_startq($lei); # wait for keyword updates
205 for my $mitem ($mset->items) {
206 my $smsg = smsg_for($self, $mitem) or next;
207 $each_smsg->($smsg, $mitem);
209 } while (_mset_more($mset, $mo));
210 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
211 $lei->{ovv}->ovv_atexit_child($lei);
214 sub each_remote_eml { # callback for MboxReader->mboxrd
215 my ($eml, $self, $lei, $each_smsg) = @_;
216 my $xoids = $lei->{ale}->xoids_for($eml, 1);
217 if ($self->{import_sto} && !$xoids) {
218 $self->{import_sto}->ipc_do('add_eml', $eml);
220 my $smsg = bless {}, 'PublicInbox::Smsg';
221 $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
222 : git_sha(1, $eml)->hexdigest;
223 $smsg->populate($eml);
224 $smsg->parse_references($eml, mids($eml));
225 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
226 delete @$smsg{qw(From Subject -ds -ts)};
228 if ($lei->{-progress}) {
229 ++$lei->{-nr_remote_eml};
231 my $next = $lei->{-next_progress} //= ($now + 1);
233 $lei->{-next_progress} = $now + 1;
234 my $nr = $lei->{-nr_remote_eml};
235 mset_progress($lei, $lei->{-current_url}, $nr, '?');
238 $each_smsg->($smsg, undef, $eml);
241 sub query_remote_mboxrd {
242 my ($self, $uris) = @_;
243 local $0 = "$0 query_remote_mboxrd";
244 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
245 my $lei = $self->{lei};
246 my $opt = $lei->{opt};
247 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
248 push(@qform, t => 1) if $opt->{threads};
249 my $verbose = $opt->{verbose};
250 my ($reap_tail, $reap_curl);
251 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
252 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
253 my $rdr = { 2 => $cerr, pgid => 0 };
254 my $sigint_reap = $lei->can('sigint_reap');
256 # spawn a process to force line-buffering, otherwise curl
257 # will write 1 character at-a-time and parallel outputs
258 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
259 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
260 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
261 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
263 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
264 push @$curl, '-s', '-d', '';
265 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
266 $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
267 for my $uri (@$uris) {
268 $lei->{-current_url} = $uri->as_string;
269 $lei->{-nr_remote_eml} = 0;
270 $uri->query_form(@qform);
271 my $cmd = $curl->for_uri($lei, $uri);
272 $lei->qerr("# $cmd");
273 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
274 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
275 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
276 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
278 my $err = waitpid($pid, 0) == $pid ? undef
279 : "BUG: waitpid($cmd): $!";
280 @$reap_curl = (); # cancel OnDestroy
282 my $nr = $lei->{-nr_remote_eml};
283 if ($nr && $lei->{sto}) {
284 my $wait = $lei->{sto}->ipc_do('done');
287 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
292 seek($cerr, 0, SEEK_SET) or
293 $lei->err("seek($cmd stderr): $!");
294 $err = do { local $/; <$cerr> } //
295 "read($cmd stderr): $!";
296 truncate($cerr, 0) or
297 $lei->err("truncate($cmd stderr): $!");
299 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
300 $uri->query_form(q => $lei->{mset_opt}->{qstr});
301 $lei->child_error($?, "E: <$uri> $err");
304 $lei->{ovv}->ovv_atexit_child($lei);
307 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
309 sub xsearch_done_wait { # dwaitpid callback
310 my ($arg, $pid) = @_;
311 my ($wq, $lei) = @$arg;
312 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
315 sub query_done { # EOF callback for main daemon
317 my $l2m = delete $lei->{l2m};
318 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
319 if (my $lxs = delete $lei->{lxs}) {
320 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
322 my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
323 $lei->{ovv}->ovv_end($lei);
324 if ($l2m) { # close() calls LeiToMail reap_compress
325 if (my $out = delete $lei->{old_1}) {
326 if (my $mbout = $lei->{1}) {
327 close($mbout) or return $lei->fail(<<"");
328 Error closing $lei->{ovv}->{dst}: $!
333 if ($l2m->lock_free) {
336 } else { # mbox users
337 delete $l2m->{mbl}; # drop dotlock
341 $lei->{-progress} and
342 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
346 sub do_post_augment {
348 my $l2m = $lei->{l2m} or return; # client disconnected
350 eval { $l2m->post_augment($lei) };
353 if (my $lxs = delete $lei->{lxs}) {
355 $lxs->wq_close(0, undef, $lei);
359 if (!$err && delete $lei->{early_mua}) { # non-augment case
362 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
365 sub incr_post_augment { # called whenever an l2m shard finishes augment
367 my $l2m = $lei->{l2m} or return; # client disconnected
368 return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
369 do_post_augment($lei);
372 my $MAX_PER_HOST = 4;
375 my ($self, $opt) = @_;
376 my $nl = $opt->{threads} ? locals($self) : 1;
377 my $nr = remotes($self);
378 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
382 sub start_query { # always runs in main (lei-daemon) process
384 if ($self->{threads}) {
385 for my $ibxish (locals($self)) {
386 $self->wq_io_do('query_thread_mset', [], $ibxish);
388 } elsif (locals($self)) {
389 $self->wq_io_do('query_mset', []);
393 for my $uri (remotes($self)) {
394 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
397 $self->wq_io_do('query_remote_mboxrd', [], $uris);
399 $self->wq_close(1); # lei_xsearch workers stop when done
402 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
403 my ($self, $l2m) = @_;
404 return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
408 sub ipc_atfork_child {
410 $self->{lei}->_lei_atfork_child;
411 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
412 $self->SUPER::ipc_atfork_child;
416 my ($self, $lei) = @_;
417 my $l2m = $lei->{l2m};
419 '|' => [ $lei->can('sigpipe_handler'), $lei ],
420 '!' => [ $lei->can('fail_handler'), $lei ],
421 '.' => [ \&do_post_augment, $lei ],
422 '+' => [ \&incr_post_augment, $lei ],
423 '' => [ \&query_done, $lei ],
424 'mset_progress' => [ \&mset_progress, $lei ],
425 'x_it' => [ $lei->can('x_it'), $lei ],
426 'child_error' => [ $lei->can('child_error'), $lei ],
427 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
429 $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
430 my $end = $lei->pkt_op_pair;
431 $lei->{1}->autoflush(1);
432 $lei->start_pager if delete $lei->{need_pager};
433 $lei->{ovv}->ovv_begin($lei);
434 die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
436 $l2m->pre_augment($lei);
437 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
440 $l2m->wq_workers_start('lei2mail', undef,
441 $lei->oldset, { lei => $lei });
442 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
444 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
446 $self->wq_workers_start('lei_xsearch', undef,
447 $lei->oldset, { lei => $lei });
448 my $op_c = delete $lei->{pkt_op_c};
449 delete $lei->{pkt_op_p};
451 $self->{threads} = $lei->{opt}->{threads};
453 $l2m->net_merge_complete unless $lei->{auth};
457 $lei->event_step_init; # wait for shutdowns
458 $op_c->op_wait_event($ops);
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;