1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
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.
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)
16 package PublicInbox::ExtSearchIdx;
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);
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";
40 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
42 creat => $opt->{creat},
43 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
50 lock_path => "$dir/ei.lock",
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;
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";
67 if (!defined($ibx->uidvalidity)) {
68 warn "W: skipping $key (no UIDVALIDITY)\n";
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;
76 $ibx = PublicInbox::InboxWritable->new($ibx);
77 $self->{ibx_map}->{$key} //= do {
78 push @{$self->{ibx_list}}, $ibx;
83 sub _ibx_attach { # each_inbox callback
84 my ($ibx, $self) = @_;
85 attach_inbox($self, $ibx);
89 my ($self, $cfg) = @_;
91 $cfg->each_inbox(\&_ibx_attach, $self);
94 sub is_bad_blob ($$$$) {
95 my ($oid, $type, $size, $expect_oid) = @_;
96 if ($type ne 'blob') {
97 carp "W: $expect_oid is not a blob (type=$type)";
100 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
101 $size == 0 ? 1 : 0; # size == 0 means purged
104 sub check_batch_limit ($) {
106 my $self = $req->{self};
107 my $new_smsg = $req->{new_smsg};
109 # {raw_bytes} may be unset, so just use {bytes}
110 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
112 # set flag for PublicInbox::V2Writable::index_todo:
113 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
117 my ($req, $smsg) = @_;
118 my $self = $req->{self};
119 my $docid = $smsg->{num};
120 my $idx = $self->idx_shard($docid);
121 my $oid = $req->{oid};
122 my $xibx = $req->{ibx};
123 my $eml = $req->{eml};
124 my $eidx_key = $xibx->eidx_key;
125 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
126 my $xnum = $req->{xnum};
127 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
128 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
129 check_batch_limit($req);
132 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
135 $idx->shard_remove($docid);
136 } elsif ($rm_eidx_info) {
137 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
142 # called by V2Writable::sync_prepare
143 sub artnum_max { $_[0]->{oidx}->eidx_max }
145 sub index_unseen ($) {
147 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
148 my $eml = delete $req->{eml};
149 $new_smsg->populate($eml, $req);
150 my $self = $req->{self};
151 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
152 $new_smsg->{num} = $docid;
153 my $idx = $self->idx_shard($docid);
154 $self->{oidx}->add_overview($eml, $new_smsg);
155 my $oid = $new_smsg->{blob};
156 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
157 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
158 $idx->index_raw(undef, $eml, $new_smsg, $ibx);
159 check_batch_limit($req);
162 sub do_finalize ($) {
164 if (my $indexed = $req->{indexed}) {
165 do_xpost($req, $_) for @$indexed;
166 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
169 # `d' message was already unindexed in the v1/v2 inboxes,
170 # so it's too noisy to warn, here.
172 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
173 if (defined(my $cur_cmt = $req->{cur_cmt})) {
174 ${$req->{latest_cmt}} = $cur_cmt;
178 sub do_step ($) { # main iterator for adding messages to the index
180 my $self = $req->{self};
182 if (my $next_arg = $req->{next_arg}) {
183 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
184 $req->{cur_smsg} = $smsg;
185 $self->git->cat_async($smsg->{blob},
186 \&ck_existing, $req);
187 return; # ck_existing calls do_step
189 delete $req->{cur_smsg};
190 delete $req->{next_arg};
192 my $mid = shift(@{$req->{mids}});
193 last unless defined $mid;
195 $req->{next_arg} = [ $mid, \$id, \$prev ];
201 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
203 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
204 my $self = $req->{self};
205 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
206 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
208 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
209 die "BUG: xref $keep[0] has no OID";
211 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
212 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
213 my $saved = $self->{oidx}->get_art($smsg->{num});
215 $self->{oidx}->delete_by_num($smsg->{num});
219 sub ck_existing { # git->cat_async callback
220 my ($bref, $oid, $type, $size, $req) = @_;
221 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
222 if ($type eq 'missing') {
224 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
225 my $cur = PublicInbox::Eml->new($bref);
226 if (content_hash($cur) eq $req->{chash}) {
227 push @{$req->{indexed}}, $smsg; # for do_xpost
228 } # else { index_unseen later }
233 # is the messages visible in the inbox currently being indexed?
234 # return the number if so
235 sub cur_ibx_xnum ($$) {
236 my ($req, $bref) = @_;
237 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
239 $req->{eml} = PublicInbox::Eml->new($bref);
240 $req->{chash} = content_hash($req->{eml});
241 $req->{mids} = mids($req->{eml});
242 my @q = @{$req->{mids}}; # copy
243 while (defined(my $mid = shift @q)) {
245 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
246 return $x->{num} if $x->{blob} eq $req->{oid};
252 sub index_oid { # git->cat_async callback for 'm'
253 my ($bref, $oid, $type, $size, $req) = @_;
254 my $self = $req->{self};
255 local $self->{current_info} = "$self->{current_info} $oid";
256 return if is_bad_blob($oid, $type, $size, $req->{oid});
257 my $new_smsg = $req->{new_smsg} = bless {
259 }, 'PublicInbox::Smsg';
260 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
261 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
266 sub unindex_oid { # git->cat_async callback for 'd'
267 my ($bref, $oid, $type, $size, $req) = @_;
268 my $self = $req->{self};
269 local $self->{current_info} = "$self->{current_info} $oid";
270 return if is_bad_blob($oid, $type, $size, $req->{oid});
271 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
275 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
277 my ($self, $sync) = @_;
279 my $ekey = $sync->{ibx}->eidx_key;
280 my $uv = $sync->{ibx}->uidvalidity;
281 for my $i (0..$sync->{epoch_max}) {
282 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
287 sub _sync_inbox ($$$) {
288 my ($self, $sync, $ibx) = @_;
290 $sync->{nr} = \(my $nr = 0);
291 my $v = $ibx->version;
292 my $ekey = $ibx->eidx_key;
295 defined($ibx->git_dir_latest(\$epoch_max)) or return;
296 $sync->{epoch_max} = $epoch_max;
297 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
299 my $uv = $ibx->uidvalidity;
300 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
301 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
302 my $unit = { stack => $stk, git => $ibx->git };
303 push @{$sync->{todo}}, $unit;
305 warn "E: $ekey unsupported inbox version (v$v)\n";
308 for my $unit (@{delete($sync->{todo}) // []}) {
309 last if $sync->{quit};
310 index_todo($self, $sync, $unit);
312 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
313 $ibx->git->cleanup; # done with this inbox, now
316 sub unref_doc ($$$$) {
317 my ($self, $ibx_id, $eidx_key, $docid) = @_;
318 my $dbh = $self->{oidx}->dbh;
320 # for debug/info purposes, oids may no longer be accessible
321 my $sth = $dbh->prepare_cached(<<'', undef, 1);
322 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
324 $sth->execute($docid, $ibx_id);
325 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
327 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
328 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
330 my $remain = $self->{oidx}->get_xref3($docid);
331 my $idx = $self->idx_shard($docid);
334 warn "I: unref #$docid $eidx_key $oid\n";
335 $idx->shard_remove_eidx_info($docid, $eidx_key);
338 warn "I: remove #$docid $eidx_key @oid\n";
339 $idx->shard_remove($docid);
344 my ($self, $opt) = @_;
345 $self->{cfg} or die "E: GC requires ->attach_config\n";
347 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
349 my $dbh = $self->{oidx}->dbh;
350 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
351 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
352 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
355 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
356 next if $self->{ibx_map}->{$eidx_key};
357 $self->{midx}->remove_eidx_key($eidx_key);
358 warn "I: deleting messages for $eidx_key...\n";
359 $x3_doc->execute($ibx_id);
360 while (defined(my $docid = $x3_doc->fetchrow_array)) {
361 unref_doc($self, $ibx_id, $eidx_key, $docid);
363 $dbh->prepare_cached(<<'')->execute($ibx_id);
364 DELETE FROM inboxes WHERE ibx_id = ?
366 # drop last_commit info
368 $pat =~ s/([_%])/\\$1/g;
369 $lc_i->execute("lc-%:$pat//%");
370 while (my ($key) = $lc_i->fetchrow_array) {
371 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
372 warn "I: removing $key\n";
373 $dbh->prepare_cached(<<'')->execute($key);
374 DELETE FROM eidx_meta WHERE key = ?
378 warn "I: $eidx_key removed\n";
381 # it's not real unless it's in `over', we use parallelism here,
382 # shards will be reading directly from over, so commit
383 $self->{oidx}->commit_lazy;
384 $self->{oidx}->begin_lazy;
386 for my $idx (@{$self->{idx_shards}}) {
387 warn "I: cleaning up shard #$idx->{shard}\n";
388 $idx->shard_over_check($self->{oidx});
390 my $nr = $dbh->do(<<'');
391 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
393 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
398 sub eidx_sync { # main entry point
399 my ($self, $opt) = @_;
400 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
401 $self->{oidx}->rethread_prepare($opt);
403 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
404 local $self->{current_info} = '';
405 local $SIG{__WARN__} = sub {
406 $warn_cb->($self->{current_info}, ': ', @_);
409 need_checkpoint => \(my $need_checkpoint = 0),
410 reindex => $opt->{reindex},
413 -regen_fmt => "%u/?\n",
415 local $SIG{USR1} = sub { $need_checkpoint = 1 };
416 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
417 local $SIG{QUIT} = $quit;
418 local $SIG{INT} = $quit;
419 local $SIG{TERM} = $quit;
421 # don't use $_ here, it'll get clobbered by reindex_checkpoint
422 for my $ibx (@{$self->{ibx_list}}) {
423 last if $sync->{quit};
424 _sync_inbox($self, $sync, $ibx);
426 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
428 PublicInbox::V2Writable::done($self);
431 sub update_last_commit { # overrides V2Writable
432 my ($self, $sync, $stk) = @_;
433 my $unit = $sync->{unit} // return;
434 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
435 defined($latest_cmt) or return;
436 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
437 my $ekey = $ibx->eidx_key;
438 my $uv = $ibx->uidvalidity;
439 my $epoch = $unit->{epoch};
441 my $v = $ibx->version;
443 die 'No {epoch} for v2 unit' unless defined $epoch;
444 $meta_key = "lc-v2:$ekey//$uv;$epoch";
446 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
447 $meta_key = "lc-v1:$ekey//$uv";
449 die "Unsupported inbox version: $v";
451 my $last = $self->{oidx}->eidx_meta($meta_key);
452 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
453 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
454 chomp(my $n = $unit->{git}->qx(@cmd));
455 return if $n ne '' && $n == 0;
457 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
460 sub _idx_init { # with_umask callback
461 my ($self, $opt) = @_;
462 PublicInbox::V2Writable::_idx_init($self, $opt);
463 $self->{midx} = PublicInbox::MiscIdx->new($self);
466 sub idx_init { # similar to V2Writable
467 my ($self, $opt) = @_;
468 return if $self->{idx_shards};
472 my $ALL = $self->git->{git_dir}; # ALL.git
473 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
474 my $info_dir = "$ALL/objects/info";
475 my $alt = "$info_dir/alternates";
477 my (@old, @new, %seen); # seen: st_dev + st_ino
479 open(my $fh, '<', $alt) or die "open $alt: $!";
480 $mode = (stat($fh))[2] & 07777;
481 while (my $line = <$fh>) {
482 chomp(my $d = $line);
483 if (my @st = stat($d)) {
484 next if $seen{"$st[0]\0$st[1]"}++;
486 warn "W: stat($d) failed (from $alt): $!\n";
487 next if $opt->{-idx_gc};
492 for my $ibx (@{$self->{ibx_list}}) {
493 my $line = $ibx->git->{git_dir} . "/objects\n";
494 chomp(my $d = $line);
495 if (my @st = stat($d)) {
496 next if $seen{"$st[0]\0$st[1]"}++;
498 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
499 next if $opt->{-idx_gc};
506 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
508 $self->parallel_init($self->{indexlevel});
509 $self->umask_prepare;
510 $self->with_umask(\&_idx_init, $self, $opt);
511 $self->{oidx}->begin_lazy;
512 $self->{oidx}->eidx_prep;
513 $self->{midx}->begin_txn;
517 *done = \&PublicInbox::V2Writable::done;
518 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
519 *with_umask = \&PublicInbox::InboxWritable::with_umask;
520 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
521 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
522 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
523 *index_todo = \&PublicInbox::V2Writable::index_todo;
524 *count_shards = \&PublicInbox::V2Writable::count_shards;
525 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
526 *idx_shard = \&PublicInbox::V2Writable::idx_shard;