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;
19 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
23 PublicInbox::Search::load_xapian();
25 qp_flags => $PublicInbox::Search::QP_FLAGS |
26 PublicInbox::Search::FLAG_PURE_NOT(),
31 my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
32 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
33 my $srch = $ibxish->search or
34 return warn("$desc not indexed for Xapian\n");
35 my @shards = $srch->xdb_shards_flat or
36 return warn("$desc has no Xapian shards\n");
38 if (delete $self->{xdb}) { # XXX: do we need this?
39 # clobber existing {xdb} if amending
40 my $expect = delete $self->{nshard};
41 my $shards = delete $self->{shards_flat};
42 scalar(@$shards) == $expect or die
43 "BUG: {nshard}$expect != shards=".scalar(@$shards);
46 for my $old_ibxish (@{$self->{shard2ibx}}) {
47 next if $prev == $old_ibxish;
49 my @shards = $old_ibxish->search->xdb_shards_flat;
50 push @{$self->{shards_flat}}, @shards;
52 my $nr = scalar(@{$self->{shards_flat}});
54 "BUG: reloaded $nr shards, expected $expect"
56 push @{$self->{shards_flat}}, @shards;
57 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
60 # returns a list of local inboxes (or count in scalar context)
61 sub locals { @{$_[0]->{locals} // []} }
63 sub remotes { @{$_[0]->{remotes} // []} }
65 # called by PublicInbox::Search::xdb
66 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
70 my ($self, $mitem) = @_;
71 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
72 my $nshard = $self->{nshard};
73 my $docid = $mitem->get_docid;
74 my $shard = ($docid - 1) % $nshard;
75 my $num = int(($docid - 1) / $nshard) + 1;
76 my $ibx = $self->{shard2ibx}->[$shard];
77 my $smsg = $ibx->over->get_art($num);
78 if (ref($ibx->can('msg_keywords'))) {
79 my $kw = xap_terms('K', $mitem->get_document);
80 $smsg->{kw} = [ sort keys %$kw ];
82 $smsg->{docid} = $docid;
87 my ($self, $qstr, $opt) = @_;
89 $opt->{relevance} //= -2;
90 $self->mset($qstr //= 'bytes:1..', $opt);
97 my $size = $mset->size;
98 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
101 # $startq will EOF when query_prepare is done augmenting and allow
102 # query_mset and query_thread_mset to proceed.
103 sub wait_startq ($) {
105 my $startq = delete $lei->{startq} or return;
107 my $n = sysread($startq, my $query_prepare_done, 1);
109 return if $n == 0; # no MUA
110 if ($query_prepare_done eq 'q') {
111 $lei->{opt}->{quiet} = 1;
112 delete $lei->{opt}->{verbose};
113 delete $lei->{-progress};
115 $lei->fail("$$ WTF `$query_prepare_done'");
119 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
125 return if $lei->{early_mua} || !$lei->{-progress};
126 if ($lei->{pkt_op_p}) {
127 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
128 } else { # single lei-daemon consumer
129 my ($desc, $mset_size, $mset_total_est) = @_;
130 $lei->{-mset_total} += $mset_size;
131 $lei->qerr("# $desc $mset_size/$mset_total_est");
135 sub query_thread_mset { # for --threads
136 my ($self, $ibxish) = @_;
137 local $0 = "$0 query_thread_mset";
138 my $lei = $self->{lei};
139 my ($srch, $over) = ($ibxish->search, $ibxish->over);
140 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
141 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
142 my $mo = { %{$lei->{mset_opt}} };
144 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
146 $mset = $srch->mset($mo->{qstr}, $mo);
147 mset_progress($lei, $desc, $mset->size,
148 $mset->get_matches_estimated);
149 my $ids = $srch->mset_to_artnums($mset, $mo);
150 my $ctx = { ids => $ids };
152 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
153 while ($over->expand_thread($ctx)) {
154 for my $n (@{$ctx->{xids}}) {
155 my $smsg = $over->get_art($n) or next;
157 my $mitem = delete $n2item{$smsg->{num}};
158 $each_smsg->($smsg, $mitem);
160 @{$ctx->{xids}} = ();
162 } while (_mset_more($mset, $mo));
163 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
164 $lei->{ovv}->ovv_atexit_child($lei);
167 sub query_mset { # non-parallel for non-"--threads" users
169 local $0 = "$0 query_mset";
170 my $lei = $self->{lei};
171 my $mo = { %{$lei->{mset_opt}} };
173 for my $loc (locals($self)) {
174 attach_external($self, $loc);
176 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
178 $mset = $self->mset($mo->{qstr}, $mo);
179 mset_progress($lei, 'xsearch', $mset->size,
180 $mset->size, $mset->get_matches_estimated);
181 for my $mitem ($mset->items) {
182 my $smsg = smsg_for($self, $mitem) or next;
184 $each_smsg->($smsg, $mitem);
186 } while (_mset_more($mset, $mo));
187 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
188 $lei->{ovv}->ovv_atexit_child($lei);
191 sub each_eml { # callback for MboxReader->mboxrd
192 my ($eml, $self, $lei, $each_smsg) = @_;
193 my $smsg = bless {}, 'PublicInbox::Smsg';
194 $smsg->populate($eml);
195 $smsg->parse_references($eml, mids($eml));
196 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
197 delete @$smsg{qw(From Subject -ds -ts)};
199 if ($lei->{-progress}) {
200 ++$lei->{-nr_remote_eml};
202 my $next = $lei->{-next_progress} //= ($now + 1);
204 $lei->{-next_progress} = $now + 1;
205 my $nr = $lei->{-nr_remote_eml};
206 $lei->err("# $lei->{-current_url} $nr/?");
209 $each_smsg->($smsg, undef, $eml);
212 sub query_remote_mboxrd {
213 my ($self, $uris) = @_;
214 local $0 = "$0 query_remote_mboxrd";
215 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
216 my $lei = $self->{lei};
217 my ($opt, $env) = @$lei{qw(opt env)};
218 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
219 push(@qform, t => 1) if $opt->{threads};
220 my $verbose = $opt->{verbose};
221 my ($reap_tail, $reap_curl);
222 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
223 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
224 my $rdr = { 2 => $cerr, pgid => 0 };
225 my $sigint_reap = $lei->can('sigint_reap');
227 # spawn a process to force line-buffering, otherwise curl
228 # will write 1 character at-a-time and parallel outputs
229 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
230 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
231 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
232 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
234 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
235 push @$curl, '-s', '-d', '';
236 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
237 for my $uri (@$uris) {
238 $lei->{-current_url} = $uri->as_string;
239 $lei->{-nr_remote_eml} = 0;
240 $uri->query_form(@qform);
241 my $cmd = $curl->for_uri($lei, $uri);
242 $lei->qerr("# $cmd");
243 my ($fh, $pid) = popen_rd($cmd, $env, $rdr);
244 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
245 $fh = IO::Uncompress::Gunzip->new($fh);
246 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
248 my $err = waitpid($pid, 0) == $pid ? undef
249 : "BUG: waitpid($cmd): $!";
250 @$reap_curl = (); # cancel OnDestroy
253 my $nr = $lei->{-nr_remote_eml};
254 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
259 seek($cerr, 0, SEEK_SET) or
260 $lei->err("seek($cmd stderr): $!");
261 $err = do { local $/; <$cerr> } //
262 "read($cmd stderr): $!";
263 truncate($cerr, 0) or
264 $lei->err("truncate($cmd stderr): $!");
266 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
267 $uri->query_form(q => $lei->{mset_opt}->{qstr});
268 $lei->child_error($?, "E: <$uri> $err");
271 $lei->{ovv}->ovv_atexit_child($lei);
274 # called by LeiOverview::each_smsg_cb
275 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
280 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
281 for my $ibxish (locals($self)) {
282 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
283 $seen{$d} //= push @dirs, "$d/objects\n"
285 my $git_dir = $tmp->dirname;
286 PublicInbox::Import::init_bare($git_dir);
287 my $f = "$git_dir/objects/info/alternates";
288 open my $alt, '>', $f or die "open($f): $!";
289 print $alt @dirs or die "print $f: $!";
290 close $alt or die "close $f: $!";
291 my $git = PublicInbox::Git->new($git_dir);
296 sub xsearch_done_wait { # dwaitpid callback
297 my ($arg, $pid) = @_;
298 my ($wq, $lei) = @$arg;
299 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
302 sub query_done { # EOF callback for main daemon
304 my $l2m = delete $lei->{l2m};
305 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
306 if (my $lxs = delete $lei->{lxs}) {
307 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
309 $lei->{ovv}->ovv_end($lei);
310 if ($l2m) { # close() calls LeiToMail reap_compress
311 if (my $out = delete $lei->{old_1}) {
312 if (my $mbout = $lei->{1}) {
313 close($mbout) or return $lei->fail(<<"");
314 Error closing $lei->{ovv}->{dst}: $!
319 $l2m->lock_free ? $l2m->poke_dst : $lei->start_mua;
321 $lei->{-progress} and
322 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
326 sub do_post_augment {
328 my $l2m = $lei->{l2m};
331 eval { $l2m->post_augment($lei) };
334 if (my $lxs = delete $lei->{lxs}) {
336 $lxs->wq_close(0, undef, $lei);
341 if (!$err && delete $lei->{early_mua}) { # non-augment case
344 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
347 my $MAX_PER_HOST = 4;
350 my ($self, $opt) = @_;
351 my $nl = $opt->{threads} ? locals($self) : 1;
352 my $nr = remotes($self);
353 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
357 sub start_query { # always runs in main (lei-daemon) process
358 my ($self, $lei) = @_;
359 if ($lei->{opt}->{threads}) {
360 for my $ibxish (locals($self)) {
361 $self->wq_io_do('query_thread_mset', [], $ibxish);
363 } elsif (locals($self)) {
364 $self->wq_io_do('query_mset', []);
368 for my $uri (remotes($self)) {
369 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
372 $self->wq_io_do('query_remote_mboxrd', [], $uris);
376 sub ipc_atfork_child {
378 $self->{lei}->lei_atfork_child;
379 $self->SUPER::ipc_atfork_child;
382 sub query_prepare { # called by wq_io_do
384 local $0 = "$0 query_prepare";
385 my $lei = $self->{lei};
386 eval { $lei->{l2m}->do_augment($lei) };
387 $lei->fail($@) if $@;
388 pkt_do($lei->{pkt_op_p}, '.') == 1 or die "do_post_augment trigger: $!"
392 my ($self, $lei) = @_;
394 '|' => [ $lei->can('sigpipe_handler'), $lei ],
395 '!' => [ $lei->can('fail_handler'), $lei ],
396 '.' => [ \&do_post_augment, $lei ],
397 '' => [ \&query_done, $lei ],
398 'mset_progress' => [ \&mset_progress, $lei ],
399 'x_it' => [ $lei->can('x_it'), $lei ],
400 'child_error' => [ $lei->can('child_error'), $lei ],
402 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
403 $lei->{1}->autoflush(1);
404 $lei->start_pager if delete $lei->{need_pager};
405 $lei->{ovv}->ovv_begin($lei);
406 my $l2m = $lei->{l2m};
408 $l2m->pre_augment($lei);
409 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
412 $l2m->wq_workers_start('lei2mail', $l2m->{jobs},
413 $lei->oldset, { lei => $lei });
414 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
416 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
418 if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
419 # lei->{git_tmp} is set for wq_wait_old so we don't
420 # delete until all lei2mail + lei_xsearch workers are reaped
421 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
423 $self->wq_workers_start('lei_xsearch', $self->{jobs},
424 $lei->oldset, { lei => $lei });
425 my $op = delete $lei->{pkt_op_c};
426 delete $lei->{pkt_op_p};
427 $l2m->wq_close(1) if $l2m;
428 $lei->event_step_init; # wait for shutdowns
429 $self->wq_io_do('query_prepare', []) if $l2m; # for augment/dedupe
430 start_query($self, $lei);
431 $self->wq_close(1); # lei_xsearch workers stop when done
432 if ($lei->{oneshot}) {
433 while ($op->{sock}) { $op->event_step }
438 my ($self, $uri) = @_;
439 if (my $curl = $self->{curl} //= which('curl') // 0) {
440 require PublicInbox::MboxReader;
441 require IO::Uncompress::Gunzip;
442 require PublicInbox::LeiCurl;
443 push @{$self->{remotes}}, $uri;
445 warn "curl missing, ignoring $uri\n";
449 sub prepare_external {
450 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
451 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
452 return add_uri($self, $loc) if $loc->can('scheme');
453 } elsif ($loc =~ m!\Ahttps?://!) {
455 return add_uri($self, URI->new($loc));
456 } elsif (-f "$loc/ei.lock") {
457 require PublicInbox::ExtSearch;
458 $loc = PublicInbox::ExtSearch->new($loc);
459 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
460 require PublicInbox::Inbox; # v2, v1
461 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
463 warn "W: ignoring $loc, unable to determine type\n";
466 push @{$self->{locals}}, $loc;