]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei q: auto-memoize remote messages into lei/store
[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(now);
12 use PublicInbox::PktOp qw(pkt_do);
13 use File::Temp 0.19 (); # 0.19 for ->newdir
14 use File::Spec ();
15 use PublicInbox::Search qw(xap_terms);
16 use PublicInbox::Spawn qw(popen_rd spawn which);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::Smsg;
19 use PublicInbox::Eml;
20 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
21
22 sub new {
23         my ($class) = @_;
24         PublicInbox::Search::load_xapian();
25         bless {
26                 qp_flags => $PublicInbox::Search::QP_FLAGS |
27                                 PublicInbox::Search::FLAG_PURE_NOT(),
28         }, $class
29 }
30
31 sub attach_external {
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");
38
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);
45
46                 my $prev = {};
47                 for my $old_ibxish (@{$self->{shard2ibx}}) {
48                         next if $prev == $old_ibxish;
49                         $prev = $old_ibxish;
50                         my @shards = $old_ibxish->search->xdb_shards_flat;
51                         push @{$self->{shards_flat}}, @shards;
52                 }
53                 my $nr = scalar(@{$self->{shards_flat}});
54                 $nr == $expect or die
55                         "BUG: reloaded $nr shards, expected $expect"
56         }
57         push @{$self->{shards_flat}}, @shards;
58         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
59 }
60
61 # returns a list of local inboxes (or count in scalar context)
62 sub locals { @{$_[0]->{locals} // []} }
63
64 sub remotes { @{$_[0]->{remotes} // []} }
65
66 # called by PublicInbox::Search::xdb
67 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
68
69 # like over->get_art
70 sub smsg_for {
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 ];
82         }
83         $smsg->{docid} = $docid;
84         $smsg;
85 }
86
87 sub recent {
88         my ($self, $qstr, $opt) = @_;
89         $opt //= {};
90         $opt->{relevance} //= -2;
91         $self->mset($qstr //= 'bytes:1..', $opt);
92 }
93
94 sub over {}
95
96 sub _mset_more ($$) {
97         my ($mset, $mo) = @_;
98         my $size = $mset->size;
99         $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
100 }
101
102 # $startq will EOF when do_augment is done augmenting and allow
103 # query_mset and query_thread_mset to proceed.
104 sub wait_startq ($) {
105         my ($lei) = @_;
106         my $startq = delete $lei->{startq} or return;
107         while (1) {
108                 my $n = sysread($startq, my $do_augment_done, 1);
109                 if (defined $n) {
110                         return if $n == 0; # no MUA
111                         if ($do_augment_done eq 'q') {
112                                 $lei->{opt}->{quiet} = 1;
113                                 delete $lei->{opt}->{verbose};
114                                 delete $lei->{-progress};
115                         } else {
116                                 $lei->fail("$$ WTF `$do_augment_done'");
117                         }
118                         return;
119                 }
120                 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
121         }
122 }
123
124 sub mset_progress {
125         my $lei = shift;
126         return if $lei->{early_mua} || !$lei->{-progress};
127         if ($lei->{pkt_op_p}) {
128                 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
129         } else { # single lei-daemon consumer
130                 my ($desc, $mset_size, $mset_total_est) = @_;
131                 $lei->{-mset_total} += $mset_size;
132                 $lei->qerr("# $desc $mset_size/$mset_total_est");
133         }
134 }
135
136 sub query_thread_mset { # for --threads
137         my ($self, $ibxish) = @_;
138         local $0 = "$0 query_thread_mset";
139         my $lei = $self->{lei};
140         my ($srch, $over) = ($ibxish->search, $ibxish->over);
141         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
142         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
143         my $mo = { %{$lei->{mset_opt}} };
144         my $mset;
145         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
146         do {
147                 $mset = $srch->mset($mo->{qstr}, $mo);
148                 mset_progress($lei, $desc, $mset->size,
149                                 $mset->get_matches_estimated);
150                 my $ids = $srch->mset_to_artnums($mset, $mo);
151                 my $ctx = { ids => $ids };
152                 my $i = 0;
153                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
154                 while ($over->expand_thread($ctx)) {
155                         for my $n (@{$ctx->{xids}}) {
156                                 my $smsg = $over->get_art($n) or next;
157                                 wait_startq($lei);
158                                 my $mitem = delete $n2item{$smsg->{num}};
159                                 $each_smsg->($smsg, $mitem);
160                         }
161                         @{$ctx->{xids}} = ();
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 query_mset { # non-parallel for non-"--threads" users
169         my ($self) = @_;
170         local $0 = "$0 query_mset";
171         my $lei = $self->{lei};
172         my $mo = { %{$lei->{mset_opt}} };
173         my $mset;
174         for my $loc (locals($self)) {
175                 attach_external($self, $loc);
176         }
177         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
178         do {
179                 $mset = $self->mset($mo->{qstr}, $mo);
180                 mset_progress($lei, 'xsearch', $mset->size,
181                                 $mset->size, $mset->get_matches_estimated);
182                 for my $mitem ($mset->items) {
183                         my $smsg = smsg_for($self, $mitem) or next;
184                         wait_startq($lei);
185                         $each_smsg->($smsg, $mitem);
186                 }
187         } while (_mset_more($mset, $mo));
188         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
189         $lei->{ovv}->ovv_atexit_child($lei);
190 }
191
192 sub each_remote_eml { # callback for MboxReader->mboxrd
193         my ($eml, $self, $lei, $each_smsg) = @_;
194         $lei->{sto}->ipc_do('set_eml', $eml) if $lei->{sto}; # --import-remote
195         my $smsg = bless {}, 'PublicInbox::Smsg';
196         $smsg->populate($eml);
197         $smsg->parse_references($eml, mids($eml));
198         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
199         delete @$smsg{qw(From Subject -ds -ts)};
200         wait_startq($lei);
201         if ($lei->{-progress}) {
202                 ++$lei->{-nr_remote_eml};
203                 my $now = now();
204                 my $next = $lei->{-next_progress} //= ($now + 1);
205                 if ($now > $next) {
206                         $lei->{-next_progress} = $now + 1;
207                         my $nr = $lei->{-nr_remote_eml};
208                         $lei->err("# $lei->{-current_url} $nr/?");
209                 }
210         }
211         $each_smsg->($smsg, undef, $eml);
212 }
213
214 sub query_remote_mboxrd {
215         my ($self, $uris) = @_;
216         local $0 = "$0 query_remote_mboxrd";
217         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
218         my $lei = $self->{lei};
219         my $opt = $lei->{opt};
220         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
221         push(@qform, t => 1) if $opt->{threads};
222         my $verbose = $opt->{verbose};
223         my ($reap_tail, $reap_curl);
224         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
225         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
226         my $rdr = { 2 => $cerr, pgid => 0 };
227         my $sigint_reap = $lei->can('sigint_reap');
228         if ($verbose) {
229                 # spawn a process to force line-buffering, otherwise curl
230                 # will write 1 character at-a-time and parallel outputs
231                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
232                 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
233                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
234                 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
235         }
236         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
237         push @$curl, '-s', '-d', '';
238         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
239         for my $uri (@$uris) {
240                 $lei->{-current_url} = $uri->as_string;
241                 $lei->{-nr_remote_eml} = 0;
242                 $uri->query_form(@qform);
243                 my $cmd = $curl->for_uri($lei, $uri);
244                 $lei->qerr("# $cmd");
245                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
246                 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
247                 $fh = IO::Uncompress::Gunzip->new($fh);
248                 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
249                                                 $lei, $each_smsg);
250                 my $err = waitpid($pid, 0) == $pid ? undef
251                                                 : "BUG: waitpid($cmd): $!";
252                 @$reap_curl = (); # cancel OnDestroy
253                 die $err if $err;
254                 my $nr = $lei->{-nr_remote_eml};
255                 if ($nr && $lei->{sto}) {
256                         my $wait = $lei->{sto}->ipc_do('done');
257                 }
258                 if ($? == 0) {
259                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
260                         next;
261                 }
262                 $err = '';
263                 if (-s $cerr) {
264                         seek($cerr, 0, SEEK_SET) or
265                                         $lei->err("seek($cmd stderr): $!");
266                         $err = do { local $/; <$cerr> } //
267                                         "read($cmd stderr): $!";
268                         truncate($cerr, 0) or
269                                         $lei->err("truncate($cmd stderr): $!");
270                 }
271                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
272                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
273                 $lei->child_error($?, "E: <$uri> $err");
274         }
275         undef $each_smsg;
276         $lei->{ovv}->ovv_atexit_child($lei);
277 }
278
279 # called by LeiOverview::each_smsg_cb
280 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
281
282 sub git_tmp ($) {
283         my ($self) = @_;
284         my (%seen, @dirs);
285         my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
286         for my $ibxish (locals($self)) {
287                 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
288                 $seen{$d} //= push @dirs, "$d/objects\n"
289         }
290         my $git_dir = $tmp->dirname;
291         PublicInbox::Import::init_bare($git_dir);
292         my $f = "$git_dir/objects/info/alternates";
293         open my $alt, '>', $f or die "open($f): $!";
294         print $alt @dirs or die "print $f: $!";
295         close $alt or die "close $f: $!";
296         my $git = PublicInbox::Git->new($git_dir);
297         $git->{-tmp} = $tmp;
298         $git;
299 }
300
301 sub xsearch_done_wait { # dwaitpid callback
302         my ($arg, $pid) = @_;
303         my ($wq, $lei) = @$arg;
304         $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
305 }
306
307 sub query_done { # EOF callback for main daemon
308         my ($lei) = @_;
309         my $l2m = delete $lei->{l2m};
310         $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
311         if (my $lxs = delete $lei->{lxs}) {
312                 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
313         }
314         $lei->{ovv}->ovv_end($lei);
315         if ($l2m) { # close() calls LeiToMail reap_compress
316                 if (my $out = delete $lei->{old_1}) {
317                         if (my $mbout = $lei->{1}) {
318                                 close($mbout) or return $lei->fail(<<"");
319 Error closing $lei->{ovv}->{dst}: $!
320
321                         }
322                         $lei->{1} = $out;
323                 }
324                 if ($l2m->lock_free) {
325                         $l2m->poke_dst;
326                         $lei->poke_mua;
327                 } else { # mbox users
328                         $lei->start_mua;
329                 }
330         }
331         $lei->{-progress} and
332                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
333         $lei->dclose;
334 }
335
336 sub do_post_augment {
337         my ($lei) = @_;
338         my $l2m = $lei->{l2m} or die 'BUG: unexpected do_post_augment';
339         my $err;
340         eval { $l2m->post_augment($lei) };
341         $err = $@;
342         if ($err) {
343                 if (my $lxs = delete $lei->{lxs}) {
344                         $lxs->wq_kill;
345                         $lxs->wq_close(0, undef, $lei);
346                 }
347                 $lei->fail("$err");
348         }
349         if (!$err && delete $lei->{early_mua}) { # non-augment case
350                 $lei->start_mua;
351         }
352         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
353 }
354
355 sub incr_post_augment { # called whenever an l2m shard finishes augment
356         my ($lei) = @_;
357         my $l2m = $lei->{l2m} or die 'BUG: unexpected incr_post_augment';
358         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
359         do_post_augment($lei);
360 }
361
362 my $MAX_PER_HOST = 4;
363
364 sub concurrency {
365         my ($self, $opt) = @_;
366         my $nl = $opt->{threads} ? locals($self) : 1;
367         my $nr = remotes($self);
368         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
369         $nl + $nr;
370 }
371
372 sub start_query { # always runs in main (lei-daemon) process
373         my ($self) = @_;
374         if ($self->{threads}) {
375                 for my $ibxish (locals($self)) {
376                         $self->wq_io_do('query_thread_mset', [], $ibxish);
377                 }
378         } elsif (locals($self)) {
379                 $self->wq_io_do('query_mset', []);
380         }
381         my $i = 0;
382         my $q = [];
383         for my $uri (remotes($self)) {
384                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
385         }
386         for my $uris (@$q) {
387                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
388         }
389         $self->wq_close(1); # lei_xsearch workers stop when done
390 }
391
392 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
393         my ($self, $l2m) = @_;
394         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
395         start_query($self);
396 }
397
398 sub ipc_atfork_child {
399         my ($self) = @_;
400         $self->{lei}->lei_atfork_child;
401         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
402         $self->SUPER::ipc_atfork_child;
403 }
404
405 sub do_query {
406         my ($self, $lei) = @_;
407         my $l2m = $lei->{l2m};
408         my $ops = {
409                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
410                 '!' => [ $lei->can('fail_handler'), $lei ],
411                 '.' => [ \&do_post_augment, $lei ],
412                 '+' => [ \&incr_post_augment, $lei ],
413                 '' => [ \&query_done, $lei ],
414                 'mset_progress' => [ \&mset_progress, $lei ],
415                 'x_it' => [ $lei->can('x_it'), $lei ],
416                 'child_error' => [ $lei->can('child_error'), $lei ],
417                 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
418         };
419         $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
420         ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
421         $lei->{1}->autoflush(1);
422         $lei->start_pager if delete $lei->{need_pager};
423         $lei->{ovv}->ovv_begin($lei);
424         if ($l2m) {
425                 $l2m->pre_augment($lei);
426                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
427                         $lei->start_mua;
428                 }
429                 $l2m->wq_workers_start('lei2mail', undef,
430                                         $lei->oldset, { lei => $lei });
431                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
432                 # 1031: F_SETPIPE_SZ
433                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
434         }
435         if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
436                 # lei->{git_tmp} is set for wq_wait_old so we don't
437                 # delete until all lei2mail + lei_xsearch workers are reaped
438                 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
439         }
440         $self->wq_workers_start('lei_xsearch', undef,
441                                 $lei->oldset, { lei => $lei });
442         my $op = delete $lei->{pkt_op_c};
443         delete $lei->{pkt_op_p};
444         $self->{threads} = $lei->{opt}->{threads};
445         if ($l2m) {
446                 $l2m->net_merge_complete unless $lei->{auth};
447         } else {
448                 start_query($self);
449         }
450         $lei->event_step_init; # wait for shutdowns
451         if ($lei->{oneshot}) {
452                 while ($op->{sock}) { $op->event_step }
453         }
454 }
455
456 sub add_uri {
457         my ($self, $uri) = @_;
458         if (my $curl = $self->{curl} //= which('curl') // 0) {
459                 require PublicInbox::MboxReader;
460                 require IO::Uncompress::Gunzip;
461                 require PublicInbox::LeiCurl;
462                 push @{$self->{remotes}}, $uri;
463         } else {
464                 warn "curl missing, ignoring $uri\n";
465         }
466 }
467
468 sub prepare_external {
469         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
470         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
471                 return add_uri($self, $loc) if $loc->can('scheme');
472         } elsif ($loc =~ m!\Ahttps?://!) {
473                 require URI;
474                 return add_uri($self, URI->new($loc));
475         } elsif (-f "$loc/ei.lock") {
476                 require PublicInbox::ExtSearch;
477                 $loc = PublicInbox::ExtSearch->new($loc);
478         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
479                 require PublicInbox::Inbox; # v2, v1
480                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
481         } else {
482                 warn "W: ignoring $loc, unable to determine type\n";
483                 return;
484         }
485         push @{$self->{locals}}, $loc;
486 }
487
488
489 1;