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 $self->{ibx_map}->{$key} //= do {
76 push @{$self->{ibx_list}}, $ibx;
81 sub _ibx_attach { # each_inbox callback
82 my ($ibx, $self) = @_;
83 attach_inbox($self, $ibx);
87 my ($self, $cfg) = @_;
89 $cfg->each_inbox(\&_ibx_attach, $self);
92 sub check_batch_limit ($) {
94 my $self = $req->{self};
95 my $new_smsg = $req->{new_smsg};
97 # {raw_bytes} may be unset, so just use {bytes}
98 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
100 # set flag for PublicInbox::V2Writable::index_todo:
101 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
105 my ($req, $smsg) = @_;
106 my $self = $req->{self};
107 my $docid = $smsg->{num};
108 my $idx = $self->idx_shard($docid);
109 my $oid = $req->{oid};
110 my $xibx = $req->{ibx};
111 my $eml = $req->{eml};
112 my $eidx_key = $xibx->eidx_key;
113 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
114 my $xnum = $req->{xnum};
115 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
116 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
117 check_batch_limit($req);
120 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
123 $self->{oidx}->eidxq_del($docid);
124 $idx->shard_remove($docid);
125 } elsif ($rm_eidx_info) {
126 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
127 $self->{oidx}->eidxq_add($docid); # yes, add
132 # called by V2Writable::sync_prepare
133 sub artnum_max { $_[0]->{oidx}->eidx_max }
135 sub index_unseen ($) {
137 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
138 my $eml = delete $req->{eml};
139 $new_smsg->populate($eml, $req);
140 my $self = $req->{self};
141 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
142 $new_smsg->{num} = $docid;
143 my $idx = $self->idx_shard($docid);
144 $self->{oidx}->add_overview($eml, $new_smsg);
145 my $oid = $new_smsg->{blob};
146 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
147 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
148 $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
149 check_batch_limit($req);
152 sub do_finalize ($) {
154 if (my $indexed = $req->{indexed}) {
155 do_xpost($req, $_) for @$indexed;
156 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
159 # `d' message was already unindexed in the v1/v2 inboxes,
160 # so it's too noisy to warn, here.
162 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
163 if (defined(my $cur_cmt = $req->{cur_cmt})) {
164 ${$req->{latest_cmt}} = $cur_cmt;
168 sub do_step ($) { # main iterator for adding messages to the index
170 my $self = $req->{self} // die 'BUG: {self} missing';
172 if (my $next_arg = $req->{next_arg}) {
173 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
174 $req->{cur_smsg} = $smsg;
175 $self->git->cat_async($smsg->{blob},
176 \&ck_existing, $req);
177 return; # ck_existing calls do_step
179 delete $req->{cur_smsg};
180 delete $req->{next_arg};
182 my $mid = shift(@{$req->{mids}});
183 last unless defined $mid;
185 $req->{next_arg} = [ $mid, \$id, \$prev ];
191 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
193 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
194 my $self = $req->{self};
195 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
196 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
198 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
199 die "BUG: xref $keep[0] has no OID";
201 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
202 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
203 my $saved = $self->{oidx}->get_art($smsg->{num});
205 $self->{oidx}->delete_by_num($smsg->{num});
209 sub ck_existing { # git->cat_async callback
210 my ($bref, $oid, $type, $size, $req) = @_;
211 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
212 if ($type eq 'missing') {
214 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
215 my $self = $req->{self} // die 'BUG: {self} missing';
216 local $self->{current_info} = "$self->{current_info} $oid";
217 my $cur = PublicInbox::Eml->new($bref);
218 if (content_hash($cur) eq $req->{chash}) {
219 push @{$req->{indexed}}, $smsg; # for do_xpost
220 } # else { index_unseen later }
225 # is the messages visible in the inbox currently being indexed?
226 # return the number if so
227 sub cur_ibx_xnum ($$) {
228 my ($req, $bref) = @_;
229 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
231 $req->{eml} = PublicInbox::Eml->new($bref);
232 $req->{chash} = content_hash($req->{eml});
233 $req->{mids} = mids($req->{eml});
234 my @q = @{$req->{mids}}; # copy
235 while (defined(my $mid = shift @q)) {
237 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
238 return $x->{num} if $x->{blob} eq $req->{oid};
244 sub index_oid { # git->cat_async callback for 'm'
245 my ($bref, $oid, $type, $size, $req) = @_;
246 my $self = $req->{self};
247 local $self->{current_info} = "$self->{current_info} $oid";
248 return if is_bad_blob($oid, $type, $size, $req->{oid});
249 my $new_smsg = $req->{new_smsg} = bless {
251 }, 'PublicInbox::Smsg';
252 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
253 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
258 sub unindex_oid { # git->cat_async callback for 'd'
259 my ($bref, $oid, $type, $size, $req) = @_;
260 my $self = $req->{self};
261 local $self->{current_info} = "$self->{current_info} $oid";
262 return if is_bad_blob($oid, $type, $size, $req->{oid});
263 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
267 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
269 my ($self, $sync) = @_;
271 my $ekey = $sync->{ibx}->eidx_key;
272 my $uv = $sync->{ibx}->uidvalidity;
273 for my $i (0..$sync->{epoch_max}) {
274 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
279 sub _sync_inbox ($$$) {
280 my ($self, $sync, $ibx) = @_;
282 $sync->{nr} = \(my $nr = 0);
283 my $v = $ibx->version;
284 my $ekey = $ibx->eidx_key;
286 $sync->{epoch_max} = $ibx->max_git_epoch // return;
287 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
289 my $uv = $ibx->uidvalidity;
290 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
291 my $head = $ibx->mm->last_commit;
292 unless (defined $head) {
293 warn "E: $ibx->{inboxdir} is not indexed\n";
296 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
297 my $unit = { stack => $stk, git => $ibx->git };
298 push @{$sync->{todo}}, $unit;
300 warn "E: $ekey unsupported inbox version (v$v)\n";
303 for my $unit (@{delete($sync->{todo}) // []}) {
304 last if $sync->{quit};
305 index_todo($self, $sync, $unit);
307 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
308 $ibx->git->cleanup; # done with this inbox, now
311 sub gc_unref_doc ($$$$) {
312 my ($self, $ibx_id, $eidx_key, $docid) = @_;
313 my $dbh = $self->{oidx}->dbh;
315 # for debug/info purposes, oids may no longer be accessible
316 my $sth = $dbh->prepare_cached(<<'', undef, 1);
317 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
319 $sth->execute($docid, $ibx_id);
320 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
322 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
323 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
325 my $remain = $self->{oidx}->get_xref3($docid);
326 if (scalar(@$remain)) {
327 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
329 warn "I: unref #$docid $eidx_key $oid\n";
332 warn "I: remove #$docid $eidx_key @oid\n";
333 $self->idx_shard($docid)->shard_remove($docid);
338 my ($self, $opt) = @_;
339 $self->{cfg} or die "E: GC requires ->attach_config\n";
341 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
343 my $dbh = $self->{oidx}->dbh;
344 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
345 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
346 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
349 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
350 next if $self->{ibx_map}->{$eidx_key};
351 $self->{midx}->remove_eidx_key($eidx_key);
352 warn "I: deleting messages for $eidx_key...\n";
353 $x3_doc->execute($ibx_id);
354 while (defined(my $docid = $x3_doc->fetchrow_array)) {
355 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
357 $dbh->prepare_cached(<<'')->execute($ibx_id);
358 DELETE FROM inboxes WHERE ibx_id = ?
360 # drop last_commit info
362 $pat =~ s/([_%])/\\$1/g;
363 $lc_i->execute("lc-%:$pat//%");
364 while (my ($key) = $lc_i->fetchrow_array) {
365 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
366 warn "I: removing $key\n";
367 $dbh->prepare_cached(<<'')->execute($key);
368 DELETE FROM eidx_meta WHERE key = ?
372 warn "I: $eidx_key removed\n";
375 # it's not real unless it's in `over', we use parallelism here,
376 # shards will be reading directly from over, so commit
377 $self->{oidx}->commit_lazy;
378 $self->{oidx}->begin_lazy;
380 for my $idx (@{$self->{idx_shards}}) {
381 warn "I: cleaning up shard #$idx->{shard}\n";
382 $idx->shard_over_check($self->{oidx});
384 my $nr = $dbh->do(<<'');
385 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
387 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
393 my ($self, $sync, $smsg) = @_;
394 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
395 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
396 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
399 sub _reindex_finalize ($$$) {
400 my ($req, $smsg, $eml) = @_;
401 my $sync = $req->{sync};
402 my $self = $sync->{self};
403 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
404 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
405 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
406 my $docid = $smsg->{num} = $orig_smsg->{num};
407 $self->{oidx}->add_overview($eml, $smsg); # may rethread
408 check_batch_limit({ %$sync, new_smsg => $smsg });
409 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
410 my $stable = delete($by_chash->{$chash0}) //
411 die "BUG: $smsg->{blob} chash missing";
412 my $idx = $self->idx_shard($docid);
413 my $top_smsg = pop @$stable;
414 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
415 my $ibx = _ibx_for($self, $sync, $smsg);
416 $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
417 for my $x (reverse @$stable) {
418 $ibx = _ibx_for($self, $sync, $x);
419 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
420 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
422 return if $nr == 1; # likely, all good
424 warn "W: #$docid split into $nr due to deduplication change\n";
426 for my $ary (values %$by_chash) {
427 for my $x (reverse @$ary) {
428 warn "removing #$docid xref3 $x->{blob}\n";
429 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
430 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
432 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
433 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
434 $ibx = _ibx_for($self, $sync, $x);
435 my $e = $ibx->over->get_art($x->{num});
436 $e->{blob} eq $x->{blob} or die <<EOF;
437 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
439 push @todo, $ibx, $e;
442 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
443 reindex_unseen($self, $sync, $ibx, $e);
447 sub _reindex_oid { # git->cat_async callback
448 my ($bref, $oid, $type, $size, $req) = @_;
449 my $sync = $req->{sync};
450 my $self = $sync->{self};
451 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
452 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
453 my $docid = $orig_smsg->{num};
454 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
455 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
457 warn "W: #$docid gone or corrupted\n";
458 $self->idx_shard($docid)->shard_remove($docid);
459 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
460 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
462 warn "BUG: #$docid gone (UNEXPECTED)\n";
463 $self->idx_shard($docid)->shard_remove($docid);
467 my $ci = $self->{current_info};
468 local $self->{current_info} = "$ci #$docid $oid";
469 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
470 $re_smsg->{bytes} = $size + crlf_adjust($$bref);
471 my $eml = PublicInbox::Eml->new($bref);
472 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
473 cotime => $orig_smsg->{ts} });
474 my $chash = content_hash($eml);
475 $re_smsg->{chash} = $chash;
476 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
477 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
478 $re_smsg->{hdr} = $eml->header_obj;
479 push @{$req->{by_chash}->{$chash}}, $re_smsg;
480 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
481 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
482 } else { # last $re_smsg is the highest priority xref3
483 local $self->{current_info} = "$ci #$docid";
484 _reindex_finalize($req, $re_smsg, $eml);
488 sub _reindex_smsg ($$$) {
489 my ($self, $sync, $smsg) = @_;
490 my $docid = $smsg->{num};
491 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
492 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
494 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
496 $self->{oidx}->delete_by_num($docid);
497 $self->idx_shard($docid)->shard_remove($docid);
501 # we sort {xr3r} in the reverse order of {ibx_list} so we can
502 # hit the common case in _reindex_finalize without rereading
503 # from git (or holding multiple messages in memory).
504 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
506 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
508 $b->[1] <=> $a->[1] # break ties with {xnum}
510 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
511 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
512 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
515 sub checkpoint_due ($) {
517 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
521 # I've copied FS images and only changed the hostname before,
522 # so prepend hostname. Use `state' since these a BOFH can change
523 # these while this process is running and we always want to be
524 # able to release locks taken by this process.
525 state $retval = hostname . '-' . do {
526 my $m; # machine-id(5) is systemd
527 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
528 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
529 chomp($m ||= `{ sysctl -n kern.hostid ||
530 hostid || ghostid; } 2>/dev/null`
531 || "no-machine-id-or-hostid-on-$^O");
538 my $expect = delete($self->{-eidxq_locked}) or return;
539 my ($owner_pid, undef) = split(/-/, $expect);
540 return if $owner_pid != $$; # shards may fork
541 my $oidx = $self->{oidx};
543 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
544 if ($cur eq $expect) {
545 $oidx->eidx_meta('eidxq_lock', '');
547 } elsif ($cur ne '') {
548 warn "E: eidxq_lock($expect) stolen by $cur\n";
550 warn "E: eidxq_lock($expect) released by another process\n";
557 eidxq_release($self) and $self->{oidx}->commit_lazy;
560 sub _eidxq_take ($) {
562 my $val = "$$-${\time}-$>-".host_ident;
563 $self->{oidx}->eidx_meta('eidxq_lock', $val);
564 $self->{-eidxq_locked} = $val;
567 sub eidxq_lock_acquire ($) {
569 my $oidx = $self->{oidx};
571 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
572 if (my $locked = $self->{-eidxq_locked}) { # be lazy
573 return $locked if $locked eq $cur;
575 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
576 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
577 if ($euid == $> && $ident eq host_ident) {
580 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
584 warn "I: eidxq_lock is stale ($cur), clobbering\n";
585 return _eidxq_take($self);
587 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
589 my $fn = $oidx->dbh->sqlite_db_filename;
591 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
592 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
593 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
598 sub eidxq_process ($$) { # for reindexing
599 my ($self, $sync) = @_;
601 return unless eidxq_lock_acquire($self);
602 my $dbh = $self->{oidx}->dbh;
603 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
605 $sync->{-regen_fmt} = "%u/$tot\n";
606 my $pr = $sync->{-opt}->{-progress};
608 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
609 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
610 $pr->("Xapian indexing $min..$max (total=$tot)\n");
612 $sync->{id2pos} //= do {
615 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
620 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
621 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
623 while (defined(my $docid = $iter->fetchrow_array)) {
624 last if $sync->{quit};
625 if (my $smsg = $self->{oidx}->get_art($docid)) {
626 _reindex_smsg($self, $sync, $smsg);
628 warn "E: #$docid does not exist in over\n";
630 $del->execute($docid);
633 if (checkpoint_due($sync)) {
634 $dbh = $del = $iter = undef;
635 reindex_checkpoint($self, $sync); # release lock
636 $dbh = $self->{oidx}->dbh;
640 $self->git->async_wait_all;
641 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
644 sub _reindex_unseen { # git->cat_async callback
645 my ($bref, $oid, $type, $size, $req) = @_;
646 return if is_bad_blob($oid, $type, $size, $req->{oid});
647 my $self = $req->{self} // die 'BUG: {self} unset';
648 local $self->{current_info} = "$self->{current_info} $oid";
649 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
650 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
651 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
652 $req->{new_smsg} = $new_smsg;
653 $req->{chash} = content_hash($eml);
654 $req->{mids} = mids($eml); # do_step iterates through this
655 do_step($req); # enter the normal indexing flow
658 # --reindex may catch totally unseen messages, this handles them
659 sub reindex_unseen ($$$$) {
660 my ($self, $sync, $ibx, $xsmsg) = @_;
663 autime => $xsmsg->{ds},
664 cotime => $xsmsg->{ts},
665 oid => $xsmsg->{blob},
667 xnum => $xsmsg->{num},
668 # {mids} and {chash} will be filled in at _reindex_unseen
670 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
671 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
674 sub _reindex_check_unseen ($$$) {
675 my ($self, $sync, $ibx) = @_;
676 my $ibx_id = $ibx->{-ibx_id};
678 my ($beg, $end) = (1, $slice);
680 # first, check if we missed any messages in target $ibx
682 my $pr = $sync->{-opt}->{-progress};
683 my $ekey = $ibx->eidx_key;
684 $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
687 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
688 ${$sync->{nr}} = $beg;
689 $beg = $msgs->[-1]->{num} + 1;
690 $end = $beg + $slice;
691 if (checkpoint_due($sync)) {
692 reindex_checkpoint($self, $sync); # release lock
695 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
696 SELECT DISTINCT(docid) FROM xref3 WHERE
697 ibx_id = ? AND xnum = ? AND oidbin = ?
699 for my $xsmsg (@$msgs) {
700 my $oidbin = pack('H*', $xsmsg->{blob});
701 $inx3->bind_param(1, $ibx_id);
702 $inx3->bind_param(2, $xsmsg->{num});
703 $inx3->bind_param(3, $oidbin, SQL_BLOB);
705 my $docids = $inx3->fetchall_arrayref;
706 # index messages which were totally missed
707 # the first time around ASAP:
708 if (scalar(@$docids) == 0) {
709 reindex_unseen($self, $sync, $ibx, $xsmsg);
710 } else { # already seen, reindex later
711 for my $r (@$docids) {
712 $self->{oidx}->eidxq_add($r->[0]);
715 last if $sync->{quit};
717 last if $sync->{quit};
721 sub _reindex_check_stale ($$$) {
722 my ($self, $sync, $ibx) = @_;
724 my $pr = $sync->{-opt}->{-progress};
726 my $ekey = $ibx->eidx_key;
727 $sync->{-regen_fmt} =
728 "$ekey check stale/missing %u/".$ibx->over->max."\n";
731 if (checkpoint_due($sync)) {
732 reindex_checkpoint($self, $sync); # release lock
734 # now, check if there's stale xrefs
735 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
736 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
737 ORDER BY docid,xnum ASC LIMIT 10000
739 $iter->execute($ibx->{-ibx_id}, $min);
742 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
743 return if $sync->{quit};
744 ${$sync->{nr}} = $xnum;
746 $fetching = $min = $docid;
747 my $smsg = $ibx->over->get_art($xnum);
748 my $oidhex = unpack('H*', $oidbin);
752 } elsif ($smsg->{blob} ne $oidhex) {
753 $err = "mismatch (!= $smsg->{blob})";
755 next; # likely, all good
757 # current_info already has eidx_key
758 warn "$xnum:$oidhex (#$docid): $err\n";
759 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
760 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
762 $del->bind_param(1, $ibx->{-ibx_id});
763 $del->bind_param(2, $xnum);
764 $del->bind_param(3, $oidbin, SQL_BLOB);
767 # get_xref3 over-fetches, but this is a rare path:
768 my $xr3 = $self->{oidx}->get_xref3($docid);
769 my $idx = $self->idx_shard($docid);
770 if (scalar(@$xr3) == 0) { # all gone
771 $self->{oidx}->delete_by_num($docid);
772 $self->{oidx}->eidxq_del($docid);
773 $idx->shard_remove($docid);
774 } else { # enqueue for reindex of remaining messages
775 $idx->shard_remove_eidx_info($docid,
777 $self->{oidx}->eidxq_add($docid); # yes, add
780 } while (defined $fetching);
783 sub _reindex_inbox ($$$) {
784 my ($self, $sync, $ibx) = @_;
785 local $self->{current_info} = $ibx->eidx_key;
786 _reindex_check_unseen($self, $sync, $ibx);
787 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
788 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
792 my ($self, $sync) = @_;
794 # acquire eidxq_lock early because full reindex takes forever
795 # and incremental -extindex processes can run during our checkpoints
796 if (!eidxq_lock_acquire($self)) {
797 warn "E: aborting --reindex\n";
800 for my $ibx (@{$self->{ibx_list}}) {
801 _reindex_inbox($self, $sync, $ibx);
802 last if $sync->{quit};
804 $self->git->async_wait_all; # ensure eidxq gets filled completely
805 eidxq_process($self, $sync) unless $sync->{quit};
808 sub eidx_sync { # main entry point
809 my ($self, $opt) = @_;
811 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
812 local $self->{current_info} = '';
813 local $SIG{__WARN__} = sub {
814 $warn_cb->($self->{current_info}, ': ', @_);
816 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
817 $self->{oidx}->rethread_prepare($opt);
819 need_checkpoint => \(my $need_checkpoint = 0),
821 next_check => now() + 10,
823 # DO NOT SET {reindex} here, it's incompatible with reused
824 # V2Writable code, reindex is totally different here
825 # compared to v1/v2 inboxes because we have multiple histories
827 -regen_fmt => "%u/?\n",
829 local $SIG{USR1} = sub { $need_checkpoint = 1 };
830 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
831 local $SIG{QUIT} = $quit;
832 local $SIG{INT} = $quit;
833 local $SIG{TERM} = $quit;
834 for my $ibx (@{$self->{ibx_list}}) {
835 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
837 if (delete($opt->{reindex})) {
838 $sync->{checkpoint_unlocks} = 1;
839 eidx_reindex($self, $sync);
842 # don't use $_ here, it'll get clobbered by reindex_checkpoint
843 for my $ibx (@{$self->{ibx_list}}) {
844 last if $sync->{quit};
845 _sync_inbox($self, $sync, $ibx);
847 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
848 eidxq_process($self, $sync) unless $sync->{quit};
850 eidxq_release($self);
851 PublicInbox::V2Writable::done($self);
854 sub update_last_commit { # overrides V2Writable
855 my ($self, $sync, $stk) = @_;
856 my $unit = $sync->{unit} // return;
857 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
858 defined($latest_cmt) or return;
859 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
860 my $ekey = $ibx->eidx_key;
861 my $uv = $ibx->uidvalidity;
862 my $epoch = $unit->{epoch};
864 my $v = $ibx->version;
866 die 'No {epoch} for v2 unit' unless defined $epoch;
867 $meta_key = "lc-v2:$ekey//$uv;$epoch";
869 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
870 $meta_key = "lc-v1:$ekey//$uv";
872 die "Unsupported inbox version: $v";
874 my $last = $self->{oidx}->eidx_meta($meta_key);
875 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
876 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
877 chomp(my $n = $unit->{git}->qx(@cmd));
878 return if $n ne '' && $n == 0;
880 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
883 sub _idx_init { # with_umask callback
884 my ($self, $opt) = @_;
885 PublicInbox::V2Writable::_idx_init($self, $opt);
886 $self->{midx} = PublicInbox::MiscIdx->new($self);
889 sub idx_init { # similar to V2Writable
890 my ($self, $opt) = @_;
891 return if $self->{idx_shards};
895 my $ALL = $self->git->{git_dir}; # ALL.git
896 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
897 my $info_dir = "$ALL/objects/info";
898 my $alt = "$info_dir/alternates";
900 my (@old, @new, %seen); # seen: st_dev + st_ino
902 open(my $fh, '<', $alt) or die "open $alt: $!";
903 $mode = (stat($fh))[2] & 07777;
904 while (my $line = <$fh>) {
905 chomp(my $d = $line);
906 if (my @st = stat($d)) {
907 next if $seen{"$st[0]\0$st[1]"}++;
909 warn "W: stat($d) failed (from $alt): $!\n";
910 next if $opt->{-idx_gc};
915 for my $ibx (@{$self->{ibx_list}}) {
916 my $line = $ibx->git->{git_dir} . "/objects\n";
917 chomp(my $d = $line);
918 if (my @st = stat($d)) {
919 next if $seen{"$st[0]\0$st[1]"}++;
921 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
922 next if $opt->{-idx_gc};
929 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
931 $self->parallel_init($self->{indexlevel});
932 $self->umask_prepare;
933 $self->with_umask(\&_idx_init, $self, $opt);
934 $self->{oidx}->begin_lazy;
935 $self->{oidx}->eidx_prep;
936 $self->{midx}->begin_txn;
940 *done = \&PublicInbox::V2Writable::done;
941 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
942 *with_umask = \&PublicInbox::InboxWritable::with_umask;
943 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
944 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
945 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
946 *index_todo = \&PublicInbox::V2Writable::index_todo;
947 *count_shards = \&PublicInbox::V2Writable::count_shards;
948 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
949 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
950 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;