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