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