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