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 Scalar::Util qw(blessed);
22 use Sys::Hostname qw(hostname);
23 use POSIX qw(strftime);
24 use File::Glob qw(bsd_glob GLOB_NOSORT);
25 use PublicInbox::MultiGit;
26 use PublicInbox::Search;
27 use PublicInbox::SearchIdx qw(prepare_stack is_ancestor is_bad_blob);
28 use PublicInbox::OverIdx;
29 use PublicInbox::MiscIdx;
30 use PublicInbox::MID qw(mids);
31 use PublicInbox::V2Writable;
32 use PublicInbox::InboxWritable;
33 use PublicInbox::ContentHash qw(content_hash);
35 use PublicInbox::DS qw(now add_timer);
36 use DBI qw(:sql_types); # SQL_BLOB
39 my (undef, $dir, $opt) = @_;
40 my $l = $opt->{indexlevel} // 'full';
41 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
42 die "invalid indexlevel=$l\n";
43 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
45 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
47 creat => $opt->{creat},
48 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
49 ibx_active => [], # by config section order
50 ibx_known => [], # by config section order
56 lock_path => "$dir/ei.lock",
58 $self->{shards} = $self->count_shards ||
59 nproc_shards({ nproc => $opt->{jobs} });
60 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
61 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
62 $self->{oidx} = $oidx;
67 my ($self, $ibx, $types) = @_;
68 $self->{ibx_map}->{$ibx->eidx_key} //= do {
69 delete $self->{-ibx_ary_known}; # invalidate cache
70 delete $self->{-ibx_ary_active}; # invalidate cache
71 $types //= [ qw(active known) ];
73 push @{$self->{"ibx_$t"}}, $ibx;
79 sub _ibx_attach { # each_inbox callback
80 my ($ibx, $self, $types) = @_;
81 attach_inbox($self, $ibx, $types);
85 my ($self, $cfg, $ibxs) = @_;
89 for my $ibx (@$ibxs) {
90 $self->{ibx_map}->{$ibx->eidx_key} //= do {
91 push @{$self->{ibx_active}}, $ibx;
92 push @{$self->{ibx_known}}, $ibx;
97 delete $self->{-ibx_ary_known};
98 delete $self->{-ibx_ary_active};
101 $types //= [ qw(known active) ];
102 $cfg->each_inbox(\&_ibx_attach, $self, $types);
105 sub check_batch_limit ($) {
107 my $self = $req->{self};
108 my $new_smsg = $req->{new_smsg};
109 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
111 # set flag for PublicInbox::V2Writable::index_todo:
112 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
115 sub apply_boost ($$) {
116 my ($req, $smsg) = @_;
117 my $id2pos = $req->{id2pos}; # index in ibx_sorted
118 my $xr3 = $req->{self}->{oidx}->get_xref3($smsg->{num}, 1);
120 $id2pos->{$a->[0]} <=> $id2pos->{$b->[0]}
122 $a->[1] <=> $b->[1] # break ties with {xnum}
124 my $new_smsg = $req->{new_smsg};
125 return if $xr3->[0]->[2] ne pack('H*', $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);
133 sub remove_doc ($$) {
134 my ($self, $docid) = @_;
135 $self->{oidx}->delete_by_num($docid);
136 $self->{oidx}->eidxq_del($docid);
137 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
140 sub _unref_doc ($$$$$;$) {
141 my ($sync, $docid, $ibx, $xnum, $oidbin, $eml) = @_;
145 $docid = $smsg->{num};
147 if (defined($oidbin) && defined($xnum) && blessed($ibx) && $ibx->over) {
148 my $smsg = $ibx->over->get_art($xnum);
149 if ($smsg && pack('H*', $smsg->{blob}) eq $oidbin) {
150 carp("BUG: (non-fatal) ".$ibx->eidx_key.
151 " #$xnum $smsg->{blob} still valid");
155 my $s = 'DELETE FROM xref3 WHERE oidbin = ?';
156 $s .= ' AND ibx_id = ?' if defined($ibx);
157 $s .= ' AND xnum = ?' if defined($xnum);
158 my $del = $sync->{self}->{oidx}->dbh->prepare_cached($s);
160 $del->bind_param(++$col, $oidbin, SQL_BLOB);
161 $del->bind_param(++$col, $ibx->{-ibx_id}) if $ibx;
162 $del->bind_param(++$col, $xnum) if defined($xnum);
164 my $xr3 = $sync->{self}->{oidx}->get_xref3($docid);
165 if (scalar(@$xr3) == 0) { # all gone
166 remove_doc($sync->{self}, $docid);
167 } else { # enqueue for reindex of remaining messages
169 my $ekey = $ibx->{-gc_eidx_key} // $ibx->eidx_key;
170 my $idx = $sync->{self}->idx_shard($docid);
171 $idx->ipc_do('remove_eidx_info', $docid, $ekey, $eml);
172 } # else: we can't remove_eidx_info in reindex-only path
174 # replace invalidated blob ASAP with something which should be
175 # readable since we may commit the transaction on checkpoint.
176 # eidxq processing will re-apply boost
177 $smsg //= $sync->{self}->{oidx}->get_art($docid);
178 my $hex = unpack('H*', $oidbin);
179 if ($smsg && $smsg->{blob} eq $hex) {
180 $xr3->[0] =~ /:([a-f0-9]{40,}+)\z/ or
181 die "BUG: xref $xr3->[0] has no OID";
182 $sync->{self}->{oidx}->update_blob($smsg, $1);
184 # yes, add, we'll need to re-apply boost
185 $sync->{self}->{oidx}->eidxq_add($docid);
191 my ($req, $smsg) = @_;
192 my $self = $req->{self};
193 my $docid = $smsg->{num};
194 my $oid = $req->{oid};
195 my $xibx = $req->{ibx};
196 my $eml = $req->{eml};
197 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
198 my $eidx_key = $xibx->eidx_key;
199 my $xnum = $req->{xnum};
200 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
201 my $idx = $self->idx_shard($docid);
202 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
203 apply_boost($req, $smsg) if $req->{boost_in_use};
204 } else { # 'd' no {xnum}
205 $self->git->async_wait_all;
206 $oid = pack('H*', $oid);
207 _unref_doc($req, $docid, $xibx, undef, $oid, $eml);
211 # called by V2Writable::sync_prepare
212 sub artnum_max { $_[0]->{oidx}->eidx_max }
214 sub index_unseen ($) {
216 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
217 my $eml = delete $req->{eml};
218 $new_smsg->populate($eml, $req);
219 my $self = $req->{self};
220 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
221 $new_smsg->{num} = $docid;
222 my $idx = $self->idx_shard($docid);
223 $self->{oidx}->add_overview($eml, $new_smsg);
224 my $oid = $new_smsg->{blob};
225 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
226 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
227 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
228 check_batch_limit($req);
231 sub do_finalize ($) {
233 if (my $indexed = $req->{indexed}) { # duplicated messages
234 do_xpost($req, $_) for @$indexed;
235 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
238 # `d' message was already unindexed in the v1/v2 inboxes,
239 # so it's too noisy to warn, here.
241 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
242 if (defined(my $cur_cmt = $req->{cur_cmt})) {
243 ${$req->{latest_cmt}} = $cur_cmt;
247 sub do_step ($) { # main iterator for adding messages to the index
249 my $self = $req->{self} // die 'BUG: {self} missing';
251 if (my $next_arg = $req->{next_arg}) {
252 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
253 $req->{cur_smsg} = $smsg;
254 $self->git->cat_async($smsg->{blob},
255 \&ck_existing, $req);
256 return; # ck_existing calls do_step
258 delete $req->{next_arg};
260 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
261 my $mid = shift(@{$req->{mids}}) // last;
263 $req->{next_arg} = [ $mid, \$id, \$prev ];
269 sub _blob_missing ($$) { # called when a known $smsg->{blob} is gone
270 my ($req, $smsg) = @_;
271 # xnum and ibx are unknown, we only call this when an entry from
272 # /ei*/over.sqlite3 is bad, not on entries from xap*/over.sqlite3
273 my $oidbin = pack('H*', $smsg->{blob});
274 $req->{self}->git->async_wait_all;
275 _unref_doc($req, $smsg, undef, undef, $oidbin);
278 sub ck_existing { # git->cat_async callback
279 my ($bref, $oid, $type, $size, $req) = @_;
280 my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
281 if ($type eq 'missing') {
282 _blob_missing($req, $smsg);
283 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
284 my $self = $req->{self} // die 'BUG: {self} missing';
285 local $self->{current_info} = "$self->{current_info} $oid";
286 my $cur = PublicInbox::Eml->new($bref);
287 if (content_hash($cur) eq $req->{chash}) {
288 push @{$req->{indexed}}, $smsg; # for do_xpost
289 } # else { index_unseen later }
294 # is the messages visible in the inbox currently being indexed?
295 # return the number if so
296 sub cur_ibx_xnum ($$) {
297 my ($req, $bref) = @_;
298 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
300 $req->{eml} = PublicInbox::Eml->new($bref);
301 $req->{chash} = content_hash($req->{eml});
302 $req->{mids} = mids($req->{eml});
303 for my $mid (@{$req->{mids}}) {
305 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
306 return $x->{num} if $x->{blob} eq $req->{oid};
312 sub index_oid { # git->cat_async callback for 'm'
313 my ($bref, $oid, $type, $size, $req) = @_;
314 my $self = $req->{self};
315 local $self->{current_info} = "$self->{current_info} $oid";
316 return if is_bad_blob($oid, $type, $size, $req->{oid});
317 my $new_smsg = $req->{new_smsg} = bless {
319 }, 'PublicInbox::Smsg';
320 $new_smsg->set_bytes($$bref, $size);
321 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
326 sub unindex_oid { # git->cat_async callback for 'd'
327 my ($bref, $oid, $type, $size, $req) = @_;
328 my $self = $req->{self};
329 local $self->{current_info} = "$self->{current_info} $oid";
330 return if is_bad_blob($oid, $type, $size, $req->{oid});
331 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
335 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
337 my ($self, $sync) = @_;
339 my $ekey = $sync->{ibx}->eidx_key;
340 my $uv = $sync->{ibx}->uidvalidity;
341 for my $i (0..$sync->{epoch_max}) {
342 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
347 sub _ibx_index_reject ($) {
349 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
350 $ibx->uidvalidity // return 'no UIDVALIDITY';
351 $ibx->over // return 'unindexed, no over.sqlite3';
355 sub _sync_inbox ($$$) {
356 my ($self, $sync, $ibx) = @_;
357 my $ekey = $ibx->eidx_key;
358 if (defined(my $err = _ibx_index_reject($ibx))) {
359 return "W: skipping $ekey ($err)";
362 $sync->{nr} = \(my $nr = 0);
363 my $v = $ibx->version;
365 $sync->{epoch_max} = $ibx->max_git_epoch // return;
366 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
368 my $uv = $ibx->uidvalidity;
369 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
370 my $head = $ibx->mm->last_commit //
371 return "E: $ibx->{inboxdir} is not indexed";
372 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
373 my $unit = { stack => $stk, git => $ibx->git };
374 push @{$sync->{todo}}, $unit;
376 return "E: $ekey unsupported inbox version (v$v)";
378 for my $unit (@{delete($sync->{todo}) // []}) {
379 last if $sync->{quit};
380 index_todo($self, $sync, $unit);
382 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
383 $ibx->git->cleanup; # done with this inbox, now
387 sub eidx_gc_scan_inboxes ($$) {
388 my ($self, $sync) = @_;
389 my ($x3_doc, $ibx_ck);
391 $x3_doc = $self->{oidx}->dbh->prepare(<<EOM);
392 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ?
394 $ibx_ck = $self->{oidx}->dbh->prepare(<<EOM);
395 SELECT ibx_id,eidx_key FROM inboxes
398 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
399 next if $self->{ibx_map}->{$eidx_key};
400 $self->{midx}->remove_eidx_key($eidx_key);
401 warn "I: deleting messages for $eidx_key...\n";
402 $x3_doc->execute($ibx_id);
403 my $ibx = { -ibx_id => $ibx_id, -gc_eidx_key => $eidx_key };
404 while (my ($docid, $xnum, $oid) = $x3_doc->fetchrow_array) {
405 my $r = _unref_doc($sync, $docid, $ibx, $xnum, $oid);
406 $oid = unpack('H*', $oid);
407 $r = $r ? 'unref' : 'remove';
408 warn "I: $r #$docid $eidx_key $oid\n";
409 if (checkpoint_due($sync)) {
410 $x3_doc = $ibx_ck = undef;
411 reindex_checkpoint($self, $sync);
415 $self->{oidx}->dbh->do(<<'', undef, $ibx_id);
416 DELETE FROM inboxes WHERE ibx_id = ?
418 # drop last_commit info
420 $pat =~ s/([_%\\])/\\$1/g;
421 $self->{oidx}->dbh->do('PRAGMA case_sensitive_like = ON');
422 my $lc_i = $self->{oidx}->dbh->prepare(<<'');
423 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
425 $lc_i->execute("lc-%:$pat//%", '\\');
426 while (my ($key) = $lc_i->fetchrow_array) {
427 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
428 warn "I: removing $key\n";
429 $self->{oidx}->dbh->do(<<'', undef, $key);
430 DELETE FROM eidx_meta WHERE key = ?
433 warn "I: $eidx_key removed\n";
437 sub eidx_gc_scan_shards ($$) { # TODO: use for lei/store
438 my ($self, $sync) = @_;
439 my $nr = $self->{oidx}->dbh->do(<<'');
440 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
442 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
443 reindex_checkpoint($self, $sync) if checkpoint_due($sync);
445 # fixup from old bugs:
446 $nr = $self->{oidx}->dbh->do(<<'');
447 DELETE FROM over WHERE num > 0 AND num NOT IN (SELECT docid FROM xref3)
449 warn "I: eliminated $nr stale over entries\n" if $nr != 0;
450 reindex_checkpoint($self, $sync) if checkpoint_due($sync);
452 $nr = $self->{oidx}->dbh->do(<<'');
453 DELETE FROM eidxq WHERE docid NOT IN (SELECT num FROM over)
455 warn "I: eliminated $nr stale reindex queue entries\n" if $nr != 0;
456 reindex_checkpoint($self, $sync) if checkpoint_due($sync);
458 my ($cur) = $self->{oidx}->dbh->selectrow_array(<<EOM);
459 SELECT MIN(num) FROM over WHERE num > 0
461 $cur // return; # empty
462 my ($r, $n, %active_shards);
465 $r = $self->{oidx}->dbh->selectcol_arrayref(<<"", undef, $cur);
466 SELECT num FROM over WHERE num >= ? ORDER BY num ASC LIMIT 10000
468 last unless scalar(@$r);
469 while (defined($n = shift @$r)) {
470 for my $i ($cur..($n - 1)) {
471 my $idx = idx_shard($self, $i);
472 $idx->ipc_do('xdb_remove_quiet', $i);
473 $active_shards{$idx} = $idx;
477 if (checkpoint_due($sync)) {
478 for my $idx (values %active_shards) {
479 $nr += $idx->ipc_do('nr_quiet_rm')
482 reindex_checkpoint($self, $sync);
485 warn "I: eliminated $nr stale Xapian documents\n" if $nr != 0;
489 my ($self, $opt) = @_;
490 $self->{cfg} or die "E: GC requires ->attach_config\n";
493 need_checkpoint => \(my $need_checkpoint = 0),
495 next_check => now() + 10,
496 checkpoint_unlocks => 1,
500 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
501 eidx_gc_scan_inboxes($self, $sync);
502 eidx_gc_scan_shards($self, $sync);
507 my ($self, $sync, $smsg) = @_;
508 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
509 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
510 $self->{-ibx_ary_known}->[$pos] //
511 die "BUG: ibx for $smsg->{blob} not mapped"
514 sub _fd_constrained ($) {
516 $self->{-fd_constrained} //= do {
518 if (eval { require BSD::Resource; 1 }) {
519 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
520 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
522 chomp($soft = `sh -c 'ulimit -n'`);
524 if (defined($soft)) {
525 # $want is an estimate
526 my $want = scalar(@{$self->{ibx_active}}) + 64;
527 my $ret = $want > $soft;
530 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
535 warn "Unable to determine RLIMIT_NOFILE: $@\n";
541 sub _reindex_finalize ($$$) {
542 my ($req, $smsg, $eml) = @_;
543 my $sync = $req->{sync};
544 my $self = $sync->{self};
545 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
546 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
547 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
548 my $docid = $smsg->{num} = $orig_smsg->{num};
549 $self->{oidx}->add_overview($eml, $smsg); # may rethread
550 check_batch_limit({ %$sync, new_smsg => $smsg });
551 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
552 my $stable = delete($by_chash->{$chash0}) //
553 die "BUG: $smsg->{blob} chash missing";
554 my $idx = $self->idx_shard($docid);
555 my $top_smsg = pop @$stable;
556 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
557 my $ibx = _ibx_for($self, $sync, $smsg);
558 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
559 for my $x (reverse @$stable) {
560 $ibx = _ibx_for($self, $sync, $x);
561 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
562 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
564 return if $nr == 1; # likely, all good
566 $self->git->async_wait_all;
567 warn "W: #$docid split into $nr due to deduplication change\n";
569 for my $ary (values %$by_chash) {
570 for my $x (reverse @$ary) {
571 warn "removing #$docid xref3 $x->{blob}\n";
572 my $bin = pack('H*', $x->{blob});
573 my $n = _unref_doc($sync, $docid, undef, undef, $bin);
574 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
576 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
577 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
578 $ibx = _ibx_for($self, $sync, $x);
579 if (my $over = $ibx->over) {
580 my $e = $over->get_art($x->{num});
581 $e->{blob} eq $x->{blob} or die <<EOF;
582 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
584 push @todo, $ibx, $e;
585 $over->dbh_close if _fd_constrained($self);
587 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
591 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
592 reindex_unseen($self, $sync, $ibx, $e);
596 sub _reindex_oid { # git->cat_async callback
597 my ($bref, $oid, $type, $size, $req) = @_;
598 my $sync = $req->{sync};
599 my $self = $sync->{self};
600 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
601 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
602 my $docid = $orig_smsg->{num};
603 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
604 my $oidbin = pack('H*', $expect_oid);
605 my $remain = _unref_doc($sync, $docid, undef, undef, $oidbin);
607 warn "W: #$docid ($oid) gone or corrupt\n";
608 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
609 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
611 warn "BUG: #$docid ($oid) gone (UNEXPECTED)\n";
615 my $ci = $self->{current_info};
616 local $self->{current_info} = "$ci #$docid $oid";
617 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
618 $re_smsg->set_bytes($$bref, $size);
619 my $eml = PublicInbox::Eml->new($bref);
620 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
621 cotime => $orig_smsg->{ts} });
622 my $chash = content_hash($eml);
623 $re_smsg->{chash} = $chash;
624 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
625 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
626 $re_smsg->{hdr} = $eml->header_obj;
627 push @{$req->{by_chash}->{$chash}}, $re_smsg;
628 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
629 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
630 } else { # last $re_smsg is the highest priority xref3
631 local $self->{current_info} = "$ci #$docid";
632 _reindex_finalize($req, $re_smsg, $eml);
636 sub _reindex_smsg ($$$) {
637 my ($self, $sync, $smsg) = @_;
638 my $docid = $smsg->{num};
639 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
640 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
642 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
644 remove_doc($self, $docid);
648 # we sort {xr3r} in the reverse order of ibx_sorted so we can
649 # hit the common case in _reindex_finalize without rereading
650 # from git (or holding multiple messages in memory).
651 my $id2pos = $sync->{id2pos}; # index in ibx_sorted
653 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
655 $b->[1] <=> $a->[1] # break ties with {xnum}
657 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
658 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
659 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
662 sub checkpoint_due ($) {
664 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
668 # I've copied FS images and only changed the hostname before,
669 # so prepend hostname. Use `state' since these a BOFH can change
670 # these while this process is running and we always want to be
671 # able to release locks taken by this process.
672 state $retval = hostname . '-' . do {
673 my $m; # machine-id(5) is systemd
674 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
675 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
676 chomp($m ||= `{ sysctl -n kern.hostid ||
677 hostid || ghostid; } 2>/dev/null`
678 || "no-machine-id-or-hostid-on-$^O");
685 my $expect = delete($self->{-eidxq_locked}) or return;
686 my ($owner_pid, undef) = split(/-/, $expect);
687 return if $owner_pid != $$; # shards may fork
688 my $oidx = $self->{oidx};
690 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
691 if ($cur eq $expect) {
692 $oidx->eidx_meta('eidxq_lock', '');
694 } elsif ($cur ne '') {
695 warn "E: eidxq_lock($expect) stolen by $cur\n";
697 warn "E: eidxq_lock($expect) released by another process\n";
704 eidxq_release($self) and $self->{oidx}->commit_lazy;
707 sub _eidxq_take ($) {
709 my $val = "$$-${\time}-$>-".host_ident;
710 $self->{oidx}->eidx_meta('eidxq_lock', $val);
711 $self->{-eidxq_locked} = $val;
714 sub eidxq_lock_acquire ($) {
716 my $oidx = $self->{oidx};
718 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
719 if (my $locked = $self->{-eidxq_locked}) { # be lazy
720 return $locked if $locked eq $cur;
722 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
723 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
724 if ($euid == $> && $ident eq host_ident) {
727 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
731 warn "I: eidxq_lock is stale ($cur), clobbering\n";
732 return _eidxq_take($self);
734 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
736 my $fn = $oidx->dbh->sqlite_db_filename;
738 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
739 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
740 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
745 sub ibx_sorted ($$) {
746 my ($self, $type) = @_;
747 $self->{"-ibx_ary_$type"} //= do {
748 # highest boost first, stable for config-ordering tiebreaker
751 ($b->{boost} // 0) <=> ($a->{boost} // 0)
752 } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
756 sub prep_id2pos ($) {
760 $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
764 sub eidxq_process ($$) { # for reindexing
765 my ($self, $sync) = @_;
766 local $self->{current_info} = 'eidxq process';
767 return unless ($self->{cfg} && eidxq_lock_acquire($self));
768 my $dbh = $self->{oidx}->dbh;
769 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
771 local $sync->{-regen_fmt} = "%u/$tot\n";
772 my $pr = $sync->{-opt}->{-progress};
774 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
775 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
776 $pr->("Xapian indexing $min..$max (total=$tot)\n");
778 $sync->{id2pos} //= prep_id2pos($self);
781 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
782 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
784 while (defined(my $docid = $iter->fetchrow_array)) {
785 last if $sync->{quit};
786 if (my $smsg = $self->{oidx}->get_art($docid)) {
787 _reindex_smsg($self, $sync, $smsg);
789 warn "E: #$docid does not exist in over\n";
791 $del->execute($docid);
794 if (checkpoint_due($sync)) {
795 $dbh = $del = $iter = undef;
796 reindex_checkpoint($self, $sync); # release lock
797 $dbh = $self->{oidx}->dbh;
801 $self->git->async_wait_all;
802 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
805 sub _reindex_unseen { # git->cat_async callback
806 my ($bref, $oid, $type, $size, $req) = @_;
807 return if is_bad_blob($oid, $type, $size, $req->{oid});
808 my $self = $req->{self} // die 'BUG: {self} unset';
809 local $self->{current_info} = "$self->{current_info} $oid";
810 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
811 $new_smsg->set_bytes($$bref, $size);
812 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
813 $req->{new_smsg} = $new_smsg;
814 $req->{chash} = content_hash($eml);
815 $req->{mids} = mids($eml); # do_step iterates through this
816 do_step($req); # enter the normal indexing flow
819 # --reindex may catch totally unseen messages, this handles them
820 sub reindex_unseen ($$$$) {
821 my ($self, $sync, $ibx, $xsmsg) = @_;
824 autime => $xsmsg->{ds},
825 cotime => $xsmsg->{ts},
826 oid => $xsmsg->{blob},
828 xnum => $xsmsg->{num},
829 # {mids} and {chash} will be filled in at _reindex_unseen
831 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
832 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
835 sub _unref_stale_range ($$$) {
836 my ($sync, $ibx, $lt_or_gt) = @_;
840 $r = $sync->{self}->{oidx}->dbh->selectall_arrayref(
841 <<EOS, undef, $ibx->{-ibx_id});
842 SELECT docid,xnum,oidbin FROM xref3
843 WHERE ibx_id = ? AND xnum $lt_or_gt LIMIT $lim
845 return if $sync->{quit};
846 for (@$r) { # hopefully rare, not worth optimizing:
847 my ($docid, $xnum, $oidbin) = @$_;
848 my $hex = unpack('H*', $oidbin);
849 warn("# $xnum:$hex (#$docid): stale\n");
850 _unref_doc($sync, $docid, $ibx, $xnum, $oidbin);
852 } while (scalar(@$r) == $lim);
856 sub _reindex_check_ibx ($$$) {
857 my ($self, $sync, $ibx) = @_;
858 my $ibx_id = $ibx->{-ibx_id};
860 my $opt = { limit => $slice };
861 my ($beg, $end) = (1, $slice);
862 my $err = sync_inbox($self, $sync, $ibx) and return;
863 my $max = $ibx->over->max;
864 $end = $max if $end > $max;
866 # first, check if we missed any messages in target $ibx
868 my $pr = $sync->{-opt}->{-progress};
869 my $ekey = $ibx->eidx_key;
870 local $sync->{-regen_fmt} = "$ekey checking %u/$max\n";
872 my $fast = $sync->{-opt}->{fast};
873 my $dsu; # _unref_stale_range (< $lo) called
875 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end, $opt)})) {
876 ${$sync->{nr}} = $beg;
877 $beg = $msgs->[-1]->{num} + 1;
878 $end = $beg + $slice;
879 $end = $max if $end > $max;
880 if (checkpoint_due($sync)) {
881 reindex_checkpoint($self, $sync); # release lock
883 ($lo, $hi) = ($msgs->[0]->{num}, $msgs->[-1]->{num});
884 $dsu //= _unref_stale_range($sync, $ibx, "< $lo");
885 my $x3a = $self->{oidx}->dbh->selectall_arrayref(
886 <<"", undef, $ibx_id, $lo, $hi);
887 SELECT xnum,oidbin,docid FROM xref3 WHERE
888 ibx_id = ? AND xnum >= ? AND xnum <= ?
892 my $k = pack('J', $_->[0]) . $_->[1];
893 push @{$x3m{$k}}, $_->[2];
896 for my $xsmsg (@$msgs) {
897 my $k = pack('JH*', $xsmsg->{num}, $xsmsg->{blob});
898 my $docids = delete($x3m{$k});
899 if (!defined($docids)) {
900 reindex_unseen($self, $sync, $ibx, $xsmsg);
902 for my $num (@$docids) {
903 $self->{oidx}->eidxq_add($num);
905 return if $sync->{quit};
908 return if $sync->{quit};
909 next unless scalar keys %x3m;
910 $self->git->async_wait_all; # wait for reindex_unseen
912 # eliminate stale/mismatched entries
913 my %mismatch = map { $_->{num} => $_->{blob} } @$msgs;
914 while (my ($k, $docids) = each %x3m) {
915 my ($xnum, $hex) = unpack('JH*', $k);
916 my $bin = pack('H*', $hex);
917 my $exp = $mismatch{$xnum};
918 my $m = defined($exp) ? "mismatch (!= $exp)" : 'stale';
919 warn("# $xnum:$hex (#@$docids): $m\n");
920 for my $i (@$docids) {
921 _unref_doc($sync, $i, $ibx, $xnum, $bin);
925 _unref_stale_range($sync, $ibx, "> $hi") if defined($hi);
928 sub _reindex_inbox ($$$) {
929 my ($self, $sync, $ibx) = @_;
930 my $ekey = $ibx->eidx_key;
931 local $self->{current_info} = $ekey;
932 if (defined(my $err = _ibx_index_reject($ibx))) {
933 warn "W: cannot reindex $ekey ($err)\n";
935 _reindex_check_ibx($self, $sync, $ibx);
937 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
941 my ($self, $sync) = @_;
942 return unless $self->{cfg};
944 # acquire eidxq_lock early because full reindex takes forever
945 # and incremental -extindex processes can run during our checkpoints
946 if (!eidxq_lock_acquire($self)) {
947 warn "E: aborting --reindex\n";
950 for my $ibx (@{ibx_sorted($self, 'active')}) {
951 _reindex_inbox($self, $sync, $ibx);
952 last if $sync->{quit};
954 $self->git->async_wait_all; # ensure eidxq gets filled completely
955 eidxq_process($self, $sync) unless $sync->{quit};
959 my ($self, $sync, $ibx) = @_;
960 my $err = _sync_inbox($self, $sync, $ibx);
961 delete @$ibx{qw(mm over)};
962 warn $err, "\n" if defined($err);
966 sub dd_smsg { # git->cat_async callback
967 my ($bref, $oid, $type, $size, $dd) = @_;
968 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
969 my $self = $dd->{self} // die 'BUG: {self} missing';
970 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
971 if ($type eq 'missing') {
972 _blob_missing($dd, $smsg);
973 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
974 local $self->{current_info} = "$self->{current_info} $oid";
975 my $chash = content_hash(PublicInbox::Eml->new($bref));
976 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
978 return if $per_mid->{last_smsg} != $smsg;
979 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
980 my $keep = shift @$ary;
981 next if !scalar(@$ary);
982 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
984 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
985 join(', ', map { "#$_->{num}" } @$ary),"\n";
986 next if $per_mid->{sync}->{-opt}->{'dry-run'};
987 my $oidx = $self->{oidx};
988 for my $smsg (@$ary) {
989 my $gone = $smsg->{num};
990 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
991 remove_doc($self, $gone);
996 sub eidx_dedupe ($$$) {
997 my ($self, $sync, $msgids) = @_;
998 $sync->{dedupe_cull} = 0;
1001 return unless eidxq_lock_acquire($self);
1002 my ($iter, $cur_mid);
1005 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
1006 SELECT MAX(id) FROM msgid
1008 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
1010 # note: we could write this query more intelligently,
1011 # but that causes lock contention with read-only processes
1013 $cur_mid = $msgids->[$idx];
1014 if ($cur_mid eq '') { # all Message-IDs
1015 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1016 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
1018 $iter->execute($min_id);
1020 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1021 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
1023 $iter->execute($cur_mid, $min_id);
1025 while (my ($mid, $id) = $iter->fetchrow_array) {
1026 last if $sync->{quit};
1027 $self->{current_info} = "dedupe $mid";
1028 ${$sync->{nr}} = $min_id = $id;
1030 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
1033 next if scalar(@smsg) < 2;
1035 dd_chash => {}, # chash => [ary of smsgs]
1036 last_smsg => $smsg[-1],
1040 $candidates += scalar(@smsg) - 1;
1041 for my $smsg (@smsg) {
1043 per_mid => $per_mid,
1047 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
1049 # need to wait on every single one @smsg contents can get
1050 # invalidated inside dd_smsg for messages with multiple
1052 $self->git->async_wait_all;
1054 if (checkpoint_due($sync)) {
1056 reindex_checkpoint($self, $sync);
1057 goto dedupe_restart;
1060 goto dedupe_restart if defined($msgids->[++$idx]);
1062 my $n = delete $sync->{dedupe_cull};
1063 if (my $pr = $sync->{-opt}->{-progress}) {
1064 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1069 sub eidx_sync { # main entry point
1070 my ($self, $opt) = @_;
1072 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1073 local $self->{current_info} = '';
1074 local $SIG{__WARN__} = sub {
1075 return if PublicInbox::Eml::warn_ignore(@_);
1076 $warn_cb->($self->{current_info}, ': ', @_);
1078 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1079 $self->{oidx}->rethread_prepare($opt);
1081 need_checkpoint => \(my $need_checkpoint = 0),
1083 next_check => now() + 10,
1085 # DO NOT SET {reindex} here, it's incompatible with reused
1086 # V2Writable code, reindex is totally different here
1087 # compared to v1/v2 inboxes because we have multiple histories
1089 -regen_fmt => "%u/?\n",
1091 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1092 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1093 local $SIG{QUIT} = $quit;
1094 local $SIG{INT} = $quit;
1095 local $SIG{TERM} = $quit;
1096 for my $ibx (@{ibx_sorted($self, 'known')}) {
1097 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1100 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1101 $sync->{id2pos} //= prep_id2pos($self);
1102 $sync->{boost_in_use} = 1;
1105 if (my $msgids = delete($opt->{dedupe})) {
1106 local $sync->{checkpoint_unlocks} = 1;
1107 eidx_dedupe($self, $sync, $msgids);
1109 if (delete($opt->{reindex})) {
1110 local $sync->{checkpoint_unlocks} = 1;
1111 eidx_reindex($self, $sync);
1114 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1115 if ($opt->{scan} // 1) {
1116 for my $ibx (@{ibx_sorted($self, 'active')}) {
1117 last if $sync->{quit};
1118 sync_inbox($self, $sync, $ibx);
1121 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1122 eidxq_process($self, $sync) unless $sync->{quit};
1124 eidxq_release($self);
1126 $sync; # for eidx_watch
1129 sub update_last_commit { # overrides V2Writable
1130 my ($self, $sync, $stk) = @_;
1131 my $unit = $sync->{unit} // return;
1132 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1133 defined($latest_cmt) or return;
1134 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1135 my $ekey = $ibx->eidx_key;
1136 my $uv = $ibx->uidvalidity;
1137 my $epoch = $unit->{epoch};
1139 my $v = $ibx->version;
1141 die 'No {epoch} for v2 unit' unless defined $epoch;
1142 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1144 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1145 $meta_key = "lc-v1:$ekey//$uv";
1147 die "Unsupported inbox version: $v";
1149 my $last = $self->{oidx}->eidx_meta($meta_key);
1150 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1151 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1152 chomp(my $n = $unit->{git}->qx(@cmd));
1153 return if $n ne '' && $n == 0;
1155 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1158 sub _idx_init { # with_umask callback
1159 my ($self, $opt) = @_;
1160 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1161 $self->{midx} = PublicInbox::MiscIdx->new($self);
1164 sub symlink_packs ($$) {
1165 my ($ibx, $pd) = @_;
1167 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1168 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1169 my $src = substr($idx, 0, -length('.idx'));
1170 my $dst = $pd . substr($src, rindex($src, '/'));
1171 if (-f "$src.pack" and
1172 symlink("$src.pack", "$dst.pack") and
1173 symlink($idx, "$dst.idx") and
1176 # .promisor, .bitmap, .rev and .keep are optional
1177 # XXX should we symlink .keep here?
1178 for my $s (qw(promisor bitmap rev)) {
1179 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1181 } elsif (!$!{EEXIST}) {
1182 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1183 unlink "$dst.pack", "$dst.idx";
1189 sub idx_init { # similar to V2Writable
1190 my ($self, $opt) = @_;
1191 return if $self->{idx_shards};
1193 $self->git->cleanup;
1195 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1196 my ($has_new, $alt, $seen);
1197 if ($opt->{-private}) { # LeiStore
1198 my $local = "$self->{topdir}/local"; # lei/store
1199 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1200 'ALL.git', 'local');
1203 umask 077; # don't bother restoring for lei
1204 PublicInbox::Import::init_bare($ALL);
1205 $self->git->qx(qw(config core.sharedRepository 0600));
1207 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1208 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1209 } else { # extindex has no epochs
1210 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1212 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1214 PublicInbox::Import::init_bare($ALL);
1217 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1219 my $pd = "$ALL/objects/pack";
1220 if (opendir(my $dh, $pd)) { # drop stale symlinks
1221 while (defined(my $dn = readdir($dh))) {
1222 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1224 unlink($f) if -l $f && !-e $f;
1227 } elsif ($!{ENOENT}) {
1228 mkdir($pd) or die "mkdir($pd): $!";
1230 die "opendir($pd): $!";
1233 for my $ibx (@{ibx_sorted($self, 'active')}) {
1234 # create symlinks for multi-pack-index
1235 $git_midx += symlink_packs($ibx, $pd);
1236 # add new lines to our alternates file
1237 my $d = $ibx->git->{git_dir} . '/objects';
1238 next if exists $alt->{$d};
1239 if (my @st = stat($d)) {
1240 next if $seen->{"$st[0]\0$st[1]"}++;
1242 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1243 next if $opt->{-idx_gc};
1247 ($has_new || $new ne '') and
1248 $self->{mg}->write_alternates($mode, $alt, $new);
1249 $git_midx and $self->with_umask(sub {
1250 my @cmd = ('multi-pack-index');
1251 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1252 my $lk = $self->lock_for_scope;
1253 system('git', "--git-dir=$ALL", @cmd, 'write');
1254 # ignore errors, fairly new command, may not exist
1256 $self->parallel_init($self->{indexlevel});
1257 $self->with_umask(\&_idx_init, $self, $opt);
1258 $self->{oidx}->begin_lazy;
1259 $self->{oidx}->eidx_prep;
1260 $self->{midx}->create_xdb if $new ne '';
1263 sub _watch_commit { # PublicInbox::DS::add_timer callback
1265 delete $self->{-commit_timer};
1266 eidxq_process($self, $self->{-watch_sync});
1267 eidxq_release($self);
1268 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1269 reindex_checkpoint($self, $self->{-watch_sync});
1270 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1272 # call event_step => done unless commit_timer is armed
1273 PublicInbox::DS::requeue($self);
1276 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1277 my ($self, $ibx) = @_;
1278 my $opt = $self->{-watch_sync}->{-opt};
1279 my $pr = $opt->{-progress};
1280 my $ekey = $ibx->eidx_key;
1281 local $0 = "sync $ekey";
1282 $pr->("indexing $ekey\n") if $pr;
1283 $self->idx_init($opt);
1284 sync_inbox($self, $self->{-watch_sync}, $ibx);
1285 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1286 \&_watch_commit, $self);
1289 sub eidx_reload { # -extindex --watch SIGHUP handler
1290 my ($self, $idler) = @_;
1292 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1293 $pr->('reloading ...') if $pr;
1294 delete $self->{-resync_queue};
1295 delete $self->{-ibx_ary_known};
1296 delete $self->{-ibx_ary_active};
1297 $self->{ibx_known} = [];
1298 $self->{ibx_active} = [];
1299 %{$self->{ibx_map}} = ();
1300 delete $self->{-watch_sync}->{id2pos};
1301 my $cfg = PublicInbox::Config->new;
1302 attach_config($self, $cfg);
1303 $idler->refresh($cfg);
1304 $pr->(" done\n") if $pr;
1306 warn "reload not supported without --all\n";
1310 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1312 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1313 PublicInbox::DS::requeue($self); # trigger our ->event_step
1316 sub event_step { # PublicInbox::DS::requeue callback
1318 if (my $resync_queue = $self->{-resync_queue}) {
1319 if (my $ibx = shift(@$resync_queue)) {
1320 on_inbox_unlock($self, $ibx);
1321 PublicInbox::DS::requeue($self);
1323 delete $self->{-resync_queue};
1324 _watch_commit($self);
1327 done($self) unless $self->{-commit_timer};
1331 sub eidx_watch { # public-inbox-extindex --watch main loop
1332 my ($self, $opt) = @_;
1333 local @SIG{keys %SIG} = values %SIG;
1334 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1335 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1337 require PublicInbox::InboxIdle;
1338 require PublicInbox::DS;
1339 require PublicInbox::Syscall;
1340 require PublicInbox::Sigfd;
1341 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1342 if (!$self->{cfg}) {
1343 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1345 for my $ibx (@{ibx_sorted($self, 'active')}) {
1346 $ibx->subscribe_unlock(__PACKAGE__, $self)
1348 my $pr = $opt->{-progress};
1349 $pr->("performing initial scan ...\n") if $pr;
1350 my $sync = eidx_sync($self, $opt); # initial sync
1351 return if $sync->{quit};
1352 my $oldset = PublicInbox::DS::block_signals();
1353 local $self->{current_info} = '';
1354 my $cb = $SIG{__WARN__} || \&CORE::warn;
1355 local $SIG{__WARN__} = sub {
1356 return if PublicInbox::Eml::warn_ignore(@_);
1357 $cb->($self->{current_info}, ': ', @_);
1360 HUP => sub { eidx_reload($self, $idler) },
1361 USR1 => sub { eidx_resync_start($self) },
1362 TSTP => sub { kill('STOP', $$) },
1364 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1365 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1366 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1367 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1368 $pr->("initial scan complete, entering event loop\n") if $pr;
1369 # calls InboxIdle->event_step:
1370 PublicInbox::DS::event_loop($sig, $oldset);
1375 *done = \&PublicInbox::V2Writable::done;
1376 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1377 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1378 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1379 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1380 *index_todo = \&PublicInbox::V2Writable::index_todo;
1381 *count_shards = \&PublicInbox::V2Writable::count_shards;
1382 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1383 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1384 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1385 *checkpoint = \&PublicInbox::V2Writable::checkpoint;