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 Sys::Hostname qw(hostname);
22 use POSIX qw(strftime);
23 use PublicInbox::Search;
24 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor
26 use PublicInbox::OverIdx;
27 use PublicInbox::MiscIdx;
28 use PublicInbox::MID qw(mids);
29 use PublicInbox::V2Writable;
30 use PublicInbox::InboxWritable;
31 use PublicInbox::ContentHash qw(content_hash);
34 use PublicInbox::DS qw(now);
35 use DBI qw(:sql_types); # SQL_BLOB
38 my (undef, $dir, $opt) = @_;
39 $dir = File::Spec->canonpath($dir);
40 my $l = $opt->{indexlevel} // 'full';
41 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
42 die "invalid indexlevel=$l\n";
43 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
45 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
47 creat => $opt->{creat},
48 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
55 lock_path => "$dir/ei.lock",
57 $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
58 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
59 $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
60 $self->{oidx} = $oidx;
65 my ($self, $ibx) = @_;
66 my $key = $ibx->eidx_key;
67 if (!$ibx->over || !$ibx->mm) {
68 warn "W: skipping $key (unindexed)\n";
71 if (!defined($ibx->uidvalidity)) {
72 warn "W: skipping $key (no UIDVALIDITY)\n";
75 my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
76 if ($ibxdir ne $ibx->{inboxdir}) {
77 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
78 $ibx->{inboxdir} = $ibxdir;
80 $self->{ibx_map}->{$key} //= do {
81 push @{$self->{ibx_list}}, $ibx;
86 sub _ibx_attach { # each_inbox callback
87 my ($ibx, $self) = @_;
88 attach_inbox($self, $ibx);
92 my ($self, $cfg) = @_;
94 $cfg->each_inbox(\&_ibx_attach, $self);
97 sub check_batch_limit ($) {
99 my $self = $req->{self};
100 my $new_smsg = $req->{new_smsg};
102 # {raw_bytes} may be unset, so just use {bytes}
103 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
105 # set flag for PublicInbox::V2Writable::index_todo:
106 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
110 my ($req, $smsg) = @_;
111 my $self = $req->{self};
112 my $docid = $smsg->{num};
113 my $idx = $self->idx_shard($docid);
114 my $oid = $req->{oid};
115 my $xibx = $req->{ibx};
116 my $eml = $req->{eml};
117 my $eidx_key = $xibx->eidx_key;
118 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
119 my $xnum = $req->{xnum};
120 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
121 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
122 check_batch_limit($req);
125 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
128 $self->{oidx}->eidxq_del($docid);
129 $idx->shard_remove($docid);
130 } elsif ($rm_eidx_info) {
131 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
132 $self->{oidx}->eidxq_add($docid); # yes, add
137 # called by V2Writable::sync_prepare
138 sub artnum_max { $_[0]->{oidx}->eidx_max }
140 sub index_unseen ($) {
142 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
143 my $eml = delete $req->{eml};
144 $new_smsg->populate($eml, $req);
145 my $self = $req->{self};
146 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
147 $new_smsg->{num} = $docid;
148 my $idx = $self->idx_shard($docid);
149 $self->{oidx}->add_overview($eml, $new_smsg);
150 my $oid = $new_smsg->{blob};
151 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
152 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
153 $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
154 check_batch_limit($req);
157 sub do_finalize ($) {
159 if (my $indexed = $req->{indexed}) {
160 do_xpost($req, $_) for @$indexed;
161 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
164 # `d' message was already unindexed in the v1/v2 inboxes,
165 # so it's too noisy to warn, here.
167 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
168 if (defined(my $cur_cmt = $req->{cur_cmt})) {
169 ${$req->{latest_cmt}} = $cur_cmt;
173 sub do_step ($) { # main iterator for adding messages to the index
175 my $self = $req->{self} // die 'BUG: {self} missing';
177 if (my $next_arg = $req->{next_arg}) {
178 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
179 $req->{cur_smsg} = $smsg;
180 $self->git->cat_async($smsg->{blob},
181 \&ck_existing, $req);
182 return; # ck_existing calls do_step
184 delete $req->{cur_smsg};
185 delete $req->{next_arg};
187 my $mid = shift(@{$req->{mids}});
188 last unless defined $mid;
190 $req->{next_arg} = [ $mid, \$id, \$prev ];
196 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
198 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
199 my $self = $req->{self};
200 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
201 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
203 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
204 die "BUG: xref $keep[0] has no OID";
206 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
207 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
208 my $saved = $self->{oidx}->get_art($smsg->{num});
210 $self->{oidx}->delete_by_num($smsg->{num});
214 sub ck_existing { # git->cat_async callback
215 my ($bref, $oid, $type, $size, $req) = @_;
216 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
217 if ($type eq 'missing') {
219 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
220 my $self = $req->{self} // die 'BUG: {self} missing';
221 local $self->{current_info} = "$self->{current_info} $oid";
222 my $cur = PublicInbox::Eml->new($bref);
223 if (content_hash($cur) eq $req->{chash}) {
224 push @{$req->{indexed}}, $smsg; # for do_xpost
225 } # else { index_unseen later }
230 # is the messages visible in the inbox currently being indexed?
231 # return the number if so
232 sub cur_ibx_xnum ($$) {
233 my ($req, $bref) = @_;
234 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
236 $req->{eml} = PublicInbox::Eml->new($bref);
237 $req->{chash} = content_hash($req->{eml});
238 $req->{mids} = mids($req->{eml});
239 my @q = @{$req->{mids}}; # copy
240 while (defined(my $mid = shift @q)) {
242 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
243 return $x->{num} if $x->{blob} eq $req->{oid};
249 sub index_oid { # git->cat_async callback for 'm'
250 my ($bref, $oid, $type, $size, $req) = @_;
251 my $self = $req->{self};
252 local $self->{current_info} = "$self->{current_info} $oid";
253 return if is_bad_blob($oid, $type, $size, $req->{oid});
254 my $new_smsg = $req->{new_smsg} = bless {
256 }, 'PublicInbox::Smsg';
257 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
258 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
263 sub unindex_oid { # git->cat_async callback for 'd'
264 my ($bref, $oid, $type, $size, $req) = @_;
265 my $self = $req->{self};
266 local $self->{current_info} = "$self->{current_info} $oid";
267 return if is_bad_blob($oid, $type, $size, $req->{oid});
268 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
272 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
274 my ($self, $sync) = @_;
276 my $ekey = $sync->{ibx}->eidx_key;
277 my $uv = $sync->{ibx}->uidvalidity;
278 for my $i (0..$sync->{epoch_max}) {
279 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
284 sub _sync_inbox ($$$) {
285 my ($self, $sync, $ibx) = @_;
287 $sync->{nr} = \(my $nr = 0);
288 my $v = $ibx->version;
289 my $ekey = $ibx->eidx_key;
291 $sync->{epoch_max} = $ibx->max_git_epoch // return;
292 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
294 my $uv = $ibx->uidvalidity;
295 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
296 my $head = $ibx->mm->last_commit;
297 unless (defined $head) {
298 warn "E: $ibx->{inboxdir} is not indexed\n";
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 gc_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 if (scalar(@$remain)) {
332 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
334 warn "I: unref #$docid $eidx_key $oid\n";
337 warn "I: remove #$docid $eidx_key @oid\n";
338 $self->idx_shard($docid)->shard_remove($docid);
343 my ($self, $opt) = @_;
344 $self->{cfg} or die "E: GC requires ->attach_config\n";
346 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
348 my $dbh = $self->{oidx}->dbh;
349 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
350 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
351 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
354 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
355 next if $self->{ibx_map}->{$eidx_key};
356 $self->{midx}->remove_eidx_key($eidx_key);
357 warn "I: deleting messages for $eidx_key...\n";
358 $x3_doc->execute($ibx_id);
359 while (defined(my $docid = $x3_doc->fetchrow_array)) {
360 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
362 $dbh->prepare_cached(<<'')->execute($ibx_id);
363 DELETE FROM inboxes WHERE ibx_id = ?
365 # drop last_commit info
367 $pat =~ s/([_%])/\\$1/g;
368 $lc_i->execute("lc-%:$pat//%");
369 while (my ($key) = $lc_i->fetchrow_array) {
370 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
371 warn "I: removing $key\n";
372 $dbh->prepare_cached(<<'')->execute($key);
373 DELETE FROM eidx_meta WHERE key = ?
377 warn "I: $eidx_key removed\n";
380 # it's not real unless it's in `over', we use parallelism here,
381 # shards will be reading directly from over, so commit
382 $self->{oidx}->commit_lazy;
383 $self->{oidx}->begin_lazy;
385 for my $idx (@{$self->{idx_shards}}) {
386 warn "I: cleaning up shard #$idx->{shard}\n";
387 $idx->shard_over_check($self->{oidx});
389 my $nr = $dbh->do(<<'');
390 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
392 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
398 my ($self, $sync, $smsg) = @_;
399 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
400 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
401 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
404 sub _reindex_finalize ($$$) {
405 my ($req, $smsg, $eml) = @_;
406 my $sync = $req->{sync};
407 my $self = $sync->{self};
408 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
409 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
410 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
411 my $docid = $smsg->{num} = $orig_smsg->{num};
412 $self->{oidx}->add_overview($eml, $smsg); # may rethread
413 check_batch_limit({ %$sync, new_smsg => $smsg });
414 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
415 my $stable = delete($by_chash->{$chash0}) //
416 die "BUG: $smsg->{blob} chash missing";
417 my $idx = $self->idx_shard($docid);
418 my $top_smsg = pop @$stable;
419 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
420 my $ibx = _ibx_for($self, $sync, $smsg);
421 $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
422 for my $x (reverse @$stable) {
423 $ibx = _ibx_for($self, $sync, $x);
424 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
425 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
427 return if $nr == 1; # likely, all good
429 warn "W: #$docid split into $nr due to deduplication change\n";
431 for my $ary (values %$by_chash) {
432 for my $x (reverse @$ary) {
433 warn "removing #$docid xref3 $x->{blob}\n";
434 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
435 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
437 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
438 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
439 $ibx = _ibx_for($self, $sync, $x);
440 my $e = $ibx->over->get_art($x->{num});
441 $e->{blob} eq $x->{blob} or die <<EOF;
442 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
444 push @todo, $ibx, $e;
447 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
448 reindex_unseen($self, $sync, $ibx, $e);
452 sub _reindex_oid { # git->cat_async callback
453 my ($bref, $oid, $type, $size, $req) = @_;
454 my $sync = $req->{sync};
455 my $self = $sync->{self};
456 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
457 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
458 my $docid = $orig_smsg->{num};
459 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
460 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
462 warn "W: #$docid gone or corrupted\n";
463 $self->idx_shard($docid)->shard_remove($docid);
464 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
465 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
467 warn "BUG: #$docid gone (UNEXPECTED)\n";
468 $self->idx_shard($docid)->shard_remove($docid);
472 my $ci = $self->{current_info};
473 local $self->{current_info} = "$ci #$docid $oid";
474 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
475 $re_smsg->{bytes} = $size + crlf_adjust($$bref);
476 my $eml = PublicInbox::Eml->new($bref);
477 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
478 cotime => $orig_smsg->{ts} });
479 my $chash = content_hash($eml);
480 $re_smsg->{chash} = $chash;
481 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
482 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
483 $re_smsg->{hdr} = $eml->header_obj;
484 push @{$req->{by_chash}->{$chash}}, $re_smsg;
485 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
486 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
487 } else { # last $re_smsg is the highest priority xref3
488 local $self->{current_info} = "$ci #$docid";
489 _reindex_finalize($req, $re_smsg, $eml);
493 sub _reindex_smsg ($$$) {
494 my ($self, $sync, $smsg) = @_;
495 my $docid = $smsg->{num};
496 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
497 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
499 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
501 $self->{oidx}->delete_by_num($docid);
502 $self->idx_shard($docid)->shard_remove($docid);
506 # we sort {xr3r} in the reverse order of {ibx_list} so we can
507 # hit the common case in _reindex_finalize without rereading
508 # from git (or holding multiple messages in memory).
509 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
511 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
513 $b->[1] <=> $a->[1] # break ties with {xnum}
515 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
516 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
517 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
520 sub checkpoint_due ($) {
522 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
526 # I've copied FS images and only changed the hostname before,
527 # so prepend hostname. Use `state' since these a BOFH can change
528 # these while this process is running and we always want to be
529 # able to release locks taken by this process.
530 state $retval = hostname . '-' . do {
531 my $m; # machine-id(5) is systemd
532 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
533 # hostid(1) is in GNU coreutils, kern.hostid is FreeBSD
534 chomp($m ||= `hostid` || `sysctl -n kern.hostid`);
541 my $expect = delete($self->{-eidxq_locked}) or return;
542 my ($owner_pid, undef) = split(/-/, $expect);
543 return if $owner_pid != $$; # shards may fork
544 my $oidx = $self->{oidx};
546 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
547 if ($cur eq $expect) {
548 $oidx->eidx_meta('eidxq_lock', '');
550 } elsif ($cur ne '') {
551 warn "E: eidxq_lock($expect) stolen by $cur\n";
553 warn "E: eidxq_lock($expect) released by another process\n";
560 eidxq_release($self) and $self->{oidx}->commit_lazy;
563 sub _eidxq_take ($) {
565 my $val = "$$-${\time}-$>-".host_ident;
566 $self->{oidx}->eidx_meta('eidxq_lock', $val);
567 $self->{-eidxq_locked} = $val;
570 sub eidxq_lock_acquire ($) {
572 my $oidx = $self->{oidx};
574 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
575 if (my $locked = $self->{-eidxq_locked}) { # be lazy
576 return $locked if $locked eq $cur;
578 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
579 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
580 if ($euid == $> && $ident eq host_ident) {
583 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
587 warn "I: eidxq_lock is stale ($cur), clobbering\n";
588 return _eidxq_take($self);
590 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
592 my $fn = $oidx->dbh->sqlite_db_filename;
594 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
595 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
596 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
601 sub eidxq_process ($$) { # for reindexing
602 my ($self, $sync) = @_;
604 return unless eidxq_lock_acquire($self);
605 my $dbh = $self->{oidx}->dbh;
606 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
608 $sync->{-regen_fmt} = "%u/$tot\n";
609 my $pr = $sync->{-opt}->{-progress};
611 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
612 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
613 $pr->("Xapian indexing $min..$max (total=$tot)\n");
615 $sync->{id2pos} //= do {
618 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
623 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
624 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
626 while (defined(my $docid = $iter->fetchrow_array)) {
627 last if $sync->{quit};
628 if (my $smsg = $self->{oidx}->get_art($docid)) {
629 _reindex_smsg($self, $sync, $smsg);
631 warn "E: #$docid does not exist in over\n";
633 $del->execute($docid);
636 if (checkpoint_due($sync)) {
637 $dbh = $del = $iter = undef;
638 reindex_checkpoint($self, $sync); # release lock
639 $dbh = $self->{oidx}->dbh;
643 $self->git->async_wait_all;
644 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
647 sub _reindex_unseen { # git->cat_async callback
648 my ($bref, $oid, $type, $size, $req) = @_;
649 return if is_bad_blob($oid, $type, $size, $req->{oid});
650 my $self = $req->{self} // die 'BUG: {self} unset';
651 local $self->{current_info} = "$self->{current_info} $oid";
652 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
653 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
654 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
655 $req->{new_smsg} = $new_smsg;
656 $req->{chash} = content_hash($eml);
657 $req->{mids} = mids($eml); # do_step iterates through this
658 do_step($req); # enter the normal indexing flow
661 # --reindex may catch totally unseen messages, this handles them
662 sub reindex_unseen ($$$$) {
663 my ($self, $sync, $ibx, $xsmsg) = @_;
666 autime => $xsmsg->{ds},
667 cotime => $xsmsg->{ts},
668 oid => $xsmsg->{blob},
670 xnum => $xsmsg->{num},
671 # {mids} and {chash} will be filled in at _reindex_unseen
673 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
674 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
677 sub _reindex_check_unseen ($$$) {
678 my ($self, $sync, $ibx) = @_;
679 my $ibx_id = $ibx->{-ibx_id};
681 my ($beg, $end) = (1, $slice);
683 # first, check if we missed any messages in target $ibx
685 my $pr = $sync->{-opt}->{-progress};
686 my $ekey = $ibx->eidx_key;
687 $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
690 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
691 ${$sync->{nr}} = $beg;
692 $beg = $msgs->[-1]->{num} + 1;
693 $end = $beg + $slice;
694 if (checkpoint_due($sync)) {
695 reindex_checkpoint($self, $sync); # release lock
698 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
699 SELECT DISTINCT(docid) FROM xref3 WHERE
700 ibx_id = ? AND xnum = ? AND oidbin = ?
702 for my $xsmsg (@$msgs) {
703 my $oidbin = pack('H*', $xsmsg->{blob});
704 $inx3->bind_param(1, $ibx_id);
705 $inx3->bind_param(2, $xsmsg->{num});
706 $inx3->bind_param(3, $oidbin, SQL_BLOB);
708 my $docids = $inx3->fetchall_arrayref;
709 # index messages which were totally missed
710 # the first time around ASAP:
711 if (scalar(@$docids) == 0) {
712 reindex_unseen($self, $sync, $ibx, $xsmsg);
713 } else { # already seen, reindex later
714 for my $r (@$docids) {
715 $self->{oidx}->eidxq_add($r->[0]);
718 last if $sync->{quit};
720 last if $sync->{quit};
724 sub _reindex_check_stale ($$$) {
725 my ($self, $sync, $ibx) = @_;
727 my $pr = $sync->{-opt}->{-progress};
729 my $ekey = $ibx->eidx_key;
730 $sync->{-regen_fmt} =
731 "$ekey check stale/missing %u/".$ibx->over->max."\n";
734 if (checkpoint_due($sync)) {
735 reindex_checkpoint($self, $sync); # release lock
737 # now, check if there's stale xrefs
738 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
739 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
740 ORDER BY docid,xnum ASC LIMIT 10000
742 $iter->execute($ibx->{-ibx_id}, $min);
745 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
746 return if $sync->{quit};
747 ${$sync->{nr}} = $xnum;
749 $fetching = $min = $docid;
750 my $smsg = $ibx->over->get_art($xnum);
751 my $oidhex = unpack('H*', $oidbin);
755 } elsif ($smsg->{blob} ne $oidhex) {
756 $err = "mismatch (!= $smsg->{blob})";
758 next; # likely, all good
760 # current_info already has eidx_key
761 warn "$xnum:$oidhex (#$docid): $err\n";
762 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
763 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
765 $del->bind_param(1, $ibx->{-ibx_id});
766 $del->bind_param(2, $xnum);
767 $del->bind_param(3, $oidbin, SQL_BLOB);
770 # get_xref3 over-fetches, but this is a rare path:
771 my $xr3 = $self->{oidx}->get_xref3($docid);
772 my $idx = $self->idx_shard($docid);
773 if (scalar(@$xr3) == 0) { # all gone
774 $self->{oidx}->delete_by_num($docid);
775 $self->{oidx}->eidxq_del($docid);
776 $idx->shard_remove($docid);
777 } else { # enqueue for reindex of remaining messages
778 $idx->shard_remove_eidx_info($docid,
780 $self->{oidx}->eidxq_add($docid); # yes, add
783 } while (defined $fetching);
786 sub _reindex_inbox ($$$) {
787 my ($self, $sync, $ibx) = @_;
788 local $self->{current_info} = $ibx->eidx_key;
789 _reindex_check_unseen($self, $sync, $ibx);
790 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
791 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
795 my ($self, $sync) = @_;
797 # acquire eidxq_lock early because full reindex takes forever
798 # and incremental -extindex processes can run during our checkpoints
799 if (!eidxq_lock_acquire($self)) {
800 warn "E: aborting --reindex\n";
803 for my $ibx (@{$self->{ibx_list}}) {
804 _reindex_inbox($self, $sync, $ibx);
805 last if $sync->{quit};
807 $self->git->async_wait_all; # ensure eidxq gets filled completely
808 eidxq_process($self, $sync) unless $sync->{quit};
811 sub eidx_sync { # main entry point
812 my ($self, $opt) = @_;
814 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
815 local $self->{current_info} = '';
816 local $SIG{__WARN__} = sub {
817 $warn_cb->($self->{current_info}, ': ', @_);
819 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
820 $self->{oidx}->rethread_prepare($opt);
822 need_checkpoint => \(my $need_checkpoint = 0),
824 next_check => now() + 10,
826 # DO NOT SET {reindex} here, it's incompatible with reused
827 # V2Writable code, reindex is totally different here
828 # compared to v1/v2 inboxes because we have multiple histories
830 -regen_fmt => "%u/?\n",
832 local $SIG{USR1} = sub { $need_checkpoint = 1 };
833 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
834 local $SIG{QUIT} = $quit;
835 local $SIG{INT} = $quit;
836 local $SIG{TERM} = $quit;
837 for my $ibx (@{$self->{ibx_list}}) {
838 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
840 if (delete($opt->{reindex})) {
841 $sync->{checkpoint_unlocks} = 1;
842 eidx_reindex($self, $sync);
845 # don't use $_ here, it'll get clobbered by reindex_checkpoint
846 for my $ibx (@{$self->{ibx_list}}) {
847 last if $sync->{quit};
848 _sync_inbox($self, $sync, $ibx);
850 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
851 eidxq_process($self, $sync) unless $sync->{quit};
853 eidxq_release($self);
854 PublicInbox::V2Writable::done($self);
857 sub update_last_commit { # overrides V2Writable
858 my ($self, $sync, $stk) = @_;
859 my $unit = $sync->{unit} // return;
860 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
861 defined($latest_cmt) or return;
862 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
863 my $ekey = $ibx->eidx_key;
864 my $uv = $ibx->uidvalidity;
865 my $epoch = $unit->{epoch};
867 my $v = $ibx->version;
869 die 'No {epoch} for v2 unit' unless defined $epoch;
870 $meta_key = "lc-v2:$ekey//$uv;$epoch";
872 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
873 $meta_key = "lc-v1:$ekey//$uv";
875 die "Unsupported inbox version: $v";
877 my $last = $self->{oidx}->eidx_meta($meta_key);
878 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
879 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
880 chomp(my $n = $unit->{git}->qx(@cmd));
881 return if $n ne '' && $n == 0;
883 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
886 sub _idx_init { # with_umask callback
887 my ($self, $opt) = @_;
888 PublicInbox::V2Writable::_idx_init($self, $opt);
889 $self->{midx} = PublicInbox::MiscIdx->new($self);
892 sub idx_init { # similar to V2Writable
893 my ($self, $opt) = @_;
894 return if $self->{idx_shards};
898 my $ALL = $self->git->{git_dir}; # ALL.git
899 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
900 my $info_dir = "$ALL/objects/info";
901 my $alt = "$info_dir/alternates";
903 my (@old, @new, %seen); # seen: st_dev + st_ino
905 open(my $fh, '<', $alt) or die "open $alt: $!";
906 $mode = (stat($fh))[2] & 07777;
907 while (my $line = <$fh>) {
908 chomp(my $d = $line);
909 if (my @st = stat($d)) {
910 next if $seen{"$st[0]\0$st[1]"}++;
912 warn "W: stat($d) failed (from $alt): $!\n";
913 next if $opt->{-idx_gc};
918 for my $ibx (@{$self->{ibx_list}}) {
919 my $line = $ibx->git->{git_dir} . "/objects\n";
920 chomp(my $d = $line);
921 if (my @st = stat($d)) {
922 next if $seen{"$st[0]\0$st[1]"}++;
924 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
925 next if $opt->{-idx_gc};
932 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
934 $self->parallel_init($self->{indexlevel});
935 $self->umask_prepare;
936 $self->with_umask(\&_idx_init, $self, $opt);
937 $self->{oidx}->begin_lazy;
938 $self->{oidx}->eidx_prep;
939 $self->{midx}->begin_txn;
943 *done = \&PublicInbox::V2Writable::done;
944 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
945 *with_umask = \&PublicInbox::InboxWritable::with_umask;
946 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
947 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
948 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
949 *index_todo = \&PublicInbox::V2Writable::index_todo;
950 *count_shards = \&PublicInbox::V2Writable::count_shards;
951 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
952 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
953 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;