]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
1c093a94ca35389aadfdeabf622cfccd25af821a
[public-inbox.git] / lib / PublicInbox / LeiXSearch.pm
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>
3
4 # Combine any combination of PublicInbox::Search,
5 # PublicInbox::ExtSearch, and PublicInbox::LeiSearch objects
6 # into one Xapian DB
7 package PublicInbox::LeiXSearch;
8 use strict;
9 use v5.10.1;
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
15 use File::Spec ();
16 use PublicInbox::Search qw(xap_terms);
17 use PublicInbox::Spawn qw(popen_rd);
18
19 sub new {
20         my ($class) = @_;
21         PublicInbox::Search::load_xapian();
22         bless {
23                 qp_flags => $PublicInbox::Search::QP_FLAGS |
24                                 PublicInbox::Search::FLAG_PURE_NOT(),
25         }, $class
26 }
27
28 sub attach_external {
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");
35
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);
42
43                 my $prev = {};
44                 for my $old_ibxish (@{$self->{shard2ibx}}) {
45                         next if $prev == $old_ibxish;
46                         $prev = $old_ibxish;
47                         my @shards = $old_ibxish->search->xdb_shards_flat;
48                         push @{$self->{shards_flat}}, @shards;
49                 }
50                 my $nr = scalar(@{$self->{shards_flat}});
51                 $nr == $expect or die
52                         "BUG: reloaded $nr shards, expected $expect"
53         }
54         push @{$self->{shards_flat}}, @shards;
55         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
56 }
57
58 # returns a list of local inboxes (or count in scalar context)
59 sub locals { @{$_[0]->{locals} // []} }
60
61 sub remotes { @{$_[0]->{remotes} // []} }
62
63 # called by PublicInbox::Search::xdb
64 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
65
66 # like over->get_art
67 sub smsg_for {
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 ];
79         }
80         $smsg->{docid} = $docid;
81         $smsg;
82 }
83
84 sub recent {
85         my ($self, $qstr, $opt) = @_;
86         $opt //= {};
87         $opt->{relevance} //= -2;
88         $self->mset($qstr //= 'bytes:1..', $opt);
89 }
90
91 sub over {}
92
93 sub _mset_more ($$) {
94         my ($mset, $mo) = @_;
95         my $size = $mset->size;
96         $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
97 }
98
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 ($) {
102         my ($startq) = @_;
103         $_[0] = undef;
104         read($startq, my $query_prepare_done, 1);
105 }
106
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;
113
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";
118                 return;
119         }
120         my $mo = { %{$lei->{mset_opt}} };
121         my $mset;
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;
125         do {
126                 $mset = $srch->mset($mo->{qstr}, $mo);
127                 my $ids = $srch->mset_to_artnums($mset, $mo);
128                 my $ctx = { ids => $ids };
129                 my $i = 0;
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);
138                         }
139                         @{$ctx->{xids}} = ();
140                 }
141         } while (_mset_more($mset, $mo));
142         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
143         $lei->{ovv}->ovv_atexit_child($lei);
144 }
145
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}} };
153         my $mset;
154         for my $loc (locals($self)) {
155                 attach_external($self, $loc);
156         }
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;
160         do {
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);
167                 }
168         } while (_mset_more($mset, $mo));
169         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
170         $lei->{ovv}->ovv_atexit_child($lei);
171 }
172
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);
182 }
183
184 sub query_remote_mboxrd {
185         my ($self, $lei, $uris) = @_;
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, $env) = @$lei{qw(opt env)};
190         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
191         push(@qform, t => 1) if $opt->{thread};
192         my $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
193         $dedupe->prepare_dedupe;
194         my @cmd = qw(curl -XPOST -sSf);
195         my $verbose = $opt->{verbose};
196         push @cmd, '-v' if $verbose;
197         for my $o ($lei->curl_opt) {
198                 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
199                 if ($o =~ s/=[is]@\z//) {
200                         my $ary = $opt->{$o} or next;
201                         push @cmd, map { ("--$o", $_) } @$ary;
202                 } elsif ($o =~ s/=[is]\z//) {
203                         my $val = $opt->{$o} // next;
204                         push @cmd, "--$o", $val;
205                 } elsif ($opt->{$o}) {
206                         push @cmd, "--$o";
207                 }
208         }
209         $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
210         my $tor = $opt->{torsocks} //= 'auto';
211         for my $uri (@$uris) {
212                 $uri->query_form(@qform);
213                 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $uri);
214                 my $cmd = [ @cmd, $uri->as_string ];
215                 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
216                                 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
217                         unshift @$cmd, 'torsocks';
218                 } elsif (PublicInbox::Config::git_bool($tor)) {
219                         unshift @$cmd, 'torsocks';
220                 }
221                 $lei->err("# @$cmd") if $verbose;
222                 $? = 0;
223                 my $fh = popen_rd($cmd, $env, { 2 => $lei->{2} });
224                 $fh = IO::Uncompress::Gunzip->new($fh);
225                 eval {
226                         PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
227                                                         $lei, $each_smsg);
228                 };
229                 return $lei->fail("E: @$cmd: $@") if $@;
230                 if (($? >> 8) == 22) { # HTTP 404 from curl(1)
231                         $uri->query_form(q => $lei->{mset_opt}->{qstr});
232                         $lei->err('# no results from '.$uri->as_string);
233                 } elsif ($?) {
234                         $uri->query_form(q => $lei->{mset_opt}->{qstr});
235                         $lei->err('E: '.$uri->as_string);
236                         $lei->child_error($?);
237                 }
238         }
239         $lei->{ovv}->ovv_atexit_child($lei);
240 }
241
242 sub git {
243         my ($self) = @_;
244         my (%seen, @dirs);
245         my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
246         for my $ibx (@{$self->{shard2ibx} // []}) {
247                 my $d = File::Spec->canonpath($ibx->git->{git_dir});
248                 $seen{$d} //= push @dirs, "$d/objects\n"
249         }
250         my $git_dir = $tmp->dirname;
251         PublicInbox::Import::init_bare($git_dir);
252         my $f = "$git_dir/objects/info/alternates";
253         open my $alt, '>', $f or die "open($f): $!";
254         print $alt @dirs or die "print $f: $!";
255         close $alt or die "close $f: $!";
256         my $git = PublicInbox::Git->new($git_dir);
257         $git->{-tmp} = $tmp;
258         $git;
259 }
260
261 sub query_done { # EOF callback
262         my ($lei) = @_;
263         my $has_l2m = exists $lei->{l2m};
264         for my $f (qw(lxs l2m)) {
265                 my $wq = delete $lei->{$f} or next;
266                 $wq->wq_wait_old;
267         }
268         $lei->{ovv}->ovv_end($lei);
269         if ($has_l2m) { # close() calls LeiToMail reap_compress
270                 if (my $out = delete $lei->{old_1}) {
271                         if (my $mbout = $lei->{1}) {
272                                 close($mbout) or return $lei->fail(<<"");
273 Error closing $lei->{ovv}->{dst}: $!
274
275                         }
276                         $lei->{1} = $out;
277                 }
278                 $lei->start_mua;
279         }
280         $lei->dclose;
281 }
282
283 sub do_post_augment {
284         my ($lei, $zpipe, $au_done) = @_;
285         my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
286         eval { $l2m->post_augment($lei, $zpipe) };
287         if (my $err = $@) {
288                 if (my $lxs = delete $lei->{lxs}) {
289                         $lxs->wq_kill;
290                         $lxs->wq_close;
291                 }
292                 $lei->fail("$err");
293         }
294         close $au_done; # triggers wait_startq
295 }
296
297 my $MAX_PER_HOST = 4;
298 sub MAX_PER_HOST { $MAX_PER_HOST }
299
300 sub concurrency {
301         my ($self, $opt) = @_;
302         my $nl = $opt->{thread} ? locals($self) : 1;
303         my $nr = remotes($self);
304         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
305         $nl + $nr;
306 }
307
308 sub start_query { # always runs in main (lei-daemon) process
309         my ($self, $io, $lei) = @_;
310         if ($lei->{opt}->{thread}) {
311                 for my $ibxish (locals($self)) {
312                         $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
313                 }
314         } else {
315                 $self->wq_do('query_mset', $io, $lei);
316         }
317         my $i = 0;
318         my $q = [];
319         for my $uri (remotes($self)) {
320                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
321         }
322         for my $uris (@$q) {
323                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
324         }
325         @$io = ();
326 }
327
328 sub query_prepare { # called by wq_do
329         my ($self, $lei) = @_;
330         local $0 = "$0 query_prepare";
331         my %sig = $lei->atfork_child_wq($self);
332         -p $lei->{0} or die "BUG: \$done pipe expected";
333         local @SIG{keys %sig} = values %sig;
334         eval { $lei->{l2m}->do_augment($lei) };
335         $lei->fail($@) if $@;
336         syswrite($lei->{0}, '.') == 1 or die "do_post_augment trigger: $!";
337 }
338
339 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
340         my ($lei) = @_;
341         my $lxs = delete $lei->{lxs};
342         if ($lxs && $lxs->wq_kill_old) {
343                 kill 'PIPE', $$;
344                 $lxs->wq_wait_old;
345         }
346         close(delete $lei->{1}) if $lei->{1};
347 }
348
349 sub do_query {
350         my ($self, $lei_orig) = @_;
351         my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
352         $io[0] = undef;
353         pipe(my $done, $io[0]) or die "pipe $!";
354         $lei_orig->{1}->autoflush(1);
355
356         $lei_orig->event_step_init; # wait for shutdowns
357         my $done_op = {
358                 '' => [ \&query_done, $lei_orig ],
359                 '!' => [ \&sigpipe_handler, $lei_orig ]
360         };
361         my $in_loop = exists $lei_orig->{sock};
362         $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
363         my $l2m = $lei->{l2m};
364         if ($l2m) {
365                 # may redirect $lei->{1} for mbox
366                 my $zpipe = $l2m->pre_augment($lei_orig);
367                 $io[1] = $lei_orig->{1};
368                 pipe(my ($startq, $au_done)) or die "pipe: $!";
369                 $done_op->{'.'} = [ \&do_post_augment, $lei_orig,
370                                         $zpipe, $au_done ];
371                 local $io[4] = *STDERR{GLOB}; # don't send l2m->{-wq_s1}
372                 die "BUG: unexpected \$io[5]: $io[5]" if $io[5];
373                 $self->wq_do('query_prepare', \@io, $lei);
374                 fcntl($startq, 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
375                 $io[5] = $startq;
376                 $io[1] = $zpipe->[1] if $zpipe;
377         }
378         start_query($self, \@io, $lei);
379         $self->wq_close(1);
380         unless ($in_loop) {
381                 # for the $lei->atfork_child_wq PIPE handler:
382                 while ($done->{sock}) { $done->event_step }
383         }
384 }
385
386 sub ipc_atfork_prepare {
387         my ($self) = @_;
388         if (exists $self->{remotes}) {
389                 require PublicInbox::MboxReader;
390                 require IO::Uncompress::Gunzip;
391         }
392         # (0: done_wr, 1: stdout|mbox, 2: stderr,
393         #  3: sock, 4: $l2m->{-wq_s1}, 5: $startq)
394         $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= +<&= <&=]);
395         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
396 }
397
398 sub prepare_external {
399         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
400         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
401                 return push(@{$self->{remotes}}, $loc) if $loc->can('scheme');
402         } elsif ($loc =~ m!\Ahttps?://!) {
403                 require URI;
404                 return push(@{$self->{remotes}}, URI->new($loc));
405         } elsif (-f "$loc/ei.lock") {
406                 require PublicInbox::ExtSearch;
407                 $loc = PublicInbox::ExtSearch->new($loc);
408         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
409                 require PublicInbox::Inbox; # v2, v1
410                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
411         } else {
412                 warn "W: ignoring $loc, unable to determine type\n";
413                 return;
414         }
415         push @{$self->{locals}}, $loc;
416 }
417
418
419 1;