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, $oid, $xibx, $eml);
129 check_batch_limit($req);
132 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
135 $idx->shard_remove($oid, $docid);
136 } elsif ($rm_eidx_info) {
137 $idx->shard_remove_eidx_info($docid, $oid, $eidx_key,
143 # called by V2Writable::sync_prepare
144 sub artnum_max { $_[0]->{oidx}->eidx_max }
146 sub index_unseen ($) {
148 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
149 my $eml = delete $req->{eml};
150 $new_smsg->populate($eml, $req);
151 my $self = $req->{self};
152 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
153 $new_smsg->{num} = $docid;
154 my $idx = $self->idx_shard($docid);
155 $self->{oidx}->add_overview($eml, $new_smsg);
156 my $oid = $new_smsg->{blob};
157 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
158 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
159 $idx->index_raw(undef, $eml, $new_smsg, $ibx);
160 check_batch_limit($req);
163 sub do_finalize ($) {
165 if (my $indexed = $req->{indexed}) {
166 do_xpost($req, $_) for @$indexed;
167 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
170 # `d' message was already unindexed in the v1/v2 inboxes,
171 # so it's too noisy to warn, here.
173 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
174 if (defined(my $cur_cmt = $req->{cur_cmt})) {
175 ${$req->{latest_cmt}} = $cur_cmt;
179 sub do_step ($) { # main iterator for adding messages to the index
181 my $self = $req->{self};
183 if (my $next_arg = $req->{next_arg}) {
184 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
185 $req->{cur_smsg} = $smsg;
186 $self->git->cat_async($smsg->{blob},
187 \&ck_existing, $req);
188 return; # ck_existing calls do_step
190 delete $req->{cur_smsg};
191 delete $req->{next_arg};
193 my $mid = shift(@{$req->{mids}});
194 last unless defined $mid;
196 $req->{next_arg} = [ $mid, \$id, \$prev ];
202 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
204 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
205 my $self = $req->{self};
206 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
207 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
209 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
210 die "BUG: xref $keep[0] has no OID";
212 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
213 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
214 my $saved = $self->{oidx}->get_art($smsg->{num});
216 $self->{oidx}->delete_by_num($smsg->{num});
220 sub ck_existing { # git->cat_async callback
221 my ($bref, $oid, $type, $size, $req) = @_;
222 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
223 if ($type eq 'missing') {
225 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
226 my $cur = PublicInbox::Eml->new($bref);
227 if (content_hash($cur) eq $req->{chash}) {
228 push @{$req->{indexed}}, $smsg; # for do_xpost
229 } # else { index_unseen later }
234 # is the messages visible in the inbox currently being indexed?
235 # return the number if so
236 sub cur_ibx_xnum ($$) {
237 my ($req, $bref) = @_;
238 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
240 $req->{eml} = PublicInbox::Eml->new($bref);
241 $req->{chash} = content_hash($req->{eml});
242 $req->{mids} = mids($req->{eml});
243 my @q = @{$req->{mids}}; # copy
244 while (defined(my $mid = shift @q)) {
246 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
247 return $x->{num} if $x->{blob} eq $req->{oid};
253 sub index_oid { # git->cat_async callback for 'm'
254 my ($bref, $oid, $type, $size, $req) = @_;
255 my $self = $req->{self};
256 local $self->{current_info} = "$self->{current_info} $oid";
257 return if is_bad_blob($oid, $type, $size, $req->{oid});
258 my $new_smsg = $req->{new_smsg} = bless {
260 }, 'PublicInbox::Smsg';
261 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
262 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
267 sub unindex_oid { # git->cat_async callback for 'd'
268 my ($bref, $oid, $type, $size, $req) = @_;
269 my $self = $req->{self};
270 local $self->{current_info} = "$self->{current_info} $oid";
271 return if is_bad_blob($oid, $type, $size, $req->{oid});
272 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
276 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
278 my ($self, $sync) = @_;
280 my $ekey = $sync->{ibx}->eidx_key;
281 my $uv = $sync->{ibx}->uidvalidity;
282 for my $i (0..$sync->{epoch_max}) {
283 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
288 sub _sync_inbox ($$$) {
289 my ($self, $sync, $ibx) = @_;
291 $sync->{nr} = \(my $nr = 0);
292 my $v = $ibx->version;
293 my $ekey = $ibx->eidx_key;
296 defined($ibx->git_dir_latest(\$epoch_max)) or return;
297 $sync->{epoch_max} = $epoch_max;
298 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
300 my $uv = $ibx->uidvalidity;
301 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
302 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
303 my $unit = { stack => $stk, git => $ibx->git };
304 push @{$sync->{todo}}, $unit;
306 warn "E: $ekey unsupported inbox version (v$v)\n";
309 for my $unit (@{delete($sync->{todo}) // []}) {
310 last if $sync->{quit};
311 index_todo($self, $sync, $unit);
313 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
314 $ibx->git->cleanup; # done with this inbox, now
317 sub unref_doc ($$$$) {
318 my ($self, $ibx_id, $eidx_key, $docid) = @_;
319 my $dbh = $self->{oidx}->dbh;
321 # for debug/info purposes, oids may no longer be accessible
322 my $sth = $dbh->prepare_cached(<<'', undef, 1);
323 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
325 $sth->execute($docid, $ibx_id);
326 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
328 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
329 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
331 my $remain = $self->{oidx}->get_xref3($docid);
332 my $idx = $self->idx_shard($docid);
335 warn "I: unref #$docid $eidx_key $oid\n";
336 $idx->shard_remove_eidx_info($docid, $oid, $eidx_key);
340 warn "I: remove #$docid $eidx_key $oid\n";
341 $idx->shard_remove($oid, $docid);
347 my ($self, $opt) = @_;
348 $self->{cfg} or die "E: GC requires ->attach_config\n";
350 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
352 my $dbh = $self->{oidx}->dbh;
353 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
354 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
355 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
358 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
359 next if $self->{ibx_map}->{$eidx_key};
360 $self->{midx}->remove_eidx_key($eidx_key);
361 warn "I: deleting messages for $eidx_key...\n";
362 $x3_doc->execute($ibx_id);
363 while (defined(my $docid = $x3_doc->fetchrow_array)) {
364 unref_doc($self, $ibx_id, $eidx_key, $docid);
366 $dbh->prepare_cached(<<'')->execute($ibx_id);
367 DELETE FROM inboxes WHERE ibx_id = ?
369 # drop last_commit info
371 $pat =~ s/([_%])/\\$1/g;
372 $lc_i->execute("lc-%:$pat//%");
373 while (my ($key) = $lc_i->fetchrow_array) {
374 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
375 warn "I: removing $key\n";
376 $dbh->prepare_cached(<<'')->execute($key);
377 DELETE FROM eidx_meta WHERE key = ?
381 warn "I: $eidx_key removed\n";
384 # it's not real unless it's in `over', we use parallelism here,
385 # shards will be reading directly from over, so commit
386 $self->{oidx}->commit_lazy;
387 $self->{oidx}->begin_lazy;
389 for my $idx (@{$self->{idx_shards}}) {
390 warn "I: cleaning up shard #$idx->{shard}\n";
391 $idx->shard_over_check($self->{oidx});
393 my $nr = $dbh->do(<<'');
394 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
396 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
401 sub eidx_sync { # main entry point
402 my ($self, $opt) = @_;
403 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
404 $self->{oidx}->rethread_prepare($opt);
406 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
407 local $self->{current_info} = '';
408 local $SIG{__WARN__} = sub {
409 $warn_cb->($self->{current_info}, ': ', @_);
412 need_checkpoint => \(my $need_checkpoint = 0),
413 reindex => $opt->{reindex},
416 -regen_fmt => "%u/?\n",
418 local $SIG{USR1} = sub { $need_checkpoint = 1 };
419 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
420 local $SIG{QUIT} = $quit;
421 local $SIG{INT} = $quit;
422 local $SIG{TERM} = $quit;
424 # don't use $_ here, it'll get clobbered by reindex_checkpoint
425 for my $ibx (@{$self->{ibx_list}}) {
426 last if $sync->{quit};
427 _sync_inbox($self, $sync, $ibx);
429 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
431 PublicInbox::V2Writable::done($self);
434 sub update_last_commit { # overrides V2Writable
435 my ($self, $sync, $stk) = @_;
436 my $unit = $sync->{unit} // return;
437 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
438 defined($latest_cmt) or return;
439 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
440 my $ekey = $ibx->eidx_key;
441 my $uv = $ibx->uidvalidity;
442 my $epoch = $unit->{epoch};
444 my $v = $ibx->version;
446 die 'No {epoch} for v2 unit' unless defined $epoch;
447 $meta_key = "lc-v2:$ekey//$uv;$epoch";
449 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
450 $meta_key = "lc-v1:$ekey//$uv";
452 die "Unsupported inbox version: $v";
454 my $last = $self->{oidx}->eidx_meta($meta_key);
455 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
456 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
457 chomp(my $n = $unit->{git}->qx(@cmd));
458 return if $n ne '' && $n == 0;
460 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
463 sub _idx_init { # with_umask callback
464 my ($self, $opt) = @_;
465 PublicInbox::V2Writable::_idx_init($self, $opt);
466 $self->{midx} = PublicInbox::MiscIdx->new($self);
469 sub idx_init { # similar to V2Writable
470 my ($self, $opt) = @_;
471 return if $self->{idx_shards};
475 my $ALL = $self->git->{git_dir}; # ALL.git
476 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
477 my $info_dir = "$ALL/objects/info";
478 my $alt = "$info_dir/alternates";
480 my (@old, @new, %seen); # seen: st_dev + st_ino
482 open(my $fh, '<', $alt) or die "open $alt: $!";
483 $mode = (stat($fh))[2] & 07777;
484 while (my $line = <$fh>) {
485 chomp(my $d = $line);
486 if (my @st = stat($d)) {
487 next if $seen{"$st[0]\0$st[1]"}++;
489 warn "W: stat($d) failed (from $alt): $!\n";
490 next if $opt->{-idx_gc};
495 for my $ibx (@{$self->{ibx_list}}) {
496 my $line = $ibx->git->{git_dir} . "/objects\n";
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 $ibx->{inboxdir}): $!\n";
502 next if $opt->{-idx_gc};
509 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
511 $self->parallel_init($self->{indexlevel});
512 $self->umask_prepare;
513 $self->with_umask(\&_idx_init, $self, $opt);
514 $self->{oidx}->begin_lazy;
515 $self->{oidx}->eidx_prep;
516 $self->{midx}->begin_txn;
520 *done = \&PublicInbox::V2Writable::done;
521 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
522 *with_umask = \&PublicInbox::InboxWritable::with_umask;
523 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
524 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
525 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
526 *index_todo = \&PublicInbox::V2Writable::index_todo;
527 *count_shards = \&PublicInbox::V2Writable::count_shards;
528 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
529 *idx_shard = \&PublicInbox::V2Writable::idx_shard;