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