1 # Copyright (C) 2020-2021 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(prepare_stack is_ancestor is_bad_blob);
25 use PublicInbox::OverIdx;
26 use PublicInbox::MiscIdx;
27 use PublicInbox::MID qw(mids);
28 use PublicInbox::V2Writable;
29 use PublicInbox::InboxWritable;
30 use PublicInbox::ContentHash qw(content_hash);
32 use PublicInbox::DS qw(now add_timer);
33 use DBI qw(:sql_types); # SQL_BLOB
36 my (undef, $dir, $opt) = @_;
37 my $l = $opt->{indexlevel} // 'full';
38 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
39 die "invalid indexlevel=$l\n";
40 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
42 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
44 creat => $opt->{creat},
45 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
52 lock_path => "$dir/ei.lock",
54 $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
55 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
56 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
57 $self->{oidx} = $oidx;
62 my ($self, $ibx) = @_;
63 $self->{ibx_map}->{$ibx->eidx_key} //= do {
64 push @{$self->{ibx_list}}, $ibx;
69 sub _ibx_attach { # each_inbox callback
70 my ($ibx, $self) = @_;
71 attach_inbox($self, $ibx);
75 my ($self, $cfg) = @_;
77 $cfg->each_inbox(\&_ibx_attach, $self);
80 sub check_batch_limit ($) {
82 my $self = $req->{self};
83 my $new_smsg = $req->{new_smsg};
84 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
86 # set flag for PublicInbox::V2Writable::index_todo:
87 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
91 my ($req, $smsg) = @_;
92 my $self = $req->{self};
93 my $docid = $smsg->{num};
94 my $idx = $self->idx_shard($docid);
95 my $oid = $req->{oid};
96 my $xibx = $req->{ibx};
97 my $eml = $req->{eml};
98 my $eidx_key = $xibx->eidx_key;
99 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
100 my $xnum = $req->{xnum};
101 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
102 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
103 check_batch_limit($req);
106 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
109 $self->{oidx}->eidxq_del($docid);
110 $idx->ipc_do('xdb_remove', $docid);
111 } elsif ($rm_eidx_info) {
112 $idx->ipc_do('remove_eidx_info',
113 $docid, $eidx_key, $eml);
114 $self->{oidx}->eidxq_add($docid); # yes, add
119 # called by V2Writable::sync_prepare
120 sub artnum_max { $_[0]->{oidx}->eidx_max }
122 sub index_unseen ($) {
124 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
125 my $eml = delete $req->{eml};
126 $new_smsg->populate($eml, $req);
127 my $self = $req->{self};
128 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
129 $new_smsg->{num} = $docid;
130 my $idx = $self->idx_shard($docid);
131 $self->{oidx}->add_overview($eml, $new_smsg);
132 my $oid = $new_smsg->{blob};
133 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
134 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
135 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
136 check_batch_limit($req);
139 sub do_finalize ($) {
141 if (my $indexed = $req->{indexed}) {
142 do_xpost($req, $_) for @$indexed;
143 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
146 # `d' message was already unindexed in the v1/v2 inboxes,
147 # so it's too noisy to warn, here.
149 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
150 if (defined(my $cur_cmt = $req->{cur_cmt})) {
151 ${$req->{latest_cmt}} = $cur_cmt;
155 sub do_step ($) { # main iterator for adding messages to the index
157 my $self = $req->{self} // die 'BUG: {self} missing';
159 if (my $next_arg = $req->{next_arg}) {
160 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
161 $req->{cur_smsg} = $smsg;
162 $self->git->cat_async($smsg->{blob},
163 \&ck_existing, $req);
164 return; # ck_existing calls do_step
166 delete $req->{cur_smsg};
167 delete $req->{next_arg};
169 my $mid = shift(@{$req->{mids}});
170 last unless defined $mid;
172 $req->{next_arg} = [ $mid, \$id, \$prev ];
178 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
180 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
181 my $self = $req->{self};
182 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
183 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
185 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
186 die "BUG: xref $keep[0] has no OID";
188 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
189 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
190 my $saved = $self->{oidx}->get_art($smsg->{num});
192 $self->{oidx}->delete_by_num($smsg->{num});
196 sub ck_existing { # git->cat_async callback
197 my ($bref, $oid, $type, $size, $req) = @_;
198 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
199 if ($type eq 'missing') {
201 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
202 my $self = $req->{self} // die 'BUG: {self} missing';
203 local $self->{current_info} = "$self->{current_info} $oid";
204 my $cur = PublicInbox::Eml->new($bref);
205 if (content_hash($cur) eq $req->{chash}) {
206 push @{$req->{indexed}}, $smsg; # for do_xpost
207 } # else { index_unseen later }
212 # is the messages visible in the inbox currently being indexed?
213 # return the number if so
214 sub cur_ibx_xnum ($$) {
215 my ($req, $bref) = @_;
216 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
218 $req->{eml} = PublicInbox::Eml->new($bref);
219 $req->{chash} = content_hash($req->{eml});
220 $req->{mids} = mids($req->{eml});
221 my @q = @{$req->{mids}}; # copy
222 while (defined(my $mid = shift @q)) {
224 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
225 return $x->{num} if $x->{blob} eq $req->{oid};
231 sub index_oid { # git->cat_async callback for 'm'
232 my ($bref, $oid, $type, $size, $req) = @_;
233 my $self = $req->{self};
234 local $self->{current_info} = "$self->{current_info} $oid";
235 return if is_bad_blob($oid, $type, $size, $req->{oid});
236 my $new_smsg = $req->{new_smsg} = bless {
238 }, 'PublicInbox::Smsg';
239 $new_smsg->set_bytes($$bref, $size);
240 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
245 sub unindex_oid { # git->cat_async callback for 'd'
246 my ($bref, $oid, $type, $size, $req) = @_;
247 my $self = $req->{self};
248 local $self->{current_info} = "$self->{current_info} $oid";
249 return if is_bad_blob($oid, $type, $size, $req->{oid});
250 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
254 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
256 my ($self, $sync) = @_;
258 my $ekey = $sync->{ibx}->eidx_key;
259 my $uv = $sync->{ibx}->uidvalidity;
260 for my $i (0..$sync->{epoch_max}) {
261 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
266 sub _ibx_index_reject ($) {
268 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
269 $ibx->uidvalidity // return 'no UIDVALIDITY';
270 $ibx->over // return 'unindexed, no over.sqlite3';
274 sub _sync_inbox ($$$) {
275 my ($self, $sync, $ibx) = @_;
276 my $ekey = $ibx->eidx_key;
277 if (defined(my $err = _ibx_index_reject($ibx))) {
278 return "W: skipping $ekey ($err)";
281 $sync->{nr} = \(my $nr = 0);
282 my $v = $ibx->version;
284 $sync->{epoch_max} = $ibx->max_git_epoch // return;
285 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
287 my $uv = $ibx->uidvalidity;
288 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
289 my $head = $ibx->mm->last_commit //
290 return "E: $ibx->{inboxdir} is not indexed";
291 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
292 my $unit = { stack => $stk, git => $ibx->git };
293 push @{$sync->{todo}}, $unit;
295 return "E: $ekey unsupported inbox version (v$v)";
297 for my $unit (@{delete($sync->{todo}) // []}) {
298 last if $sync->{quit};
299 index_todo($self, $sync, $unit);
301 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
302 $ibx->git->cleanup; # done with this inbox, now
306 sub gc_unref_doc ($$$$) {
307 my ($self, $ibx_id, $eidx_key, $docid) = @_;
308 my $dbh = $self->{oidx}->dbh;
310 # for debug/info purposes, oids may no longer be accessible
311 my $sth = $dbh->prepare_cached(<<'', undef, 1);
312 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
314 $sth->execute($docid, $ibx_id);
315 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
317 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
318 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
320 my $remain = $self->{oidx}->get_xref3($docid);
321 if (scalar(@$remain)) {
322 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
324 warn "I: unref #$docid $eidx_key $oid\n";
327 warn "I: remove #$docid $eidx_key @oid\n";
328 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
333 my ($self, $opt) = @_;
334 $self->{cfg} or die "E: GC requires ->attach_config\n";
336 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
338 my $dbh = $self->{oidx}->dbh;
339 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
340 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
341 my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
344 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
345 next if $self->{ibx_map}->{$eidx_key};
346 $self->{midx}->remove_eidx_key($eidx_key);
347 warn "I: deleting messages for $eidx_key...\n";
348 $x3_doc->execute($ibx_id);
349 while (defined(my $docid = $x3_doc->fetchrow_array)) {
350 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
352 $dbh->prepare_cached(<<'')->execute($ibx_id);
353 DELETE FROM inboxes WHERE ibx_id = ?
355 # drop last_commit info
357 $pat =~ s/([_%])/\\$1/g;
358 $lc_i->execute("lc-%:$pat//%");
359 while (my ($key) = $lc_i->fetchrow_array) {
360 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
361 warn "I: removing $key\n";
362 $dbh->prepare_cached(<<'')->execute($key);
363 DELETE FROM eidx_meta WHERE key = ?
367 warn "I: $eidx_key removed\n";
370 # it's not real unless it's in `over', we use parallelism here,
371 # shards will be reading directly from over, so commit
372 $self->{oidx}->commit_lazy;
373 $self->{oidx}->begin_lazy;
375 for my $idx (@{$self->{idx_shards}}) {
376 warn "I: cleaning up shard #$idx->{shard}\n";
377 $idx->shard_over_check($self->{oidx});
379 my $nr = $dbh->do(<<'');
380 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
382 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
388 my ($self, $sync, $smsg) = @_;
389 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
390 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
391 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
394 sub _fd_constrained ($) {
396 $self->{-fd_constrained} //= do {
398 if (eval { require BSD::Resource; 1 }) {
399 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
400 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
402 chomp($soft = `sh -c 'ulimit -n'`);
404 if (defined($soft)) {
405 my $want = scalar(@{$self->{ibx_list}}) + 64; # estimate
406 my $ret = $want > $soft;
409 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
414 warn "Unable to determine RLIMIT_NOFILE: $@\n";
420 sub _reindex_finalize ($$$) {
421 my ($req, $smsg, $eml) = @_;
422 my $sync = $req->{sync};
423 my $self = $sync->{self};
424 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
425 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
426 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
427 my $docid = $smsg->{num} = $orig_smsg->{num};
428 $self->{oidx}->add_overview($eml, $smsg); # may rethread
429 check_batch_limit({ %$sync, new_smsg => $smsg });
430 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
431 my $stable = delete($by_chash->{$chash0}) //
432 die "BUG: $smsg->{blob} chash missing";
433 my $idx = $self->idx_shard($docid);
434 my $top_smsg = pop @$stable;
435 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
436 my $ibx = _ibx_for($self, $sync, $smsg);
437 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
438 for my $x (reverse @$stable) {
439 $ibx = _ibx_for($self, $sync, $x);
440 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
441 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
443 return if $nr == 1; # likely, all good
445 warn "W: #$docid split into $nr due to deduplication change\n";
447 for my $ary (values %$by_chash) {
448 for my $x (reverse @$ary) {
449 warn "removing #$docid xref3 $x->{blob}\n";
450 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
451 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
453 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
454 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
455 $ibx = _ibx_for($self, $sync, $x);
456 if (my $over = $ibx->over) {
457 my $e = $over->get_art($x->{num});
458 $e->{blob} eq $x->{blob} or die <<EOF;
459 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
461 push @todo, $ibx, $e;
462 $over->dbh_close if _fd_constrained($self);
464 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
468 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
469 reindex_unseen($self, $sync, $ibx, $e);
473 sub _reindex_oid { # git->cat_async callback
474 my ($bref, $oid, $type, $size, $req) = @_;
475 my $sync = $req->{sync};
476 my $self = $sync->{self};
477 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
478 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
479 my $docid = $orig_smsg->{num};
480 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
481 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
483 warn "W: #$docid gone or corrupted\n";
484 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
485 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
486 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
488 warn "BUG: #$docid gone (UNEXPECTED)\n";
489 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
493 my $ci = $self->{current_info};
494 local $self->{current_info} = "$ci #$docid $oid";
495 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
496 $re_smsg->set_bytes($$bref, $size);
497 my $eml = PublicInbox::Eml->new($bref);
498 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
499 cotime => $orig_smsg->{ts} });
500 my $chash = content_hash($eml);
501 $re_smsg->{chash} = $chash;
502 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
503 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
504 $re_smsg->{hdr} = $eml->header_obj;
505 push @{$req->{by_chash}->{$chash}}, $re_smsg;
506 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
507 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
508 } else { # last $re_smsg is the highest priority xref3
509 local $self->{current_info} = "$ci #$docid";
510 _reindex_finalize($req, $re_smsg, $eml);
514 sub _reindex_smsg ($$$) {
515 my ($self, $sync, $smsg) = @_;
516 my $docid = $smsg->{num};
517 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
518 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
520 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
522 $self->{oidx}->delete_by_num($docid);
523 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
527 # we sort {xr3r} in the reverse order of {ibx_list} so we can
528 # hit the common case in _reindex_finalize without rereading
529 # from git (or holding multiple messages in memory).
530 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
532 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
534 $b->[1] <=> $a->[1] # break ties with {xnum}
536 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
537 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
538 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
541 sub checkpoint_due ($) {
543 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
547 # I've copied FS images and only changed the hostname before,
548 # so prepend hostname. Use `state' since these a BOFH can change
549 # these while this process is running and we always want to be
550 # able to release locks taken by this process.
551 state $retval = hostname . '-' . do {
552 my $m; # machine-id(5) is systemd
553 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
554 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
555 chomp($m ||= `{ sysctl -n kern.hostid ||
556 hostid || ghostid; } 2>/dev/null`
557 || "no-machine-id-or-hostid-on-$^O");
564 my $expect = delete($self->{-eidxq_locked}) or return;
565 my ($owner_pid, undef) = split(/-/, $expect);
566 return if $owner_pid != $$; # shards may fork
567 my $oidx = $self->{oidx};
569 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
570 if ($cur eq $expect) {
571 $oidx->eidx_meta('eidxq_lock', '');
573 } elsif ($cur ne '') {
574 warn "E: eidxq_lock($expect) stolen by $cur\n";
576 warn "E: eidxq_lock($expect) released by another process\n";
583 eidxq_release($self) and $self->{oidx}->commit_lazy;
586 sub _eidxq_take ($) {
588 my $val = "$$-${\time}-$>-".host_ident;
589 $self->{oidx}->eidx_meta('eidxq_lock', $val);
590 $self->{-eidxq_locked} = $val;
593 sub eidxq_lock_acquire ($) {
595 my $oidx = $self->{oidx};
597 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
598 if (my $locked = $self->{-eidxq_locked}) { # be lazy
599 return $locked if $locked eq $cur;
601 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
602 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
603 if ($euid == $> && $ident eq host_ident) {
606 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
610 warn "I: eidxq_lock is stale ($cur), clobbering\n";
611 return _eidxq_take($self);
613 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
615 my $fn = $oidx->dbh->sqlite_db_filename;
617 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
618 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
619 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
624 sub eidxq_process ($$) { # for reindexing
625 my ($self, $sync) = @_;
627 return unless eidxq_lock_acquire($self);
628 my $dbh = $self->{oidx}->dbh;
629 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
631 local $sync->{-regen_fmt} = "%u/$tot\n";
632 my $pr = $sync->{-opt}->{-progress};
634 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
635 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
636 $pr->("Xapian indexing $min..$max (total=$tot)\n");
638 $sync->{id2pos} //= do {
641 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
646 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
647 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
649 while (defined(my $docid = $iter->fetchrow_array)) {
650 last if $sync->{quit};
651 if (my $smsg = $self->{oidx}->get_art($docid)) {
652 _reindex_smsg($self, $sync, $smsg);
654 warn "E: #$docid does not exist in over\n";
656 $del->execute($docid);
659 if (checkpoint_due($sync)) {
660 $dbh = $del = $iter = undef;
661 reindex_checkpoint($self, $sync); # release lock
662 $dbh = $self->{oidx}->dbh;
666 $self->git->async_wait_all;
667 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
670 sub _reindex_unseen { # git->cat_async callback
671 my ($bref, $oid, $type, $size, $req) = @_;
672 return if is_bad_blob($oid, $type, $size, $req->{oid});
673 my $self = $req->{self} // die 'BUG: {self} unset';
674 local $self->{current_info} = "$self->{current_info} $oid";
675 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
676 $new_smsg->set_bytes($$bref, $size);
677 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
678 $req->{new_smsg} = $new_smsg;
679 $req->{chash} = content_hash($eml);
680 $req->{mids} = mids($eml); # do_step iterates through this
681 do_step($req); # enter the normal indexing flow
684 # --reindex may catch totally unseen messages, this handles them
685 sub reindex_unseen ($$$$) {
686 my ($self, $sync, $ibx, $xsmsg) = @_;
689 autime => $xsmsg->{ds},
690 cotime => $xsmsg->{ts},
691 oid => $xsmsg->{blob},
693 xnum => $xsmsg->{num},
694 # {mids} and {chash} will be filled in at _reindex_unseen
696 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
697 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
700 sub _reindex_check_unseen ($$$) {
701 my ($self, $sync, $ibx) = @_;
702 my $ibx_id = $ibx->{-ibx_id};
704 my ($beg, $end) = (1, $slice);
706 # first, check if we missed any messages in target $ibx
708 my $pr = $sync->{-opt}->{-progress};
709 my $ekey = $ibx->eidx_key;
710 local $sync->{-regen_fmt} =
711 "$ekey checking unseen %u/".$ibx->over->max."\n";
714 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
715 ${$sync->{nr}} = $beg;
716 $beg = $msgs->[-1]->{num} + 1;
717 $end = $beg + $slice;
718 if (checkpoint_due($sync)) {
719 reindex_checkpoint($self, $sync); # release lock
722 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
723 SELECT DISTINCT(docid) FROM xref3 WHERE
724 ibx_id = ? AND xnum = ? AND oidbin = ?
726 for my $xsmsg (@$msgs) {
727 my $oidbin = pack('H*', $xsmsg->{blob});
728 $inx3->bind_param(1, $ibx_id);
729 $inx3->bind_param(2, $xsmsg->{num});
730 $inx3->bind_param(3, $oidbin, SQL_BLOB);
732 my $docids = $inx3->fetchall_arrayref;
733 # index messages which were totally missed
734 # the first time around ASAP:
735 if (scalar(@$docids) == 0) {
736 reindex_unseen($self, $sync, $ibx, $xsmsg);
737 } else { # already seen, reindex later
738 for my $r (@$docids) {
739 $self->{oidx}->eidxq_add($r->[0]);
742 last if $sync->{quit};
744 last if $sync->{quit};
748 sub _reindex_check_stale ($$$) {
749 my ($self, $sync, $ibx) = @_;
751 my $pr = $sync->{-opt}->{-progress};
753 my $ekey = $ibx->eidx_key;
754 local $sync->{-regen_fmt} =
755 "$ekey check stale/missing %u/".$ibx->over->max."\n";
758 if (checkpoint_due($sync)) {
759 reindex_checkpoint($self, $sync); # release lock
761 # now, check if there's stale xrefs
762 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
763 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
764 ORDER BY docid,xnum ASC LIMIT 10000
766 $iter->execute($ibx->{-ibx_id}, $min);
769 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
770 return if $sync->{quit};
771 ${$sync->{nr}} = $xnum;
773 $fetching = $min = $docid;
774 my $smsg = $ibx->over->get_art($xnum);
775 my $oidhex = unpack('H*', $oidbin);
779 } elsif ($smsg->{blob} ne $oidhex) {
780 $err = "mismatch (!= $smsg->{blob})";
782 next; # likely, all good
784 # current_info already has eidx_key
785 warn "$xnum:$oidhex (#$docid): $err\n";
786 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
787 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
789 $del->bind_param(1, $ibx->{-ibx_id});
790 $del->bind_param(2, $xnum);
791 $del->bind_param(3, $oidbin, SQL_BLOB);
794 # get_xref3 over-fetches, but this is a rare path:
795 my $xr3 = $self->{oidx}->get_xref3($docid);
796 my $idx = $self->idx_shard($docid);
797 if (scalar(@$xr3) == 0) { # all gone
798 $self->{oidx}->delete_by_num($docid);
799 $self->{oidx}->eidxq_del($docid);
800 $idx->ipc_do('xdb_remove', $docid);
801 } else { # enqueue for reindex of remaining messages
802 $idx->ipc_do('remove_eidx_info',
803 $docid, $ibx->eidx_key);
804 $self->{oidx}->eidxq_add($docid); # yes, add
807 } while (defined $fetching);
810 sub _reindex_inbox ($$$) {
811 my ($self, $sync, $ibx) = @_;
812 my $ekey = $ibx->eidx_key;
813 local $self->{current_info} = $ekey;
814 if (defined(my $err = _ibx_index_reject($ibx))) {
815 warn "W: cannot reindex $ekey ($err)\n";
817 _reindex_check_unseen($self, $sync, $ibx);
818 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
820 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
824 my ($self, $sync) = @_;
826 # acquire eidxq_lock early because full reindex takes forever
827 # and incremental -extindex processes can run during our checkpoints
828 if (!eidxq_lock_acquire($self)) {
829 warn "E: aborting --reindex\n";
832 for my $ibx (@{$self->{ibx_list}}) {
833 _reindex_inbox($self, $sync, $ibx);
834 last if $sync->{quit};
836 $self->git->async_wait_all; # ensure eidxq gets filled completely
837 eidxq_process($self, $sync) unless $sync->{quit};
841 my ($self, $sync, $ibx) = @_;
842 my $err = _sync_inbox($self, $sync, $ibx);
843 delete @$ibx{qw(mm over)};
844 warn $err, "\n" if defined($err);
847 sub eidx_sync { # main entry point
848 my ($self, $opt) = @_;
850 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
851 local $self->{current_info} = '';
852 local $SIG{__WARN__} = sub {
853 $warn_cb->($self->{current_info}, ': ', @_);
855 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
856 $self->{oidx}->rethread_prepare($opt);
858 need_checkpoint => \(my $need_checkpoint = 0),
860 next_check => now() + 10,
862 # DO NOT SET {reindex} here, it's incompatible with reused
863 # V2Writable code, reindex is totally different here
864 # compared to v1/v2 inboxes because we have multiple histories
866 -regen_fmt => "%u/?\n",
868 local $SIG{USR1} = sub { $need_checkpoint = 1 };
869 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
870 local $SIG{QUIT} = $quit;
871 local $SIG{INT} = $quit;
872 local $SIG{TERM} = $quit;
873 for my $ibx (@{$self->{ibx_list}}) {
874 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
876 if (delete($opt->{reindex})) {
877 local $sync->{checkpoint_unlocks} = 1;
878 eidx_reindex($self, $sync);
881 # don't use $_ here, it'll get clobbered by reindex_checkpoint
882 if ($opt->{scan} // 1) {
883 for my $ibx (@{$self->{ibx_list}}) {
884 last if $sync->{quit};
885 sync_inbox($self, $sync, $ibx);
888 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
889 eidxq_process($self, $sync) unless $sync->{quit};
891 eidxq_release($self);
893 $sync; # for eidx_watch
896 sub update_last_commit { # overrides V2Writable
897 my ($self, $sync, $stk) = @_;
898 my $unit = $sync->{unit} // return;
899 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
900 defined($latest_cmt) or return;
901 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
902 my $ekey = $ibx->eidx_key;
903 my $uv = $ibx->uidvalidity;
904 my $epoch = $unit->{epoch};
906 my $v = $ibx->version;
908 die 'No {epoch} for v2 unit' unless defined $epoch;
909 $meta_key = "lc-v2:$ekey//$uv;$epoch";
911 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
912 $meta_key = "lc-v1:$ekey//$uv";
914 die "Unsupported inbox version: $v";
916 my $last = $self->{oidx}->eidx_meta($meta_key);
917 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
918 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
919 chomp(my $n = $unit->{git}->qx(@cmd));
920 return if $n ne '' && $n == 0;
922 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
925 sub _idx_init { # with_umask callback
926 my ($self, $opt) = @_;
927 PublicInbox::V2Writable::_idx_init($self, $opt);
928 $self->{midx} = PublicInbox::MiscIdx->new($self);
931 sub idx_init { # similar to V2Writable
932 my ($self, $opt) = @_;
933 return if $self->{idx_shards};
937 my $ALL = $self->git->{git_dir}; # ALL.git
939 if ($opt->{-private}) { # LeiStore
942 umask 077; # don't bother restoring
943 PublicInbox::Import::init_bare($ALL);
944 $self->git->qx(qw(config core.sharedRepository 0600));
947 PublicInbox::Import::init_bare($ALL) unless $old;
949 my $info_dir = "$ALL/objects/info";
950 my $alt = "$info_dir/alternates";
951 my (@old, @new, %seen); # seen: st_dev + st_ino
953 open(my $fh, '<', $alt) or die "open $alt: $!";
954 $mode = (stat($fh))[2] & 07777;
955 while (my $line = <$fh>) {
956 chomp(my $d = $line);
958 # expand relative path (/local/ stuff)
959 substr($d, 0, 3) eq '../' and
960 $d = "$ALL/objects/$d";
961 if (my @st = stat($d)) {
962 next if $seen{"$st[0]\0$st[1]"}++;
964 warn "W: stat($d) failed (from $alt): $!\n";
965 next if $opt->{-idx_gc};
971 # for LeiStore, and possibly some mirror-only state
972 if (opendir(my $dh, my $local = "$self->{topdir}/local")) {
973 # highest numbered epoch first
974 for my $n (sort { $b <=> $a } map { substr($_, 0, -4) + 0 }
975 grep(/\A[0-9]+\.git\z/, readdir($dh))) {
976 my $d = "$local/$n.git/objects"; # absolute path
977 if (my @st = stat($d)) {
978 next if $seen{"$st[0]\0$st[1]"}++;
979 # favor relative paths for rename-friendliness
980 push @new, "../../local/$n.git/objects\n";
982 warn "W: stat($d) failed: $!\n";
986 for my $ibx (@{$self->{ibx_list}}) {
987 my $line = $ibx->git->{git_dir} . "/objects\n";
988 chomp(my $d = $line);
989 if (my @st = stat($d)) {
990 next if $seen{"$st[0]\0$st[1]"}++;
992 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
993 next if $opt->{-idx_gc};
1000 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
1002 $self->parallel_init($self->{indexlevel});
1003 $self->with_umask(\&_idx_init, $self, $opt);
1004 $self->{oidx}->begin_lazy;
1005 $self->{oidx}->eidx_prep;
1006 $self->{midx}->create_xdb if @new;
1009 sub _watch_commit { # PublicInbox::DS::add_timer callback
1011 delete $self->{-commit_timer};
1012 eidxq_process($self, $self->{-watch_sync});
1013 eidxq_release($self);
1014 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1015 reindex_checkpoint($self, $self->{-watch_sync});
1016 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1018 # call event_step => done unless commit_timer is armed
1019 PublicInbox::DS::requeue($self);
1022 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1023 my ($self, $ibx) = @_;
1024 my $opt = $self->{-watch_sync}->{-opt};
1025 my $pr = $opt->{-progress};
1026 my $ekey = $ibx->eidx_key;
1027 local $0 = "sync $ekey";
1028 $pr->("indexing $ekey\n") if $pr;
1029 $self->idx_init($opt);
1030 sync_inbox($self, $self->{-watch_sync}, $ibx);
1031 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1032 \&_watch_commit, $self);
1035 sub eidx_reload { # -extindex --watch SIGHUP handler
1036 my ($self, $idler) = @_;
1038 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1039 $pr->('reloading ...') if $pr;
1040 delete $self->{-resync_queue};
1041 @{$self->{ibx_list}} = ();
1042 %{$self->{ibx_map}} = ();
1043 delete $self->{-watch_sync}->{id2pos};
1044 my $cfg = PublicInbox::Config->new;
1045 attach_config($self, $cfg);
1046 $idler->refresh($cfg);
1047 $pr->(" done\n") if $pr;
1049 warn "reload not supported without --all\n";
1053 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1055 $self->{-resync_queue} //= [ @{$self->{ibx_list}} ];
1056 PublicInbox::DS::requeue($self); # trigger our ->event_step
1059 sub event_step { # PublicInbox::DS::requeue callback
1061 if (my $resync_queue = $self->{-resync_queue}) {
1062 if (my $ibx = shift(@$resync_queue)) {
1063 on_inbox_unlock($self, $ibx);
1064 PublicInbox::DS::requeue($self);
1066 delete $self->{-resync_queue};
1067 _watch_commit($self);
1070 done($self) unless $self->{-commit_timer};
1074 sub eidx_watch { # public-inbox-extindex --watch main loop
1075 my ($self, $opt) = @_;
1077 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1078 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1080 require PublicInbox::InboxIdle;
1081 require PublicInbox::DS;
1082 require PublicInbox::Syscall;
1083 require PublicInbox::Sigfd;
1084 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1085 if (!$self->{cfg}) {
1086 $idler->watch_inbox($_) for @{$self->{ibx_list}};
1088 $_->subscribe_unlock(__PACKAGE__, $self) for @{$self->{ibx_list}};
1089 my $pr = $opt->{-progress};
1090 $pr->("performing initial scan ...\n") if $pr;
1091 my $sync = eidx_sync($self, $opt); # initial sync
1092 return if $sync->{quit};
1093 my $oldset = PublicInbox::DS::block_signals();
1094 local $self->{current_info} = '';
1095 my $cb = $SIG{__WARN__} || \&CORE::warn;
1096 local $SIG{__WARN__} = sub { $cb->($self->{current_info}, ': ', @_) };
1098 HUP => sub { eidx_reload($self, $idler) },
1099 USR1 => sub { eidx_resync_start($self) },
1100 TSTP => sub { kill('STOP', $$) },
1102 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1103 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1104 my $sigfd = PublicInbox::Sigfd->new($sig,
1105 $PublicInbox::Syscall::SFD_NONBLOCK);
1106 %SIG = (%SIG, %$sig) if !$sigfd;
1107 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1109 # wake up every second to accept signals if we don't
1110 # have signalfd or IO::KQueue:
1111 PublicInbox::DS::sig_setmask($oldset);
1112 PublicInbox::DS->SetLoopTimeout(1000);
1114 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1115 $pr->("initial scan complete, entering event loop\n") if $pr;
1116 PublicInbox::DS->EventLoop; # calls InboxIdle->event_step
1121 *done = \&PublicInbox::V2Writable::done;
1122 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1123 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1124 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1125 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1126 *index_todo = \&PublicInbox::V2Writable::index_todo;
1127 *count_shards = \&PublicInbox::V2Writable::count_shards;
1128 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1129 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1130 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1131 *checkpoint = \&PublicInbox::V2Writable::checkpoint;