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
24 use PublicInbox::OverIdx;
25 use PublicInbox::MiscIdx;
26 use PublicInbox::MID qw(mids);
27 use PublicInbox::V2Writable;
28 use PublicInbox::InboxWritable;
29 use PublicInbox::ContentHash qw(content_hash);
34 my (undef, $dir, $opt) = @_;
35 $dir = File::Spec->canonpath($dir);
36 my $l = $opt->{indexlevel} // 'full';
37 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
38 die "invalid indexlevel=$l\n";
39 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
41 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
43 creat => $opt->{creat},
44 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
51 lock_path => "$dir/ei.lock",
53 $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
54 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
55 $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
56 $self->{oidx} = $oidx;
61 my ($self, $ibx) = @_;
62 $ibx = PublicInbox::InboxWritable->new($ibx);
63 my $key = $ibx->eidx_key;
64 if (!$ibx->over || !$ibx->mm) {
65 warn "W: skipping $key (unindexed)\n";
68 if (!defined($ibx->uidvalidity)) {
69 warn "W: skipping $key (no UIDVALIDITY)\n";
72 my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
73 if ($ibxdir ne $ibx->{inboxdir}) {
74 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
75 $ibx->{inboxdir} = $ibxdir;
77 $ibx = PublicInbox::InboxWritable->new($ibx);
78 $self->{ibx_map}->{$key} //= do {
79 push @{$self->{ibx_list}}, $ibx;
84 sub _ibx_attach { # each_inbox callback
85 my ($ibx, $self) = @_;
86 attach_inbox($self, $ibx);
90 my ($self, $cfg) = @_;
92 $cfg->each_inbox(\&_ibx_attach, $self);
95 sub check_batch_limit ($) {
97 my $self = $req->{self};
98 my $new_smsg = $req->{new_smsg};
100 # {raw_bytes} may be unset, so just use {bytes}
101 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
103 # set flag for PublicInbox::V2Writable::index_todo:
104 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
108 my ($req, $smsg) = @_;
109 my $self = $req->{self};
110 my $docid = $smsg->{num};
111 my $idx = $self->idx_shard($docid);
112 my $oid = $req->{oid};
113 my $xibx = $req->{ibx};
114 my $eml = $req->{eml};
115 my $eidx_key = $xibx->eidx_key;
116 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
117 my $xnum = $req->{xnum};
118 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
119 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
120 check_batch_limit($req);
123 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
126 $idx->shard_remove($docid);
127 } elsif ($rm_eidx_info) {
128 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
133 # called by V2Writable::sync_prepare
134 sub artnum_max { $_[0]->{oidx}->eidx_max }
136 sub index_unseen ($) {
138 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
139 my $eml = delete $req->{eml};
140 $new_smsg->populate($eml, $req);
141 my $self = $req->{self};
142 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
143 $new_smsg->{num} = $docid;
144 my $idx = $self->idx_shard($docid);
145 $self->{oidx}->add_overview($eml, $new_smsg);
146 my $oid = $new_smsg->{blob};
147 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
148 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
149 $idx->index_raw(undef, $eml, $new_smsg, $ibx);
150 check_batch_limit($req);
153 sub do_finalize ($) {
155 if (my $indexed = $req->{indexed}) {
156 do_xpost($req, $_) for @$indexed;
157 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
160 # `d' message was already unindexed in the v1/v2 inboxes,
161 # so it's too noisy to warn, here.
163 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
164 if (defined(my $cur_cmt = $req->{cur_cmt})) {
165 ${$req->{latest_cmt}} = $cur_cmt;
169 sub do_step ($) { # main iterator for adding messages to the index
171 my $self = $req->{self};
173 if (my $next_arg = $req->{next_arg}) {
174 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
175 $req->{cur_smsg} = $smsg;
176 $self->git->cat_async($smsg->{blob},
177 \&ck_existing, $req);
178 return; # ck_existing calls do_step
180 delete $req->{cur_smsg};
181 delete $req->{next_arg};
183 my $mid = shift(@{$req->{mids}});
184 last unless defined $mid;
186 $req->{next_arg} = [ $mid, \$id, \$prev ];
192 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
194 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
195 my $self = $req->{self};
196 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
197 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
199 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
200 die "BUG: xref $keep[0] has no OID";
202 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
203 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
204 my $saved = $self->{oidx}->get_art($smsg->{num});
206 $self->{oidx}->delete_by_num($smsg->{num});
210 sub ck_existing { # git->cat_async callback
211 my ($bref, $oid, $type, $size, $req) = @_;
212 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
213 if ($type eq 'missing') {
215 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
216 my $self = $req->{self} // die 'BUG: {self} missing';
217 local $self->{current_info} = "$self->{current_info} $oid";
218 my $cur = PublicInbox::Eml->new($bref);
219 if (content_hash($cur) eq $req->{chash}) {
220 push @{$req->{indexed}}, $smsg; # for do_xpost
221 } # else { index_unseen later }
226 # is the messages visible in the inbox currently being indexed?
227 # return the number if so
228 sub cur_ibx_xnum ($$) {
229 my ($req, $bref) = @_;
230 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
232 $req->{eml} = PublicInbox::Eml->new($bref);
233 $req->{chash} = content_hash($req->{eml});
234 $req->{mids} = mids($req->{eml});
235 my @q = @{$req->{mids}}; # copy
236 while (defined(my $mid = shift @q)) {
238 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
239 return $x->{num} if $x->{blob} eq $req->{oid};
245 sub index_oid { # git->cat_async callback for 'm'
246 my ($bref, $oid, $type, $size, $req) = @_;
247 my $self = $req->{self};
248 local $self->{current_info} = "$self->{current_info} $oid";
249 return if is_bad_blob($oid, $type, $size, $req->{oid});
250 my $new_smsg = $req->{new_smsg} = bless {
252 }, 'PublicInbox::Smsg';
253 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
254 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
259 sub unindex_oid { # git->cat_async callback for 'd'
260 my ($bref, $oid, $type, $size, $req) = @_;
261 my $self = $req->{self};
262 local $self->{current_info} = "$self->{current_info} $oid";
263 return if is_bad_blob($oid, $type, $size, $req->{oid});
264 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
268 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
270 my ($self, $sync) = @_;
272 my $ekey = $sync->{ibx}->eidx_key;
273 my $uv = $sync->{ibx}->uidvalidity;
274 for my $i (0..$sync->{epoch_max}) {
275 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
280 sub _sync_inbox ($$$) {
281 my ($self, $sync, $ibx) = @_;
283 $sync->{nr} = \(my $nr = 0);
284 my $v = $ibx->version;
285 my $ekey = $ibx->eidx_key;
288 defined($ibx->git_dir_latest(\$epoch_max)) or return;
289 $sync->{epoch_max} = $epoch_max;
290 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
292 my $uv = $ibx->uidvalidity;
293 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
294 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
295 my $unit = { stack => $stk, git => $ibx->git };
296 push @{$sync->{todo}}, $unit;
298 warn "E: $ekey unsupported inbox version (v$v)\n";
301 for my $unit (@{delete($sync->{todo}) // []}) {
302 last if $sync->{quit};
303 index_todo($self, $sync, $unit);
305 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
306 $ibx->git->cleanup; # done with this inbox, now
309 sub unref_doc ($$$$) {
310 my ($self, $ibx_id, $eidx_key, $docid) = @_;
311 my $dbh = $self->{oidx}->dbh;
313 # for debug/info purposes, oids may no longer be accessible
314 my $sth = $dbh->prepare_cached(<<'', undef, 1);
315 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
317 $sth->execute($docid, $ibx_id);
318 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
320 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
321 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
323 my $remain = $self->{oidx}->get_xref3($docid);
324 my $idx = $self->idx_shard($docid);
327 warn "I: unref #$docid $eidx_key $oid\n";
328 $idx->shard_remove_eidx_info($docid, $eidx_key);
331 warn "I: remove #$docid $eidx_key @oid\n";
332 $idx->shard_remove($docid);
337 my ($self, $opt) = @_;
338 $self->{cfg} or die "E: GC requires ->attach_config\n";
340 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
342 my $dbh = $self->{oidx}->dbh;
343 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
344 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
345 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
348 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
349 next if $self->{ibx_map}->{$eidx_key};
350 $self->{midx}->remove_eidx_key($eidx_key);
351 warn "I: deleting messages for $eidx_key...\n";
352 $x3_doc->execute($ibx_id);
353 while (defined(my $docid = $x3_doc->fetchrow_array)) {
354 unref_doc($self, $ibx_id, $eidx_key, $docid);
356 $dbh->prepare_cached(<<'')->execute($ibx_id);
357 DELETE FROM inboxes WHERE ibx_id = ?
359 # drop last_commit info
361 $pat =~ s/([_%])/\\$1/g;
362 $lc_i->execute("lc-%:$pat//%");
363 while (my ($key) = $lc_i->fetchrow_array) {
364 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
365 warn "I: removing $key\n";
366 $dbh->prepare_cached(<<'')->execute($key);
367 DELETE FROM eidx_meta WHERE key = ?
371 warn "I: $eidx_key removed\n";
374 # it's not real unless it's in `over', we use parallelism here,
375 # shards will be reading directly from over, so commit
376 $self->{oidx}->commit_lazy;
377 $self->{oidx}->begin_lazy;
379 for my $idx (@{$self->{idx_shards}}) {
380 warn "I: cleaning up shard #$idx->{shard}\n";
381 $idx->shard_over_check($self->{oidx});
383 my $nr = $dbh->do(<<'');
384 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
386 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
391 sub eidx_sync { # main entry point
392 my ($self, $opt) = @_;
393 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
394 $self->{oidx}->rethread_prepare($opt);
396 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
397 local $self->{current_info} = '';
398 local $SIG{__WARN__} = sub {
399 $warn_cb->($self->{current_info}, ': ', @_);
402 need_checkpoint => \(my $need_checkpoint = 0),
403 reindex => $opt->{reindex},
406 -regen_fmt => "%u/?\n",
408 local $SIG{USR1} = sub { $need_checkpoint = 1 };
409 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
410 local $SIG{QUIT} = $quit;
411 local $SIG{INT} = $quit;
412 local $SIG{TERM} = $quit;
414 # don't use $_ here, it'll get clobbered by reindex_checkpoint
415 for my $ibx (@{$self->{ibx_list}}) {
416 last if $sync->{quit};
417 _sync_inbox($self, $sync, $ibx);
419 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
421 PublicInbox::V2Writable::done($self);
424 sub update_last_commit { # overrides V2Writable
425 my ($self, $sync, $stk) = @_;
426 my $unit = $sync->{unit} // return;
427 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
428 defined($latest_cmt) or return;
429 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
430 my $ekey = $ibx->eidx_key;
431 my $uv = $ibx->uidvalidity;
432 my $epoch = $unit->{epoch};
434 my $v = $ibx->version;
436 die 'No {epoch} for v2 unit' unless defined $epoch;
437 $meta_key = "lc-v2:$ekey//$uv;$epoch";
439 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
440 $meta_key = "lc-v1:$ekey//$uv";
442 die "Unsupported inbox version: $v";
444 my $last = $self->{oidx}->eidx_meta($meta_key);
445 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
446 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
447 chomp(my $n = $unit->{git}->qx(@cmd));
448 return if $n ne '' && $n == 0;
450 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
453 sub _idx_init { # with_umask callback
454 my ($self, $opt) = @_;
455 PublicInbox::V2Writable::_idx_init($self, $opt);
456 $self->{midx} = PublicInbox::MiscIdx->new($self);
459 sub idx_init { # similar to V2Writable
460 my ($self, $opt) = @_;
461 return if $self->{idx_shards};
465 my $ALL = $self->git->{git_dir}; # ALL.git
466 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
467 my $info_dir = "$ALL/objects/info";
468 my $alt = "$info_dir/alternates";
470 my (@old, @new, %seen); # seen: st_dev + st_ino
472 open(my $fh, '<', $alt) or die "open $alt: $!";
473 $mode = (stat($fh))[2] & 07777;
474 while (my $line = <$fh>) {
475 chomp(my $d = $line);
476 if (my @st = stat($d)) {
477 next if $seen{"$st[0]\0$st[1]"}++;
479 warn "W: stat($d) failed (from $alt): $!\n";
480 next if $opt->{-idx_gc};
485 for my $ibx (@{$self->{ibx_list}}) {
486 my $line = $ibx->git->{git_dir} . "/objects\n";
487 chomp(my $d = $line);
488 if (my @st = stat($d)) {
489 next if $seen{"$st[0]\0$st[1]"}++;
491 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
492 next if $opt->{-idx_gc};
499 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
501 $self->parallel_init($self->{indexlevel});
502 $self->umask_prepare;
503 $self->with_umask(\&_idx_init, $self, $opt);
504 $self->{oidx}->begin_lazy;
505 $self->{oidx}->eidx_prep;
506 $self->{midx}->begin_txn;
510 *done = \&PublicInbox::V2Writable::done;
511 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
512 *with_umask = \&PublicInbox::InboxWritable::with_umask;
513 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
514 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
515 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
516 *index_todo = \&PublicInbox::V2Writable::index_todo;
517 *count_shards = \&PublicInbox::V2Writable::count_shards;
518 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
519 *idx_shard = \&PublicInbox::V2Writable::idx_shard;