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