]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei: add some labels support
[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_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 query_thread_mset { # for --threads
148         my ($self, $ibxish) = @_;
149         local $0 = "$0 query_thread_mset";
150         my $lei = $self->{lei};
151         my ($srch, $over) = ($ibxish->search, $ibxish->over);
152         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
153         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
154         my $mo = { %{$lei->{mset_opt}} };
155         my $mset;
156         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
157         my $can_kw = !!$ibxish->can('msg_keywords');
158         my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
159         do {
160                 $mset = $srch->mset($mo->{qstr}, $mo);
161                 mset_progress($lei, $desc, $mset->size,
162                                 $mset->get_matches_estimated);
163                 wait_startq($lei); # wait for keyword updates
164                 my $ids = $srch->mset_to_artnums($mset, $mo);
165                 my $ctx = { ids => $ids };
166                 my $i = 0;
167                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
168                 while ($over->expand_thread($ctx)) {
169                         for my $n (@{$ctx->{xids}}) {
170                                 my $smsg = $over->get_art($n) or next;
171                                 my $mitem = delete $n2item{$smsg->{num}};
172                                 next if $smsg->{bytes} == 0;
173                                 if ($mitem) {
174                                         if ($can_kw) {
175                                                 mitem_kw($smsg, $mitem, $fl);
176                                         } elsif ($fl) {
177                                                 # call ->xsmsg_vmd, later
178                                                 $smsg->{lei_q_tt_flagged} = 1;
179                                         }
180                                 }
181                                 $each_smsg->($smsg, $mitem);
182                         }
183                         @{$ctx->{xids}} = ();
184                 }
185         } while (_mset_more($mset, $mo));
186         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
187         $lei->{ovv}->ovv_atexit_child($lei);
188 }
189
190 sub query_mset { # non-parallel for non-"--threads" users
191         my ($self) = @_;
192         local $0 = "$0 query_mset";
193         my $lei = $self->{lei};
194         my $mo = { %{$lei->{mset_opt}} };
195         my $mset;
196         for my $loc (locals($self)) {
197                 attach_external($self, $loc);
198         }
199         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
200         do {
201                 $mset = $self->mset($mo->{qstr}, $mo);
202                 mset_progress($lei, 'xsearch', $mset->size,
203                                 $mset->size, $mset->get_matches_estimated);
204                 wait_startq($lei); # wait for keyword updates
205                 for my $mitem ($mset->items) {
206                         my $smsg = smsg_for($self, $mitem) or next;
207                         $each_smsg->($smsg, $mitem);
208                 }
209         } while (_mset_more($mset, $mo));
210         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
211         $lei->{ovv}->ovv_atexit_child($lei);
212 }
213
214 sub each_remote_eml { # callback for MboxReader->mboxrd
215         my ($eml, $self, $lei, $each_smsg) = @_;
216         my $xoids = $lei->{ale}->xoids_for($eml, 1);
217         if ($self->{import_sto} && !$xoids) {
218                 $self->{import_sto}->ipc_do('add_eml', $eml);
219         }
220         my $smsg = bless {}, 'PublicInbox::Smsg';
221         $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
222                                 : git_sha(1, $eml)->hexdigest;
223         $smsg->populate($eml);
224         $smsg->parse_references($eml, mids($eml));
225         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
226         delete @$smsg{qw(From Subject -ds -ts)};
227         wait_startq($lei);
228         if ($lei->{-progress}) {
229                 ++$lei->{-nr_remote_eml};
230                 my $now = now();
231                 my $next = $lei->{-next_progress} //= ($now + 1);
232                 if ($now > $next) {
233                         $lei->{-next_progress} = $now + 1;
234                         my $nr = $lei->{-nr_remote_eml};
235                         $lei->err("# $lei->{-current_url} $nr/?");
236                 }
237         }
238         $each_smsg->($smsg, undef, $eml);
239 }
240
241 sub query_remote_mboxrd {
242         my ($self, $uris) = @_;
243         local $0 = "$0 query_remote_mboxrd";
244         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
245         my $lei = $self->{lei};
246         my $opt = $lei->{opt};
247         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
248         push(@qform, t => 1) if $opt->{threads};
249         my $verbose = $opt->{verbose};
250         my ($reap_tail, $reap_curl);
251         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
252         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
253         my $rdr = { 2 => $cerr, pgid => 0 };
254         my $sigint_reap = $lei->can('sigint_reap');
255         if ($verbose) {
256                 # spawn a process to force line-buffering, otherwise curl
257                 # will write 1 character at-a-time and parallel outputs
258                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
259                 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
260                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
261                 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
262         }
263         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
264         push @$curl, '-s', '-d', '';
265         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
266         $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
267         for my $uri (@$uris) {
268                 $lei->{-current_url} = $uri->as_string;
269                 $lei->{-nr_remote_eml} = 0;
270                 $uri->query_form(@qform);
271                 my $cmd = $curl->for_uri($lei, $uri);
272                 $lei->qerr("# $cmd");
273                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
274                 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
275                 $fh = IO::Uncompress::Gunzip->new($fh);
276                 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
277                                                 $lei, $each_smsg);
278                 my $err = waitpid($pid, 0) == $pid ? undef
279                                                 : "BUG: waitpid($cmd): $!";
280                 @$reap_curl = (); # cancel OnDestroy
281                 die $err if $err;
282                 my $nr = $lei->{-nr_remote_eml};
283                 if ($nr && $lei->{sto}) {
284                         my $wait = $lei->{sto}->ipc_do('done');
285                 }
286                 if ($? == 0) {
287                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
288                         next;
289                 }
290                 $err = '';
291                 if (-s $cerr) {
292                         seek($cerr, 0, SEEK_SET) or
293                                         $lei->err("seek($cmd stderr): $!");
294                         $err = do { local $/; <$cerr> } //
295                                         "read($cmd stderr): $!";
296                         truncate($cerr, 0) or
297                                         $lei->err("truncate($cmd stderr): $!");
298                 }
299                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
300                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
301                 $lei->child_error($?, "E: <$uri> $err");
302         }
303         undef $each_smsg;
304         $lei->{ovv}->ovv_atexit_child($lei);
305 }
306
307 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
308
309 sub xsearch_done_wait { # dwaitpid callback
310         my ($arg, $pid) = @_;
311         my ($wq, $lei) = @$arg;
312         $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
313 }
314
315 sub query_done { # EOF callback for main daemon
316         my ($lei) = @_;
317         my $l2m = delete $lei->{l2m};
318         $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
319         if (my $lxs = delete $lei->{lxs}) {
320                 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
321         }
322         $lei->{ovv}->ovv_end($lei);
323         if ($l2m) { # close() calls LeiToMail reap_compress
324                 if (my $out = delete $lei->{old_1}) {
325                         if (my $mbout = $lei->{1}) {
326                                 close($mbout) or return $lei->fail(<<"");
327 Error closing $lei->{ovv}->{dst}: $!
328
329                         }
330                         $lei->{1} = $out;
331                 }
332                 if ($l2m->lock_free) {
333                         $l2m->poke_dst;
334                         $lei->poke_mua;
335                 } else { # mbox users
336                         delete $l2m->{mbl}; # drop dotlock
337                         $lei->start_mua;
338                 }
339         }
340         $lei->{-progress} and
341                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
342         $lei->dclose;
343 }
344
345 sub do_post_augment {
346         my ($lei) = @_;
347         my $l2m = $lei->{l2m} or return; # client disconnected
348         my $err;
349         eval { $l2m->post_augment($lei) };
350         $err = $@;
351         if ($err) {
352                 if (my $lxs = delete $lei->{lxs}) {
353                         $lxs->wq_kill;
354                         $lxs->wq_close(0, undef, $lei);
355                 }
356                 $lei->fail("$err");
357         }
358         if (!$err && delete $lei->{early_mua}) { # non-augment case
359                 $lei->start_mua;
360         }
361         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
362 }
363
364 sub incr_post_augment { # called whenever an l2m shard finishes augment
365         my ($lei) = @_;
366         my $l2m = $lei->{l2m} or return; # client disconnected
367         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
368         do_post_augment($lei);
369 }
370
371 my $MAX_PER_HOST = 4;
372
373 sub concurrency {
374         my ($self, $opt) = @_;
375         my $nl = $opt->{threads} ? locals($self) : 1;
376         my $nr = remotes($self);
377         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
378         $nl + $nr;
379 }
380
381 sub start_query { # always runs in main (lei-daemon) process
382         my ($self) = @_;
383         if ($self->{threads}) {
384                 for my $ibxish (locals($self)) {
385                         $self->wq_io_do('query_thread_mset', [], $ibxish);
386                 }
387         } elsif (locals($self)) {
388                 $self->wq_io_do('query_mset', []);
389         }
390         my $i = 0;
391         my $q = [];
392         for my $uri (remotes($self)) {
393                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
394         }
395         for my $uris (@$q) {
396                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
397         }
398         $self->wq_close(1); # lei_xsearch workers stop when done
399 }
400
401 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
402         my ($self, $l2m) = @_;
403         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
404         start_query($self);
405 }
406
407 sub ipc_atfork_child {
408         my ($self) = @_;
409         $self->{lei}->_lei_atfork_child;
410         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
411         $self->SUPER::ipc_atfork_child;
412 }
413
414 sub do_query {
415         my ($self, $lei) = @_;
416         my $l2m = $lei->{l2m};
417         my $ops = {
418                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
419                 '!' => [ $lei->can('fail_handler'), $lei ],
420                 '.' => [ \&do_post_augment, $lei ],
421                 '+' => [ \&incr_post_augment, $lei ],
422                 '' => [ \&query_done, $lei ],
423                 'mset_progress' => [ \&mset_progress, $lei ],
424                 'x_it' => [ $lei->can('x_it'), $lei ],
425                 'child_error' => [ $lei->can('child_error'), $lei ],
426                 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
427         };
428         $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
429         my $end = $lei->pkt_op_pair($ops);
430         $lei->{1}->autoflush(1);
431         $lei->start_pager if delete $lei->{need_pager};
432         $lei->{ovv}->ovv_begin($lei);
433         if ($l2m) {
434                 $l2m->pre_augment($lei);
435                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
436                         $lei->start_mua;
437                 }
438                 $l2m->wq_workers_start('lei2mail', undef,
439                                         $lei->oldset, { lei => $lei });
440                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
441                 # 1031: F_SETPIPE_SZ
442                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
443         }
444         $self->wq_workers_start('lei_xsearch', undef,
445                                 $lei->oldset, { lei => $lei });
446         my $op = delete $lei->{pkt_op_c};
447         delete $lei->{pkt_op_p};
448         @$end = ();
449         $self->{threads} = $lei->{opt}->{threads};
450         if ($l2m) {
451                 $l2m->net_merge_complete unless $lei->{auth};
452         } else {
453                 start_query($self);
454         }
455         $lei->event_step_init; # wait for shutdowns
456         if ($lei->{oneshot}) {
457                 while ($op->{sock}) { $op->event_step }
458         }
459 }
460
461 sub add_uri {
462         my ($self, $uri) = @_;
463         if (my $curl = $self->{curl} //= which('curl') // 0) {
464                 require PublicInbox::MboxReader;
465                 require IO::Uncompress::Gunzip;
466                 require PublicInbox::LeiCurl;
467                 push @{$self->{remotes}}, $uri;
468         } else {
469                 warn "curl missing, ignoring $uri\n";
470         }
471 }
472
473 sub prepare_external {
474         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
475         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
476                 return add_uri($self, $loc) if $loc->can('scheme');
477         } elsif ($loc =~ m!\Ahttps?://!) {
478                 require URI;
479                 return add_uri($self, URI->new($loc));
480         } elsif (-f "$loc/ei.lock") {
481                 require PublicInbox::ExtSearch;
482                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
483                 $loc = PublicInbox::ExtSearch->new($loc);
484         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
485                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
486                 require PublicInbox::Inbox; # v2, v1
487                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
488         } else {
489                 warn "W: ignoring $loc, unable to determine type\n";
490                 return;
491         }
492         push @{$self->{locals}}, $loc;
493 }
494
495
496 1;