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 $self->{ibx_map}->{$ibx->eidx_key} //= do {
65 push @{$self->{ibx_list}}, $ibx;
70 sub _ibx_attach { # each_inbox callback
71 my ($ibx, $self) = @_;
72 attach_inbox($self, $ibx);
76 my ($self, $cfg) = @_;
78 $cfg->each_inbox(\&_ibx_attach, $self);
81 sub check_batch_limit ($) {
83 my $self = $req->{self};
84 my $new_smsg = $req->{new_smsg};
86 # {raw_bytes} may be unset, so just use {bytes}
87 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
89 # set flag for PublicInbox::V2Writable::index_todo:
90 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
94 my ($req, $smsg) = @_;
95 my $self = $req->{self};
96 my $docid = $smsg->{num};
97 my $idx = $self->idx_shard($docid);
98 my $oid = $req->{oid};
99 my $xibx = $req->{ibx};
100 my $eml = $req->{eml};
101 my $eidx_key = $xibx->eidx_key;
102 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
103 my $xnum = $req->{xnum};
104 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
105 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
106 check_batch_limit($req);
109 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
112 $self->{oidx}->eidxq_del($docid);
113 $idx->shard_remove($docid);
114 } elsif ($rm_eidx_info) {
115 $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
116 $self->{oidx}->eidxq_add($docid); # yes, add
121 # called by V2Writable::sync_prepare
122 sub artnum_max { $_[0]->{oidx}->eidx_max }
124 sub index_unseen ($) {
126 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
127 my $eml = delete $req->{eml};
128 $new_smsg->populate($eml, $req);
129 my $self = $req->{self};
130 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
131 $new_smsg->{num} = $docid;
132 my $idx = $self->idx_shard($docid);
133 $self->{oidx}->add_overview($eml, $new_smsg);
134 my $oid = $new_smsg->{blob};
135 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
136 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
137 $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
138 check_batch_limit($req);
141 sub do_finalize ($) {
143 if (my $indexed = $req->{indexed}) {
144 do_xpost($req, $_) for @$indexed;
145 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
148 # `d' message was already unindexed in the v1/v2 inboxes,
149 # so it's too noisy to warn, here.
151 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
152 if (defined(my $cur_cmt = $req->{cur_cmt})) {
153 ${$req->{latest_cmt}} = $cur_cmt;
157 sub do_step ($) { # main iterator for adding messages to the index
159 my $self = $req->{self} // die 'BUG: {self} missing';
161 if (my $next_arg = $req->{next_arg}) {
162 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
163 $req->{cur_smsg} = $smsg;
164 $self->git->cat_async($smsg->{blob},
165 \&ck_existing, $req);
166 return; # ck_existing calls do_step
168 delete $req->{cur_smsg};
169 delete $req->{next_arg};
171 my $mid = shift(@{$req->{mids}});
172 last unless defined $mid;
174 $req->{next_arg} = [ $mid, \$id, \$prev ];
180 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
182 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
183 my $self = $req->{self};
184 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
185 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
187 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
188 die "BUG: xref $keep[0] has no OID";
190 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
191 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
192 my $saved = $self->{oidx}->get_art($smsg->{num});
194 $self->{oidx}->delete_by_num($smsg->{num});
198 sub ck_existing { # git->cat_async callback
199 my ($bref, $oid, $type, $size, $req) = @_;
200 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
201 if ($type eq 'missing') {
203 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
204 my $self = $req->{self} // die 'BUG: {self} missing';
205 local $self->{current_info} = "$self->{current_info} $oid";
206 my $cur = PublicInbox::Eml->new($bref);
207 if (content_hash($cur) eq $req->{chash}) {
208 push @{$req->{indexed}}, $smsg; # for do_xpost
209 } # else { index_unseen later }
214 # is the messages visible in the inbox currently being indexed?
215 # return the number if so
216 sub cur_ibx_xnum ($$) {
217 my ($req, $bref) = @_;
218 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
220 $req->{eml} = PublicInbox::Eml->new($bref);
221 $req->{chash} = content_hash($req->{eml});
222 $req->{mids} = mids($req->{eml});
223 my @q = @{$req->{mids}}; # copy
224 while (defined(my $mid = shift @q)) {
226 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
227 return $x->{num} if $x->{blob} eq $req->{oid};
233 sub index_oid { # git->cat_async callback for 'm'
234 my ($bref, $oid, $type, $size, $req) = @_;
235 my $self = $req->{self};
236 local $self->{current_info} = "$self->{current_info} $oid";
237 return if is_bad_blob($oid, $type, $size, $req->{oid});
238 my $new_smsg = $req->{new_smsg} = bless {
240 }, 'PublicInbox::Smsg';
241 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
242 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
247 sub unindex_oid { # git->cat_async callback for 'd'
248 my ($bref, $oid, $type, $size, $req) = @_;
249 my $self = $req->{self};
250 local $self->{current_info} = "$self->{current_info} $oid";
251 return if is_bad_blob($oid, $type, $size, $req->{oid});
252 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
256 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
258 my ($self, $sync) = @_;
260 my $ekey = $sync->{ibx}->eidx_key;
261 my $uv = $sync->{ibx}->uidvalidity;
262 for my $i (0..$sync->{epoch_max}) {
263 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
268 sub _ibx_index_reject ($) {
270 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
271 $ibx->uidvalidity // return 'no UIDVALIDITY';
272 $ibx->over // return 'unindexed, no over.sqlite3';
276 sub _sync_inbox ($$$) {
277 my ($self, $sync, $ibx) = @_;
278 my $ekey = $ibx->eidx_key;
279 if (defined(my $err = _ibx_index_reject($ibx))) {
280 return "W: skipping $ekey ($err)";
283 $sync->{nr} = \(my $nr = 0);
284 my $v = $ibx->version;
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 return "E: $ibx->{inboxdir} is not indexed";
293 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
294 my $unit = { stack => $stk, git => $ibx->git };
295 push @{$sync->{todo}}, $unit;
297 return "E: $ekey unsupported inbox version (v$v)";
299 for my $unit (@{delete($sync->{todo}) // []}) {
300 last if $sync->{quit};
301 index_todo($self, $sync, $unit);
303 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
304 $ibx->git->cleanup; # done with this inbox, now
308 sub gc_unref_doc ($$$$) {
309 my ($self, $ibx_id, $eidx_key, $docid) = @_;
310 my $dbh = $self->{oidx}->dbh;
312 # for debug/info purposes, oids may no longer be accessible
313 my $sth = $dbh->prepare_cached(<<'', undef, 1);
314 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
316 $sth->execute($docid, $ibx_id);
317 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
319 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
320 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
322 my $remain = $self->{oidx}->get_xref3($docid);
323 if (scalar(@$remain)) {
324 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
326 warn "I: unref #$docid $eidx_key $oid\n";
329 warn "I: remove #$docid $eidx_key @oid\n";
330 $self->idx_shard($docid)->shard_remove($docid);
335 my ($self, $opt) = @_;
336 $self->{cfg} or die "E: GC requires ->attach_config\n";
338 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
340 my $dbh = $self->{oidx}->dbh;
341 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
342 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
343 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
346 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
347 next if $self->{ibx_map}->{$eidx_key};
348 $self->{midx}->remove_eidx_key($eidx_key);
349 warn "I: deleting messages for $eidx_key...\n";
350 $x3_doc->execute($ibx_id);
351 while (defined(my $docid = $x3_doc->fetchrow_array)) {
352 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
354 $dbh->prepare_cached(<<'')->execute($ibx_id);
355 DELETE FROM inboxes WHERE ibx_id = ?
357 # drop last_commit info
359 $pat =~ s/([_%])/\\$1/g;
360 $lc_i->execute("lc-%:$pat//%");
361 while (my ($key) = $lc_i->fetchrow_array) {
362 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
363 warn "I: removing $key\n";
364 $dbh->prepare_cached(<<'')->execute($key);
365 DELETE FROM eidx_meta WHERE key = ?
369 warn "I: $eidx_key removed\n";
372 # it's not real unless it's in `over', we use parallelism here,
373 # shards will be reading directly from over, so commit
374 $self->{oidx}->commit_lazy;
375 $self->{oidx}->begin_lazy;
377 for my $idx (@{$self->{idx_shards}}) {
378 warn "I: cleaning up shard #$idx->{shard}\n";
379 $idx->shard_over_check($self->{oidx});
381 my $nr = $dbh->do(<<'');
382 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
384 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
390 my ($self, $sync, $smsg) = @_;
391 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
392 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
393 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
396 sub _fd_constrained ($) {
398 $self->{-fd_constrained} //= do {
400 if (eval { require BSD::Resource; 1 }) {
401 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
402 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
404 chomp($soft = `sh -c 'ulimit -n'`);
406 if (defined($soft)) {
407 my $want = scalar(@{$self->{ibx_list}}) + 64; # estimate
408 my $ret = $want > $soft;
411 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
416 warn "Unable to determine RLIMIT_NOFILE: $@\n";
422 sub _reindex_finalize ($$$) {
423 my ($req, $smsg, $eml) = @_;
424 my $sync = $req->{sync};
425 my $self = $sync->{self};
426 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
427 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
428 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
429 my $docid = $smsg->{num} = $orig_smsg->{num};
430 $self->{oidx}->add_overview($eml, $smsg); # may rethread
431 check_batch_limit({ %$sync, new_smsg => $smsg });
432 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
433 my $stable = delete($by_chash->{$chash0}) //
434 die "BUG: $smsg->{blob} chash missing";
435 my $idx = $self->idx_shard($docid);
436 my $top_smsg = pop @$stable;
437 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
438 my $ibx = _ibx_for($self, $sync, $smsg);
439 $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
440 for my $x (reverse @$stable) {
441 $ibx = _ibx_for($self, $sync, $x);
442 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
443 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
445 return if $nr == 1; # likely, all good
447 warn "W: #$docid split into $nr due to deduplication change\n";
449 for my $ary (values %$by_chash) {
450 for my $x (reverse @$ary) {
451 warn "removing #$docid xref3 $x->{blob}\n";
452 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
453 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
455 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
456 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
457 $ibx = _ibx_for($self, $sync, $x);
458 if (my $over = $ibx->over) {
459 my $e = $over->get_art($x->{num});
460 $e->{blob} eq $x->{blob} or die <<EOF;
461 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
463 push @todo, $ibx, $e;
464 $over->dbh_close if _fd_constrained($self);
466 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
470 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
471 reindex_unseen($self, $sync, $ibx, $e);
475 sub _reindex_oid { # git->cat_async callback
476 my ($bref, $oid, $type, $size, $req) = @_;
477 my $sync = $req->{sync};
478 my $self = $sync->{self};
479 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
480 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
481 my $docid = $orig_smsg->{num};
482 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
483 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
485 warn "W: #$docid gone or corrupted\n";
486 $self->idx_shard($docid)->shard_remove($docid);
487 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
488 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
490 warn "BUG: #$docid gone (UNEXPECTED)\n";
491 $self->idx_shard($docid)->shard_remove($docid);
495 my $ci = $self->{current_info};
496 local $self->{current_info} = "$ci #$docid $oid";
497 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
498 $re_smsg->{bytes} = $size + crlf_adjust($$bref);
499 my $eml = PublicInbox::Eml->new($bref);
500 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
501 cotime => $orig_smsg->{ts} });
502 my $chash = content_hash($eml);
503 $re_smsg->{chash} = $chash;
504 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
505 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
506 $re_smsg->{hdr} = $eml->header_obj;
507 push @{$req->{by_chash}->{$chash}}, $re_smsg;
508 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
509 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
510 } else { # last $re_smsg is the highest priority xref3
511 local $self->{current_info} = "$ci #$docid";
512 _reindex_finalize($req, $re_smsg, $eml);
516 sub _reindex_smsg ($$$) {
517 my ($self, $sync, $smsg) = @_;
518 my $docid = $smsg->{num};
519 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
520 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
522 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
524 $self->{oidx}->delete_by_num($docid);
525 $self->idx_shard($docid)->shard_remove($docid);
529 # we sort {xr3r} in the reverse order of {ibx_list} so we can
530 # hit the common case in _reindex_finalize without rereading
531 # from git (or holding multiple messages in memory).
532 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
534 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
536 $b->[1] <=> $a->[1] # break ties with {xnum}
538 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
539 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
540 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
543 sub checkpoint_due ($) {
545 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
549 # I've copied FS images and only changed the hostname before,
550 # so prepend hostname. Use `state' since these a BOFH can change
551 # these while this process is running and we always want to be
552 # able to release locks taken by this process.
553 state $retval = hostname . '-' . do {
554 my $m; # machine-id(5) is systemd
555 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
556 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
557 chomp($m ||= `{ sysctl -n kern.hostid ||
558 hostid || ghostid; } 2>/dev/null`
559 || "no-machine-id-or-hostid-on-$^O");
566 my $expect = delete($self->{-eidxq_locked}) or return;
567 my ($owner_pid, undef) = split(/-/, $expect);
568 return if $owner_pid != $$; # shards may fork
569 my $oidx = $self->{oidx};
571 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
572 if ($cur eq $expect) {
573 $oidx->eidx_meta('eidxq_lock', '');
575 } elsif ($cur ne '') {
576 warn "E: eidxq_lock($expect) stolen by $cur\n";
578 warn "E: eidxq_lock($expect) released by another process\n";
585 eidxq_release($self) and $self->{oidx}->commit_lazy;
588 sub _eidxq_take ($) {
590 my $val = "$$-${\time}-$>-".host_ident;
591 $self->{oidx}->eidx_meta('eidxq_lock', $val);
592 $self->{-eidxq_locked} = $val;
595 sub eidxq_lock_acquire ($) {
597 my $oidx = $self->{oidx};
599 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
600 if (my $locked = $self->{-eidxq_locked}) { # be lazy
601 return $locked if $locked eq $cur;
603 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
604 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
605 if ($euid == $> && $ident eq host_ident) {
608 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
612 warn "I: eidxq_lock is stale ($cur), clobbering\n";
613 return _eidxq_take($self);
615 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
617 my $fn = $oidx->dbh->sqlite_db_filename;
619 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
620 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
621 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
626 sub eidxq_process ($$) { # for reindexing
627 my ($self, $sync) = @_;
629 return unless eidxq_lock_acquire($self);
630 my $dbh = $self->{oidx}->dbh;
631 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
633 $sync->{-regen_fmt} = "%u/$tot\n";
634 my $pr = $sync->{-opt}->{-progress};
636 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
637 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
638 $pr->("Xapian indexing $min..$max (total=$tot)\n");
640 $sync->{id2pos} //= do {
643 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
648 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
649 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
651 while (defined(my $docid = $iter->fetchrow_array)) {
652 last if $sync->{quit};
653 if (my $smsg = $self->{oidx}->get_art($docid)) {
654 _reindex_smsg($self, $sync, $smsg);
656 warn "E: #$docid does not exist in over\n";
658 $del->execute($docid);
661 if (checkpoint_due($sync)) {
662 $dbh = $del = $iter = undef;
663 reindex_checkpoint($self, $sync); # release lock
664 $dbh = $self->{oidx}->dbh;
668 $self->git->async_wait_all;
669 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
672 sub _reindex_unseen { # git->cat_async callback
673 my ($bref, $oid, $type, $size, $req) = @_;
674 return if is_bad_blob($oid, $type, $size, $req->{oid});
675 my $self = $req->{self} // die 'BUG: {self} unset';
676 local $self->{current_info} = "$self->{current_info} $oid";
677 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
678 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
679 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
680 $req->{new_smsg} = $new_smsg;
681 $req->{chash} = content_hash($eml);
682 $req->{mids} = mids($eml); # do_step iterates through this
683 do_step($req); # enter the normal indexing flow
686 # --reindex may catch totally unseen messages, this handles them
687 sub reindex_unseen ($$$$) {
688 my ($self, $sync, $ibx, $xsmsg) = @_;
691 autime => $xsmsg->{ds},
692 cotime => $xsmsg->{ts},
693 oid => $xsmsg->{blob},
695 xnum => $xsmsg->{num},
696 # {mids} and {chash} will be filled in at _reindex_unseen
698 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
699 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
702 sub _reindex_check_unseen ($$$) {
703 my ($self, $sync, $ibx) = @_;
704 my $ibx_id = $ibx->{-ibx_id};
706 my ($beg, $end) = (1, $slice);
708 # first, check if we missed any messages in target $ibx
710 my $pr = $sync->{-opt}->{-progress};
711 my $ekey = $ibx->eidx_key;
712 $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
715 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
716 ${$sync->{nr}} = $beg;
717 $beg = $msgs->[-1]->{num} + 1;
718 $end = $beg + $slice;
719 if (checkpoint_due($sync)) {
720 reindex_checkpoint($self, $sync); # release lock
723 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
724 SELECT DISTINCT(docid) FROM xref3 WHERE
725 ibx_id = ? AND xnum = ? AND oidbin = ?
727 for my $xsmsg (@$msgs) {
728 my $oidbin = pack('H*', $xsmsg->{blob});
729 $inx3->bind_param(1, $ibx_id);
730 $inx3->bind_param(2, $xsmsg->{num});
731 $inx3->bind_param(3, $oidbin, SQL_BLOB);
733 my $docids = $inx3->fetchall_arrayref;
734 # index messages which were totally missed
735 # the first time around ASAP:
736 if (scalar(@$docids) == 0) {
737 reindex_unseen($self, $sync, $ibx, $xsmsg);
738 } else { # already seen, reindex later
739 for my $r (@$docids) {
740 $self->{oidx}->eidxq_add($r->[0]);
743 last if $sync->{quit};
745 last if $sync->{quit};
749 sub _reindex_check_stale ($$$) {
750 my ($self, $sync, $ibx) = @_;
752 my $pr = $sync->{-opt}->{-progress};
754 my $ekey = $ibx->eidx_key;
755 $sync->{-regen_fmt} =
756 "$ekey check stale/missing %u/".$ibx->over->max."\n";
759 if (checkpoint_due($sync)) {
760 reindex_checkpoint($self, $sync); # release lock
762 # now, check if there's stale xrefs
763 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
764 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
765 ORDER BY docid,xnum ASC LIMIT 10000
767 $iter->execute($ibx->{-ibx_id}, $min);
770 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
771 return if $sync->{quit};
772 ${$sync->{nr}} = $xnum;
774 $fetching = $min = $docid;
775 my $smsg = $ibx->over->get_art($xnum);
776 my $oidhex = unpack('H*', $oidbin);
780 } elsif ($smsg->{blob} ne $oidhex) {
781 $err = "mismatch (!= $smsg->{blob})";
783 next; # likely, all good
785 # current_info already has eidx_key
786 warn "$xnum:$oidhex (#$docid): $err\n";
787 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
788 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
790 $del->bind_param(1, $ibx->{-ibx_id});
791 $del->bind_param(2, $xnum);
792 $del->bind_param(3, $oidbin, SQL_BLOB);
795 # get_xref3 over-fetches, but this is a rare path:
796 my $xr3 = $self->{oidx}->get_xref3($docid);
797 my $idx = $self->idx_shard($docid);
798 if (scalar(@$xr3) == 0) { # all gone
799 $self->{oidx}->delete_by_num($docid);
800 $self->{oidx}->eidxq_del($docid);
801 $idx->shard_remove($docid);
802 } else { # enqueue for reindex of remaining messages
803 $idx->shard_remove_eidx_info($docid,
805 $self->{oidx}->eidxq_add($docid); # yes, add
808 } while (defined $fetching);
811 sub _reindex_inbox ($$$) {
812 my ($self, $sync, $ibx) = @_;
813 my $ekey = $ibx->eidx_key;
814 local $self->{current_info} = $ekey;
815 if (defined(my $err = _ibx_index_reject($ibx))) {
816 warn "W: cannot reindex $ekey ($err)\n";
818 _reindex_check_unseen($self, $sync, $ibx);
819 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
821 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
825 my ($self, $sync) = @_;
827 # acquire eidxq_lock early because full reindex takes forever
828 # and incremental -extindex processes can run during our checkpoints
829 if (!eidxq_lock_acquire($self)) {
830 warn "E: aborting --reindex\n";
833 for my $ibx (@{$self->{ibx_list}}) {
834 _reindex_inbox($self, $sync, $ibx);
835 last if $sync->{quit};
837 $self->git->async_wait_all; # ensure eidxq gets filled completely
838 eidxq_process($self, $sync) unless $sync->{quit};
841 sub eidx_sync { # main entry point
842 my ($self, $opt) = @_;
844 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
845 local $self->{current_info} = '';
846 local $SIG{__WARN__} = sub {
847 $warn_cb->($self->{current_info}, ': ', @_);
849 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
850 $self->{oidx}->rethread_prepare($opt);
852 need_checkpoint => \(my $need_checkpoint = 0),
854 next_check => now() + 10,
856 # DO NOT SET {reindex} here, it's incompatible with reused
857 # V2Writable code, reindex is totally different here
858 # compared to v1/v2 inboxes because we have multiple histories
860 -regen_fmt => "%u/?\n",
862 local $SIG{USR1} = sub { $need_checkpoint = 1 };
863 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
864 local $SIG{QUIT} = $quit;
865 local $SIG{INT} = $quit;
866 local $SIG{TERM} = $quit;
867 for my $ibx (@{$self->{ibx_list}}) {
868 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
870 if (delete($opt->{reindex})) {
871 $sync->{checkpoint_unlocks} = 1;
872 eidx_reindex($self, $sync);
875 # don't use $_ here, it'll get clobbered by reindex_checkpoint
876 for my $ibx (@{$self->{ibx_list}}) {
877 last if $sync->{quit};
878 my $err = _sync_inbox($self, $sync, $ibx);
879 delete @$ibx{qw(mm over)};
880 warn $err, "\n" if defined($err);
882 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
883 eidxq_process($self, $sync) unless $sync->{quit};
885 eidxq_release($self);
886 PublicInbox::V2Writable::done($self);
889 sub update_last_commit { # overrides V2Writable
890 my ($self, $sync, $stk) = @_;
891 my $unit = $sync->{unit} // return;
892 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
893 defined($latest_cmt) or return;
894 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
895 my $ekey = $ibx->eidx_key;
896 my $uv = $ibx->uidvalidity;
897 my $epoch = $unit->{epoch};
899 my $v = $ibx->version;
901 die 'No {epoch} for v2 unit' unless defined $epoch;
902 $meta_key = "lc-v2:$ekey//$uv;$epoch";
904 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
905 $meta_key = "lc-v1:$ekey//$uv";
907 die "Unsupported inbox version: $v";
909 my $last = $self->{oidx}->eidx_meta($meta_key);
910 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
911 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
912 chomp(my $n = $unit->{git}->qx(@cmd));
913 return if $n ne '' && $n == 0;
915 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
918 sub _idx_init { # with_umask callback
919 my ($self, $opt) = @_;
920 PublicInbox::V2Writable::_idx_init($self, $opt);
921 $self->{midx} = PublicInbox::MiscIdx->new($self);
924 sub idx_init { # similar to V2Writable
925 my ($self, $opt) = @_;
926 return if $self->{idx_shards};
930 my $ALL = $self->git->{git_dir}; # ALL.git
931 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
932 my $info_dir = "$ALL/objects/info";
933 my $alt = "$info_dir/alternates";
935 my (@old, @new, %seen); # seen: st_dev + st_ino
937 open(my $fh, '<', $alt) or die "open $alt: $!";
938 $mode = (stat($fh))[2] & 07777;
939 while (my $line = <$fh>) {
940 chomp(my $d = $line);
941 if (my @st = stat($d)) {
942 next if $seen{"$st[0]\0$st[1]"}++;
944 warn "W: stat($d) failed (from $alt): $!\n";
945 next if $opt->{-idx_gc};
950 for my $ibx (@{$self->{ibx_list}}) {
951 my $line = $ibx->git->{git_dir} . "/objects\n";
952 chomp(my $d = $line);
953 if (my @st = stat($d)) {
954 next if $seen{"$st[0]\0$st[1]"}++;
956 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
957 next if $opt->{-idx_gc};
964 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
966 $self->parallel_init($self->{indexlevel});
967 $self->with_umask(\&_idx_init, $self, $opt);
968 $self->{oidx}->begin_lazy;
969 $self->{oidx}->eidx_prep;
970 $self->{midx}->begin_txn;
974 *done = \&PublicInbox::V2Writable::done;
975 *with_umask = \&PublicInbox::InboxWritable::with_umask;
976 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
977 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
978 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
979 *index_todo = \&PublicInbox::V2Writable::index_todo;
980 *count_shards = \&PublicInbox::V2Writable::count_shards;
981 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
982 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
983 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;