]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
isearch: emulate per-inbox search with ->ALL
[public-inbox.git] / lib / PublicInbox / ExtSearchIdx.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
6 #
7 # It's based on the same ideas as public-inbox-v2-format(5) using
8 # over.sqlite3 for dedupe and sharded Xapian.  msgmap.sqlite3 is
9 # missing, so there is no Message-ID conflict resolution, meaning
10 # no NNTP support for now.
11 #
12 # v2 has a 1:1 mapping of index:inbox or msgmap for NNTP support.
13 # This is intended to be an M:N index:inbox mapping, but it'll likely
14 # be 1:N in common practice (M==1)
15
16 package PublicInbox::ExtSearchIdx;
17 use strict;
18 use v5.10.1;
19 use parent qw(PublicInbox::ExtSearch PublicInbox::Lock);
20 use Carp qw(croak carp);
21 use PublicInbox::Search;
22 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor);
23 use PublicInbox::OverIdx;
24 use PublicInbox::MiscIdx;
25 use PublicInbox::MID qw(mids);
26 use PublicInbox::V2Writable;
27 use PublicInbox::InboxWritable;
28 use PublicInbox::ContentHash qw(content_hash);
29 use PublicInbox::Eml;
30 use File::Spec;
31
32 sub new {
33         my (undef, $dir, $opt) = @_;
34         $dir = File::Spec->canonpath($dir);
35         my $l = $opt->{indexlevel} // 'full';
36         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
37                 die "invalid indexlevel=$l\n";
38         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
39         my $self = bless {
40                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
41                 topdir => $dir,
42                 creat => $opt->{creat},
43                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
44                 ibx_list => [],
45                 indexlevel => $l,
46                 transact_bytes => 0,
47                 total_bytes => 0,
48                 current_info => '',
49                 parallel => 1,
50                 lock_path => "$dir/ei.lock",
51         }, __PACKAGE__;
52         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
53         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
54         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
55         $self->{oidx} = $oidx;
56         $self
57 }
58
59 sub attach_inbox {
60         my ($self, $ibx) = @_;
61         $ibx = PublicInbox::InboxWritable->new($ibx);
62         my $key = $ibx->eidx_key;
63         if (!$ibx->over || !$ibx->mm) {
64                 warn "W: skipping $key (unindexed)\n";
65                 return;
66         }
67         if (!defined($ibx->uidvalidity)) {
68                 warn "W: skipping $key (no UIDVALIDITY)\n";
69                 return;
70         }
71         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
72         if ($ibxdir ne $ibx->{inboxdir}) {
73                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
74                 $ibx->{inboxdir} = $ibxdir;
75         }
76         $ibx = PublicInbox::InboxWritable->new($ibx);
77         $self->{ibx_map}->{$key} //= do {
78                 push @{$self->{ibx_list}}, $ibx;
79                 $ibx;
80         }
81 }
82
83 sub _ibx_attach { # each_inbox callback
84         my ($ibx, $self) = @_;
85         attach_inbox($self, $ibx);
86 }
87
88 sub attach_config {
89         my ($self, $cfg) = @_;
90         $self->{cfg} = $cfg;
91         $cfg->each_inbox(\&_ibx_attach, $self);
92 }
93
94 sub git_blob_digest ($) {
95         my ($bref) = @_;
96         my $dig = Digest::SHA->new(1); # XXX SHA256 later
97         $dig->add('blob '.length($$bref)."\0");
98         $dig->add($$bref);
99         $dig;
100 }
101
102 sub is_bad_blob ($$$$) {
103         my ($oid, $type, $size, $expect_oid) = @_;
104         if ($type ne 'blob') {
105                 carp "W: $expect_oid is not a blob (type=$type)";
106                 return 1;
107         }
108         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
109         $size == 0 ? 1 : 0; # size == 0 means purged
110 }
111
112 sub check_batch_limit ($) {
113         my ($req) = @_;
114         my $self = $req->{self};
115         my $new_smsg = $req->{new_smsg};
116
117         # {raw_bytes} may be unset, so just use {bytes}
118         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
119
120         # set flag for PublicInbox::V2Writable::index_todo:
121         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
122 }
123
124 sub do_xpost ($$) {
125         my ($req, $smsg) = @_;
126         my $self = $req->{self};
127         my $docid = $smsg->{num};
128         my $idx = $self->idx_shard($docid);
129         my $oid = $req->{oid};
130         my $xibx = $req->{ibx};
131         my $eml = $req->{eml};
132         my $eidx_key = $xibx->eidx_key;
133         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
134                 my $xnum = $req->{xnum};
135                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
136                 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
137                 check_batch_limit($req);
138         } else { # 'd'
139                 my $rm_eidx_info;
140                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
141                                                         \$rm_eidx_info);
142                 if ($nr == 0) {
143                         $idx->shard_remove($oid, $docid);
144                 } elsif ($rm_eidx_info) {
145                         $idx->shard_remove_eidx_info($docid, $oid, $eidx_key,
146                                                         $eml);
147                 }
148         }
149 }
150
151 # called by V2Writable::sync_prepare
152 sub artnum_max { $_[0]->{oidx}->eidx_max }
153
154 sub index_unseen ($) {
155         my ($req) = @_;
156         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
157         my $eml = delete $req->{eml};
158         $new_smsg->populate($eml, $req);
159         my $self = $req->{self};
160         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
161         $new_smsg->{num} = $docid;
162         my $idx = $self->idx_shard($docid);
163         $self->{oidx}->add_overview($eml, $new_smsg);
164         my $oid = $new_smsg->{blob};
165         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
166         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
167         $idx->index_raw(undef, $eml, $new_smsg, $ibx);
168         check_batch_limit($req);
169 }
170
171 sub do_finalize ($) {
172         my ($req) = @_;
173         if (my $indexed = $req->{indexed}) {
174                 do_xpost($req, $_) for @$indexed;
175         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
176                 index_unseen($req);
177         } else {
178                 # `d' message was already unindexed in the v1/v2 inboxes,
179                 # so it's too noisy to warn, here.
180         }
181         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
182         if (defined(my $cur_cmt = $req->{cur_cmt})) {
183                 ${$req->{latest_cmt}} = $cur_cmt;
184         }
185 }
186
187 sub do_step ($) { # main iterator for adding messages to the index
188         my ($req) = @_;
189         my $self = $req->{self};
190         while (1) {
191                 if (my $next_arg = $req->{next_arg}) {
192                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
193                                 $req->{cur_smsg} = $smsg;
194                                 $self->git->cat_async($smsg->{blob},
195                                                         \&ck_existing, $req);
196                                 return; # ck_existing calls do_step
197                         }
198                         delete $req->{cur_smsg};
199                         delete $req->{next_arg};
200                 }
201                 my $mid = shift(@{$req->{mids}});
202                 last unless defined $mid;
203                 my ($id, $prev);
204                 $req->{next_arg} = [ $mid, \$id, \$prev ];
205                 # loop again
206         }
207         do_finalize($req);
208 }
209
210 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
211         my ($req) = @_;
212         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
213         my $self = $req->{self};
214         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
215         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
216         if (@keep) {
217                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
218                         die "BUG: xref $keep[0] has no OID";
219                 my $oidhex = $1;
220                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
221                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
222                 my $saved = $self->{oidx}->get_art($smsg->{num});
223         } else {
224                 $self->{oidx}->delete_by_num($smsg->{num});
225         }
226 }
227
228 sub ck_existing { # git->cat_async callback
229         my ($bref, $oid, $type, $size, $req) = @_;
230         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
231         if ($type eq 'missing') {
232                 _blob_missing($req);
233         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
234                 my $cur = PublicInbox::Eml->new($bref);
235                 if (content_hash($cur) eq $req->{chash}) {
236                         push @{$req->{indexed}}, $smsg; # for do_xpost
237                 } # else { index_unseen later }
238         }
239         do_step($req);
240 }
241
242 # is the messages visible in the inbox currently being indexed?
243 # return the number if so
244 sub cur_ibx_xnum ($$) {
245         my ($req, $bref) = @_;
246         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
247
248         # XXX overkill?
249         git_blob_digest($bref)->hexdigest eq $req->{oid} or die
250                 "BUG: blob mismatch $req->{oid}";
251
252         $req->{eml} = PublicInbox::Eml->new($bref);
253         $req->{chash} = content_hash($req->{eml});
254         $req->{mids} = mids($req->{eml});
255         my @q = @{$req->{mids}}; # copy
256         while (defined(my $mid = shift @q)) {
257                 my ($id, $prev);
258                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
259                         return $x->{num} if $x->{blob} eq $req->{oid};
260                 }
261         }
262         undef;
263 }
264
265 sub index_oid { # git->cat_async callback for 'm'
266         my ($bref, $oid, $type, $size, $req) = @_;
267         my $self = $req->{self};
268         local $self->{current_info} = "$self->{current_info} $oid";
269         return if is_bad_blob($oid, $type, $size, $req->{oid});
270         my $new_smsg = $req->{new_smsg} = bless {
271                 blob => $oid,
272         }, 'PublicInbox::Smsg';
273         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
274         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
275         ++${$req->{nr}};
276         do_step($req);
277 }
278
279 sub unindex_oid { # git->cat_async callback for 'd'
280         my ($bref, $oid, $type, $size, $req) = @_;
281         my $self = $req->{self};
282         local $self->{current_info} = "$self->{current_info} $oid";
283         return if is_bad_blob($oid, $type, $size, $req->{oid});
284         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
285         do_step($req);
286 }
287
288 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
289 sub last_commits {
290         my ($self, $sync) = @_;
291         my $heads = [];
292         my $ekey = $sync->{ibx}->eidx_key;
293         my $uv = $sync->{ibx}->uidvalidity;
294         for my $i (0..$sync->{epoch_max}) {
295                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
296         }
297         $heads;
298 }
299
300 sub _sync_inbox ($$$) {
301         my ($self, $sync, $ibx) = @_;
302         $sync->{ibx} = $ibx;
303         $sync->{nr} = \(my $nr = 0);
304         my $v = $ibx->version;
305         my $ekey = $ibx->eidx_key;
306         if ($v == 2) {
307                 my $epoch_max;
308                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
309                 $sync->{epoch_max} = $epoch_max;
310                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
311         } elsif ($v == 1) {
312                 my $uv = $ibx->uidvalidity;
313                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
314                 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
315                 my $unit = { stack => $stk, git => $ibx->git };
316                 push @{$sync->{todo}}, $unit;
317         } else {
318                 warn "E: $ekey unsupported inbox version (v$v)\n";
319                 return;
320         }
321         for my $unit (@{delete($sync->{todo}) // []}) {
322                 last if $sync->{quit};
323                 index_todo($self, $sync, $unit);
324         }
325         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
326         $ibx->git->cleanup; # done with this inbox, now
327 }
328
329 sub unref_doc ($$$$) {
330         my ($self, $ibx_id, $eidx_key, $docid) = @_;
331         my $dbh = $self->{oidx}->dbh;
332
333         # for debug/info purposes, oids may no longer be accessible
334         my $sth = $dbh->prepare_cached(<<'', undef, 1);
335 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
336
337         $sth->execute($docid, $ibx_id);
338         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
339
340         $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
341 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
342
343         my $remain = $self->{oidx}->get_xref3($docid);
344         my $idx = $self->idx_shard($docid);
345         if (@$remain) {
346                 for my $oid (@oid) {
347                         warn "I: unref #$docid $eidx_key $oid\n";
348                         $idx->shard_remove_eidx_info($docid, $oid, $eidx_key);
349                 }
350         } else {
351                 for my $oid (@oid) {
352                         warn "I: remove #$docid $eidx_key $oid\n";
353                         $idx->shard_remove($oid, $docid);
354                 }
355         }
356 }
357
358 sub eidx_gc {
359         my ($self, $opt) = @_;
360         $self->{cfg} or die "E: GC requires ->attach_config\n";
361         $opt->{-idx_gc} = 1;
362         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
363
364         my $dbh = $self->{oidx}->dbh;
365         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
366         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
367         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
368
369         $ibx_ck->execute;
370         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
371                 next if $self->{ibx_map}->{$eidx_key};
372                 $self->{midx}->remove_eidx_key($eidx_key);
373                 warn "I: deleting messages for $eidx_key...\n";
374                 $x3_doc->execute($ibx_id);
375                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
376                         unref_doc($self, $ibx_id, $eidx_key, $docid);
377                 }
378                 $dbh->prepare_cached(<<'')->execute($ibx_id);
379 DELETE FROM inboxes WHERE ibx_id = ?
380
381                 # drop last_commit info
382                 my $pat = $eidx_key;
383                 $pat =~ s/([_%])/\\$1/g;
384                 $lc_i->execute("lc-%:$pat//%");
385                 while (my ($key) = $lc_i->fetchrow_array) {
386                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
387                         warn "I: removing $key\n";
388                         $dbh->prepare_cached(<<'')->execute($key);
389 DELETE FROM eidx_meta WHERE key = ?
390
391                 }
392
393                 warn "I: $eidx_key removed\n";
394         }
395
396         # it's not real unless it's in `over', we use parallelism here,
397         # shards will be reading directly from over, so commit
398         $self->{oidx}->commit_lazy;
399         $self->{oidx}->begin_lazy;
400
401         for my $idx (@{$self->{idx_shards}}) {
402                 warn "I: cleaning up shard #$idx->{shard}\n";
403                 $idx->shard_over_check($self->{oidx});
404         }
405         my $nr = $dbh->do(<<'');
406 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
407
408         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
409
410         done($self);
411 }
412
413 sub eidx_sync { # main entry point
414         my ($self, $opt) = @_;
415         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
416         $self->{oidx}->rethread_prepare($opt);
417
418         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
419         local $self->{current_info} = '';
420         local $SIG{__WARN__} = sub {
421                 $warn_cb->($self->{current_info}, ': ', @_);
422         };
423         my $sync = {
424                 need_checkpoint => \(my $need_checkpoint = 0),
425                 reindex => $opt->{reindex},
426                 -opt => $opt,
427                 self => $self,
428                 -regen_fmt => "%u/?\n",
429         };
430         local $SIG{USR1} = sub { $need_checkpoint = 1 };
431         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
432         local $SIG{QUIT} = $quit;
433         local $SIG{INT} = $quit;
434         local $SIG{TERM} = $quit;
435
436         # don't use $_ here, it'll get clobbered by reindex_checkpoint
437         for my $ibx (@{$self->{ibx_list}}) {
438                 last if $sync->{quit};
439                 _sync_inbox($self, $sync, $ibx);
440         }
441         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
442
443         PublicInbox::V2Writable::done($self);
444 }
445
446 sub update_last_commit { # overrides V2Writable
447         my ($self, $sync, $stk) = @_;
448         my $unit = $sync->{unit} // return;
449         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
450         defined($latest_cmt) or return;
451         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
452         my $ekey = $ibx->eidx_key;
453         my $uv = $ibx->uidvalidity;
454         my $epoch = $unit->{epoch};
455         my $meta_key;
456         my $v = $ibx->version;
457         if ($v == 2) {
458                 die 'No {epoch} for v2 unit' unless defined $epoch;
459                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
460         } elsif ($v == 1) {
461                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
462                 $meta_key = "lc-v1:$ekey//$uv";
463         } else {
464                 die "Unsupported inbox version: $v";
465         }
466         my $last = $self->{oidx}->eidx_meta($meta_key);
467         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
468                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
469                 chomp(my $n = $unit->{git}->qx(@cmd));
470                 return if $n ne '' && $n == 0;
471         }
472         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
473 }
474
475 sub _idx_init { # with_umask callback
476         my ($self, $opt) = @_;
477         PublicInbox::V2Writable::_idx_init($self, $opt);
478         $self->{midx} = PublicInbox::MiscIdx->new($self);
479 }
480
481 sub idx_init { # similar to V2Writable
482         my ($self, $opt) = @_;
483         return if $self->{idx_shards};
484
485         $self->git->cleanup;
486
487         my $ALL = $self->git->{git_dir}; # ALL.git
488         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
489         my $info_dir = "$ALL/objects/info";
490         my $alt = "$info_dir/alternates";
491         my $mode = 0644;
492         my (@old, @new, %seen); # seen: st_dev + st_ino
493         if (-e $alt) {
494                 open(my $fh, '<', $alt) or die "open $alt: $!";
495                 $mode = (stat($fh))[2] & 07777;
496                 while (my $line = <$fh>) {
497                         chomp(my $d = $line);
498                         if (my @st = stat($d)) {
499                                 next if $seen{"$st[0]\0$st[1]"}++;
500                         } else {
501                                 warn "W: stat($d) failed (from $alt): $!\n";
502                                 next if $opt->{-idx_gc};
503                         }
504                         push @old, $line;
505                 }
506         }
507         for my $ibx (@{$self->{ibx_list}}) {
508                 my $line = $ibx->git->{git_dir} . "/objects\n";
509                 chomp(my $d = $line);
510                 if (my @st = stat($d)) {
511                         next if $seen{"$st[0]\0$st[1]"}++;
512                 } else {
513                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
514                         next if $opt->{-idx_gc};
515                 }
516                 push @new, $line;
517         }
518         if (scalar @new) {
519                 push @old, @new;
520                 my $o = \@old;
521                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
522         }
523         $self->parallel_init($self->{indexlevel});
524         $self->umask_prepare;
525         $self->with_umask(\&_idx_init, $self, $opt);
526         $self->{oidx}->begin_lazy;
527         $self->{oidx}->eidx_prep;
528         $self->{midx}->begin_txn;
529 }
530
531 no warnings 'once';
532 *done = \&PublicInbox::V2Writable::done;
533 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
534 *with_umask = \&PublicInbox::InboxWritable::with_umask;
535 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
536 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
537 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
538 *index_todo = \&PublicInbox::V2Writable::index_todo;
539 *count_shards = \&PublicInbox::V2Writable::count_shards;
540 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
541 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
542
543 1;