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(dwaitpid);
12 use PublicInbox::PktOp;
13 use PublicInbox::Import;
14 use File::Temp 0.19 (); # 0.19 for ->newdir
16 use Socket qw(MSG_EOR);
17 use PublicInbox::Search qw(xap_terms);
18 use PublicInbox::Spawn qw(popen_rd spawn which);
19 use PublicInbox::MID qw(mids);
20 use PublicInbox::Smsg;
21 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
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
68 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
72 my ($self, $mitem) = @_;
73 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
74 my $nshard = $self->{nshard};
75 my $docid = $mitem->get_docid;
76 my $shard = ($docid - 1) % $nshard;
77 my $num = int(($docid - 1) / $nshard) + 1;
78 my $ibx = $self->{shard2ibx}->[$shard];
79 my $smsg = $ibx->over->get_art($num);
80 if (ref($ibx->can('msg_keywords'))) {
81 my $kw = xap_terms('K', $mitem->get_document);
82 $smsg->{kw} = [ sort keys %$kw ];
84 $smsg->{docid} = $docid;
89 my ($self, $qstr, $opt) = @_;
91 $opt->{relevance} //= -2;
92 $self->mset($qstr //= 'bytes:1..', $opt);
99 my $size = $mset->size;
100 $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
103 # $startq will EOF when query_prepare is done augmenting and allow
104 # query_mset and query_thread_mset to proceed.
105 sub wait_startq ($) {
108 read($startq, my $query_prepare_done, 1);
111 sub query_thread_mset { # for --thread
112 my ($self, $lei, $ibxish) = @_;
113 local $0 = "$0 query_thread_mset";
114 $lei->atfork_child_wq($self);
115 my $startq = delete $lei->{startq};
117 my ($srch, $over) = ($ibxish->search, $ibxish->over);
118 unless ($srch && $over) {
119 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
120 warn "$desc not indexed by Xapian\n";
123 my $mo = { %{$lei->{mset_opt}} };
125 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
127 $mset = $srch->mset($mo->{qstr}, $mo);
128 my $ids = $srch->mset_to_artnums($mset, $mo);
129 my $ctx = { ids => $ids };
131 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
132 while ($over->expand_thread($ctx)) {
133 for my $n (@{$ctx->{xids}}) {
134 my $smsg = $over->get_art($n) or next;
135 wait_startq($startq) if $startq;
136 my $mitem = delete $n2item{$smsg->{num}};
137 $each_smsg->($smsg, $mitem);
139 @{$ctx->{xids}} = ();
141 } while (_mset_more($mset, $mo));
142 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
143 $lei->{ovv}->ovv_atexit_child($lei);
146 sub query_mset { # non-parallel for non-"--thread" users
147 my ($self, $lei) = @_;
148 local $0 = "$0 query_mset";
149 $lei->atfork_child_wq($self);
150 my $startq = delete $lei->{startq};
151 my $mo = { %{$lei->{mset_opt}} };
153 for my $loc (locals($self)) {
154 attach_external($self, $loc);
156 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
158 $mset = $self->mset($mo->{qstr}, $mo);
159 for my $mitem ($mset->items) {
160 my $smsg = smsg_for($self, $mitem) or next;
161 wait_startq($startq) if $startq;
162 $each_smsg->($smsg, $mitem);
164 } while (_mset_more($mset, $mo));
165 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
166 $lei->{ovv}->ovv_atexit_child($lei);
169 sub each_eml { # callback for MboxReader->mboxrd
170 my ($eml, $self, $lei, $each_smsg) = @_;
171 my $smsg = bless {}, 'PublicInbox::Smsg';
172 $smsg->populate($eml);
173 $smsg->parse_references($eml, mids($eml));
174 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
175 delete @$smsg{qw(From Subject -ds -ts)};
176 if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
177 $each_smsg->($smsg, undef, $eml);
180 # PublicInbox::OnDestroy callback
183 kill('KILL', $pid); # spawn() blocks other signals
187 sub query_remote_mboxrd {
188 my ($self, $lei, $uris) = @_;
189 local $0 = "$0 query_remote_mboxrd";
190 $lei->atfork_child_wq($self);
191 my ($opt, $env) = @$lei{qw(opt env)};
192 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
193 push(@qform, t => 1) if $opt->{thread};
194 my @cmd = ($self->{curl}, qw(-sSf -d), '');
195 my $verbose = $opt->{verbose};
197 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
198 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
199 my $rdr = { 2 => $cerr };
202 # spawn a process to force line-buffering, otherwise curl
203 # will write 1 character at-a-time and parallel outputs
204 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
206 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
207 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
208 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
210 for my $o ($lei->curl_opt) {
211 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
212 if ($o =~ s/=[is]@\z//) {
213 my $ary = $opt->{$o} or next;
214 push @cmd, map { ("--$o", $_) } @$ary;
215 } elsif ($o =~ s/=[is]\z//) {
216 my $val = $opt->{$o} // next;
217 push @cmd, "--$o", $val;
218 } elsif ($opt->{$o}) {
222 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
223 my $tor = $opt->{torsocks} //= 'auto';
224 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
225 for my $uri (@$uris) {
226 $uri->query_form(@qform);
227 my $cmd = [ @cmd, $uri->as_string ];
228 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
229 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
230 unshift @$cmd, which('torsocks');
231 } elsif (PublicInbox::Config::git_bool($tor)) {
232 unshift @$cmd, which('torsocks');
235 # continue anyways if torsocks is missing; a proxy may be
236 # specified via CLI, curlrc, environment variable, or even
238 shift(@$cmd) if !$cmd->[0];
240 $lei->err("# @$cmd") if $verbose;
242 my $fh = popen_rd($cmd, $env, $rdr);
243 $fh = IO::Uncompress::Gunzip->new($fh);
245 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
248 return $lei->fail("E: @$cmd: $@") if $@;
250 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
251 my $e = do { local $/; <$cerr> } //
252 die "read(curl stderr): $!\n";
254 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
255 $lei->child_error($?);
256 $uri->query_form(q => $lei->{mset_opt}->{qstr});
257 # --verbose already showed the error via tail(1)
258 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
261 $lei->{ovv}->ovv_atexit_child($lei);
267 my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
268 for my $ibx (@{$self->{shard2ibx} // []}) {
269 my $d = File::Spec->canonpath($ibx->git->{git_dir});
270 $seen{$d} //= push @dirs, "$d/objects\n"
272 my $git_dir = $tmp->dirname;
273 PublicInbox::Import::init_bare($git_dir);
274 my $f = "$git_dir/objects/info/alternates";
275 open my $alt, '>', $f or die "open($f): $!";
276 print $alt @dirs or die "print $f: $!";
277 close $alt or die "close $f: $!";
278 my $git = PublicInbox::Git->new($git_dir);
283 sub query_done { # EOF callback
285 my $has_l2m = exists $lei->{l2m};
286 for my $f (qw(lxs l2m)) {
287 my $wq = delete $lei->{$f} or next;
288 $wq->wq_wait_old($lei);
290 $lei->{ovv}->ovv_end($lei);
291 if ($has_l2m) { # close() calls LeiToMail reap_compress
292 if (my $out = delete $lei->{old_1}) {
293 if (my $mbout = $lei->{1}) {
294 close($mbout) or return $lei->fail(<<"");
295 Error closing $lei->{ovv}->{dst}: $!
305 sub do_post_augment {
306 my ($lei, $zpipe, $au_done) = @_;
307 my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
308 eval { $l2m->post_augment($lei, $zpipe) };
310 if (my $lxs = delete $lei->{lxs}) {
316 close $au_done; # triggers wait_startq
319 my $MAX_PER_HOST = 4;
320 sub MAX_PER_HOST { $MAX_PER_HOST }
323 my ($self, $opt) = @_;
324 my $nl = $opt->{thread} ? locals($self) : 1;
325 my $nr = remotes($self);
326 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
330 sub start_query { # always runs in main (lei-daemon) process
331 my ($self, $io, $lei) = @_;
332 if ($lei->{opt}->{thread}) {
333 for my $ibxish (locals($self)) {
334 $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
336 } elsif (locals($self)) {
337 $self->wq_do('query_mset', $io, $lei);
341 for my $uri (remotes($self)) {
342 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
345 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
350 sub query_prepare { # called by wq_do
351 my ($self, $lei) = @_;
352 local $0 = "$0 query_prepare";
353 $lei->atfork_child_wq($self);
354 delete $lei->{l2m}->{-wq_s1};
355 eval { $lei->{l2m}->do_augment($lei) };
356 $lei->fail($@) if $@;
357 send($lei->{pkt_op}, '.', MSG_EOR) == 1 or
358 die "do_post_augment trigger: $!"
361 sub fail_handler ($;$$) {
362 my ($lei, $code, $io) = @_;
363 if (my $lxs = delete $lei->{lxs}) {
364 $lxs->wq_wait_old($lei) if $lxs->wq_kill_old; # lei-daemon
366 close($io) if $io; # needed to avoid warnings on SIGPIPE
367 $lei->x_it($code // (1 >> 8));
370 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
371 fail_handler($_[0], 13, delete $_[0]->{1});
375 my ($self, $lei) = @_;
376 $lei->{1}->autoflush(1);
377 my ($au_done, $zpipe);
378 my $l2m = $lei->{l2m};
380 pipe($lei->{startq}, $au_done) or die "pipe: $!";
382 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
383 $zpipe = $l2m->pre_augment($lei);
385 my $in_loop = exists $lei->{sock};
387 '|' => [ \&sigpipe_handler, $lei ],
388 '!' => [ \&fail_handler, $lei ],
389 '.' => [ \&do_post_augment, $lei, $zpipe, $au_done ],
390 '' => [ \&query_done, $lei ],
392 (my $op, $lei->{pkt_op}) = PublicInbox::PktOp->pair($ops, $in_loop);
393 my ($lei_ipc, @io) = $lei->atfork_parent_wq($self);
394 delete($lei->{pkt_op});
396 $lei->event_step_init; # wait for shutdowns
398 $self->wq_do('query_prepare', \@io, $lei_ipc);
399 $io[1] = $zpipe->[1] if $zpipe;
401 start_query($self, \@io, $lei_ipc);
404 # for the $lei_ipc->atfork_child_wq PIPE handler:
405 while ($op->{sock}) { $op->event_step }
410 my ($self, $uri) = @_;
411 if (my $curl = $self->{curl} //= which('curl') // 0) {
412 require PublicInbox::MboxReader;
413 require IO::Uncompress::Gunzip;
414 push @{$self->{remotes}}, $uri;
416 warn "curl missing, ignoring $uri\n";
420 sub prepare_external {
421 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
422 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
423 return add_uri($self, $loc) if $loc->can('scheme');
424 } elsif ($loc =~ m!\Ahttps?://!) {
426 return add_uri($self, URI->new($loc));
427 } elsif (-f "$loc/ei.lock") {
428 require PublicInbox::ExtSearch;
429 $loc = PublicInbox::ExtSearch->new($loc);
430 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
431 require PublicInbox::Inbox; # v2, v1
432 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
434 warn "W: ignoring $loc, unable to determine type\n";
437 push @{$self->{locals}}, $loc;