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::OpPipe;
13 use PublicInbox::Import;
14 use File::Temp 0.19 (); # 0.19 for ->newdir
16 use PublicInbox::Search qw(xap_terms);
17 use PublicInbox::Spawn qw(popen_rd spawn which);
18 use PublicInbox::MID qw(mids);
19 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->{offset} += $size) < ($mo->{limit} // 10000));
102 # $startq will EOF when query_prepare is done augmenting and allow
103 # query_mset and query_thread_mset to proceed.
104 sub wait_startq ($) {
107 read($startq, my $query_prepare_done, 1);
110 sub query_thread_mset { # for --thread
111 my ($self, $lei, $ibxish) = @_;
112 local $0 = "$0 query_thread_mset";
113 $lei->atfork_child_wq($self);
114 my $startq = delete $lei->{startq};
116 my ($srch, $over) = ($ibxish->search, $ibxish->over);
117 unless ($srch && $over) {
118 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
119 warn "$desc not indexed by Xapian\n";
122 my $mo = { %{$lei->{mset_opt}} };
124 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
126 $mset = $srch->mset($mo->{qstr}, $mo);
127 my $ids = $srch->mset_to_artnums($mset, $mo);
128 my $ctx = { ids => $ids };
130 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
131 while ($over->expand_thread($ctx)) {
132 for my $n (@{$ctx->{xids}}) {
133 my $smsg = $over->get_art($n) or next;
134 wait_startq($startq) if $startq;
135 my $mitem = delete $n2item{$smsg->{num}};
136 $each_smsg->($smsg, $mitem);
138 @{$ctx->{xids}} = ();
140 } while (_mset_more($mset, $mo));
141 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
142 $lei->{ovv}->ovv_atexit_child($lei);
145 sub query_mset { # non-parallel for non-"--thread" users
146 my ($self, $lei) = @_;
147 local $0 = "$0 query_mset";
148 $lei->atfork_child_wq($self);
149 my $startq = delete $lei->{startq};
150 my $mo = { %{$lei->{mset_opt}} };
152 for my $loc (locals($self)) {
153 attach_external($self, $loc);
155 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
157 $mset = $self->mset($mo->{qstr}, $mo);
158 for my $mitem ($mset->items) {
159 my $smsg = smsg_for($self, $mitem) or next;
160 wait_startq($startq) if $startq;
161 $each_smsg->($smsg, $mitem);
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 each_eml { # callback for MboxReader->mboxrd
169 my ($eml, $self, $lei, $each_smsg) = @_;
170 my $smsg = bless {}, 'PublicInbox::Smsg';
171 $smsg->populate($eml);
172 $smsg->parse_references($eml, mids($eml));
173 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
174 delete @$smsg{qw(From Subject -ds -ts)};
175 if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
176 $each_smsg->($smsg, undef, $eml);
179 # PublicInbox::OnDestroy callback
182 kill('KILL', $pid); # spawn() blocks other signals
186 sub query_remote_mboxrd {
187 my ($self, $lei, $uris) = @_;
188 local $0 = "$0 query_remote_mboxrd";
189 $lei->atfork_child_wq($self);
190 my ($opt, $env) = @$lei{qw(opt env)};
191 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
192 push(@qform, t => 1) if $opt->{thread};
193 my @cmd = ($self->{curl}, qw(-sSf -d), '');
194 my $verbose = $opt->{verbose};
196 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
197 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
198 my $rdr = { 2 => $cerr };
201 # spawn a process to force line-buffering, otherwise curl
202 # will write 1 character at-a-time and parallel outputs
203 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
205 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
206 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
207 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
209 for my $o ($lei->curl_opt) {
210 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
211 if ($o =~ s/=[is]@\z//) {
212 my $ary = $opt->{$o} or next;
213 push @cmd, map { ("--$o", $_) } @$ary;
214 } elsif ($o =~ s/=[is]\z//) {
215 my $val = $opt->{$o} // next;
216 push @cmd, "--$o", $val;
217 } elsif ($opt->{$o}) {
221 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
222 my $tor = $opt->{torsocks} //= 'auto';
223 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
224 for my $uri (@$uris) {
225 $uri->query_form(@qform);
226 my $cmd = [ @cmd, $uri->as_string ];
227 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
228 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
229 unshift @$cmd, which('torsocks');
230 } elsif (PublicInbox::Config::git_bool($tor)) {
231 unshift @$cmd, which('torsocks');
234 # continue anyways if torsocks is missing; a proxy may be
235 # specified via CLI, curlrc, environment variable, or even
237 shift(@$cmd) if !$cmd->[0];
239 $lei->err("# @$cmd") if $verbose;
241 my $fh = popen_rd($cmd, $env, $rdr);
242 $fh = IO::Uncompress::Gunzip->new($fh);
244 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
247 return $lei->fail("E: @$cmd: $@") if $@;
249 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
250 my $e = do { local $/; <$cerr> } //
251 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);
266 my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
267 for my $ibx (@{$self->{shard2ibx} // []}) {
268 my $d = File::Spec->canonpath($ibx->git->{git_dir});
269 $seen{$d} //= push @dirs, "$d/objects\n"
271 my $git_dir = $tmp->dirname;
272 PublicInbox::Import::init_bare($git_dir);
273 my $f = "$git_dir/objects/info/alternates";
274 open my $alt, '>', $f or die "open($f): $!";
275 print $alt @dirs or die "print $f: $!";
276 close $alt or die "close $f: $!";
277 my $git = PublicInbox::Git->new($git_dir);
282 sub query_done { # EOF callback
284 my $has_l2m = exists $lei->{l2m};
285 for my $f (qw(lxs l2m)) {
286 my $wq = delete $lei->{$f} or next;
287 $wq->wq_wait_old($lei);
289 $lei->{ovv}->ovv_end($lei);
290 if ($has_l2m) { # close() calls LeiToMail reap_compress
291 if (my $out = delete $lei->{old_1}) {
292 if (my $mbout = $lei->{1}) {
293 close($mbout) or return $lei->fail(<<"");
294 Error closing $lei->{ovv}->{dst}: $!
304 sub do_post_augment {
305 my ($lei, $zpipe, $au_done) = @_;
306 my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
307 eval { $l2m->post_augment($lei, $zpipe) };
309 if (my $lxs = delete $lei->{lxs}) {
315 close $au_done; # triggers wait_startq
318 my $MAX_PER_HOST = 4;
319 sub MAX_PER_HOST { $MAX_PER_HOST }
322 my ($self, $opt) = @_;
323 my $nl = $opt->{thread} ? locals($self) : 1;
324 my $nr = remotes($self);
325 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
329 sub start_query { # always runs in main (lei-daemon) process
330 my ($self, $io, $lei) = @_;
331 if ($lei->{opt}->{thread}) {
332 for my $ibxish (locals($self)) {
333 $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
335 } elsif (locals($self)) {
336 $self->wq_do('query_mset', $io, $lei);
340 for my $uri (remotes($self)) {
341 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
344 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
349 sub query_prepare { # called by wq_do
350 my ($self, $lei) = @_;
351 local $0 = "$0 query_prepare";
352 $lei->atfork_child_wq($self);
353 delete $lei->{l2m}->{-wq_s1};
354 eval { $lei->{l2m}->do_augment($lei) };
355 $lei->fail($@) if $@;
356 syswrite($lei->{op_pipe}, '.') == 1 or die "do_post_augment trigger: $!"
359 sub fail_handler ($;$$) {
360 my ($lei, $code, $io) = @_;
361 if (my $lxs = delete $lei->{lxs}) {
362 $lxs->wq_wait_old($lei) if $lxs->wq_kill_old; # lei-daemon
364 close($io) if $io; # needed to avoid warnings on SIGPIPE
365 $lei->x_it($code // (1 >> 8));
368 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
369 fail_handler($_[0], 13, delete $_[0]->{1});
373 my ($self, $lei) = @_;
374 $lei->{1}->autoflush(1);
375 my ($au_done, $zpipe);
376 my $l2m = $lei->{l2m};
378 pipe($lei->{startq}, $au_done) or die "pipe: $!";
380 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
381 $zpipe = $l2m->pre_augment($lei);
383 pipe(my $done, $lei->{op_pipe}) or die "pipe $!";
384 my ($lei_ipc, @io) = $lei->atfork_parent_wq($self);
385 delete($lei->{op_pipe});
387 $lei->event_step_init; # wait for shutdowns
389 '' => [ \&query_done, $lei ],
390 '|' => [ \&sigpipe_handler, $lei ],
391 '!' => [ \&fail_handler, $lei ]
393 my $in_loop = exists $lei->{sock};
394 $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
396 $done_op->{'.'} = [ \&do_post_augment, $lei, $zpipe, $au_done ];
397 $self->wq_do('query_prepare', \@io, $lei_ipc);
398 $io[1] = $zpipe->[1] if $zpipe;
400 start_query($self, \@io, $lei_ipc);
403 # for the $lei_ipc->atfork_child_wq PIPE handler:
404 while ($done->{sock}) { $done->event_step }
409 my ($self, $uri) = @_;
410 if (my $curl = $self->{curl} //= which('curl') // 0) {
411 require PublicInbox::MboxReader;
412 require IO::Uncompress::Gunzip;
413 push @{$self->{remotes}}, $uri;
415 warn "curl missing, ignoring $uri\n";
419 sub prepare_external {
420 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
421 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
422 return add_uri($self, $loc) if $loc->can('scheme');
423 } elsif ($loc =~ m!\Ahttps?://!) {
425 return add_uri($self, URI->new($loc));
426 } elsif (-f "$loc/ei.lock") {
427 require PublicInbox::ExtSearch;
428 $loc = PublicInbox::ExtSearch->new($loc);
429 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
430 require PublicInbox::Inbox; # v2, v1
431 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
433 warn "W: ignoring $loc, unable to determine type\n";
436 push @{$self->{locals}}, $loc;