]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
defe5e67cc2c6e905e2e8d37da7978e9321cb3f5
[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, $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';
203         }
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}) {
215                         push @cmd, "--$o";
216                 }
217         }
218         push @cmd, $uri->as_string;
219         $lei->err("# @cmd") if $verbose;
220         $? = 0;
221         my $fh = popen_rd(\@cmd, $lei->{env}, { 2 => $lei->{2} });
222         $fh = IO::Uncompress::Gunzip->new($fh);
223         eval {
224                 PublicInbox::MboxReader->mboxrd($fh, \&each_eml,
225                                                 $self, $lei, $each_smsg);
226         };
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);
231         } elsif ($?) {
232                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
233                 $lei->err('E: '.$uri->as_string);
234                 $lei->child_error($?);
235         }
236         undef $each_smsg;
237         $lei->{ovv}->ovv_atexit_child($lei);
238 }
239
240 sub git {
241         my ($self) = @_;
242         my (%seen, @dirs);
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"
247         }
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);
255         $git->{-tmp} = $tmp;
256         $git;
257 }
258
259 sub query_done { # EOF callback
260         my ($lei) = @_;
261         my $has_l2m = exists $lei->{l2m};
262         for my $f (qw(lxs l2m)) {
263                 my $wq = delete $lei->{$f} or next;
264                 $wq->wq_wait_old;
265         }
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}: $!
272
273                         }
274                         $lei->{1} = $out;
275                 }
276                 $lei->start_mua;
277         }
278         $lei->dclose;
279 }
280
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) };
285         if (my $err = $@) {
286                 if (my $lxs = delete $lei->{lxs}) {
287                         $lxs->wq_kill;
288                         $lxs->wq_close;
289                 }
290                 $lei->fail("$err");
291         }
292         close $au_done; # triggers wait_startq
293 }
294
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);
300                 }
301         } else {
302                 $self->wq_do('query_mset', $io, $lei);
303         }
304         for my $uri (remotes($self)) {
305                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uri);
306         }
307         @$io = ();
308 }
309
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: $!";
319 }
320
321 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
322         my ($lei) = @_;
323         my $lxs = delete $lei->{lxs};
324         if ($lxs && $lxs->wq_kill_old) {
325                 kill 'PIPE', $$;
326                 $lxs->wq_wait_old;
327         }
328         close(delete $lei->{1}) if $lei->{1};
329 }
330
331 sub do_query {
332         my ($self, $lei_orig) = @_;
333         my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
334         $io[0] = undef;
335         pipe(my $done, $io[0]) or die "pipe $!";
336         $lei_orig->{1}->autoflush(1);
337
338         $lei_orig->event_step_init; # wait for shutdowns
339         my $done_op = {
340                 '' => [ \&query_done, $lei_orig ],
341                 '!' => [ \&sigpipe_handler, $lei_orig ]
342         };
343         my $in_loop = exists $lei_orig->{sock};
344         $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
345         my $l2m = $lei->{l2m};
346         if ($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,
352                                         $zpipe, $au_done ];
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
357                 $io[5] = $startq;
358                 $io[1] = $zpipe->[1] if $zpipe;
359         }
360         start_query($self, \@io, $lei);
361         $self->wq_close(1);
362         unless ($in_loop) {
363                 # for the $lei->atfork_child_wq PIPE handler:
364                 while ($done->{sock}) { $done->event_step }
365         }
366 }
367
368 sub ipc_atfork_prepare {
369         my ($self) = @_;
370         if (exists $self->{remotes}) {
371                 require PublicInbox::MboxReader;
372                 require IO::Uncompress::Gunzip;
373         }
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
378 }
379
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?://!) {
385                 require URI;
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';
393         } else {
394                 warn "W: ignoring $loc, unable to determine type\n";
395                 return;
396         }
397         push @{$self->{locals}}, $loc;
398 }
399
400
401 1;