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 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{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 local $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 local $sync->{-regen_fmt} =
713 "$ekey checking unseen %u/".$ibx->over->max."\n";
716 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
717 ${$sync->{nr}} = $beg;
718 $beg = $msgs->[-1]->{num} + 1;
719 $end = $beg + $slice;
720 if (checkpoint_due($sync)) {
721 reindex_checkpoint($self, $sync); # release lock
724 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
725 SELECT DISTINCT(docid) FROM xref3 WHERE
726 ibx_id = ? AND xnum = ? AND oidbin = ?
728 for my $xsmsg (@$msgs) {
729 my $oidbin = pack('H*', $xsmsg->{blob});
730 $inx3->bind_param(1, $ibx_id);
731 $inx3->bind_param(2, $xsmsg->{num});
732 $inx3->bind_param(3, $oidbin, SQL_BLOB);
734 my $docids = $inx3->fetchall_arrayref;
735 # index messages which were totally missed
736 # the first time around ASAP:
737 if (scalar(@$docids) == 0) {
738 reindex_unseen($self, $sync, $ibx, $xsmsg);
739 } else { # already seen, reindex later
740 for my $r (@$docids) {
741 $self->{oidx}->eidxq_add($r->[0]);
744 last if $sync->{quit};
746 last if $sync->{quit};
750 sub _reindex_check_stale ($$$) {
751 my ($self, $sync, $ibx) = @_;
753 my $pr = $sync->{-opt}->{-progress};
755 my $ekey = $ibx->eidx_key;
756 local $sync->{-regen_fmt} =
757 "$ekey check stale/missing %u/".$ibx->over->max."\n";
760 if (checkpoint_due($sync)) {
761 reindex_checkpoint($self, $sync); # release lock
763 # now, check if there's stale xrefs
764 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
765 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
766 ORDER BY docid,xnum ASC LIMIT 10000
768 $iter->execute($ibx->{-ibx_id}, $min);
771 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
772 return if $sync->{quit};
773 ${$sync->{nr}} = $xnum;
775 $fetching = $min = $docid;
776 my $smsg = $ibx->over->get_art($xnum);
777 my $oidhex = unpack('H*', $oidbin);
781 } elsif ($smsg->{blob} ne $oidhex) {
782 $err = "mismatch (!= $smsg->{blob})";
784 next; # likely, all good
786 # current_info already has eidx_key
787 warn "$xnum:$oidhex (#$docid): $err\n";
788 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
789 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
791 $del->bind_param(1, $ibx->{-ibx_id});
792 $del->bind_param(2, $xnum);
793 $del->bind_param(3, $oidbin, SQL_BLOB);
796 # get_xref3 over-fetches, but this is a rare path:
797 my $xr3 = $self->{oidx}->get_xref3($docid);
798 my $idx = $self->idx_shard($docid);
799 if (scalar(@$xr3) == 0) { # all gone
800 $self->{oidx}->delete_by_num($docid);
801 $self->{oidx}->eidxq_del($docid);
802 $idx->shard_remove($docid);
803 } else { # enqueue for reindex of remaining messages
804 $idx->shard_remove_eidx_info($docid,
806 $self->{oidx}->eidxq_add($docid); # yes, add
809 } while (defined $fetching);
812 sub _reindex_inbox ($$$) {
813 my ($self, $sync, $ibx) = @_;
814 my $ekey = $ibx->eidx_key;
815 local $self->{current_info} = $ekey;
816 if (defined(my $err = _ibx_index_reject($ibx))) {
817 warn "W: cannot reindex $ekey ($err)\n";
819 _reindex_check_unseen($self, $sync, $ibx);
820 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
822 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
826 my ($self, $sync) = @_;
828 # acquire eidxq_lock early because full reindex takes forever
829 # and incremental -extindex processes can run during our checkpoints
830 if (!eidxq_lock_acquire($self)) {
831 warn "E: aborting --reindex\n";
834 for my $ibx (@{$self->{ibx_list}}) {
835 _reindex_inbox($self, $sync, $ibx);
836 last if $sync->{quit};
838 $self->git->async_wait_all; # ensure eidxq gets filled completely
839 eidxq_process($self, $sync) unless $sync->{quit};
843 my ($self, $sync, $ibx) = @_;
844 my $err = _sync_inbox($self, $sync, $ibx);
845 delete @$ibx{qw(mm over)};
846 warn $err, "\n" if defined($err);
849 sub eidx_sync { # main entry point
850 my ($self, $opt) = @_;
852 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
853 local $self->{current_info} = '';
854 local $SIG{__WARN__} = sub {
855 $warn_cb->($self->{current_info}, ': ', @_);
857 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
858 $self->{oidx}->rethread_prepare($opt);
860 need_checkpoint => \(my $need_checkpoint = 0),
862 next_check => now() + 10,
864 # DO NOT SET {reindex} here, it's incompatible with reused
865 # V2Writable code, reindex is totally different here
866 # compared to v1/v2 inboxes because we have multiple histories
868 -regen_fmt => "%u/?\n",
870 local $SIG{USR1} = sub { $need_checkpoint = 1 };
871 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
872 local $SIG{QUIT} = $quit;
873 local $SIG{INT} = $quit;
874 local $SIG{TERM} = $quit;
875 for my $ibx (@{$self->{ibx_list}}) {
876 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
878 if (delete($opt->{reindex})) {
879 local $sync->{checkpoint_unlocks} = 1;
880 eidx_reindex($self, $sync);
883 # don't use $_ here, it'll get clobbered by reindex_checkpoint
884 if ($opt->{scan} // 1) {
885 for my $ibx (@{$self->{ibx_list}}) {
886 last if $sync->{quit};
887 sync_inbox($self, $sync, $ibx);
890 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
891 eidxq_process($self, $sync) unless $sync->{quit};
893 eidxq_release($self);
895 $sync; # for eidx_watch
898 sub update_last_commit { # overrides V2Writable
899 my ($self, $sync, $stk) = @_;
900 my $unit = $sync->{unit} // return;
901 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
902 defined($latest_cmt) or return;
903 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
904 my $ekey = $ibx->eidx_key;
905 my $uv = $ibx->uidvalidity;
906 my $epoch = $unit->{epoch};
908 my $v = $ibx->version;
910 die 'No {epoch} for v2 unit' unless defined $epoch;
911 $meta_key = "lc-v2:$ekey//$uv;$epoch";
913 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
914 $meta_key = "lc-v1:$ekey//$uv";
916 die "Unsupported inbox version: $v";
918 my $last = $self->{oidx}->eidx_meta($meta_key);
919 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
920 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
921 chomp(my $n = $unit->{git}->qx(@cmd));
922 return if $n ne '' && $n == 0;
924 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
927 sub _idx_init { # with_umask callback
928 my ($self, $opt) = @_;
929 PublicInbox::V2Writable::_idx_init($self, $opt);
930 $self->{midx} = PublicInbox::MiscIdx->new($self);
933 sub idx_init { # similar to V2Writable
934 my ($self, $opt) = @_;
935 return if $self->{idx_shards};
939 my $ALL = $self->git->{git_dir}; # ALL.git
941 if ($opt->{-private}) { # LeiStore
944 umask 077; # don't bother restoring
945 PublicInbox::Import::init_bare($ALL);
946 $self->git->qx(qw(config core.sharedRepository 0600));
949 PublicInbox::Import::init_bare($ALL) unless $old;
951 my $info_dir = "$ALL/objects/info";
952 my $alt = "$info_dir/alternates";
953 my (@old, @new, %seen); # seen: st_dev + st_ino
955 open(my $fh, '<', $alt) or die "open $alt: $!";
956 $mode = (stat($fh))[2] & 07777;
957 while (my $line = <$fh>) {
958 chomp(my $d = $line);
960 # expand relative path (/local/ stuff)
961 substr($d, 0, 3) eq '../' and
962 $d = "$ALL/objects/$d";
963 if (my @st = stat($d)) {
964 next if $seen{"$st[0]\0$st[1]"}++;
966 warn "W: stat($d) failed (from $alt): $!\n";
967 next if $opt->{-idx_gc};
973 # for LeiStore, and possibly some mirror-only state
974 if (opendir(my $dh, my $local = "$self->{topdir}/local")) {
975 # highest numbered epoch first
976 for my $n (sort { $b <=> $a } map { substr($_, 0, -4) + 0 }
977 grep(/\A[0-9]+\.git\z/, readdir($dh))) {
978 my $d = "$local/$n.git/objects"; # absolute path
979 if (my @st = stat($d)) {
980 next if $seen{"$st[0]\0$st[1]"}++;
981 # favor relative paths for rename-friendliness
982 push @new, "../../local/$n.git/objects\n";
984 warn "W: stat($d) failed: $!\n";
988 for my $ibx (@{$self->{ibx_list}}) {
989 my $line = $ibx->git->{git_dir} . "/objects\n";
990 chomp(my $d = $line);
991 if (my @st = stat($d)) {
992 next if $seen{"$st[0]\0$st[1]"}++;
994 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
995 next if $opt->{-idx_gc};
1002 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
1004 $self->parallel_init($self->{indexlevel});
1005 $self->with_umask(\&_idx_init, $self, $opt);
1006 $self->{oidx}->begin_lazy;
1007 $self->{oidx}->eidx_prep;
1008 $self->{midx}->begin_txn;
1011 sub _watch_commit { # PublicInbox::DS::add_timer callback
1013 delete $self->{-commit_timer};
1014 eidxq_process($self, $self->{-watch_sync});
1015 eidxq_release($self);
1016 delete local $self->{-watch_sync}->{-regen_fmt};
1017 reindex_checkpoint($self, $self->{-watch_sync});
1019 # call event_step => done unless commit_timer is armed
1020 PublicInbox::DS::requeue($self);
1023 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1024 my ($self, $ibx) = @_;
1025 my $opt = $self->{-watch_sync}->{-opt};
1026 my $pr = $opt->{-progress};
1027 my $ekey = $ibx->eidx_key;
1028 local $0 = "sync $ekey";
1029 $pr->("indexing $ekey\n") if $pr;
1030 $self->idx_init($opt);
1031 sync_inbox($self, $self->{-watch_sync}, $ibx);
1032 $self->{-commit_timer} //= PublicInbox::DS::add_timer(
1033 $opt->{'commit-interval'} // 10,
1034 \&_watch_commit, $self);
1037 sub eidx_reload { # -extindex --watch SIGHUP handler
1038 my ($self, $idler) = @_;
1040 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1041 $pr->('reloading ...') if $pr;
1042 delete $self->{-resync_queue};
1043 @{$self->{ibx_list}} = ();
1044 %{$self->{ibx_map}} = ();
1045 delete $self->{-watch_sync}->{id2pos};
1046 my $cfg = PublicInbox::Config->new;
1047 attach_config($self, $cfg);
1048 $idler->refresh($cfg);
1049 $pr->(" done\n") if $pr;
1051 warn "reload not supported without --all\n";
1055 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1057 $self->{-resync_queue} //= [ @{$self->{ibx_list}} ];
1058 PublicInbox::DS::requeue($self); # trigger our ->event_step
1061 sub event_step { # PublicInbox::DS::requeue callback
1063 if (my $resync_queue = $self->{-resync_queue}) {
1064 if (my $ibx = shift(@$resync_queue)) {
1065 on_inbox_unlock($self, $ibx);
1066 PublicInbox::DS::requeue($self);
1068 delete $self->{-resync_queue};
1069 _watch_commit($self);
1072 done($self) unless $self->{-commit_timer};
1076 sub eidx_watch { # public-inbox-extindex --watch main loop
1077 my ($self, $opt) = @_;
1079 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1080 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1082 require PublicInbox::InboxIdle;
1083 require PublicInbox::DS;
1084 require PublicInbox::Syscall;
1085 require PublicInbox::Sigfd;
1086 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1087 if (!$self->{cfg}) {
1088 $idler->watch_inbox($_) for @{$self->{ibx_list}};
1090 $_->subscribe_unlock(__PACKAGE__, $self) for @{$self->{ibx_list}};
1091 my $pr = $opt->{-progress};
1092 $pr->("performing initial scan ...\n") if $pr;
1093 my $sync = eidx_sync($self, $opt); # initial sync
1094 return if $sync->{quit};
1095 my $oldset = PublicInbox::Sigfd::block_signals();
1096 local $self->{current_info} = '';
1097 my $cb = $SIG{__WARN__} || \&CORE::warn;
1098 local $SIG{__WARN__} = sub { $cb->($self->{current_info}, ': ', @_) };
1100 HUP => sub { eidx_reload($self, $idler) },
1101 USR1 => sub { eidx_resync_start($self) },
1102 TSTP => sub { kill('STOP', $$) },
1104 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1105 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1106 my $sigfd = PublicInbox::Sigfd->new($sig,
1107 $PublicInbox::Syscall::SFD_NONBLOCK);
1108 %SIG = (%SIG, %$sig) if !$sigfd;
1109 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1111 # wake up every second to accept signals if we don't
1112 # have signalfd or IO::KQueue:
1113 PublicInbox::Sigfd::sig_setmask($oldset);
1114 PublicInbox::DS->SetLoopTimeout(1000);
1116 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1117 $pr->("initial scan complete, entering event loop\n") if $pr;
1118 PublicInbox::DS->EventLoop; # calls InboxIdle->event_step
1123 *done = \&PublicInbox::V2Writable::done;
1124 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1125 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1126 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1127 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1128 *index_todo = \&PublicInbox::V2Writable::index_todo;
1129 *count_shards = \&PublicInbox::V2Writable::count_shards;
1130 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1131 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1132 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;