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
67 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
71 my ($self, $mitem) = @_;
72 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
73 my $nshard = $self->{nshard};
74 my $docid = $mitem->get_docid;
75 my $shard = ($docid - 1) % $nshard;
76 my $num = int(($docid - 1) / $nshard) + 1;
77 my $ibx = $self->{shard2ibx}->[$shard];
78 my $smsg = $ibx->over->get_art($num);
79 if (ref($ibx->can('msg_keywords'))) {
80 my $kw = xap_terms('K', $mitem->get_document);
81 $smsg->{kw} = [ sort keys %$kw ];
83 $smsg->{docid} = $docid;
88 my ($self, $qstr, $opt) = @_;
90 $opt->{relevance} //= -2;
91 $self->mset($qstr //= 'bytes:1..', $opt);
98 my $size = $mset->size;
99 $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
102 # $startq will EOF when do_augment is done augmenting and allow
103 # query_mset and query_thread_mset to proceed.
104 sub wait_startq ($) {
106 my $startq = delete $lei->{startq} or return;
108 my $n = sysread($startq, my $do_augment_done, 1);
110 return if $n == 0; # no MUA
111 if ($do_augment_done eq 'q') {
112 $lei->{opt}->{quiet} = 1;
113 delete $lei->{opt}->{verbose};
114 delete $lei->{-progress};
116 $lei->fail("$$ WTF `$do_augment_done'");
120 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
126 return if $lei->{early_mua} || !$lei->{-progress};
127 if ($lei->{pkt_op_p}) {
128 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
129 } else { # single lei-daemon consumer
130 my ($desc, $mset_size, $mset_total_est) = @_;
131 $lei->{-mset_total} += $mset_size;
132 $lei->qerr("# $desc $mset_size/$mset_total_est");
136 sub query_thread_mset { # for --threads
137 my ($self, $ibxish) = @_;
138 local $0 = "$0 query_thread_mset";
139 my $lei = $self->{lei};
140 my ($srch, $over) = ($ibxish->search, $ibxish->over);
141 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
142 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
143 my $mo = { %{$lei->{mset_opt}} };
145 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
147 $mset = $srch->mset($mo->{qstr}, $mo);
148 mset_progress($lei, $desc, $mset->size,
149 $mset->get_matches_estimated);
150 my $ids = $srch->mset_to_artnums($mset, $mo);
151 my $ctx = { ids => $ids };
153 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
154 while ($over->expand_thread($ctx)) {
155 for my $n (@{$ctx->{xids}}) {
156 my $smsg = $over->get_art($n) or next;
158 my $mitem = delete $n2item{$smsg->{num}};
159 $each_smsg->($smsg, $mitem);
161 @{$ctx->{xids}} = ();
163 } while (_mset_more($mset, $mo));
164 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
165 $lei->{ovv}->ovv_atexit_child($lei);
168 sub query_mset { # non-parallel for non-"--threads" users
170 local $0 = "$0 query_mset";
171 my $lei = $self->{lei};
172 my $mo = { %{$lei->{mset_opt}} };
174 for my $loc (locals($self)) {
175 attach_external($self, $loc);
177 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
179 $mset = $self->mset($mo->{qstr}, $mo);
180 mset_progress($lei, 'xsearch', $mset->size,
181 $mset->size, $mset->get_matches_estimated);
182 for my $mitem ($mset->items) {
183 my $smsg = smsg_for($self, $mitem) or next;
185 $each_smsg->($smsg, $mitem);
187 } while (_mset_more($mset, $mo));
188 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
189 $lei->{ovv}->ovv_atexit_child($lei);
192 sub each_eml { # callback for MboxReader->mboxrd
193 my ($eml, $self, $lei, $each_smsg) = @_;
194 my $smsg = bless {}, 'PublicInbox::Smsg';
195 $smsg->populate($eml);
196 $smsg->parse_references($eml, mids($eml));
197 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
198 delete @$smsg{qw(From Subject -ds -ts)};
200 if ($lei->{-progress}) {
201 ++$lei->{-nr_remote_eml};
203 my $next = $lei->{-next_progress} //= ($now + 1);
205 $lei->{-next_progress} = $now + 1;
206 my $nr = $lei->{-nr_remote_eml};
207 $lei->err("# $lei->{-current_url} $nr/?");
210 $each_smsg->($smsg, undef, $eml);
213 sub query_remote_mboxrd {
214 my ($self, $uris) = @_;
215 local $0 = "$0 query_remote_mboxrd";
216 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
217 my $lei = $self->{lei};
218 my ($opt, $env) = @$lei{qw(opt env)};
219 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
220 push(@qform, t => 1) if $opt->{threads};
221 my $verbose = $opt->{verbose};
222 my ($reap_tail, $reap_curl);
223 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
224 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
225 my $rdr = { 2 => $cerr, pgid => 0 };
226 my $sigint_reap = $lei->can('sigint_reap');
228 # spawn a process to force line-buffering, otherwise curl
229 # will write 1 character at-a-time and parallel outputs
230 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
231 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
232 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
233 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
235 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
236 push @$curl, '-s', '-d', '';
237 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
238 for my $uri (@$uris) {
239 $lei->{-current_url} = $uri->as_string;
240 $lei->{-nr_remote_eml} = 0;
241 $uri->query_form(@qform);
242 my $cmd = $curl->for_uri($lei, $uri);
243 $lei->qerr("# $cmd");
244 my ($fh, $pid) = popen_rd($cmd, $env, $rdr);
245 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
246 $fh = IO::Uncompress::Gunzip->new($fh);
247 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
249 my $err = waitpid($pid, 0) == $pid ? undef
250 : "BUG: waitpid($cmd): $!";
251 @$reap_curl = (); # cancel OnDestroy
254 my $nr = $lei->{-nr_remote_eml};
255 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
260 seek($cerr, 0, SEEK_SET) or
261 $lei->err("seek($cmd stderr): $!");
262 $err = do { local $/; <$cerr> } //
263 "read($cmd stderr): $!";
264 truncate($cerr, 0) or
265 $lei->err("truncate($cmd stderr): $!");
267 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
268 $uri->query_form(q => $lei->{mset_opt}->{qstr});
269 $lei->child_error($?, "E: <$uri> $err");
272 $lei->{ovv}->ovv_atexit_child($lei);
275 # called by LeiOverview::each_smsg_cb
276 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
281 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
282 for my $ibxish (locals($self)) {
283 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
284 $seen{$d} //= push @dirs, "$d/objects\n"
286 my $git_dir = $tmp->dirname;
287 PublicInbox::Import::init_bare($git_dir);
288 my $f = "$git_dir/objects/info/alternates";
289 open my $alt, '>', $f or die "open($f): $!";
290 print $alt @dirs or die "print $f: $!";
291 close $alt or die "close $f: $!";
292 my $git = PublicInbox::Git->new($git_dir);
297 sub xsearch_done_wait { # dwaitpid callback
298 my ($arg, $pid) = @_;
299 my ($wq, $lei) = @$arg;
300 $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
303 sub query_done { # EOF callback for main daemon
305 my $l2m = delete $lei->{l2m};
306 $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
307 if (my $lxs = delete $lei->{lxs}) {
308 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
310 $lei->{ovv}->ovv_end($lei);
311 if ($l2m) { # close() calls LeiToMail reap_compress
312 if (my $out = delete $lei->{old_1}) {
313 if (my $mbout = $lei->{1}) {
314 close($mbout) or return $lei->fail(<<"");
315 Error closing $lei->{ovv}->{dst}: $!
320 if ($l2m->lock_free) {
323 } else { # mbox users
327 $lei->{-progress} and
328 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
332 sub do_post_augment {
334 my $l2m = $lei->{l2m};
337 eval { $l2m->post_augment($lei) };
340 if (my $lxs = delete $lei->{lxs}) {
342 $lxs->wq_close(0, undef, $lei);
347 if (!$err && delete $lei->{early_mua}) { # non-augment case
350 close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
353 my $MAX_PER_HOST = 4;
356 my ($self, $opt) = @_;
357 my $nl = $opt->{threads} ? locals($self) : 1;
358 my $nr = remotes($self);
359 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
363 sub start_query { # always runs in main (lei-daemon) process
364 my ($self, $lei) = @_;
365 if ($lei->{opt}->{threads}) {
366 for my $ibxish (locals($self)) {
367 $self->wq_io_do('query_thread_mset', [], $ibxish);
369 } elsif (locals($self)) {
370 $self->wq_io_do('query_mset', []);
374 for my $uri (remotes($self)) {
375 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
378 $self->wq_io_do('query_remote_mboxrd', [], $uris);
382 sub ipc_atfork_child {
384 $self->{lei}->lei_atfork_child;
385 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
386 $self->SUPER::ipc_atfork_child;
390 my ($self, $lei) = @_;
392 '|' => [ $lei->can('sigpipe_handler'), $lei ],
393 '!' => [ $lei->can('fail_handler'), $lei ],
394 '.' => [ \&do_post_augment, $lei ],
395 '' => [ \&query_done, $lei ],
396 'mset_progress' => [ \&mset_progress, $lei ],
397 'x_it' => [ $lei->can('x_it'), $lei ],
398 'child_error' => [ $lei->can('child_error'), $lei ],
400 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
401 $lei->{1}->autoflush(1);
402 $lei->start_pager if delete $lei->{need_pager};
403 $lei->{ovv}->ovv_begin($lei);
404 my $l2m = $lei->{l2m};
406 $l2m->pre_augment($lei);
407 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
410 $l2m->wq_workers_start('lei2mail', undef,
411 $lei->oldset, { lei => $lei });
412 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
414 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
416 if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
417 # lei->{git_tmp} is set for wq_wait_old so we don't
418 # delete until all lei2mail + lei_xsearch workers are reaped
419 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
421 $self->wq_workers_start('lei_xsearch', undef,
422 $lei->oldset, { lei => $lei });
423 my $op = delete $lei->{pkt_op_c};
424 delete $lei->{pkt_op_p};
425 $l2m->wq_close(1) if $l2m;
426 $lei->event_step_init; # wait for shutdowns
427 start_query($self, $lei);
428 $self->wq_close(1); # lei_xsearch workers stop when done
429 if ($lei->{oneshot}) {
430 while ($op->{sock}) { $op->event_step }
435 my ($self, $uri) = @_;
436 if (my $curl = $self->{curl} //= which('curl') // 0) {
437 require PublicInbox::MboxReader;
438 require IO::Uncompress::Gunzip;
439 require PublicInbox::LeiCurl;
440 push @{$self->{remotes}}, $uri;
442 warn "curl missing, ignoring $uri\n";
446 sub prepare_external {
447 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
448 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
449 return add_uri($self, $loc) if $loc->can('scheme');
450 } elsif ($loc =~ m!\Ahttps?://!) {
452 return add_uri($self, URI->new($loc));
453 } elsif (-f "$loc/ei.lock") {
454 require PublicInbox::ExtSearch;
455 $loc = PublicInbox::ExtSearch->new($loc);
456 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
457 require PublicInbox::Inbox; # v2, v1
458 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
460 warn "W: ignoring $loc, unable to determine type\n";
463 push @{$self->{locals}}, $loc;