]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei <q|up>: distinguish between mset and l2m counts
[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 use PublicInbox::ContentHash qw(git_sha);
22
23 sub new {
24         my ($class) = @_;
25         PublicInbox::Search::load_xapian();
26         bless {
27                 qp_flags => $PublicInbox::Search::QP_FLAGS |
28                                 PublicInbox::Search::FLAG_PURE_NOT(),
29         }, $class
30 }
31
32 sub attach_external {
33         my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
34         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
35         my $srch = $ibxish->search or
36                 return warn("$desc not indexed for Xapian\n");
37         my @shards = $srch->xdb_shards_flat or
38                 return warn("$desc has no Xapian shards\n");
39
40         if (delete $self->{xdb}) { # XXX: do we need this?
41                 # clobber existing {xdb} if amending
42                 my $expect = delete $self->{nshard};
43                 my $shards = delete $self->{shards_flat};
44                 scalar(@$shards) == $expect or die
45                         "BUG: {nshard}$expect != shards=".scalar(@$shards);
46
47                 my $prev = {};
48                 for my $old_ibxish (@{$self->{shard2ibx}}) {
49                         next if $prev == $old_ibxish;
50                         $prev = $old_ibxish;
51                         my @shards = $old_ibxish->search->xdb_shards_flat;
52                         push @{$self->{shards_flat}}, @shards;
53                 }
54                 my $nr = scalar(@{$self->{shards_flat}});
55                 $nr == $expect or die
56                         "BUG: reloaded $nr shards, expected $expect"
57         }
58         push @{$self->{shards_flat}}, @shards;
59         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
60 }
61
62 # returns a list of local inboxes (or count in scalar context)
63 sub locals { @{$_[0]->{locals} // []} }
64
65 sub remotes { @{$_[0]->{remotes} // []} }
66
67 # called by PublicInbox::Search::xdb (usually via ->mset)
68 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
69
70 sub mitem_kw ($$;$) {
71         my ($smsg, $mitem, $flagged) = @_;
72         my $kw = xap_terms('K', my $doc = $mitem->get_document);
73         $kw->{flagged} = 1 if $flagged;
74         # we keep the empty {kw} array here to prevent expensive work in
75         # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
76         $smsg->{kw} = [ sort keys %$kw ];
77         my $L = xap_terms('L', $doc);
78         $smsg->{L} = [ sort keys %$L ] if scalar(keys %$L);
79 }
80
81 # like over->get_art
82 sub smsg_for {
83         my ($self, $mitem) = @_;
84         # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
85         my $nshard = $self->{nshard};
86         my $docid = $mitem->get_docid;
87         my $shard = ($docid - 1) % $nshard;
88         my $num = int(($docid - 1) / $nshard) + 1;
89         my $ibx = $self->{shard2ibx}->[$shard];
90         my $smsg = $ibx->over->get_art($num);
91         return if $smsg->{bytes} == 0; # external message
92         if ($ibx->can('msg_keywords')) {
93                 mitem_kw($smsg, $mitem);
94         }
95         $smsg;
96 }
97
98 sub recent {
99         my ($self, $qstr, $opt) = @_;
100         $opt //= {};
101         $opt->{relevance} //= -2;
102         $self->mset($qstr //= 'z:1..', $opt);
103 }
104
105 sub over {}
106
107 sub _mset_more ($$) {
108         my ($mset, $mo) = @_;
109         my $size = $mset->size;
110         $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
111 }
112
113 # $startq will EOF when do_augment is done augmenting and allow
114 # query_combined_mset and query_thread_mset to proceed.
115 sub wait_startq ($) {
116         my ($lei) = @_;
117         my $startq = delete $lei->{startq} or return;
118         while (1) {
119                 my $n = sysread($startq, my $do_augment_done, 1);
120                 if (defined $n) {
121                         return if $n == 0; # no MUA
122                         if ($do_augment_done eq 'q') {
123                                 $lei->{opt}->{quiet} = 1;
124                                 delete $lei->{opt}->{verbose};
125                                 delete $lei->{-progress};
126                         } else {
127                                 $lei->fail("$$ WTF `$do_augment_done'");
128                         }
129                         return;
130                 }
131                 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
132         }
133 }
134
135 sub mset_progress {
136         my $lei = shift;
137         return if $lei->{early_mua} || !$lei->{-progress};
138         if ($lei->{pkt_op_p}) {
139                 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
140         } else { # single lei-daemon consumer
141                 my ($desc, $mset_size, $mset_total_est) = @_;
142                 $lei->{-mset_total} += $mset_size;
143                 $lei->qerr("# $desc $mset_size/$mset_total_est");
144         }
145 }
146
147 sub l2m_progress {
148         my ($lei, $nr) = @_;
149         $lei->{-nr_write} += $nr;
150 }
151
152 sub query_one_mset { # for --threads and l2m w/o sort
153         my ($self, $ibxish) = @_;
154         local $0 = "$0 query_one_mset";
155         my $lei = $self->{lei};
156         my ($srch, $over) = ($ibxish->search, $ibxish->over);
157         my $dir = $ibxish->{inboxdir} // $ibxish->{topdir};
158         return warn("$dir not indexed by Xapian\n") unless ($srch && $over);
159         my $mo = { %{$lei->{mset_opt}} }; # copy
160         my $mset;
161         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
162         my $can_kw = !!$ibxish->can('msg_keywords');
163         my $threads = $lei->{opt}->{threads} // 0;
164         my $fl = $threads > 1 ? 1 : undef;
165         my $lss = $lei->{dedupe};
166         $lss = undef unless $lss && $lss->can('cfg_set'); # saved search
167         my $maxk = "external.$dir.maxuid";
168         my $stop_at = $lss ? $lss->{-cfg}->{$maxk} : undef;
169         if (defined $stop_at) {
170                 die "$maxk=$stop_at has multiple values" if ref $stop_at;
171                 my @e;
172                 local $SIG{__WARN__} = sub { push @e, @_ };
173                 $stop_at += 0;
174                 return warn("$maxk=$stop_at: @e") if @e;
175         }
176         my $first_ids;
177         do {
178                 $mset = $srch->mset($mo->{qstr}, $mo);
179                 mset_progress($lei, $dir, $mset->size,
180                                 $mset->get_matches_estimated);
181                 wait_startq($lei); # wait for keyword updates
182                 my $ids = $srch->mset_to_artnums($mset, $mo);
183                 @$ids = grep { $_ > $stop_at } @$ids if defined($stop_at);
184                 my $i = 0;
185                 if ($threads) {
186                         # copy $ids if $lss since over->expand_thread
187                         # shifts @{$ctx->{ids}}
188                         $first_ids = [ @$ids ] if $lss;
189                         my $ctx = { ids => $ids };
190                         my %n2item = map { ($ids->[$i++], $_) } $mset->items;
191                         while ($over->expand_thread($ctx)) {
192                                 for my $n (@{$ctx->{xids}}) {
193                                         my $smsg = $over->get_art($n) or next;
194                                         my $mitem = delete $n2item{$n};
195                                         next if $smsg->{bytes} == 0;
196                                         if ($mitem && $can_kw) {
197                                                 mitem_kw($smsg, $mitem, $fl);
198                                         } elsif ($mitem && $fl) {
199                                                 # call ->xsmsg_vmd, later
200                                                 $smsg->{lei_q_tt_flagged} = 1;
201                                         }
202                                         $each_smsg->($smsg, $mitem);
203                                 }
204                                 @{$ctx->{xids}} = ();
205                         }
206                 } else {
207                         $first_ids = $ids;
208                         my @items = $mset->items;
209                         for my $n (@$ids) {
210                                 my $mitem = $items[$i++];
211                                 my $smsg = $over->get_art($n) or next;
212                                 next if $smsg->{bytes} == 0;
213                                 mitem_kw($smsg, $mitem, $fl) if $can_kw;
214                                 $each_smsg->($smsg, $mitem);
215                         }
216                 }
217         } while (_mset_more($mset, $mo));
218         if ($lss && scalar(@$first_ids)) {
219                 undef $stop_at;
220                 my $max = $first_ids->[0];
221                 $lss->cfg_set($maxk, $max);
222                 undef $lss;
223         }
224         undef $each_smsg; # may commit
225         $lei->{ovv}->ovv_atexit_child($lei);
226 }
227
228 sub query_combined_mset { # non-parallel for non-"--threads" users
229         my ($self) = @_;
230         local $0 = "$0 query_combined_mset";
231         my $lei = $self->{lei};
232         my $mo = { %{$lei->{mset_opt}} };
233         my $mset;
234         for my $loc (locals($self)) {
235                 attach_external($self, $loc);
236         }
237         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
238         do {
239                 $mset = $self->mset($mo->{qstr}, $mo);
240                 mset_progress($lei, 'xsearch', $mset->size,
241                                 $mset->size, $mset->get_matches_estimated);
242                 wait_startq($lei); # wait for keyword updates
243                 for my $mitem ($mset->items) {
244                         my $smsg = smsg_for($self, $mitem) or next;
245                         $each_smsg->($smsg, $mitem);
246                 }
247         } while (_mset_more($mset, $mo));
248         undef $each_smsg; # may commit
249         $lei->{ovv}->ovv_atexit_child($lei);
250 }
251
252 sub each_remote_eml { # callback for MboxReader->mboxrd
253         my ($eml, $self, $lei, $each_smsg) = @_;
254         my $xoids = $lei->{ale}->xoids_for($eml, 1);
255         if ($self->{import_sto} && !$xoids) {
256                 $self->{import_sto}->ipc_do('add_eml', $eml);
257         }
258         my $smsg = bless {}, 'PublicInbox::Smsg';
259         $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
260                                 : git_sha(1, $eml)->hexdigest;
261         $smsg->populate($eml);
262         $smsg->parse_references($eml, mids($eml));
263         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
264         delete @$smsg{qw(From Subject -ds -ts)};
265         wait_startq($lei);
266         if ($lei->{-progress}) {
267                 ++$lei->{-nr_remote_eml};
268                 my $now = now();
269                 my $next = $lei->{-next_progress} //= ($now + 1);
270                 if ($now > $next) {
271                         $lei->{-next_progress} = $now + 1;
272                         my $nr = $lei->{-nr_remote_eml};
273                         mset_progress($lei, $lei->{-current_url}, $nr, '?');
274                 }
275         }
276         $each_smsg->($smsg, undef, $eml);
277 }
278
279 sub query_remote_mboxrd {
280         my ($self, $uris) = @_;
281         local $0 = "$0 query_remote_mboxrd";
282         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
283         my $lei = $self->{lei};
284         my $opt = $lei->{opt};
285         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
286         push(@qform, t => 1) if $opt->{threads};
287         my $verbose = $opt->{verbose};
288         my ($reap_tail, $reap_curl);
289         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
290         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
291         my $rdr = { 2 => $cerr, pgid => 0 };
292         my $sigint_reap = $lei->can('sigint_reap');
293         if ($verbose) {
294                 # spawn a process to force line-buffering, otherwise curl
295                 # will write 1 character at-a-time and parallel outputs
296                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
297                 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
298                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
299                 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
300         }
301         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
302         push @$curl, '-s', '-d', '';
303         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
304         $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
305         for my $uri (@$uris) {
306                 $lei->{-current_url} = $uri->as_string;
307                 $lei->{-nr_remote_eml} = 0;
308                 $uri->query_form(@qform);
309                 my $cmd = $curl->for_uri($lei, $uri);
310                 $lei->qerr("# $cmd");
311                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
312                 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
313                 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
314                 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
315                                                 $lei, $each_smsg);
316                 my $err = waitpid($pid, 0) == $pid ? undef
317                                                 : "BUG: waitpid($cmd): $!";
318                 @$reap_curl = (); # cancel OnDestroy
319                 die $err if $err;
320                 my $nr = $lei->{-nr_remote_eml};
321                 if ($nr && $lei->{sto}) {
322                         my $wait = $lei->{sto}->ipc_do('done');
323                 }
324                 if ($? == 0) {
325                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
326                         next;
327                 }
328                 $err = '';
329                 if (-s $cerr) {
330                         seek($cerr, 0, SEEK_SET) or
331                                         $lei->err("seek($cmd stderr): $!");
332                         $err = do { local $/; <$cerr> } //
333                                         "read($cmd stderr): $!";
334                         truncate($cerr, 0) or
335                                         $lei->err("truncate($cmd stderr): $!");
336                 }
337                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
338                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
339                 $lei->child_error($?, "E: <$uri> $err");
340         }
341         undef $each_smsg;
342         $lei->{ovv}->ovv_atexit_child($lei);
343 }
344
345 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
346
347 sub xsearch_done_wait { # dwaitpid callback
348         my ($arg, $pid) = @_;
349         my ($wq, $lei) = @$arg;
350         $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
351 }
352
353 sub query_done { # EOF callback for main daemon
354         my ($lei) = @_;
355         my $l2m = delete $lei->{l2m};
356         $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
357         if (my $lxs = delete $lei->{lxs}) {
358                 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
359         }
360         my $wait = $lei->{sto} ? $lei->{sto}->ipc_do('done') : undef;
361         $lei->{ovv}->ovv_end($lei);
362         my (@out, $start_mua);
363         if ($l2m) { # close() calls LeiToMail reap_compress
364                 @out = (" in $lei->{ovv}->{dst}");
365                 if (my $out = delete $lei->{old_1}) {
366                         if (my $mbout = $lei->{1}) {
367                                 close($mbout) or return $lei->fail(<<"");
368 Error closing $lei->{ovv}->{dst}: $!
369
370                         }
371                         $lei->{1} = $out;
372                 }
373                 if ($l2m->lock_free) {
374                         $l2m->poke_dst;
375                         $lei->poke_mua;
376                 } else { # mbox users
377                         delete $l2m->{mbl}; # drop dotlock
378                         $start_mua = 1;
379                 }
380         }
381         if ($lei->{-progress}) {
382                 $lei->qerr('# ', $lei->{-mset_total} // 0, " matches", @out);
383                 my $nr = $lei->{-nr_write} // 0;
384                 $lei->qerr("# $nr written to $lei->{ovv}->{dst}") if $l2m;
385         }
386         $lei->start_mua if $start_mua;
387         $lei->dclose;
388 }
389
390 sub do_post_augment {
391         my ($lei) = @_;
392         my $l2m = $lei->{l2m} or return; # client disconnected
393         my $err;
394         eval { $l2m->post_augment($lei) };
395         $err = $@;
396         if ($err) {
397                 if (my $lxs = delete $lei->{lxs}) {
398                         $lxs->wq_kill;
399                         $lxs->wq_close(0, undef, $lei);
400                 }
401                 $lei->fail("$err");
402         }
403         if (!$err && delete $lei->{early_mua}) { # non-augment case
404                 $lei->start_mua;
405         }
406         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
407 }
408
409 sub incr_post_augment { # called whenever an l2m shard finishes augment
410         my ($lei) = @_;
411         my $l2m = $lei->{l2m} or return; # client disconnected
412         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
413         do_post_augment($lei);
414 }
415
416 my $MAX_PER_HOST = 4;
417
418 sub concurrency {
419         my ($self, $opt) = @_;
420         my $nl = $opt->{threads} ? locals($self) : 1;
421         my $nr = remotes($self);
422         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
423         $nl + $nr;
424 }
425
426 sub start_query ($;$) { # always runs in main (lei-daemon) process
427         my ($self, $l2m) = @_;
428         if ($self->{opt_threads} || ($l2m && !$self->{opt_sort})) {
429                 for my $ibxish (locals($self)) {
430                         $self->wq_io_do('query_one_mset', [], $ibxish);
431                 }
432         } elsif (locals($self)) {
433                 $self->wq_io_do('query_combined_mset', []);
434         }
435         my $i = 0;
436         my $q = [];
437         for my $uri (remotes($self)) {
438                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
439         }
440         for my $uris (@$q) {
441                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
442         }
443         $self->wq_close(1); # lei_xsearch workers stop when done
444 }
445
446 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
447         my ($self, $l2m) = @_;
448         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
449         start_query($self, $l2m);
450 }
451
452 sub ipc_atfork_child {
453         my ($self) = @_;
454         $self->{lei}->_lei_atfork_child;
455         $self->SUPER::ipc_atfork_child;
456 }
457
458 sub do_query {
459         my ($self, $lei) = @_;
460         my $l2m = $lei->{l2m};
461         my $ops = {
462                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
463                 '!' => [ $lei->can('fail_handler'), $lei ],
464                 '.' => [ \&do_post_augment, $lei ],
465                 '+' => [ \&incr_post_augment, $lei ],
466                 '' => [ \&query_done, $lei ],
467                 'mset_progress' => [ \&mset_progress, $lei ],
468                 'l2m_progress' => [ \&l2m_progress, $lei ],
469                 'x_it' => [ $lei->can('x_it'), $lei ],
470                 'child_error' => [ $lei->can('child_error'), $lei ],
471                 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
472         };
473         $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
474         my $end = $lei->pkt_op_pair;
475         $lei->{1}->autoflush(1);
476         $lei->start_pager if delete $lei->{need_pager};
477         $lei->{ovv}->ovv_begin($lei);
478         die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
479         if ($l2m) {
480                 $l2m->pre_augment($lei);
481                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
482                         $lei->start_mua;
483                 }
484                 $l2m->wq_workers_start('lei2mail', undef,
485                                         $lei->oldset, { lei => $lei });
486                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
487                 # 1031: F_SETPIPE_SZ
488                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
489         }
490         $self->wq_workers_start('lei_xsearch', undef,
491                                 $lei->oldset, { lei => $lei });
492         my $op_c = delete $lei->{pkt_op_c};
493         delete $lei->{pkt_op_p};
494         @$end = ();
495         $self->{opt_threads} = $lei->{opt}->{threads};
496         $self->{opt_sort} = $lei->{opt}->{'sort'};
497         if ($l2m) {
498                 $l2m->net_merge_complete unless $lei->{auth};
499         } else {
500                 start_query($self);
501         }
502         $lei->event_step_init; # wait for shutdowns
503         $op_c->op_wait_event($ops);
504 }
505
506 sub add_uri {
507         my ($self, $uri) = @_;
508         if (my $curl = $self->{curl} //= which('curl') // 0) {
509                 require PublicInbox::MboxReader;
510                 require IO::Uncompress::Gunzip;
511                 require PublicInbox::LeiCurl;
512                 push @{$self->{remotes}}, $uri;
513         } else {
514                 warn "curl missing, ignoring $uri\n";
515         }
516 }
517
518 sub prepare_external {
519         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
520         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
521                 return add_uri($self, $loc) if $loc->can('scheme');
522         } elsif ($loc =~ m!\Ahttps?://!) {
523                 require URI;
524                 return add_uri($self, URI->new($loc));
525         } elsif (-f "$loc/ei.lock") {
526                 require PublicInbox::ExtSearch;
527                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
528                 $loc = PublicInbox::ExtSearch->new($loc);
529         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
530                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
531                 require PublicInbox::Inbox; # v2, v1
532                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
533         } else {
534                 warn "W: ignoring $loc, unable to determine type\n";
535                 return;
536         }
537         push @{$self->{locals}}, $loc;
538 }
539
540
541 1;