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 git_blob_digest ($) {
96 my $dig = Digest::SHA->new(1); # XXX SHA256 later
97 $dig->add('blob '.length($$bref)."\0");
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)";
108 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
109 $size == 0 ? 1 : 0; # size == 0 means purged
112 sub check_batch_limit ($) {
114 my $self = $req->{self};
115 my $new_smsg = $req->{new_smsg};
117 # {raw_bytes} may be unset, so just use {bytes}
118 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
120 # set flag for PublicInbox::V2Writable::index_todo:
121 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
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);
140 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
143 $idx->shard_remove($oid, $docid);
144 } elsif ($rm_eidx_info) {
145 $idx->shard_remove_eidx_info($docid, $oid, $eidx_key,
151 # called by V2Writable::sync_prepare
152 sub artnum_max { $_[0]->{oidx}->eidx_max }
154 sub index_unseen ($) {
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);
171 sub do_finalize ($) {
173 if (my $indexed = $req->{indexed}) {
174 do_xpost($req, $_) for @$indexed;
175 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
178 # `d' message was already unindexed in the v1/v2 inboxes,
179 # so it's too noisy to warn, here.
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;
187 sub do_step ($) { # main iterator for adding messages to the index
189 my $self = $req->{self};
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
198 delete $req->{cur_smsg};
199 delete $req->{next_arg};
201 my $mid = shift(@{$req->{mids}});
202 last unless defined $mid;
204 $req->{next_arg} = [ $mid, \$id, \$prev ];
210 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
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);
217 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
218 die "BUG: xref $keep[0] has no OID";
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});
224 $self->{oidx}->delete_by_num($smsg->{num});
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') {
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 }
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';
249 git_blob_digest($bref)->hexdigest eq $req->{oid} or die
250 "BUG: blob mismatch $req->{oid}";
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)) {
258 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
259 return $x->{num} if $x->{blob} eq $req->{oid};
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 {
272 }, 'PublicInbox::Smsg';
273 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
274 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
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
288 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
290 my ($self, $sync) = @_;
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");
300 sub _sync_inbox ($$$) {
301 my ($self, $sync, $ibx) = @_;
303 $sync->{nr} = \(my $nr = 0);
304 my $v = $ibx->version;
305 my $ekey = $ibx->eidx_key;
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
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;
318 warn "E: $ekey unsupported inbox version (v$v)\n";
321 for my $unit (@{delete($sync->{todo}) // []}) {
322 last if $sync->{quit};
323 index_todo($self, $sync, $unit);
325 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
326 $ibx->git->cleanup; # done with this inbox, now
329 sub unref_doc ($$$$) {
330 my ($self, $ibx_id, $eidx_key, $docid) = @_;
331 my $dbh = $self->{oidx}->dbh;
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 = ?
337 $sth->execute($docid, $ibx_id);
338 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
340 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
341 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
343 my $remain = $self->{oidx}->get_xref3($docid);
344 my $idx = $self->idx_shard($docid);
347 warn "I: unref #$docid $eidx_key $oid\n";
348 $idx->shard_remove_eidx_info($docid, $oid, $eidx_key);
352 warn "I: remove #$docid $eidx_key $oid\n";
353 $idx->shard_remove($oid, $docid);
359 my ($self, $opt) = @_;
360 $self->{cfg} or die "E: GC requires ->attach_config\n";
362 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
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 ?');
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);
378 $dbh->prepare_cached(<<'')->execute($ibx_id);
379 DELETE FROM inboxes WHERE ibx_id = ?
381 # drop last_commit info
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 = ?
393 warn "I: $eidx_key removed\n";
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;
401 for my $idx (@{$self->{idx_shards}}) {
402 warn "I: cleaning up shard #$idx->{shard}\n";
403 $idx->shard_over_check($self->{oidx});
405 my $nr = $dbh->do(<<'');
406 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
408 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
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);
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}, ': ', @_);
424 need_checkpoint => \(my $need_checkpoint = 0),
425 reindex => $opt->{reindex},
428 -regen_fmt => "%u/?\n",
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;
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);
441 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
443 PublicInbox::V2Writable::done($self);
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};
456 my $v = $ibx->version;
458 die 'No {epoch} for v2 unit' unless defined $epoch;
459 $meta_key = "lc-v2:$ekey//$uv;$epoch";
461 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
462 $meta_key = "lc-v1:$ekey//$uv";
464 die "Unsupported inbox version: $v";
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;
472 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
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);
481 sub idx_init { # similar to V2Writable
482 my ($self, $opt) = @_;
483 return if $self->{idx_shards};
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";
492 my (@old, @new, %seen); # seen: st_dev + st_ino
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]"}++;
501 warn "W: stat($d) failed (from $alt): $!\n";
502 next if $opt->{-idx_gc};
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]"}++;
513 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
514 next if $opt->{-idx_gc};
521 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
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;
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;