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);
21 PublicInbox::Search::load_xapian();
23 qp_flags => $PublicInbox::Search::QP_FLAGS |
24 PublicInbox::Search::FLAG_PURE_NOT(),
29 my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
30 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
31 my $srch = $ibxish->search or
32 return warn("$desc not indexed for Xapian\n");
33 my @shards = $srch->xdb_shards_flat or
34 return warn("$desc has no Xapian shardsXapian\n");
36 if (delete $self->{xdb}) { # XXX: do we need this?
37 # clobber existing {xdb} if amending
38 my $expect = delete $self->{nshard};
39 my $shards = delete $self->{shards_flat};
40 scalar(@$shards) == $expect or die
41 "BUG: {nshard}$expect != shards=".scalar(@$shards);
44 for my $old_ibxish (@{$self->{shard2ibx}}) {
45 next if $prev == $old_ibxish;
47 my @shards = $old_ibxish->search->xdb_shards_flat;
48 push @{$self->{shards_flat}}, @shards;
50 my $nr = scalar(@{$self->{shards_flat}});
52 "BUG: reloaded $nr shards, expected $expect"
54 push @{$self->{shards_flat}}, @shards;
55 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
58 # returns a list of local inboxes (or count in scalar context)
59 sub locals { @{$_[0]->{locals} // []} }
61 sub remotes { @{$_[0]->{remotes} // []} }
63 # called by PublicInbox::Search::xdb
64 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
68 my ($self, $mitem) = @_;
69 # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
70 my $nshard = $self->{nshard};
71 my $docid = $mitem->get_docid;
72 my $shard = ($docid - 1) % $nshard;
73 my $num = int(($docid - 1) / $nshard) + 1;
74 my $ibx = $self->{shard2ibx}->[$shard];
75 my $smsg = $ibx->over->get_art($num);
76 if (ref($ibx->can('msg_keywords'))) {
77 my $kw = xap_terms('K', $mitem->get_document);
78 $smsg->{kw} = [ sort keys %$kw ];
80 $smsg->{docid} = $docid;
85 my ($self, $qstr, $opt) = @_;
87 $opt->{relevance} //= -2;
88 $self->mset($qstr //= 'bytes:1..', $opt);
95 my $size = $mset->size;
96 $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
99 # $startq will EOF when query_prepare is done augmenting and allow
100 # query_mset and query_thread_mset to proceed.
101 sub wait_startq ($) {
104 read($startq, my $query_prepare_done, 1);
107 sub query_thread_mset { # for --thread
108 my ($self, $lei, $ibxish) = @_;
109 local $0 = "$0 query_thread_mset";
110 my $startq = delete $self->{5};
111 my %sig = $lei->atfork_child_wq($self);
112 local @SIG{keys %sig} = values %sig;
114 my ($srch, $over) = ($ibxish->search, $ibxish->over);
115 unless ($srch && $over) {
116 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
117 warn "$desc not indexed by Xapian\n";
120 my $mo = { %{$lei->{mset_opt}} };
122 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
123 my $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
124 $dedupe->prepare_dedupe;
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 next if $dedupe->is_smsg_dup($smsg);
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 my $startq = delete $self->{5};
150 my %sig = $lei->atfork_child_wq($self);
151 local @SIG{keys %sig} = values %sig;
152 my $mo = { %{$lei->{mset_opt}} };
154 for my $loc (locals($self)) {
155 attach_external($self, $loc);
157 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
158 my $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
159 $dedupe->prepare_dedupe;
161 $mset = $self->mset($mo->{qstr}, $mo);
162 for my $mitem ($mset->items) {
163 my $smsg = smsg_for($self, $mitem) or next;
164 wait_startq($startq) if $startq;
165 next if $dedupe->is_smsg_dup($smsg);
166 $each_smsg->($smsg, $mitem);
168 } while (_mset_more($mset, $mo));
169 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
170 $lei->{ovv}->ovv_atexit_child($lei);
173 sub each_eml { # callback for MboxReader->mboxrd
174 my ($eml, $self, $lei, $each_smsg) = @_;
175 my $smsg = bless {}, 'PublicInbox::Smsg';
176 $smsg->populate($eml);
177 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
178 delete @$smsg{qw(From Subject -ds -ts)};
179 if (my $startq = delete($self->{5})) { wait_startq($startq) }
180 return if !$lei->{l2m} && $lei->{dedupe}->is_smsg_dup($smsg);
181 $each_smsg->($smsg, undef, $eml);
184 sub query_remote_mboxrd {
185 my ($self, $lei, $uri) = @_;
186 local $0 = "$0 query_remote_mboxrd";
187 my %sig = $lei->atfork_child_wq($self); # keep $self->{5} startq
188 local @SIG{keys %sig} = values %sig;
189 my $opt = $lei->{opt};
190 $uri->query_form(q => $lei->{mset_opt}->{qstr}, x => 'm',
191 $opt->{thread} ? (t => 1) : ());
192 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $uri);
193 my $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
194 $dedupe->prepare_dedupe;
195 my @cmd = qw(curl -XPOST -sSf);
196 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
197 my $tor = $opt->{torsocks} //= 'auto';
198 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
199 (($lei->{env}->{LD_PRELOAD}//'') !~ /torsocks/)) {
200 unshift @cmd, 'torsocks';
201 } elsif (PublicInbox::Config::git_bool($tor)) {
202 unshift @cmd, 'torsocks';
204 my $verbose = $opt->{verbose};
205 push @cmd, '-v' if $verbose;
206 for my $o ($lei->curl_opt) {
207 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
208 if ($o =~ s/=[is]@\z//) {
209 my $ary = $opt->{$o} or next;
210 push @cmd, map { ("--$o", $_) } @$ary;
211 } elsif ($o =~ s/=[is]\z//) {
212 my $val = $opt->{$o} // next;
213 push @cmd, "--$o", $val;
214 } elsif ($opt->{$o}) {
218 push @cmd, $uri->as_string;
219 $lei->err("# @cmd") if $verbose;
221 my $fh = popen_rd(\@cmd, $lei->{env}, { 2 => $lei->{2} });
222 $fh = IO::Uncompress::Gunzip->new($fh);
224 PublicInbox::MboxReader->mboxrd($fh, \&each_eml,
225 $self, $lei, $each_smsg);
227 return $lei->fail("E: @cmd: $@") if $@;
228 if (($? >> 8) == 22) { # HTTP 404 from curl(1)
229 $uri->query_form(q => $lei->{mset_opt}->{qstr});
230 $lei->err('# no results from '.$uri->as_string);
232 $uri->query_form(q => $lei->{mset_opt}->{qstr});
233 $lei->err('E: '.$uri->as_string);
234 $lei->child_error($?);
237 $lei->{ovv}->ovv_atexit_child($lei);
243 my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
244 for my $ibx (@{$self->{shard2ibx} // []}) {
245 my $d = File::Spec->canonpath($ibx->git->{git_dir});
246 $seen{$d} //= push @dirs, "$d/objects\n"
248 my $git_dir = $tmp->dirname;
249 PublicInbox::Import::init_bare($git_dir);
250 my $f = "$git_dir/objects/info/alternates";
251 open my $alt, '>', $f or die "open($f): $!";
252 print $alt @dirs or die "print $f: $!";
253 close $alt or die "close $f: $!";
254 my $git = PublicInbox::Git->new($git_dir);
259 sub query_done { # EOF callback
261 my $has_l2m = exists $lei->{l2m};
262 for my $f (qw(lxs l2m)) {
263 my $wq = delete $lei->{$f} or next;
266 $lei->{ovv}->ovv_end($lei);
267 if ($has_l2m) { # close() calls LeiToMail reap_compress
268 if (my $out = delete $lei->{old_1}) {
269 if (my $mbout = $lei->{1}) {
270 close($mbout) or return $lei->fail(<<"");
271 Error closing $lei->{ovv}->{dst}: $!
281 sub do_post_augment {
282 my ($lei, $zpipe, $au_done) = @_;
283 my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
284 eval { $l2m->post_augment($lei, $zpipe) };
286 if (my $lxs = delete $lei->{lxs}) {
292 close $au_done; # triggers wait_startq
295 sub start_query { # always runs in main (lei-daemon) process
296 my ($self, $io, $lei) = @_;
297 if ($lei->{opt}->{thread}) {
298 for my $ibxish (locals($self)) {
299 $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
302 $self->wq_do('query_mset', $io, $lei);
304 for my $uri (remotes($self)) {
305 $self->wq_do('query_remote_mboxrd', $io, $lei, $uri);
310 sub query_prepare { # called by wq_do
311 my ($self, $lei) = @_;
312 local $0 = "$0 query_prepare";
313 my %sig = $lei->atfork_child_wq($self);
314 -p $lei->{0} or die "BUG: \$done pipe expected";
315 local @SIG{keys %sig} = values %sig;
316 eval { $lei->{l2m}->do_augment($lei) };
317 $lei->fail($@) if $@;
318 syswrite($lei->{0}, '.') == 1 or die "do_post_augment trigger: $!";
321 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
323 my $lxs = delete $lei->{lxs};
324 if ($lxs && $lxs->wq_kill_old) {
328 close(delete $lei->{1}) if $lei->{1};
332 my ($self, $lei_orig) = @_;
333 my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
335 pipe(my $done, $io[0]) or die "pipe $!";
336 $lei_orig->{1}->autoflush(1);
338 $lei_orig->event_step_init; # wait for shutdowns
340 '' => [ \&query_done, $lei_orig ],
341 '!' => [ \&sigpipe_handler, $lei_orig ]
343 my $in_loop = exists $lei_orig->{sock};
344 $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
345 my $l2m = $lei->{l2m};
347 # may redirect $lei->{1} for mbox
348 my $zpipe = $l2m->pre_augment($lei_orig);
349 $io[1] = $lei_orig->{1};
350 pipe(my ($startq, $au_done)) or die "pipe: $!";
351 $done_op->{'.'} = [ \&do_post_augment, $lei_orig,
353 local $io[4] = *STDERR{GLOB}; # don't send l2m->{-wq_s1}
354 die "BUG: unexpected \$io[5]: $io[5]" if $io[5];
355 $self->wq_do('query_prepare', \@io, $lei);
356 fcntl($startq, 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
358 $io[1] = $zpipe->[1] if $zpipe;
360 start_query($self, \@io, $lei);
363 # for the $lei->atfork_child_wq PIPE handler:
364 while ($done->{sock}) { $done->event_step }
368 sub ipc_atfork_prepare {
370 if (exists $self->{remotes}) {
371 require PublicInbox::MboxReader;
372 require IO::Uncompress::Gunzip;
374 # (0: done_wr, 1: stdout|mbox, 2: stderr,
375 # 3: sock, 4: $l2m->{-wq_s1}, 5: $startq)
376 $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= +<&= <&=]);
377 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
380 sub prepare_external {
381 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
382 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
383 return push(@{$self->{remotes}}, $loc) if $loc->can('scheme');
384 } elsif ($loc =~ m!\Ahttps?://!) {
386 return push(@{$self->{remotes}}, URI->new($loc));
387 } elsif (-f "$loc/ei.lock") {
388 require PublicInbox::ExtSearch;
389 $loc = PublicInbox::ExtSearch->new($loc);
390 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
391 require PublicInbox::Inbox; # v2, v1
392 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
394 warn "W: ignoring $loc, unable to determine type\n";
397 push @{$self->{locals}}, $loc;