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 File::Glob qw(bsd_glob GLOB_NOSORT);
24 use PublicInbox::MultiGit;
25 use PublicInbox::Search;
26 use PublicInbox::SearchIdx qw(prepare_stack is_ancestor is_bad_blob);
27 use PublicInbox::OverIdx;
28 use PublicInbox::MiscIdx;
29 use PublicInbox::MID qw(mids);
30 use PublicInbox::V2Writable;
31 use PublicInbox::InboxWritable;
32 use PublicInbox::ContentHash qw(content_hash);
34 use PublicInbox::DS qw(now add_timer);
35 use DBI qw(:sql_types); # SQL_BLOB
38 my (undef, $dir, $opt) = @_;
39 my $l = $opt->{indexlevel} // 'full';
40 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
41 die "invalid indexlevel=$l\n";
42 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
44 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
46 creat => $opt->{creat},
47 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
48 ibx_active => [], # by config section order
49 ibx_known => [], # by config section order
55 lock_path => "$dir/ei.lock",
57 $self->{shards} = $self->count_shards ||
58 nproc_shards({ nproc => $opt->{jobs} });
59 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
60 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
61 $self->{oidx} = $oidx;
66 my ($self, $ibx, $types) = @_;
67 $self->{ibx_map}->{$ibx->eidx_key} //= do {
68 delete $self->{-ibx_ary_known}; # invalidate cache
69 delete $self->{-ibx_ary_active}; # invalidate cache
70 $types //= [ qw(active known) ];
72 push @{$self->{"ibx_$t"}}, $ibx;
78 sub _ibx_attach { # each_inbox callback
79 my ($ibx, $self, $types) = @_;
80 attach_inbox($self, $ibx, $types);
84 my ($self, $cfg, $ibxs) = @_;
88 for my $ibx (@$ibxs) {
89 $self->{ibx_map}->{$ibx->eidx_key} //= do {
90 push @{$self->{ibx_active}}, $ibx;
91 push @{$self->{ibx_known}}, $ibx;
96 delete $self->{-ibx_ary_known};
97 delete $self->{-ibx_ary_active};
100 $types //= [ qw(known active) ];
101 $cfg->each_inbox(\&_ibx_attach, $self, $types);
104 sub check_batch_limit ($) {
106 my $self = $req->{self};
107 my $new_smsg = $req->{new_smsg};
108 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
110 # set flag for PublicInbox::V2Writable::index_todo:
111 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
114 sub apply_boost ($$) {
115 my ($req, $smsg) = @_;
116 my $id2pos = $req->{id2pos}; # index in ibx_sorted
117 my $xr3 = $req->{self}->{oidx}->get_xref3($smsg->{num}, 1);
119 $id2pos->{$a->[0]} <=> $id2pos->{$b->[0]}
121 $a->[1] <=> $b->[1] # break ties with {xnum}
123 my $top_blob = unpack('H*', $xr3->[0]->[2]);
124 my $new_smsg = $req->{new_smsg};
125 return if $top_blob ne $new_smsg->{blob}; # loser
127 # replace the old smsg with the more boosted one
128 $new_smsg->{num} = $smsg->{num};
129 $new_smsg->populate($req->{eml}, $req);
130 $req->{self}->{oidx}->add_overview($req->{eml}, $new_smsg);
134 my ($req, $smsg) = @_;
135 my $self = $req->{self};
136 my $docid = $smsg->{num};
137 my $idx = $self->idx_shard($docid);
138 my $oid = $req->{oid};
139 my $xibx = $req->{ibx};
140 my $eml = $req->{eml};
141 my $eidx_key = $xibx->eidx_key;
142 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
143 my $xnum = $req->{xnum};
144 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
145 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
146 apply_boost($req, $smsg) if $req->{boost_in_use};
149 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
152 $self->{oidx}->eidxq_del($docid);
153 $idx->ipc_do('xdb_remove', $docid);
154 } elsif ($rm_eidx_info) {
155 $idx->ipc_do('remove_eidx_info',
156 $docid, $eidx_key, $eml);
157 $self->{oidx}->eidxq_add($docid); # yes, add
162 # called by V2Writable::sync_prepare
163 sub artnum_max { $_[0]->{oidx}->eidx_max }
165 sub index_unseen ($) {
167 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
168 my $eml = delete $req->{eml};
169 $new_smsg->populate($eml, $req);
170 my $self = $req->{self};
171 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
172 $new_smsg->{num} = $docid;
173 my $idx = $self->idx_shard($docid);
174 $self->{oidx}->add_overview($eml, $new_smsg);
175 my $oid = $new_smsg->{blob};
176 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
177 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
178 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
179 check_batch_limit($req);
182 sub do_finalize ($) {
184 if (my $indexed = $req->{indexed}) { # duplicated messages
185 do_xpost($req, $_) for @$indexed;
186 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
189 # `d' message was already unindexed in the v1/v2 inboxes,
190 # so it's too noisy to warn, here.
192 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
193 if (defined(my $cur_cmt = $req->{cur_cmt})) {
194 ${$req->{latest_cmt}} = $cur_cmt;
198 sub do_step ($) { # main iterator for adding messages to the index
200 my $self = $req->{self} // die 'BUG: {self} missing';
202 if (my $next_arg = $req->{next_arg}) {
203 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
204 $req->{cur_smsg} = $smsg;
205 $self->git->cat_async($smsg->{blob},
206 \&ck_existing, $req);
207 return; # ck_existing calls do_step
209 delete $req->{next_arg};
211 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
212 my $mid = shift(@{$req->{mids}}) // last;
214 $req->{next_arg} = [ $mid, \$id, \$prev ];
220 sub _blob_missing ($$) { # called when $smsg->{blob} is bad
221 my ($req, $smsg) = @_;
222 my $self = $req->{self};
223 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
224 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
226 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
227 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
228 die "BUG: xref $keep[0] has no OID";
230 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
231 $self->{oidx}->update_blob($smsg, $oidhex) or warn <<EOM;
232 E: #$smsg->{num} gone ($smsg->{blob} => $oidhex)
235 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
236 $self->{oidx}->delete_by_num($smsg->{num});
240 sub ck_existing { # git->cat_async callback
241 my ($bref, $oid, $type, $size, $req) = @_;
242 my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
243 if ($type eq 'missing') {
244 _blob_missing($req, $smsg);
245 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
246 my $self = $req->{self} // die 'BUG: {self} missing';
247 local $self->{current_info} = "$self->{current_info} $oid";
248 my $cur = PublicInbox::Eml->new($bref);
249 if (content_hash($cur) eq $req->{chash}) {
250 push @{$req->{indexed}}, $smsg; # for do_xpost
251 } # else { index_unseen later }
256 # is the messages visible in the inbox currently being indexed?
257 # return the number if so
258 sub cur_ibx_xnum ($$) {
259 my ($req, $bref) = @_;
260 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
262 $req->{eml} = PublicInbox::Eml->new($bref);
263 $req->{chash} = content_hash($req->{eml});
264 $req->{mids} = mids($req->{eml});
265 for my $mid (@{$req->{mids}}) {
267 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
268 return $x->{num} if $x->{blob} eq $req->{oid};
274 sub index_oid { # git->cat_async callback for 'm'
275 my ($bref, $oid, $type, $size, $req) = @_;
276 my $self = $req->{self};
277 local $self->{current_info} = "$self->{current_info} $oid";
278 return if is_bad_blob($oid, $type, $size, $req->{oid});
279 my $new_smsg = $req->{new_smsg} = bless {
281 }, 'PublicInbox::Smsg';
282 $new_smsg->set_bytes($$bref, $size);
283 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
288 sub unindex_oid { # git->cat_async callback for 'd'
289 my ($bref, $oid, $type, $size, $req) = @_;
290 my $self = $req->{self};
291 local $self->{current_info} = "$self->{current_info} $oid";
292 return if is_bad_blob($oid, $type, $size, $req->{oid});
293 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
297 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
299 my ($self, $sync) = @_;
301 my $ekey = $sync->{ibx}->eidx_key;
302 my $uv = $sync->{ibx}->uidvalidity;
303 for my $i (0..$sync->{epoch_max}) {
304 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
309 sub _ibx_index_reject ($) {
311 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
312 $ibx->uidvalidity // return 'no UIDVALIDITY';
313 $ibx->over // return 'unindexed, no over.sqlite3';
317 sub _sync_inbox ($$$) {
318 my ($self, $sync, $ibx) = @_;
319 my $ekey = $ibx->eidx_key;
320 if (defined(my $err = _ibx_index_reject($ibx))) {
321 return "W: skipping $ekey ($err)";
324 $sync->{nr} = \(my $nr = 0);
325 my $v = $ibx->version;
327 $sync->{epoch_max} = $ibx->max_git_epoch // return;
328 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
330 my $uv = $ibx->uidvalidity;
331 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
332 my $head = $ibx->mm->last_commit //
333 return "E: $ibx->{inboxdir} is not indexed";
334 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
335 my $unit = { stack => $stk, git => $ibx->git };
336 push @{$sync->{todo}}, $unit;
338 return "E: $ekey unsupported inbox version (v$v)";
340 for my $unit (@{delete($sync->{todo}) // []}) {
341 last if $sync->{quit};
342 index_todo($self, $sync, $unit);
344 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
345 $ibx->git->cleanup; # done with this inbox, now
349 sub gc_unref_doc ($$$$) {
350 my ($self, $ibx_id, $eidx_key, $docid) = @_;
352 # for debug/info purposes, oids may no longer be accessible
353 my $dbh = $self->{oidx}->dbh;
354 my $sth = $dbh->prepare_cached(<<'', undef, 1);
355 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
357 $sth->execute($docid, $ibx_id);
358 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
360 $remain += $self->{oidx}->remove_xref3($docid, $oid, $eidx_key);
363 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
365 warn "I: unref #$docid $eidx_key $oid\n";
368 warn "I: remove #$docid $eidx_key @oid\n";
369 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
374 my ($self, $opt) = @_;
375 $self->{cfg} or die "E: GC requires ->attach_config\n";
377 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
379 my $dbh = $self->{oidx}->dbh;
380 $dbh->do('PRAGMA case_sensitive_like = ON'); # only place we use LIKE
381 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
382 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
383 my $lc_i = $dbh->prepare(<<'');
384 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
387 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
388 next if $self->{ibx_map}->{$eidx_key};
389 $self->{midx}->remove_eidx_key($eidx_key);
390 warn "I: deleting messages for $eidx_key...\n";
391 $x3_doc->execute($ibx_id);
392 while (defined(my $docid = $x3_doc->fetchrow_array)) {
393 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
395 $dbh->prepare_cached(<<'')->execute($ibx_id);
396 DELETE FROM inboxes WHERE ibx_id = ?
398 # drop last_commit info
400 $pat =~ s/([_%\\])/\\$1/g;
401 $lc_i->execute("lc-%:$pat//%", '\\');
402 while (my ($key) = $lc_i->fetchrow_array) {
403 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
404 warn "I: removing $key\n";
405 $dbh->prepare_cached(<<'')->execute($key);
406 DELETE FROM eidx_meta WHERE key = ?
410 warn "I: $eidx_key removed\n";
413 # it's not real unless it's in `over', we use parallelism here,
414 # shards will be reading directly from over, so commit
415 $self->{oidx}->commit_lazy;
416 $self->{oidx}->begin_lazy;
418 for my $idx (@{$self->{idx_shards}}) {
419 warn "I: cleaning up shard #$idx->{shard}\n";
420 $idx->shard_over_check($self->{oidx});
422 my $nr = $dbh->do(<<'');
423 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
425 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
427 # fixup from old bugs:
428 $nr = $dbh->do(<<'');
429 DELETE FROM over WHERE num NOT IN (SELECT docid FROM xref3)
431 warn "I: eliminated $nr stale over entries\n" if $nr != 0;
436 my ($self, $sync, $smsg) = @_;
437 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
438 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
439 $self->{-ibx_ary_known}->[$pos] //
440 die "BUG: ibx for $smsg->{blob} not mapped"
443 sub _fd_constrained ($) {
445 $self->{-fd_constrained} //= do {
447 if (eval { require BSD::Resource; 1 }) {
448 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
449 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
451 chomp($soft = `sh -c 'ulimit -n'`);
453 if (defined($soft)) {
454 # $want is an estimate
455 my $want = scalar(@{$self->{ibx_active}}) + 64;
456 my $ret = $want > $soft;
459 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
464 warn "Unable to determine RLIMIT_NOFILE: $@\n";
470 sub _reindex_finalize ($$$) {
471 my ($req, $smsg, $eml) = @_;
472 my $sync = $req->{sync};
473 my $self = $sync->{self};
474 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
475 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
476 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
477 my $docid = $smsg->{num} = $orig_smsg->{num};
478 $self->{oidx}->add_overview($eml, $smsg); # may rethread
479 check_batch_limit({ %$sync, new_smsg => $smsg });
480 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
481 my $stable = delete($by_chash->{$chash0}) //
482 die "BUG: $smsg->{blob} chash missing";
483 my $idx = $self->idx_shard($docid);
484 my $top_smsg = pop @$stable;
485 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
486 my $ibx = _ibx_for($self, $sync, $smsg);
487 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
488 for my $x (reverse @$stable) {
489 $ibx = _ibx_for($self, $sync, $x);
490 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
491 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
493 return if $nr == 1; # likely, all good
495 warn "W: #$docid split into $nr due to deduplication change\n";
497 for my $ary (values %$by_chash) {
498 for my $x (reverse @$ary) {
499 warn "removing #$docid xref3 $x->{blob}\n";
500 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
501 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
503 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
504 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
505 $ibx = _ibx_for($self, $sync, $x);
506 if (my $over = $ibx->over) {
507 my $e = $over->get_art($x->{num});
508 $e->{blob} eq $x->{blob} or die <<EOF;
509 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
511 push @todo, $ibx, $e;
512 $over->dbh_close if _fd_constrained($self);
514 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
518 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
519 reindex_unseen($self, $sync, $ibx, $e);
523 sub _reindex_oid { # git->cat_async callback
524 my ($bref, $oid, $type, $size, $req) = @_;
525 my $sync = $req->{sync};
526 my $self = $sync->{self};
527 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
528 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
529 my $docid = $orig_smsg->{num};
530 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
531 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
533 warn "W: #$docid gone or corrupted\n";
534 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
535 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
536 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
538 warn "BUG: #$docid gone (UNEXPECTED)\n";
539 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
543 my $ci = $self->{current_info};
544 local $self->{current_info} = "$ci #$docid $oid";
545 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
546 $re_smsg->set_bytes($$bref, $size);
547 my $eml = PublicInbox::Eml->new($bref);
548 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
549 cotime => $orig_smsg->{ts} });
550 my $chash = content_hash($eml);
551 $re_smsg->{chash} = $chash;
552 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
553 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
554 $re_smsg->{hdr} = $eml->header_obj;
555 push @{$req->{by_chash}->{$chash}}, $re_smsg;
556 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
557 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
558 } else { # last $re_smsg is the highest priority xref3
559 local $self->{current_info} = "$ci #$docid";
560 _reindex_finalize($req, $re_smsg, $eml);
564 sub _reindex_smsg ($$$) {
565 my ($self, $sync, $smsg) = @_;
566 my $docid = $smsg->{num};
567 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
568 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
570 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
572 $self->{oidx}->delete_by_num($docid);
573 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
577 # we sort {xr3r} in the reverse order of ibx_sorted so we can
578 # hit the common case in _reindex_finalize without rereading
579 # from git (or holding multiple messages in memory).
580 my $id2pos = $sync->{id2pos}; # index in ibx_sorted
582 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
584 $b->[1] <=> $a->[1] # break ties with {xnum}
586 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
587 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
588 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
591 sub checkpoint_due ($) {
593 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
597 # I've copied FS images and only changed the hostname before,
598 # so prepend hostname. Use `state' since these a BOFH can change
599 # these while this process is running and we always want to be
600 # able to release locks taken by this process.
601 state $retval = hostname . '-' . do {
602 my $m; # machine-id(5) is systemd
603 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
604 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
605 chomp($m ||= `{ sysctl -n kern.hostid ||
606 hostid || ghostid; } 2>/dev/null`
607 || "no-machine-id-or-hostid-on-$^O");
614 my $expect = delete($self->{-eidxq_locked}) or return;
615 my ($owner_pid, undef) = split(/-/, $expect);
616 return if $owner_pid != $$; # shards may fork
617 my $oidx = $self->{oidx};
619 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
620 if ($cur eq $expect) {
621 $oidx->eidx_meta('eidxq_lock', '');
623 } elsif ($cur ne '') {
624 warn "E: eidxq_lock($expect) stolen by $cur\n";
626 warn "E: eidxq_lock($expect) released by another process\n";
633 eidxq_release($self) and $self->{oidx}->commit_lazy;
636 sub _eidxq_take ($) {
638 my $val = "$$-${\time}-$>-".host_ident;
639 $self->{oidx}->eidx_meta('eidxq_lock', $val);
640 $self->{-eidxq_locked} = $val;
643 sub eidxq_lock_acquire ($) {
645 my $oidx = $self->{oidx};
647 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
648 if (my $locked = $self->{-eidxq_locked}) { # be lazy
649 return $locked if $locked eq $cur;
651 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
652 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
653 if ($euid == $> && $ident eq host_ident) {
656 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
660 warn "I: eidxq_lock is stale ($cur), clobbering\n";
661 return _eidxq_take($self);
663 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
665 my $fn = $oidx->dbh->sqlite_db_filename;
667 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
668 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
669 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
674 sub ibx_sorted ($$) {
675 my ($self, $type) = @_;
676 $self->{"-ibx_ary_$type"} //= do {
677 # highest boost first, stable for config-ordering tiebreaker
680 ($b->{boost} // 0) <=> ($a->{boost} // 0)
681 } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
685 sub prep_id2pos ($) {
689 $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
693 sub eidxq_process ($$) { # for reindexing
694 my ($self, $sync) = @_;
695 return unless $self->{cfg};
697 return unless eidxq_lock_acquire($self);
698 my $dbh = $self->{oidx}->dbh;
699 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
701 local $sync->{-regen_fmt} = "%u/$tot\n";
702 my $pr = $sync->{-opt}->{-progress};
704 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
705 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
706 $pr->("Xapian indexing $min..$max (total=$tot)\n");
708 $sync->{id2pos} //= prep_id2pos($self);
711 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
712 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
714 while (defined(my $docid = $iter->fetchrow_array)) {
715 last if $sync->{quit};
716 if (my $smsg = $self->{oidx}->get_art($docid)) {
717 _reindex_smsg($self, $sync, $smsg);
719 warn "E: #$docid does not exist in over\n";
721 $del->execute($docid);
724 if (checkpoint_due($sync)) {
725 $dbh = $del = $iter = undef;
726 reindex_checkpoint($self, $sync); # release lock
727 $dbh = $self->{oidx}->dbh;
731 $self->git->async_wait_all;
732 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
735 sub _reindex_unseen { # git->cat_async callback
736 my ($bref, $oid, $type, $size, $req) = @_;
737 return if is_bad_blob($oid, $type, $size, $req->{oid});
738 my $self = $req->{self} // die 'BUG: {self} unset';
739 local $self->{current_info} = "$self->{current_info} $oid";
740 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
741 $new_smsg->set_bytes($$bref, $size);
742 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
743 $req->{new_smsg} = $new_smsg;
744 $req->{chash} = content_hash($eml);
745 $req->{mids} = mids($eml); # do_step iterates through this
746 do_step($req); # enter the normal indexing flow
749 # --reindex may catch totally unseen messages, this handles them
750 sub reindex_unseen ($$$$) {
751 my ($self, $sync, $ibx, $xsmsg) = @_;
754 autime => $xsmsg->{ds},
755 cotime => $xsmsg->{ts},
756 oid => $xsmsg->{blob},
758 xnum => $xsmsg->{num},
759 # {mids} and {chash} will be filled in at _reindex_unseen
761 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
762 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
765 sub _reindex_check_unseen ($$$) {
766 my ($self, $sync, $ibx) = @_;
767 my $ibx_id = $ibx->{-ibx_id};
769 my ($beg, $end) = (1, $slice);
771 # first, check if we missed any messages in target $ibx
773 my $pr = $sync->{-opt}->{-progress};
774 my $ekey = $ibx->eidx_key;
775 local $sync->{-regen_fmt} =
776 "$ekey checking unseen %u/".$ibx->over->max."\n";
779 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
780 ${$sync->{nr}} = $beg;
781 $beg = $msgs->[-1]->{num} + 1;
782 $end = $beg + $slice;
783 if (checkpoint_due($sync)) {
784 reindex_checkpoint($self, $sync); # release lock
787 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
788 SELECT DISTINCT(docid) FROM xref3 WHERE
789 ibx_id = ? AND xnum = ? AND oidbin = ?
791 for my $xsmsg (@$msgs) {
792 my $oidbin = pack('H*', $xsmsg->{blob});
793 $inx3->bind_param(1, $ibx_id);
794 $inx3->bind_param(2, $xsmsg->{num});
795 $inx3->bind_param(3, $oidbin, SQL_BLOB);
797 my $docids = $inx3->fetchall_arrayref;
798 # index messages which were totally missed
799 # the first time around ASAP:
800 if (scalar(@$docids) == 0) {
801 reindex_unseen($self, $sync, $ibx, $xsmsg);
802 } else { # already seen, reindex later
803 for my $r (@$docids) {
804 $self->{oidx}->eidxq_add($r->[0]);
807 last if $sync->{quit};
809 last if $sync->{quit};
813 sub _reindex_check_stale ($$$) {
814 my ($self, $sync, $ibx) = @_;
816 my $pr = $sync->{-opt}->{-progress};
818 my $ekey = $ibx->eidx_key;
819 local $sync->{-regen_fmt} =
820 "$ekey check stale/missing %u/".$ibx->over->max."\n";
823 if (checkpoint_due($sync)) {
824 reindex_checkpoint($self, $sync); # release lock
826 # now, check if there's stale xrefs
827 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
828 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
829 ORDER BY docid,xnum ASC LIMIT 10000
831 $iter->execute($ibx->{-ibx_id}, $min);
834 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
835 return if $sync->{quit};
836 ${$sync->{nr}} = $xnum;
838 $fetching = $min = $docid;
839 my $smsg = $ibx->over->get_art($xnum);
843 } elsif (pack('H*', $smsg->{blob}) ne $oidbin) {
844 $err = "mismatch (!= $smsg->{blob})";
846 next; # likely, all good
848 # current_info already has eidx_key
849 my $oidhex = unpack('H*', $oidbin);
850 warn "$xnum:$oidhex (#$docid): $err\n";
851 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
852 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
854 $del->bind_param(1, $ibx->{-ibx_id});
855 $del->bind_param(2, $xnum);
856 $del->bind_param(3, $oidbin, SQL_BLOB);
859 # get_xref3 over-fetches, but this is a rare path:
860 my $xr3 = $self->{oidx}->get_xref3($docid);
861 my $idx = $self->idx_shard($docid);
862 if (scalar(@$xr3) == 0) { # all gone
863 $self->{oidx}->delete_by_num($docid);
864 $self->{oidx}->eidxq_del($docid);
865 $idx->ipc_do('xdb_remove', $docid);
866 } else { # enqueue for reindex of remaining messages
867 $idx->ipc_do('remove_eidx_info',
868 $docid, $ibx->eidx_key);
869 $self->{oidx}->eidxq_add($docid); # yes, add
872 } while (defined $fetching);
875 sub _reindex_inbox ($$$) {
876 my ($self, $sync, $ibx) = @_;
877 my $ekey = $ibx->eidx_key;
878 local $self->{current_info} = $ekey;
879 if (defined(my $err = _ibx_index_reject($ibx))) {
880 warn "W: cannot reindex $ekey ($err)\n";
882 _reindex_check_unseen($self, $sync, $ibx);
883 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
885 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
889 my ($self, $sync) = @_;
890 return unless $self->{cfg};
892 # acquire eidxq_lock early because full reindex takes forever
893 # and incremental -extindex processes can run during our checkpoints
894 if (!eidxq_lock_acquire($self)) {
895 warn "E: aborting --reindex\n";
898 for my $ibx (@{ibx_sorted($self, 'active')}) {
899 _reindex_inbox($self, $sync, $ibx);
900 last if $sync->{quit};
902 $self->git->async_wait_all; # ensure eidxq gets filled completely
903 eidxq_process($self, $sync) unless $sync->{quit};
907 my ($self, $sync, $ibx) = @_;
908 my $err = _sync_inbox($self, $sync, $ibx);
909 delete @$ibx{qw(mm over)};
910 warn $err, "\n" if defined($err);
913 sub dd_smsg { # git->cat_async callback
914 my ($bref, $oid, $type, $size, $dd) = @_;
915 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
916 my $self = $dd->{self} // die 'BUG: {self} missing';
917 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
918 if ($type eq 'missing') {
919 _blob_missing($dd, $smsg);
920 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
921 local $self->{current_info} = "$self->{current_info} $oid";
922 my $chash = content_hash(PublicInbox::Eml->new($bref));
923 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
925 return if $per_mid->{last_smsg} != $smsg;
926 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
927 my $keep = shift @$ary;
928 next if !scalar(@$ary);
929 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
931 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
932 join(', ', map { "#$_->{num}" } @$ary),"\n";
933 next if $per_mid->{sync}->{-opt}->{'dry-run'};
934 my $oidx = $self->{oidx};
935 for my $smsg (@$ary) {
936 my $gone = $smsg->{num};
937 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
938 $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
939 $oidx->delete_by_num($gone);
944 sub eidx_dedupe ($$$) {
945 my ($self, $sync, $msgids) = @_;
946 $sync->{dedupe_cull} = 0;
949 return unless eidxq_lock_acquire($self);
950 my ($iter, $cur_mid);
953 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
954 SELECT MAX(id) FROM msgid
956 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
958 # note: we could write this query more intelligently,
959 # but that causes lock contention with read-only processes
961 $cur_mid = $msgids->[$idx];
962 if ($cur_mid eq '') { # all Message-IDs
963 $iter = $self->{oidx}->dbh->prepare(<<EOS);
964 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
966 $iter->execute($min_id);
968 $iter = $self->{oidx}->dbh->prepare(<<EOS);
969 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
971 $iter->execute($cur_mid, $min_id);
973 while (my ($mid, $id) = $iter->fetchrow_array) {
974 last if $sync->{quit};
975 $self->{current_info} = "dedupe $mid";
976 ${$sync->{nr}} = $min_id = $id;
978 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
981 next if scalar(@smsg) < 2;
983 dd_chash => {}, # chash => [ary of smsgs]
984 last_smsg => $smsg[-1],
988 $candidates += scalar(@smsg) - 1;
989 for my $smsg (@smsg) {
995 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
997 # need to wait on every single one @smsg contents can get
998 # invalidated inside dd_smsg for messages with multiple
1000 $self->git->async_wait_all;
1002 if (checkpoint_due($sync)) {
1004 reindex_checkpoint($self, $sync);
1005 goto dedupe_restart;
1008 goto dedupe_restart if defined($msgids->[++$idx]);
1010 my $n = delete $sync->{dedupe_cull};
1011 if (my $pr = $sync->{-opt}->{-progress}) {
1012 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1017 sub eidx_sync { # main entry point
1018 my ($self, $opt) = @_;
1020 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1021 local $self->{current_info} = '';
1022 local $SIG{__WARN__} = sub {
1023 return if PublicInbox::Eml::warn_ignore(@_);
1024 $warn_cb->($self->{current_info}, ': ', @_);
1026 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1027 $self->{oidx}->rethread_prepare($opt);
1029 need_checkpoint => \(my $need_checkpoint = 0),
1031 next_check => now() + 10,
1033 # DO NOT SET {reindex} here, it's incompatible with reused
1034 # V2Writable code, reindex is totally different here
1035 # compared to v1/v2 inboxes because we have multiple histories
1037 -regen_fmt => "%u/?\n",
1039 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1040 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1041 local $SIG{QUIT} = $quit;
1042 local $SIG{INT} = $quit;
1043 local $SIG{TERM} = $quit;
1044 for my $ibx (@{ibx_sorted($self, 'known')}) {
1045 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1048 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1049 $sync->{id2pos} //= prep_id2pos($self);
1050 $sync->{boost_in_use} = 1;
1053 if (my $msgids = delete($opt->{dedupe})) {
1054 local $sync->{checkpoint_unlocks} = 1;
1055 eidx_dedupe($self, $sync, $msgids);
1057 if (delete($opt->{reindex})) {
1058 local $sync->{checkpoint_unlocks} = 1;
1059 eidx_reindex($self, $sync);
1062 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1063 if ($opt->{scan} // 1) {
1064 for my $ibx (@{ibx_sorted($self, 'active')}) {
1065 last if $sync->{quit};
1066 sync_inbox($self, $sync, $ibx);
1069 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1070 eidxq_process($self, $sync) unless $sync->{quit};
1072 eidxq_release($self);
1074 $sync; # for eidx_watch
1077 sub update_last_commit { # overrides V2Writable
1078 my ($self, $sync, $stk) = @_;
1079 my $unit = $sync->{unit} // return;
1080 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1081 defined($latest_cmt) or return;
1082 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1083 my $ekey = $ibx->eidx_key;
1084 my $uv = $ibx->uidvalidity;
1085 my $epoch = $unit->{epoch};
1087 my $v = $ibx->version;
1089 die 'No {epoch} for v2 unit' unless defined $epoch;
1090 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1092 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1093 $meta_key = "lc-v1:$ekey//$uv";
1095 die "Unsupported inbox version: $v";
1097 my $last = $self->{oidx}->eidx_meta($meta_key);
1098 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1099 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1100 chomp(my $n = $unit->{git}->qx(@cmd));
1101 return if $n ne '' && $n == 0;
1103 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1106 sub _idx_init { # with_umask callback
1107 my ($self, $opt) = @_;
1108 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1109 $self->{midx} = PublicInbox::MiscIdx->new($self);
1112 sub symlink_packs ($$) {
1113 my ($ibx, $pd) = @_;
1115 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1116 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1117 my $src = substr($idx, 0, -length('.idx'));
1118 my $dst = $pd . substr($src, rindex($src, '/'));
1119 if (-f "$src.pack" and
1120 symlink("$src.pack", "$dst.pack") and
1121 symlink($idx, "$dst.idx") and
1124 # .promisor, .bitmap, .rev and .keep are optional
1125 # XXX should we symlink .keep here?
1126 for my $s (qw(promisor bitmap rev)) {
1127 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1129 } elsif (!$!{EEXIST}) {
1130 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1131 unlink "$dst.pack", "$dst.idx";
1137 sub idx_init { # similar to V2Writable
1138 my ($self, $opt) = @_;
1139 return if $self->{idx_shards};
1141 $self->git->cleanup;
1143 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1144 my ($has_new, $alt, $seen);
1145 if ($opt->{-private}) { # LeiStore
1146 my $local = "$self->{topdir}/local"; # lei/store
1147 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1148 'ALL.git', 'local');
1151 umask 077; # don't bother restoring for lei
1152 PublicInbox::Import::init_bare($ALL);
1153 $self->git->qx(qw(config core.sharedRepository 0600));
1155 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1156 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1157 } else { # extindex has no epochs
1158 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1160 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1162 PublicInbox::Import::init_bare($ALL);
1165 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1167 my $pd = "$ALL/objects/pack";
1168 if (opendir(my $dh, $pd)) { # drop stale symlinks
1169 while (defined(my $dn = readdir($dh))) {
1170 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1172 unlink($f) if -l $f && !-e $f;
1175 } elsif ($!{ENOENT}) {
1176 mkdir($pd) or die "mkdir($pd): $!";
1178 die "opendir($pd): $!";
1181 for my $ibx (@{ibx_sorted($self, 'active')}) {
1182 # create symlinks for multi-pack-index
1183 $git_midx += symlink_packs($ibx, $pd);
1184 # add new lines to our alternates file
1185 my $d = $ibx->git->{git_dir} . '/objects';
1186 next if exists $alt->{$d};
1187 if (my @st = stat($d)) {
1188 next if $seen->{"$st[0]\0$st[1]"}++;
1190 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1191 next if $opt->{-idx_gc};
1195 ($has_new || $new ne '') and
1196 $self->{mg}->write_alternates($mode, $alt, $new);
1197 $git_midx and $self->with_umask(sub {
1198 my @cmd = ('multi-pack-index');
1199 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1200 my $lk = $self->lock_for_scope;
1201 system('git', "--git-dir=$ALL", @cmd, 'write');
1202 # ignore errors, fairly new command, may not exist
1204 $self->parallel_init($self->{indexlevel});
1205 $self->with_umask(\&_idx_init, $self, $opt);
1206 $self->{oidx}->begin_lazy;
1207 $self->{oidx}->eidx_prep;
1208 $self->{midx}->create_xdb if $new ne '';
1211 sub _watch_commit { # PublicInbox::DS::add_timer callback
1213 delete $self->{-commit_timer};
1214 eidxq_process($self, $self->{-watch_sync});
1215 eidxq_release($self);
1216 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1217 reindex_checkpoint($self, $self->{-watch_sync});
1218 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1220 # call event_step => done unless commit_timer is armed
1221 PublicInbox::DS::requeue($self);
1224 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1225 my ($self, $ibx) = @_;
1226 my $opt = $self->{-watch_sync}->{-opt};
1227 my $pr = $opt->{-progress};
1228 my $ekey = $ibx->eidx_key;
1229 local $0 = "sync $ekey";
1230 $pr->("indexing $ekey\n") if $pr;
1231 $self->idx_init($opt);
1232 sync_inbox($self, $self->{-watch_sync}, $ibx);
1233 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1234 \&_watch_commit, $self);
1237 sub eidx_reload { # -extindex --watch SIGHUP handler
1238 my ($self, $idler) = @_;
1240 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1241 $pr->('reloading ...') if $pr;
1242 delete $self->{-resync_queue};
1243 delete $self->{-ibx_ary_known};
1244 delete $self->{-ibx_ary_active};
1245 $self->{ibx_known} = [];
1246 $self->{ibx_active} = [];
1247 %{$self->{ibx_map}} = ();
1248 delete $self->{-watch_sync}->{id2pos};
1249 my $cfg = PublicInbox::Config->new;
1250 attach_config($self, $cfg);
1251 $idler->refresh($cfg);
1252 $pr->(" done\n") if $pr;
1254 warn "reload not supported without --all\n";
1258 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1260 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1261 PublicInbox::DS::requeue($self); # trigger our ->event_step
1264 sub event_step { # PublicInbox::DS::requeue callback
1266 if (my $resync_queue = $self->{-resync_queue}) {
1267 if (my $ibx = shift(@$resync_queue)) {
1268 on_inbox_unlock($self, $ibx);
1269 PublicInbox::DS::requeue($self);
1271 delete $self->{-resync_queue};
1272 _watch_commit($self);
1275 done($self) unless $self->{-commit_timer};
1279 sub eidx_watch { # public-inbox-extindex --watch main loop
1280 my ($self, $opt) = @_;
1281 local @SIG{keys %SIG} = values %SIG;
1282 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1283 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1285 require PublicInbox::InboxIdle;
1286 require PublicInbox::DS;
1287 require PublicInbox::Syscall;
1288 require PublicInbox::Sigfd;
1289 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1290 if (!$self->{cfg}) {
1291 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1293 for my $ibx (@{ibx_sorted($self, 'active')}) {
1294 $ibx->subscribe_unlock(__PACKAGE__, $self)
1296 my $pr = $opt->{-progress};
1297 $pr->("performing initial scan ...\n") if $pr;
1298 my $sync = eidx_sync($self, $opt); # initial sync
1299 return if $sync->{quit};
1300 my $oldset = PublicInbox::DS::block_signals();
1301 local $self->{current_info} = '';
1302 my $cb = $SIG{__WARN__} || \&CORE::warn;
1303 local $SIG{__WARN__} = sub {
1304 return if PublicInbox::Eml::warn_ignore(@_);
1305 $cb->($self->{current_info}, ': ', @_);
1308 HUP => sub { eidx_reload($self, $idler) },
1309 USR1 => sub { eidx_resync_start($self) },
1310 TSTP => sub { kill('STOP', $$) },
1312 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1313 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1314 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1315 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1316 $pr->("initial scan complete, entering event loop\n") if $pr;
1317 # calls InboxIdle->event_step:
1318 PublicInbox::DS::event_loop($sig, $oldset);
1323 *done = \&PublicInbox::V2Writable::done;
1324 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1325 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1326 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1327 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1328 *index_todo = \&PublicInbox::V2Writable::index_todo;
1329 *count_shards = \&PublicInbox::V2Writable::count_shards;
1330 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1331 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1332 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1333 *checkpoint = \&PublicInbox::V2Writable::checkpoint;