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