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);
33 use PublicInbox::DS qw(now);
34 use DBI qw(:sql_types); # SQL_BLOB
37 my (undef, $dir, $opt) = @_;
38 my $l = $opt->{indexlevel} // 'full';
39 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
40 die "invalid indexlevel=$l\n";
41 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
43 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
45 creat => $opt->{creat},
46 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
53 lock_path => "$dir/ei.lock",
55 $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
56 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
57 $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
58 $self->{oidx} = $oidx;
63 my ($self, $ibx) = @_;
64 my $ekey = $ibx->eidx_key;
65 my $misc = $self->{misc};
66 if ($misc && $misc->inbox_data($ibx)) { # all good if already indexed
68 if (!$ibx->over || !$ibx->mm) {
69 warn "W: skipping $ekey (unindexed)\n";
72 if (!defined($ibx->uidvalidity)) {
73 warn "W: skipping $ekey (no UIDVALIDITY)\n";
77 $self->{ibx_map}->{$ekey} //= 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 check_batch_limit ($) {
96 my $self = $req->{self};
97 my $new_smsg = $req->{new_smsg};
99 # {raw_bytes} may be unset, so just use {bytes}
100 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
102 # set flag for PublicInbox::V2Writable::index_todo:
103 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
107 my ($req, $smsg) = @_;
108 my $self = $req->{self};
109 my $docid = $smsg->{num};
110 my $idx = $self->idx_shard($docid);
111 my $oid = $req->{oid};
112 my $xibx = $req->{ibx};
113 my $eml = $req->{eml};
114 my $eidx_key = $xibx->eidx_key;
115 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
116 my $xnum = $req->{xnum};
117 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
118 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
119 check_batch_limit($req);
122 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
125 $self->{oidx}->eidxq_del($docid);
126 $idx->shard_remove($docid);
127 } elsif ($rm_eidx_info) {
128 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
129 $self->{oidx}->eidxq_add($docid); # yes, add
134 # called by V2Writable::sync_prepare
135 sub artnum_max { $_[0]->{oidx}->eidx_max }
137 sub index_unseen ($) {
139 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
140 my $eml = delete $req->{eml};
141 $new_smsg->populate($eml, $req);
142 my $self = $req->{self};
143 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
144 $new_smsg->{num} = $docid;
145 my $idx = $self->idx_shard($docid);
146 $self->{oidx}->add_overview($eml, $new_smsg);
147 my $oid = $new_smsg->{blob};
148 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
149 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
150 $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
151 check_batch_limit($req);
154 sub do_finalize ($) {
156 if (my $indexed = $req->{indexed}) {
157 do_xpost($req, $_) for @$indexed;
158 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
161 # `d' message was already unindexed in the v1/v2 inboxes,
162 # so it's too noisy to warn, here.
164 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
165 if (defined(my $cur_cmt = $req->{cur_cmt})) {
166 ${$req->{latest_cmt}} = $cur_cmt;
170 sub do_step ($) { # main iterator for adding messages to the index
172 my $self = $req->{self} // die 'BUG: {self} missing';
174 if (my $next_arg = $req->{next_arg}) {
175 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
176 $req->{cur_smsg} = $smsg;
177 $self->git->cat_async($smsg->{blob},
178 \&ck_existing, $req);
179 return; # ck_existing calls do_step
181 delete $req->{cur_smsg};
182 delete $req->{next_arg};
184 my $mid = shift(@{$req->{mids}});
185 last unless defined $mid;
187 $req->{next_arg} = [ $mid, \$id, \$prev ];
193 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
195 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
196 my $self = $req->{self};
197 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
198 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
200 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
201 die "BUG: xref $keep[0] has no OID";
203 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
204 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
205 my $saved = $self->{oidx}->get_art($smsg->{num});
207 $self->{oidx}->delete_by_num($smsg->{num});
211 sub ck_existing { # git->cat_async callback
212 my ($bref, $oid, $type, $size, $req) = @_;
213 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
214 if ($type eq 'missing') {
216 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
217 my $self = $req->{self} // die 'BUG: {self} missing';
218 local $self->{current_info} = "$self->{current_info} $oid";
219 my $cur = PublicInbox::Eml->new($bref);
220 if (content_hash($cur) eq $req->{chash}) {
221 push @{$req->{indexed}}, $smsg; # for do_xpost
222 } # else { index_unseen later }
227 # is the messages visible in the inbox currently being indexed?
228 # return the number if so
229 sub cur_ibx_xnum ($$) {
230 my ($req, $bref) = @_;
231 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
233 $req->{eml} = PublicInbox::Eml->new($bref);
234 $req->{chash} = content_hash($req->{eml});
235 $req->{mids} = mids($req->{eml});
236 my @q = @{$req->{mids}}; # copy
237 while (defined(my $mid = shift @q)) {
239 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
240 return $x->{num} if $x->{blob} eq $req->{oid};
246 sub index_oid { # git->cat_async callback for 'm'
247 my ($bref, $oid, $type, $size, $req) = @_;
248 my $self = $req->{self};
249 local $self->{current_info} = "$self->{current_info} $oid";
250 return if is_bad_blob($oid, $type, $size, $req->{oid});
251 my $new_smsg = $req->{new_smsg} = bless {
253 }, 'PublicInbox::Smsg';
254 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
255 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
260 sub unindex_oid { # git->cat_async callback for 'd'
261 my ($bref, $oid, $type, $size, $req) = @_;
262 my $self = $req->{self};
263 local $self->{current_info} = "$self->{current_info} $oid";
264 return if is_bad_blob($oid, $type, $size, $req->{oid});
265 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
269 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
271 my ($self, $sync) = @_;
273 my $ekey = $sync->{ibx}->eidx_key;
274 my $uv = $sync->{ibx}->uidvalidity;
275 for my $i (0..$sync->{epoch_max}) {
276 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
281 sub _sync_inbox ($$$) {
282 my ($self, $sync, $ibx) = @_;
284 $sync->{nr} = \(my $nr = 0);
285 my $v = $ibx->version;
286 my $ekey = $ibx->eidx_key;
288 $sync->{epoch_max} = $ibx->max_git_epoch // return;
289 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
291 my $uv = $ibx->uidvalidity;
292 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
293 my $head = $ibx->mm->last_commit;
294 unless (defined $head) {
295 warn "E: $ibx->{inboxdir} is not indexed\n";
298 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
299 my $unit = { stack => $stk, git => $ibx->git };
300 push @{$sync->{todo}}, $unit;
302 warn "E: $ekey unsupported inbox version (v$v)\n";
305 for my $unit (@{delete($sync->{todo}) // []}) {
306 last if $sync->{quit};
307 index_todo($self, $sync, $unit);
309 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
310 $ibx->git->cleanup; # done with this inbox, now
313 sub gc_unref_doc ($$$$) {
314 my ($self, $ibx_id, $eidx_key, $docid) = @_;
315 my $dbh = $self->{oidx}->dbh;
317 # for debug/info purposes, oids may no longer be accessible
318 my $sth = $dbh->prepare_cached(<<'', undef, 1);
319 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
321 $sth->execute($docid, $ibx_id);
322 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
324 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
325 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
327 my $remain = $self->{oidx}->get_xref3($docid);
328 if (scalar(@$remain)) {
329 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
331 warn "I: unref #$docid $eidx_key $oid\n";
334 warn "I: remove #$docid $eidx_key @oid\n";
335 $self->idx_shard($docid)->shard_remove($docid);
340 my ($self, $opt) = @_;
341 $self->{cfg} or die "E: GC requires ->attach_config\n";
343 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
345 my $dbh = $self->{oidx}->dbh;
346 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
347 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
348 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
351 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
352 next if $self->{ibx_map}->{$eidx_key};
353 $self->{midx}->remove_eidx_key($eidx_key);
354 warn "I: deleting messages for $eidx_key...\n";
355 $x3_doc->execute($ibx_id);
356 while (defined(my $docid = $x3_doc->fetchrow_array)) {
357 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
359 $dbh->prepare_cached(<<'')->execute($ibx_id);
360 DELETE FROM inboxes WHERE ibx_id = ?
362 # drop last_commit info
364 $pat =~ s/([_%])/\\$1/g;
365 $lc_i->execute("lc-%:$pat//%");
366 while (my ($key) = $lc_i->fetchrow_array) {
367 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
368 warn "I: removing $key\n";
369 $dbh->prepare_cached(<<'')->execute($key);
370 DELETE FROM eidx_meta WHERE key = ?
374 warn "I: $eidx_key removed\n";
377 # it's not real unless it's in `over', we use parallelism here,
378 # shards will be reading directly from over, so commit
379 $self->{oidx}->commit_lazy;
380 $self->{oidx}->begin_lazy;
382 for my $idx (@{$self->{idx_shards}}) {
383 warn "I: cleaning up shard #$idx->{shard}\n";
384 $idx->shard_over_check($self->{oidx});
386 my $nr = $dbh->do(<<'');
387 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
389 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
395 my ($self, $sync, $smsg) = @_;
396 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
397 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
398 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
401 sub _reindex_finalize ($$$) {
402 my ($req, $smsg, $eml) = @_;
403 my $sync = $req->{sync};
404 my $self = $sync->{self};
405 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
406 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
407 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
408 my $docid = $smsg->{num} = $orig_smsg->{num};
409 $self->{oidx}->add_overview($eml, $smsg); # may rethread
410 check_batch_limit({ %$sync, new_smsg => $smsg });
411 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
412 my $stable = delete($by_chash->{$chash0}) //
413 die "BUG: $smsg->{blob} chash missing";
414 my $idx = $self->idx_shard($docid);
415 my $top_smsg = pop @$stable;
416 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
417 my $ibx = _ibx_for($self, $sync, $smsg);
418 $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
419 for my $x (reverse @$stable) {
420 $ibx = _ibx_for($self, $sync, $x);
421 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
422 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
424 return if $nr == 1; # likely, all good
426 warn "W: #$docid split into $nr due to deduplication change\n";
428 for my $ary (values %$by_chash) {
429 for my $x (reverse @$ary) {
430 warn "removing #$docid xref3 $x->{blob}\n";
431 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
432 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
434 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
435 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
436 $ibx = _ibx_for($self, $sync, $x);
437 my $e = $ibx->over->get_art($x->{num});
438 $e->{blob} eq $x->{blob} or die <<EOF;
439 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
441 push @todo, $ibx, $e;
444 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
445 reindex_unseen($self, $sync, $ibx, $e);
449 sub _reindex_oid { # git->cat_async callback
450 my ($bref, $oid, $type, $size, $req) = @_;
451 my $sync = $req->{sync};
452 my $self = $sync->{self};
453 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
454 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
455 my $docid = $orig_smsg->{num};
456 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
457 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
459 warn "W: #$docid gone or corrupted\n";
460 $self->idx_shard($docid)->shard_remove($docid);
461 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
462 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
464 warn "BUG: #$docid gone (UNEXPECTED)\n";
465 $self->idx_shard($docid)->shard_remove($docid);
469 my $ci = $self->{current_info};
470 local $self->{current_info} = "$ci #$docid $oid";
471 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
472 $re_smsg->{bytes} = $size + crlf_adjust($$bref);
473 my $eml = PublicInbox::Eml->new($bref);
474 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
475 cotime => $orig_smsg->{ts} });
476 my $chash = content_hash($eml);
477 $re_smsg->{chash} = $chash;
478 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
479 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
480 $re_smsg->{hdr} = $eml->header_obj;
481 push @{$req->{by_chash}->{$chash}}, $re_smsg;
482 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
483 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
484 } else { # last $re_smsg is the highest priority xref3
485 local $self->{current_info} = "$ci #$docid";
486 _reindex_finalize($req, $re_smsg, $eml);
490 sub _reindex_smsg ($$$) {
491 my ($self, $sync, $smsg) = @_;
492 my $docid = $smsg->{num};
493 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
494 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
496 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
498 $self->{oidx}->delete_by_num($docid);
499 $self->idx_shard($docid)->shard_remove($docid);
503 # we sort {xr3r} in the reverse order of {ibx_list} so we can
504 # hit the common case in _reindex_finalize without rereading
505 # from git (or holding multiple messages in memory).
506 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
508 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
510 $b->[1] <=> $a->[1] # break ties with {xnum}
512 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
513 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
514 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
517 sub checkpoint_due ($) {
519 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
523 # I've copied FS images and only changed the hostname before,
524 # so prepend hostname. Use `state' since these a BOFH can change
525 # these while this process is running and we always want to be
526 # able to release locks taken by this process.
527 state $retval = hostname . '-' . do {
528 my $m; # machine-id(5) is systemd
529 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
530 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
531 chomp($m ||= `{ sysctl -n kern.hostid ||
532 hostid || ghostid; } 2>/dev/null`
533 || "no-machine-id-or-hostid-on-$^O");
540 my $expect = delete($self->{-eidxq_locked}) or return;
541 my ($owner_pid, undef) = split(/-/, $expect);
542 return if $owner_pid != $$; # shards may fork
543 my $oidx = $self->{oidx};
545 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
546 if ($cur eq $expect) {
547 $oidx->eidx_meta('eidxq_lock', '');
549 } elsif ($cur ne '') {
550 warn "E: eidxq_lock($expect) stolen by $cur\n";
552 warn "E: eidxq_lock($expect) released by another process\n";
559 eidxq_release($self) and $self->{oidx}->commit_lazy;
562 sub _eidxq_take ($) {
564 my $val = "$$-${\time}-$>-".host_ident;
565 $self->{oidx}->eidx_meta('eidxq_lock', $val);
566 $self->{-eidxq_locked} = $val;
569 sub eidxq_lock_acquire ($) {
571 my $oidx = $self->{oidx};
573 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
574 if (my $locked = $self->{-eidxq_locked}) { # be lazy
575 return $locked if $locked eq $cur;
577 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
578 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
579 if ($euid == $> && $ident eq host_ident) {
582 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
586 warn "I: eidxq_lock is stale ($cur), clobbering\n";
587 return _eidxq_take($self);
589 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
591 my $fn = $oidx->dbh->sqlite_db_filename;
593 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
594 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
595 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
600 sub eidxq_process ($$) { # for reindexing
601 my ($self, $sync) = @_;
603 return unless eidxq_lock_acquire($self);
604 my $dbh = $self->{oidx}->dbh;
605 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
607 $sync->{-regen_fmt} = "%u/$tot\n";
608 my $pr = $sync->{-opt}->{-progress};
610 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
611 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
612 $pr->("Xapian indexing $min..$max (total=$tot)\n");
614 $sync->{id2pos} //= do {
617 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
622 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
623 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
625 while (defined(my $docid = $iter->fetchrow_array)) {
626 last if $sync->{quit};
627 if (my $smsg = $self->{oidx}->get_art($docid)) {
628 _reindex_smsg($self, $sync, $smsg);
630 warn "E: #$docid does not exist in over\n";
632 $del->execute($docid);
635 if (checkpoint_due($sync)) {
636 $dbh = $del = $iter = undef;
637 reindex_checkpoint($self, $sync); # release lock
638 $dbh = $self->{oidx}->dbh;
642 $self->git->async_wait_all;
643 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
646 sub _reindex_unseen { # git->cat_async callback
647 my ($bref, $oid, $type, $size, $req) = @_;
648 return if is_bad_blob($oid, $type, $size, $req->{oid});
649 my $self = $req->{self} // die 'BUG: {self} unset';
650 local $self->{current_info} = "$self->{current_info} $oid";
651 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
652 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
653 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
654 $req->{new_smsg} = $new_smsg;
655 $req->{chash} = content_hash($eml);
656 $req->{mids} = mids($eml); # do_step iterates through this
657 do_step($req); # enter the normal indexing flow
660 # --reindex may catch totally unseen messages, this handles them
661 sub reindex_unseen ($$$$) {
662 my ($self, $sync, $ibx, $xsmsg) = @_;
665 autime => $xsmsg->{ds},
666 cotime => $xsmsg->{ts},
667 oid => $xsmsg->{blob},
669 xnum => $xsmsg->{num},
670 # {mids} and {chash} will be filled in at _reindex_unseen
672 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
673 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
676 sub _reindex_check_unseen ($$$) {
677 my ($self, $sync, $ibx) = @_;
678 my $ibx_id = $ibx->{-ibx_id};
680 my ($beg, $end) = (1, $slice);
682 # first, check if we missed any messages in target $ibx
684 my $pr = $sync->{-opt}->{-progress};
685 my $ekey = $ibx->eidx_key;
686 $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
689 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
690 ${$sync->{nr}} = $beg;
691 $beg = $msgs->[-1]->{num} + 1;
692 $end = $beg + $slice;
693 if (checkpoint_due($sync)) {
694 reindex_checkpoint($self, $sync); # release lock
697 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
698 SELECT DISTINCT(docid) FROM xref3 WHERE
699 ibx_id = ? AND xnum = ? AND oidbin = ?
701 for my $xsmsg (@$msgs) {
702 my $oidbin = pack('H*', $xsmsg->{blob});
703 $inx3->bind_param(1, $ibx_id);
704 $inx3->bind_param(2, $xsmsg->{num});
705 $inx3->bind_param(3, $oidbin, SQL_BLOB);
707 my $docids = $inx3->fetchall_arrayref;
708 # index messages which were totally missed
709 # the first time around ASAP:
710 if (scalar(@$docids) == 0) {
711 reindex_unseen($self, $sync, $ibx, $xsmsg);
712 } else { # already seen, reindex later
713 for my $r (@$docids) {
714 $self->{oidx}->eidxq_add($r->[0]);
717 last if $sync->{quit};
719 last if $sync->{quit};
723 sub _reindex_check_stale ($$$) {
724 my ($self, $sync, $ibx) = @_;
726 my $pr = $sync->{-opt}->{-progress};
728 my $ekey = $ibx->eidx_key;
729 $sync->{-regen_fmt} =
730 "$ekey check stale/missing %u/".$ibx->over->max."\n";
733 if (checkpoint_due($sync)) {
734 reindex_checkpoint($self, $sync); # release lock
736 # now, check if there's stale xrefs
737 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
738 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
739 ORDER BY docid,xnum ASC LIMIT 10000
741 $iter->execute($ibx->{-ibx_id}, $min);
744 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
745 return if $sync->{quit};
746 ${$sync->{nr}} = $xnum;
748 $fetching = $min = $docid;
749 my $smsg = $ibx->over->get_art($xnum);
750 my $oidhex = unpack('H*', $oidbin);
754 } elsif ($smsg->{blob} ne $oidhex) {
755 $err = "mismatch (!= $smsg->{blob})";
757 next; # likely, all good
759 # current_info already has eidx_key
760 warn "$xnum:$oidhex (#$docid): $err\n";
761 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
762 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
764 $del->bind_param(1, $ibx->{-ibx_id});
765 $del->bind_param(2, $xnum);
766 $del->bind_param(3, $oidbin, SQL_BLOB);
769 # get_xref3 over-fetches, but this is a rare path:
770 my $xr3 = $self->{oidx}->get_xref3($docid);
771 my $idx = $self->idx_shard($docid);
772 if (scalar(@$xr3) == 0) { # all gone
773 $self->{oidx}->delete_by_num($docid);
774 $self->{oidx}->eidxq_del($docid);
775 $idx->shard_remove($docid);
776 } else { # enqueue for reindex of remaining messages
777 $idx->shard_remove_eidx_info($docid,
779 $self->{oidx}->eidxq_add($docid); # yes, add
782 } while (defined $fetching);
785 sub _reindex_inbox ($$$) {
786 my ($self, $sync, $ibx) = @_;
787 local $self->{current_info} = $ibx->eidx_key;
788 _reindex_check_unseen($self, $sync, $ibx);
789 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
790 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
794 my ($self, $sync) = @_;
796 # acquire eidxq_lock early because full reindex takes forever
797 # and incremental -extindex processes can run during our checkpoints
798 if (!eidxq_lock_acquire($self)) {
799 warn "E: aborting --reindex\n";
802 for my $ibx (@{$self->{ibx_list}}) {
803 _reindex_inbox($self, $sync, $ibx);
804 last if $sync->{quit};
806 $self->git->async_wait_all; # ensure eidxq gets filled completely
807 eidxq_process($self, $sync) unless $sync->{quit};
810 sub eidx_sync { # main entry point
811 my ($self, $opt) = @_;
813 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
814 local $self->{current_info} = '';
815 local $SIG{__WARN__} = sub {
816 $warn_cb->($self->{current_info}, ': ', @_);
818 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
819 $self->{oidx}->rethread_prepare($opt);
821 need_checkpoint => \(my $need_checkpoint = 0),
823 next_check => now() + 10,
825 # DO NOT SET {reindex} here, it's incompatible with reused
826 # V2Writable code, reindex is totally different here
827 # compared to v1/v2 inboxes because we have multiple histories
829 -regen_fmt => "%u/?\n",
831 local $SIG{USR1} = sub { $need_checkpoint = 1 };
832 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
833 local $SIG{QUIT} = $quit;
834 local $SIG{INT} = $quit;
835 local $SIG{TERM} = $quit;
836 for my $ibx (@{$self->{ibx_list}}) {
837 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
839 if (delete($opt->{reindex})) {
840 $sync->{checkpoint_unlocks} = 1;
841 eidx_reindex($self, $sync);
844 # don't use $_ here, it'll get clobbered by reindex_checkpoint
845 for my $ibx (@{$self->{ibx_list}}) {
846 last if $sync->{quit};
847 _sync_inbox($self, $sync, $ibx);
849 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
850 eidxq_process($self, $sync) unless $sync->{quit};
852 eidxq_release($self);
853 PublicInbox::V2Writable::done($self);
856 sub update_last_commit { # overrides V2Writable
857 my ($self, $sync, $stk) = @_;
858 my $unit = $sync->{unit} // return;
859 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
860 defined($latest_cmt) or return;
861 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
862 my $ekey = $ibx->eidx_key;
863 my $uv = $ibx->uidvalidity;
864 my $epoch = $unit->{epoch};
866 my $v = $ibx->version;
868 die 'No {epoch} for v2 unit' unless defined $epoch;
869 $meta_key = "lc-v2:$ekey//$uv;$epoch";
871 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
872 $meta_key = "lc-v1:$ekey//$uv";
874 die "Unsupported inbox version: $v";
876 my $last = $self->{oidx}->eidx_meta($meta_key);
877 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
878 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
879 chomp(my $n = $unit->{git}->qx(@cmd));
880 return if $n ne '' && $n == 0;
882 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
885 sub _idx_init { # with_umask callback
886 my ($self, $opt) = @_;
887 PublicInbox::V2Writable::_idx_init($self, $opt);
888 $self->{midx} = PublicInbox::MiscIdx->new($self);
891 sub idx_init { # similar to V2Writable
892 my ($self, $opt) = @_;
893 return if $self->{idx_shards};
897 my $ALL = $self->git->{git_dir}; # ALL.git
898 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
899 my $info_dir = "$ALL/objects/info";
900 my $alt = "$info_dir/alternates";
902 my (@old, @new, %seen); # seen: st_dev + st_ino
904 open(my $fh, '<', $alt) or die "open $alt: $!";
905 $mode = (stat($fh))[2] & 07777;
906 while (my $line = <$fh>) {
907 chomp(my $d = $line);
908 if (my @st = stat($d)) {
909 next if $seen{"$st[0]\0$st[1]"}++;
911 warn "W: stat($d) failed (from $alt): $!\n";
912 next if $opt->{-idx_gc};
917 for my $ibx (@{$self->{ibx_list}}) {
918 my $line = $ibx->git->{git_dir} . "/objects\n";
919 chomp(my $d = $line);
920 if (my @st = stat($d)) {
921 next if $seen{"$st[0]\0$st[1]"}++;
923 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
924 next if $opt->{-idx_gc};
931 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
933 $self->parallel_init($self->{indexlevel});
934 $self->umask_prepare;
935 $self->with_umask(\&_idx_init, $self, $opt);
936 $self->{oidx}->begin_lazy;
937 $self->{oidx}->eidx_prep;
938 $self->{midx}->begin_txn;
942 *done = \&PublicInbox::V2Writable::done;
943 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
944 *with_umask = \&PublicInbox::InboxWritable::with_umask;
945 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
946 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
947 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
948 *index_todo = \&PublicInbox::V2Writable::index_todo;
949 *count_shards = \&PublicInbox::V2Writable::count_shards;
950 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
951 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
952 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;