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 ($) {
106 read($startq, my $query_prepare_done, 1);
111 return unless $lei->{-progress};
112 if ($lei->{pkt_op_p}) {
113 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
114 } else { # single lei-daemon consumer
115 my ($desc, $mset_size, $mset_total_est) = @_;
116 $lei->{-mset_total} += $mset_size;
117 $lei->err("# $desc $mset_size/$mset_total_est");
121 sub query_thread_mset { # for --thread
122 my ($self, $ibxish) = @_;
123 local $0 = "$0 query_thread_mset";
124 my $lei = $self->{lei};
125 my $startq = delete $lei->{startq};
126 my ($srch, $over) = ($ibxish->search, $ibxish->over);
127 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
128 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
129 my $mo = { %{$lei->{mset_opt}} };
131 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
133 $mset = $srch->mset($mo->{qstr}, $mo);
134 mset_progress($lei, $desc, $mset->size,
135 $mset->get_matches_estimated);
136 my $ids = $srch->mset_to_artnums($mset, $mo);
137 my $ctx = { ids => $ids };
139 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
140 while ($over->expand_thread($ctx)) {
141 for my $n (@{$ctx->{xids}}) {
142 my $smsg = $over->get_art($n) or next;
143 wait_startq($startq) if $startq;
144 my $mitem = delete $n2item{$smsg->{num}};
145 $each_smsg->($smsg, $mitem);
147 @{$ctx->{xids}} = ();
149 } while (_mset_more($mset, $mo));
150 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
151 $lei->{ovv}->ovv_atexit_child($lei);
154 sub query_mset { # non-parallel for non-"--thread" users
156 local $0 = "$0 query_mset";
157 my $lei = $self->{lei};
158 my $startq = delete $lei->{startq};
159 my $mo = { %{$lei->{mset_opt}} };
161 for my $loc (locals($self)) {
162 attach_external($self, $loc);
164 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
166 $mset = $self->mset($mo->{qstr}, $mo);
167 mset_progress($lei, 'xsearch', $mset->size,
168 $mset->size, $mset->get_matches_estimated);
169 for my $mitem ($mset->items) {
170 my $smsg = smsg_for($self, $mitem) or next;
171 wait_startq($startq) if $startq;
172 $each_smsg->($smsg, $mitem);
174 } while (_mset_more($mset, $mo));
175 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
176 $lei->{ovv}->ovv_atexit_child($lei);
179 sub each_eml { # callback for MboxReader->mboxrd
180 my ($eml, $self, $lei, $each_smsg) = @_;
181 my $smsg = bless {}, 'PublicInbox::Smsg';
182 $smsg->populate($eml);
183 $smsg->parse_references($eml, mids($eml));
184 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
185 delete @$smsg{qw(From Subject -ds -ts)};
186 if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
187 if ($lei->{-progress}) {
188 ++$lei->{-nr_remote_eml};
190 my $next = $lei->{-next_progress} //= ($now + 1);
192 $lei->{-next_progress} = $now + 1;
193 my $nr = $lei->{-nr_remote_eml};
194 $lei->err("# $lei->{-current_url} $nr/?");
197 $each_smsg->($smsg, undef, $eml);
200 # PublicInbox::OnDestroy callback
203 kill('KILL', $pid); # spawn() blocks other signals
207 sub query_remote_mboxrd {
208 my ($self, $uris) = @_;
209 local $0 = "$0 query_remote_mboxrd";
210 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
211 my $lei = $self->{lei};
212 my ($opt, $env) = @$lei{qw(opt env)};
213 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
214 push(@qform, t => 1) if $opt->{thread};
215 my $verbose = $opt->{verbose};
217 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
218 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
219 my $rdr = { 2 => $cerr };
222 # spawn a process to force line-buffering, otherwise curl
223 # will write 1 character at-a-time and parallel outputs
224 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
225 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
226 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
227 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
229 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
230 push @$curl, '-s', '-d', '';
231 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
232 for my $uri (@$uris) {
233 $lei->{-current_url} = $uri->as_string;
234 $lei->{-nr_remote_eml} = 0;
235 $uri->query_form(@qform);
236 my $cmd = $curl->for_uri($lei, $uri);
237 $lei->err("# @$cmd") if $verbose;
238 my ($fh, $pid) = popen_rd($cmd, $env, $rdr);
239 $fh = IO::Uncompress::Gunzip->new($fh);
240 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
242 waitpid($pid, 0) == $pid or die "BUG: waitpid (curl): $!";
244 my $nr = $lei->{-nr_remote_eml};
245 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
248 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
249 my $e = do { local $/; <$cerr> } //
250 die "read(curl stderr): $!\n";
253 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
254 $lei->child_error($?);
255 $uri->query_form(q => $lei->{mset_opt}->{qstr});
256 # --verbose already showed the error via tail(1)
257 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
260 $lei->{ovv}->ovv_atexit_child($lei);
263 # called by LeiOverview::each_smsg_cb
264 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
269 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
270 for my $ibxish (locals($self)) {
271 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
272 $seen{$d} //= push @dirs, "$d/objects\n"
274 my $git_dir = $tmp->dirname;
275 PublicInbox::Import::init_bare($git_dir);
276 my $f = "$git_dir/objects/info/alternates";
277 open my $alt, '>', $f or die "open($f): $!";
278 print $alt @dirs or die "print $f: $!";
279 close $alt or die "close $f: $!";
280 my $git = PublicInbox::Git->new($git_dir);
285 sub query_done { # EOF callback for main daemon
287 my $l2m = delete $lei->{l2m};
288 $l2m->wq_wait_old($lei) if $l2m;
289 if (my $lxs = delete $lei->{lxs}) {
290 $lxs->wq_wait_old($lei);
292 $lei->{ovv}->ovv_end($lei);
293 if ($l2m) { # close() calls LeiToMail reap_compress
294 if (my $out = delete $lei->{old_1}) {
295 if (my $mbout = $lei->{1}) {
296 close($mbout) or return $lei->fail(<<"");
297 Error closing $lei->{ovv}->{dst}: $!
302 $l2m->lock_free ? $l2m->poke_dst : $lei->start_mua;
304 $lei->{-progress} and
305 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
309 sub do_post_augment {
311 eval { $lei->{l2m}->post_augment($lei) };
313 if (my $lxs = delete $lei->{lxs}) {
319 close(delete $lei->{au_done}); # triggers wait_startq
322 my $MAX_PER_HOST = 4;
325 my ($self, $opt) = @_;
326 my $nl = $opt->{thread} ? locals($self) : 1;
327 my $nr = remotes($self);
328 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
332 sub start_query { # always runs in main (lei-daemon) process
333 my ($self, $lei) = @_;
334 if (my $l2m = $lei->{l2m}) {
335 $lei->start_mua if $l2m->lock_free;
337 if ($lei->{opt}->{thread}) {
338 for my $ibxish (locals($self)) {
339 $self->wq_do('query_thread_mset', [], $ibxish);
341 } elsif (locals($self)) {
342 $self->wq_do('query_mset', []);
346 for my $uri (remotes($self)) {
347 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
350 $self->wq_do('query_remote_mboxrd', [], $uris);
354 sub ipc_atfork_child {
356 $self->{lei}->lei_atfork_child;
357 $self->SUPER::ipc_atfork_child;
360 sub query_prepare { # called by wq_do
362 local $0 = "$0 query_prepare";
363 my $lei = $self->{lei};
364 eval { $lei->{l2m}->do_augment($lei) };
365 $lei->fail($@) if $@;
366 pkt_do($lei->{pkt_op_p}, '.') == 1 or die "do_post_augment trigger: $!"
370 my ($self, $lei) = @_;
372 '|' => [ $lei->can('sigpipe_handler'), $lei ],
373 '!' => [ $lei->can('fail_handler'), $lei ],
374 '.' => [ \&do_post_augment, $lei ],
375 '' => [ \&query_done, $lei ],
376 'mset_progress' => [ \&mset_progress, $lei ],
377 'x_it' => [ $lei->can('x_it'), $lei ],
378 'child_error' => [ $lei->can('child_error'), $lei ],
380 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
381 $lei->{1}->autoflush(1);
382 $lei->start_pager if delete $lei->{need_pager};
383 $lei->{ovv}->ovv_begin($lei);
384 my $l2m = $lei->{l2m};
386 $l2m->pre_augment($lei);
387 $l2m->wq_workers_start('lei2mail', $l2m->{jobs},
388 $lei->oldset, { lei => $lei });
389 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
391 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
393 if (!$lei->{opt}->{thread} && locals($self)) { # for query_mset
394 # lei->{git_tmp} is set for wq_wait_old so we don't
395 # delete until all lei2mail + lei_xsearch workers are reaped
396 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
398 $self->wq_workers_start('lei_xsearch', $self->{jobs},
399 $lei->oldset, { lei => $lei });
400 my $op = delete $lei->{pkt_op_c};
401 delete $lei->{pkt_op_p};
402 $l2m->wq_close(1) if $l2m;
403 $lei->event_step_init; # wait for shutdowns
404 $self->wq_do('query_prepare', []) if $l2m;
405 start_query($self, $lei);
406 $self->wq_close(1); # lei_xsearch workers stop when done
407 if ($lei->{oneshot}) {
408 while ($op->{sock}) { $op->event_step }
413 my ($self, $uri) = @_;
414 if (my $curl = $self->{curl} //= which('curl') // 0) {
415 require PublicInbox::MboxReader;
416 require IO::Uncompress::Gunzip;
417 require PublicInbox::LeiCurl;
418 push @{$self->{remotes}}, $uri;
420 warn "curl missing, ignoring $uri\n";
424 sub prepare_external {
425 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
426 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
427 return add_uri($self, $loc) if $loc->can('scheme');
428 } elsif ($loc =~ m!\Ahttps?://!) {
430 return add_uri($self, URI->new($loc));
431 } elsif (-f "$loc/ei.lock") {
432 require PublicInbox::ExtSearch;
433 $loc = PublicInbox::ExtSearch->new($loc);
434 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
435 require PublicInbox::Inbox; # v2, v1
436 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
438 warn "W: ignoring $loc, unable to determine type\n";
441 push @{$self->{locals}}, $loc;