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 $key = $ibx->eidx_key;
65 if (!$ibx->over || !$ibx->mm) {
66 warn "W: skipping $key (unindexed)\n";
69 if (!defined($ibx->uidvalidity)) {
70 warn "W: skipping $key (no UIDVALIDITY)\n";
73 $self->{ibx_map}->{$key} //= do {
74 push @{$self->{ibx_list}}, $ibx;
79 sub _ibx_attach { # each_inbox callback
80 my ($ibx, $self) = @_;
81 attach_inbox($self, $ibx);
85 my ($self, $cfg) = @_;
87 $cfg->each_inbox(\&_ibx_attach, $self);
90 sub check_batch_limit ($) {
92 my $self = $req->{self};
93 my $new_smsg = $req->{new_smsg};
95 # {raw_bytes} may be unset, so just use {bytes}
96 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
98 # set flag for PublicInbox::V2Writable::index_todo:
99 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
103 my ($req, $smsg) = @_;
104 my $self = $req->{self};
105 my $docid = $smsg->{num};
106 my $idx = $self->idx_shard($docid);
107 my $oid = $req->{oid};
108 my $xibx = $req->{ibx};
109 my $eml = $req->{eml};
110 my $eidx_key = $xibx->eidx_key;
111 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
112 my $xnum = $req->{xnum};
113 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
114 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
115 check_batch_limit($req);
118 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
121 $self->{oidx}->eidxq_del($docid);
122 $idx->shard_remove($docid);
123 } elsif ($rm_eidx_info) {
124 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
125 $self->{oidx}->eidxq_add($docid); # yes, add
130 # called by V2Writable::sync_prepare
131 sub artnum_max { $_[0]->{oidx}->eidx_max }
133 sub index_unseen ($) {
135 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
136 my $eml = delete $req->{eml};
137 $new_smsg->populate($eml, $req);
138 my $self = $req->{self};
139 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
140 $new_smsg->{num} = $docid;
141 my $idx = $self->idx_shard($docid);
142 $self->{oidx}->add_overview($eml, $new_smsg);
143 my $oid = $new_smsg->{blob};
144 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
145 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
146 $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
147 check_batch_limit($req);
150 sub do_finalize ($) {
152 if (my $indexed = $req->{indexed}) {
153 do_xpost($req, $_) for @$indexed;
154 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
157 # `d' message was already unindexed in the v1/v2 inboxes,
158 # so it's too noisy to warn, here.
160 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
161 if (defined(my $cur_cmt = $req->{cur_cmt})) {
162 ${$req->{latest_cmt}} = $cur_cmt;
166 sub do_step ($) { # main iterator for adding messages to the index
168 my $self = $req->{self} // die 'BUG: {self} missing';
170 if (my $next_arg = $req->{next_arg}) {
171 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
172 $req->{cur_smsg} = $smsg;
173 $self->git->cat_async($smsg->{blob},
174 \&ck_existing, $req);
175 return; # ck_existing calls do_step
177 delete $req->{cur_smsg};
178 delete $req->{next_arg};
180 my $mid = shift(@{$req->{mids}});
181 last unless defined $mid;
183 $req->{next_arg} = [ $mid, \$id, \$prev ];
189 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
191 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
192 my $self = $req->{self};
193 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
194 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
196 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
197 die "BUG: xref $keep[0] has no OID";
199 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
200 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
201 my $saved = $self->{oidx}->get_art($smsg->{num});
203 $self->{oidx}->delete_by_num($smsg->{num});
207 sub ck_existing { # git->cat_async callback
208 my ($bref, $oid, $type, $size, $req) = @_;
209 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
210 if ($type eq 'missing') {
212 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
213 my $self = $req->{self} // die 'BUG: {self} missing';
214 local $self->{current_info} = "$self->{current_info} $oid";
215 my $cur = PublicInbox::Eml->new($bref);
216 if (content_hash($cur) eq $req->{chash}) {
217 push @{$req->{indexed}}, $smsg; # for do_xpost
218 } # else { index_unseen later }
223 # is the messages visible in the inbox currently being indexed?
224 # return the number if so
225 sub cur_ibx_xnum ($$) {
226 my ($req, $bref) = @_;
227 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
229 $req->{eml} = PublicInbox::Eml->new($bref);
230 $req->{chash} = content_hash($req->{eml});
231 $req->{mids} = mids($req->{eml});
232 my @q = @{$req->{mids}}; # copy
233 while (defined(my $mid = shift @q)) {
235 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
236 return $x->{num} if $x->{blob} eq $req->{oid};
242 sub index_oid { # git->cat_async callback for 'm'
243 my ($bref, $oid, $type, $size, $req) = @_;
244 my $self = $req->{self};
245 local $self->{current_info} = "$self->{current_info} $oid";
246 return if is_bad_blob($oid, $type, $size, $req->{oid});
247 my $new_smsg = $req->{new_smsg} = bless {
249 }, 'PublicInbox::Smsg';
250 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
251 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
256 sub unindex_oid { # git->cat_async callback for 'd'
257 my ($bref, $oid, $type, $size, $req) = @_;
258 my $self = $req->{self};
259 local $self->{current_info} = "$self->{current_info} $oid";
260 return if is_bad_blob($oid, $type, $size, $req->{oid});
261 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
265 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
267 my ($self, $sync) = @_;
269 my $ekey = $sync->{ibx}->eidx_key;
270 my $uv = $sync->{ibx}->uidvalidity;
271 for my $i (0..$sync->{epoch_max}) {
272 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
277 sub _sync_inbox ($$$) {
278 my ($self, $sync, $ibx) = @_;
280 $sync->{nr} = \(my $nr = 0);
281 my $v = $ibx->version;
282 my $ekey = $ibx->eidx_key;
284 $sync->{epoch_max} = $ibx->max_git_epoch // return;
285 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
287 my $uv = $ibx->uidvalidity;
288 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
289 my $head = $ibx->mm->last_commit;
290 unless (defined $head) {
291 warn "E: $ibx->{inboxdir} is not indexed\n";
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 gc_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 if (scalar(@$remain)) {
325 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
327 warn "I: unref #$docid $eidx_key $oid\n";
330 warn "I: remove #$docid $eidx_key @oid\n";
331 $self->idx_shard($docid)->shard_remove($docid);
336 my ($self, $opt) = @_;
337 $self->{cfg} or die "E: GC requires ->attach_config\n";
339 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
341 my $dbh = $self->{oidx}->dbh;
342 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
343 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
344 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
347 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
348 next if $self->{ibx_map}->{$eidx_key};
349 $self->{midx}->remove_eidx_key($eidx_key);
350 warn "I: deleting messages for $eidx_key...\n";
351 $x3_doc->execute($ibx_id);
352 while (defined(my $docid = $x3_doc->fetchrow_array)) {
353 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
355 $dbh->prepare_cached(<<'')->execute($ibx_id);
356 DELETE FROM inboxes WHERE ibx_id = ?
358 # drop last_commit info
360 $pat =~ s/([_%])/\\$1/g;
361 $lc_i->execute("lc-%:$pat//%");
362 while (my ($key) = $lc_i->fetchrow_array) {
363 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
364 warn "I: removing $key\n";
365 $dbh->prepare_cached(<<'')->execute($key);
366 DELETE FROM eidx_meta WHERE key = ?
370 warn "I: $eidx_key removed\n";
373 # it's not real unless it's in `over', we use parallelism here,
374 # shards will be reading directly from over, so commit
375 $self->{oidx}->commit_lazy;
376 $self->{oidx}->begin_lazy;
378 for my $idx (@{$self->{idx_shards}}) {
379 warn "I: cleaning up shard #$idx->{shard}\n";
380 $idx->shard_over_check($self->{oidx});
382 my $nr = $dbh->do(<<'');
383 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
385 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
391 my ($self, $sync, $smsg) = @_;
392 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
393 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
394 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
397 sub _reindex_finalize ($$$) {
398 my ($req, $smsg, $eml) = @_;
399 my $sync = $req->{sync};
400 my $self = $sync->{self};
401 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
402 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
403 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
404 my $docid = $smsg->{num} = $orig_smsg->{num};
405 $self->{oidx}->add_overview($eml, $smsg); # may rethread
406 check_batch_limit({ %$sync, new_smsg => $smsg });
407 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
408 my $stable = delete($by_chash->{$chash0}) //
409 die "BUG: $smsg->{blob} chash missing";
410 my $idx = $self->idx_shard($docid);
411 my $top_smsg = pop @$stable;
412 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
413 my $ibx = _ibx_for($self, $sync, $smsg);
414 $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
415 for my $x (reverse @$stable) {
416 $ibx = _ibx_for($self, $sync, $x);
417 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
418 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
420 return if $nr == 1; # likely, all good
422 warn "W: #$docid split into $nr due to deduplication change\n";
424 for my $ary (values %$by_chash) {
425 for my $x (reverse @$ary) {
426 warn "removing #$docid xref3 $x->{blob}\n";
427 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
428 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
430 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
431 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
432 $ibx = _ibx_for($self, $sync, $x);
433 my $e = $ibx->over->get_art($x->{num});
434 $e->{blob} eq $x->{blob} or die <<EOF;
435 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
437 push @todo, $ibx, $e;
440 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
441 reindex_unseen($self, $sync, $ibx, $e);
445 sub _reindex_oid { # git->cat_async callback
446 my ($bref, $oid, $type, $size, $req) = @_;
447 my $sync = $req->{sync};
448 my $self = $sync->{self};
449 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
450 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
451 my $docid = $orig_smsg->{num};
452 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
453 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
455 warn "W: #$docid gone or corrupted\n";
456 $self->idx_shard($docid)->shard_remove($docid);
457 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
458 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
460 warn "BUG: #$docid gone (UNEXPECTED)\n";
461 $self->idx_shard($docid)->shard_remove($docid);
465 my $ci = $self->{current_info};
466 local $self->{current_info} = "$ci #$docid $oid";
467 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
468 $re_smsg->{bytes} = $size + crlf_adjust($$bref);
469 my $eml = PublicInbox::Eml->new($bref);
470 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
471 cotime => $orig_smsg->{ts} });
472 my $chash = content_hash($eml);
473 $re_smsg->{chash} = $chash;
474 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
475 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
476 $re_smsg->{hdr} = $eml->header_obj;
477 push @{$req->{by_chash}->{$chash}}, $re_smsg;
478 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
479 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
480 } else { # last $re_smsg is the highest priority xref3
481 local $self->{current_info} = "$ci #$docid";
482 _reindex_finalize($req, $re_smsg, $eml);
486 sub _reindex_smsg ($$$) {
487 my ($self, $sync, $smsg) = @_;
488 my $docid = $smsg->{num};
489 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
490 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
492 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
494 $self->{oidx}->delete_by_num($docid);
495 $self->idx_shard($docid)->shard_remove($docid);
499 # we sort {xr3r} in the reverse order of {ibx_list} so we can
500 # hit the common case in _reindex_finalize without rereading
501 # from git (or holding multiple messages in memory).
502 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
504 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
506 $b->[1] <=> $a->[1] # break ties with {xnum}
508 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
509 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
510 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
513 sub checkpoint_due ($) {
515 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
519 # I've copied FS images and only changed the hostname before,
520 # so prepend hostname. Use `state' since these a BOFH can change
521 # these while this process is running and we always want to be
522 # able to release locks taken by this process.
523 state $retval = hostname . '-' . do {
524 my $m; # machine-id(5) is systemd
525 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
526 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
527 chomp($m ||= `{ sysctl -n kern.hostid ||
528 hostid || ghostid; } 2>/dev/null`
529 || "no-machine-id-or-hostid-on-$^O");
536 my $expect = delete($self->{-eidxq_locked}) or return;
537 my ($owner_pid, undef) = split(/-/, $expect);
538 return if $owner_pid != $$; # shards may fork
539 my $oidx = $self->{oidx};
541 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
542 if ($cur eq $expect) {
543 $oidx->eidx_meta('eidxq_lock', '');
545 } elsif ($cur ne '') {
546 warn "E: eidxq_lock($expect) stolen by $cur\n";
548 warn "E: eidxq_lock($expect) released by another process\n";
555 eidxq_release($self) and $self->{oidx}->commit_lazy;
558 sub _eidxq_take ($) {
560 my $val = "$$-${\time}-$>-".host_ident;
561 $self->{oidx}->eidx_meta('eidxq_lock', $val);
562 $self->{-eidxq_locked} = $val;
565 sub eidxq_lock_acquire ($) {
567 my $oidx = $self->{oidx};
569 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
570 if (my $locked = $self->{-eidxq_locked}) { # be lazy
571 return $locked if $locked eq $cur;
573 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
574 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
575 if ($euid == $> && $ident eq host_ident) {
578 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
582 warn "I: eidxq_lock is stale ($cur), clobbering\n";
583 return _eidxq_take($self);
585 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
587 my $fn = $oidx->dbh->sqlite_db_filename;
589 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
590 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
591 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
596 sub eidxq_process ($$) { # for reindexing
597 my ($self, $sync) = @_;
599 return unless eidxq_lock_acquire($self);
600 my $dbh = $self->{oidx}->dbh;
601 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
603 $sync->{-regen_fmt} = "%u/$tot\n";
604 my $pr = $sync->{-opt}->{-progress};
606 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
607 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
608 $pr->("Xapian indexing $min..$max (total=$tot)\n");
610 $sync->{id2pos} //= do {
613 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
618 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
619 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
621 while (defined(my $docid = $iter->fetchrow_array)) {
622 last if $sync->{quit};
623 if (my $smsg = $self->{oidx}->get_art($docid)) {
624 _reindex_smsg($self, $sync, $smsg);
626 warn "E: #$docid does not exist in over\n";
628 $del->execute($docid);
631 if (checkpoint_due($sync)) {
632 $dbh = $del = $iter = undef;
633 reindex_checkpoint($self, $sync); # release lock
634 $dbh = $self->{oidx}->dbh;
638 $self->git->async_wait_all;
639 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
642 sub _reindex_unseen { # git->cat_async callback
643 my ($bref, $oid, $type, $size, $req) = @_;
644 return if is_bad_blob($oid, $type, $size, $req->{oid});
645 my $self = $req->{self} // die 'BUG: {self} unset';
646 local $self->{current_info} = "$self->{current_info} $oid";
647 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
648 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
649 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
650 $req->{new_smsg} = $new_smsg;
651 $req->{chash} = content_hash($eml);
652 $req->{mids} = mids($eml); # do_step iterates through this
653 do_step($req); # enter the normal indexing flow
656 # --reindex may catch totally unseen messages, this handles them
657 sub reindex_unseen ($$$$) {
658 my ($self, $sync, $ibx, $xsmsg) = @_;
661 autime => $xsmsg->{ds},
662 cotime => $xsmsg->{ts},
663 oid => $xsmsg->{blob},
665 xnum => $xsmsg->{num},
666 # {mids} and {chash} will be filled in at _reindex_unseen
668 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
669 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
672 sub _reindex_check_unseen ($$$) {
673 my ($self, $sync, $ibx) = @_;
674 my $ibx_id = $ibx->{-ibx_id};
676 my ($beg, $end) = (1, $slice);
678 # first, check if we missed any messages in target $ibx
680 my $pr = $sync->{-opt}->{-progress};
681 my $ekey = $ibx->eidx_key;
682 $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
685 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
686 ${$sync->{nr}} = $beg;
687 $beg = $msgs->[-1]->{num} + 1;
688 $end = $beg + $slice;
689 if (checkpoint_due($sync)) {
690 reindex_checkpoint($self, $sync); # release lock
693 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
694 SELECT DISTINCT(docid) FROM xref3 WHERE
695 ibx_id = ? AND xnum = ? AND oidbin = ?
697 for my $xsmsg (@$msgs) {
698 my $oidbin = pack('H*', $xsmsg->{blob});
699 $inx3->bind_param(1, $ibx_id);
700 $inx3->bind_param(2, $xsmsg->{num});
701 $inx3->bind_param(3, $oidbin, SQL_BLOB);
703 my $docids = $inx3->fetchall_arrayref;
704 # index messages which were totally missed
705 # the first time around ASAP:
706 if (scalar(@$docids) == 0) {
707 reindex_unseen($self, $sync, $ibx, $xsmsg);
708 } else { # already seen, reindex later
709 for my $r (@$docids) {
710 $self->{oidx}->eidxq_add($r->[0]);
713 last if $sync->{quit};
715 last if $sync->{quit};
719 sub _reindex_check_stale ($$$) {
720 my ($self, $sync, $ibx) = @_;
722 my $pr = $sync->{-opt}->{-progress};
724 my $ekey = $ibx->eidx_key;
725 $sync->{-regen_fmt} =
726 "$ekey check stale/missing %u/".$ibx->over->max."\n";
729 if (checkpoint_due($sync)) {
730 reindex_checkpoint($self, $sync); # release lock
732 # now, check if there's stale xrefs
733 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
734 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
735 ORDER BY docid,xnum ASC LIMIT 10000
737 $iter->execute($ibx->{-ibx_id}, $min);
740 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
741 return if $sync->{quit};
742 ${$sync->{nr}} = $xnum;
744 $fetching = $min = $docid;
745 my $smsg = $ibx->over->get_art($xnum);
746 my $oidhex = unpack('H*', $oidbin);
750 } elsif ($smsg->{blob} ne $oidhex) {
751 $err = "mismatch (!= $smsg->{blob})";
753 next; # likely, all good
755 # current_info already has eidx_key
756 warn "$xnum:$oidhex (#$docid): $err\n";
757 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
758 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
760 $del->bind_param(1, $ibx->{-ibx_id});
761 $del->bind_param(2, $xnum);
762 $del->bind_param(3, $oidbin, SQL_BLOB);
765 # get_xref3 over-fetches, but this is a rare path:
766 my $xr3 = $self->{oidx}->get_xref3($docid);
767 my $idx = $self->idx_shard($docid);
768 if (scalar(@$xr3) == 0) { # all gone
769 $self->{oidx}->delete_by_num($docid);
770 $self->{oidx}->eidxq_del($docid);
771 $idx->shard_remove($docid);
772 } else { # enqueue for reindex of remaining messages
773 $idx->shard_remove_eidx_info($docid,
775 $self->{oidx}->eidxq_add($docid); # yes, add
778 } while (defined $fetching);
781 sub _reindex_inbox ($$$) {
782 my ($self, $sync, $ibx) = @_;
783 local $self->{current_info} = $ibx->eidx_key;
784 _reindex_check_unseen($self, $sync, $ibx);
785 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
786 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
790 my ($self, $sync) = @_;
792 # acquire eidxq_lock early because full reindex takes forever
793 # and incremental -extindex processes can run during our checkpoints
794 if (!eidxq_lock_acquire($self)) {
795 warn "E: aborting --reindex\n";
798 for my $ibx (@{$self->{ibx_list}}) {
799 _reindex_inbox($self, $sync, $ibx);
800 last if $sync->{quit};
802 $self->git->async_wait_all; # ensure eidxq gets filled completely
803 eidxq_process($self, $sync) unless $sync->{quit};
806 sub eidx_sync { # main entry point
807 my ($self, $opt) = @_;
809 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
810 local $self->{current_info} = '';
811 local $SIG{__WARN__} = sub {
812 $warn_cb->($self->{current_info}, ': ', @_);
814 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
815 $self->{oidx}->rethread_prepare($opt);
817 need_checkpoint => \(my $need_checkpoint = 0),
819 next_check => now() + 10,
821 # DO NOT SET {reindex} here, it's incompatible with reused
822 # V2Writable code, reindex is totally different here
823 # compared to v1/v2 inboxes because we have multiple histories
825 -regen_fmt => "%u/?\n",
827 local $SIG{USR1} = sub { $need_checkpoint = 1 };
828 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
829 local $SIG{QUIT} = $quit;
830 local $SIG{INT} = $quit;
831 local $SIG{TERM} = $quit;
832 for my $ibx (@{$self->{ibx_list}}) {
833 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
835 if (delete($opt->{reindex})) {
836 $sync->{checkpoint_unlocks} = 1;
837 eidx_reindex($self, $sync);
840 # don't use $_ here, it'll get clobbered by reindex_checkpoint
841 for my $ibx (@{$self->{ibx_list}}) {
842 last if $sync->{quit};
843 _sync_inbox($self, $sync, $ibx);
845 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
846 eidxq_process($self, $sync) unless $sync->{quit};
848 eidxq_release($self);
849 PublicInbox::V2Writable::done($self);
852 sub update_last_commit { # overrides V2Writable
853 my ($self, $sync, $stk) = @_;
854 my $unit = $sync->{unit} // return;
855 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
856 defined($latest_cmt) or return;
857 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
858 my $ekey = $ibx->eidx_key;
859 my $uv = $ibx->uidvalidity;
860 my $epoch = $unit->{epoch};
862 my $v = $ibx->version;
864 die 'No {epoch} for v2 unit' unless defined $epoch;
865 $meta_key = "lc-v2:$ekey//$uv;$epoch";
867 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
868 $meta_key = "lc-v1:$ekey//$uv";
870 die "Unsupported inbox version: $v";
872 my $last = $self->{oidx}->eidx_meta($meta_key);
873 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
874 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
875 chomp(my $n = $unit->{git}->qx(@cmd));
876 return if $n ne '' && $n == 0;
878 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
881 sub _idx_init { # with_umask callback
882 my ($self, $opt) = @_;
883 PublicInbox::V2Writable::_idx_init($self, $opt);
884 $self->{midx} = PublicInbox::MiscIdx->new($self);
887 sub idx_init { # similar to V2Writable
888 my ($self, $opt) = @_;
889 return if $self->{idx_shards};
893 my $ALL = $self->git->{git_dir}; # ALL.git
894 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
895 my $info_dir = "$ALL/objects/info";
896 my $alt = "$info_dir/alternates";
898 my (@old, @new, %seen); # seen: st_dev + st_ino
900 open(my $fh, '<', $alt) or die "open $alt: $!";
901 $mode = (stat($fh))[2] & 07777;
902 while (my $line = <$fh>) {
903 chomp(my $d = $line);
904 if (my @st = stat($d)) {
905 next if $seen{"$st[0]\0$st[1]"}++;
907 warn "W: stat($d) failed (from $alt): $!\n";
908 next if $opt->{-idx_gc};
913 for my $ibx (@{$self->{ibx_list}}) {
914 my $line = $ibx->git->{git_dir} . "/objects\n";
915 chomp(my $d = $line);
916 if (my @st = stat($d)) {
917 next if $seen{"$st[0]\0$st[1]"}++;
919 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
920 next if $opt->{-idx_gc};
927 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
929 $self->parallel_init($self->{indexlevel});
930 $self->umask_prepare;
931 $self->with_umask(\&_idx_init, $self, $opt);
932 $self->{oidx}->begin_lazy;
933 $self->{oidx}->eidx_prep;
934 $self->{midx}->begin_txn;
938 *done = \&PublicInbox::V2Writable::done;
939 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
940 *with_umask = \&PublicInbox::InboxWritable::with_umask;
941 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
942 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
943 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
944 *index_todo = \&PublicInbox::V2Writable::index_todo;
945 *count_shards = \&PublicInbox::V2Writable::count_shards;
946 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
947 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
948 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;