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 $new_smsg = $req->{new_smsg};
124 return if $xr3->[0]->[2] ne pack('H*', $new_smsg->{blob}); # loser
126 # replace the old smsg with the more boosted one
127 $new_smsg->{num} = $smsg->{num};
128 $new_smsg->populate($req->{eml}, $req);
129 $req->{self}->{oidx}->add_overview($req->{eml}, $new_smsg);
133 my ($req, $smsg) = @_;
134 my $self = $req->{self};
135 my $docid = $smsg->{num};
136 my $idx = $self->idx_shard($docid);
137 my $oid = $req->{oid};
138 my $xibx = $req->{ibx};
139 my $eml = $req->{eml};
140 my $eidx_key = $xibx->eidx_key;
141 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
142 my $xnum = $req->{xnum};
143 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
144 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
145 apply_boost($req, $smsg) if $req->{boost_in_use};
148 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
151 $self->{oidx}->eidxq_del($docid);
152 $idx->ipc_do('xdb_remove', $docid);
153 } elsif ($rm_eidx_info) {
154 $idx->ipc_do('remove_eidx_info',
155 $docid, $eidx_key, $eml);
156 $self->{oidx}->eidxq_add($docid); # yes, add
161 # called by V2Writable::sync_prepare
162 sub artnum_max { $_[0]->{oidx}->eidx_max }
164 sub index_unseen ($) {
166 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
167 my $eml = delete $req->{eml};
168 $new_smsg->populate($eml, $req);
169 my $self = $req->{self};
170 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
171 $new_smsg->{num} = $docid;
172 my $idx = $self->idx_shard($docid);
173 $self->{oidx}->add_overview($eml, $new_smsg);
174 my $oid = $new_smsg->{blob};
175 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
176 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
177 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
178 check_batch_limit($req);
181 sub do_finalize ($) {
183 if (my $indexed = $req->{indexed}) { # duplicated messages
184 do_xpost($req, $_) for @$indexed;
185 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
188 # `d' message was already unindexed in the v1/v2 inboxes,
189 # so it's too noisy to warn, here.
191 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
192 if (defined(my $cur_cmt = $req->{cur_cmt})) {
193 ${$req->{latest_cmt}} = $cur_cmt;
197 sub do_step ($) { # main iterator for adding messages to the index
199 my $self = $req->{self} // die 'BUG: {self} missing';
201 if (my $next_arg = $req->{next_arg}) {
202 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
203 $req->{cur_smsg} = $smsg;
204 $self->git->cat_async($smsg->{blob},
205 \&ck_existing, $req);
206 return; # ck_existing calls do_step
208 delete $req->{next_arg};
210 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
211 my $mid = shift(@{$req->{mids}}) // last;
213 $req->{next_arg} = [ $mid, \$id, \$prev ];
219 sub _blob_missing ($$) { # called when $smsg->{blob} is bad
220 my ($req, $smsg) = @_;
221 my $self = $req->{self};
222 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
223 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
225 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
226 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
227 die "BUG: xref $keep[0] has no OID";
229 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
230 $self->{oidx}->update_blob($smsg, $oidhex) or warn <<EOM;
231 E: #$smsg->{num} gone ($smsg->{blob} => $oidhex)
234 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
235 $self->{oidx}->delete_by_num($smsg->{num});
239 sub ck_existing { # git->cat_async callback
240 my ($bref, $oid, $type, $size, $req) = @_;
241 my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
242 if ($type eq 'missing') {
243 _blob_missing($req, $smsg);
244 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
245 my $self = $req->{self} // die 'BUG: {self} missing';
246 local $self->{current_info} = "$self->{current_info} $oid";
247 my $cur = PublicInbox::Eml->new($bref);
248 if (content_hash($cur) eq $req->{chash}) {
249 push @{$req->{indexed}}, $smsg; # for do_xpost
250 } # else { index_unseen later }
255 # is the messages visible in the inbox currently being indexed?
256 # return the number if so
257 sub cur_ibx_xnum ($$) {
258 my ($req, $bref) = @_;
259 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
261 $req->{eml} = PublicInbox::Eml->new($bref);
262 $req->{chash} = content_hash($req->{eml});
263 $req->{mids} = mids($req->{eml});
264 for my $mid (@{$req->{mids}}) {
266 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
267 return $x->{num} if $x->{blob} eq $req->{oid};
273 sub index_oid { # git->cat_async callback for 'm'
274 my ($bref, $oid, $type, $size, $req) = @_;
275 my $self = $req->{self};
276 local $self->{current_info} = "$self->{current_info} $oid";
277 return if is_bad_blob($oid, $type, $size, $req->{oid});
278 my $new_smsg = $req->{new_smsg} = bless {
280 }, 'PublicInbox::Smsg';
281 $new_smsg->set_bytes($$bref, $size);
282 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
287 sub unindex_oid { # git->cat_async callback for 'd'
288 my ($bref, $oid, $type, $size, $req) = @_;
289 my $self = $req->{self};
290 local $self->{current_info} = "$self->{current_info} $oid";
291 return if is_bad_blob($oid, $type, $size, $req->{oid});
292 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
296 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
298 my ($self, $sync) = @_;
300 my $ekey = $sync->{ibx}->eidx_key;
301 my $uv = $sync->{ibx}->uidvalidity;
302 for my $i (0..$sync->{epoch_max}) {
303 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
308 sub _ibx_index_reject ($) {
310 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
311 $ibx->uidvalidity // return 'no UIDVALIDITY';
312 $ibx->over // return 'unindexed, no over.sqlite3';
316 sub _sync_inbox ($$$) {
317 my ($self, $sync, $ibx) = @_;
318 my $ekey = $ibx->eidx_key;
319 if (defined(my $err = _ibx_index_reject($ibx))) {
320 return "W: skipping $ekey ($err)";
323 $sync->{nr} = \(my $nr = 0);
324 my $v = $ibx->version;
326 $sync->{epoch_max} = $ibx->max_git_epoch // return;
327 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
329 my $uv = $ibx->uidvalidity;
330 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
331 my $head = $ibx->mm->last_commit //
332 return "E: $ibx->{inboxdir} is not indexed";
333 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
334 my $unit = { stack => $stk, git => $ibx->git };
335 push @{$sync->{todo}}, $unit;
337 return "E: $ekey unsupported inbox version (v$v)";
339 for my $unit (@{delete($sync->{todo}) // []}) {
340 last if $sync->{quit};
341 index_todo($self, $sync, $unit);
343 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
344 $ibx->git->cleanup; # done with this inbox, now
348 sub gc_unref_doc ($$$$) {
349 my ($self, $ibx_id, $eidx_key, $docid) = @_;
351 # for debug/info purposes, oids may no longer be accessible
352 my $dbh = $self->{oidx}->dbh;
353 my $sth = $dbh->prepare_cached(<<'', undef, 1);
354 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
356 $sth->execute($docid, $ibx_id);
357 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
359 $remain += $self->{oidx}->remove_xref3($docid, $oid, $eidx_key);
362 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
364 warn "I: unref #$docid $eidx_key $oid\n";
367 warn "I: remove #$docid $eidx_key @oid\n";
368 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
372 sub eidx_gc_scan_inboxes ($$) {
373 my ($self, $sync) = @_;
374 my ($x3_doc, $ibx_ck);
376 $x3_doc = $self->{oidx}->dbh->prepare(<<EOM);
377 SELECT docid FROM xref3 WHERE ibx_id = ?
379 $ibx_ck = $self->{oidx}->dbh->prepare(<<EOM);
380 SELECT ibx_id,eidx_key FROM inboxes
383 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
384 next if $self->{ibx_map}->{$eidx_key};
385 $self->{midx}->remove_eidx_key($eidx_key);
386 warn "I: deleting messages for $eidx_key...\n";
387 $x3_doc->execute($ibx_id);
388 while (defined(my $docid = $x3_doc->fetchrow_array)) {
389 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
390 if (checkpoint_due($sync)) {
391 $x3_doc = $ibx_ck = undef;
392 reindex_checkpoint($self, $sync);
396 $self->{oidx}->dbh->do(<<'', undef, $ibx_id);
397 DELETE FROM inboxes WHERE ibx_id = ?
399 # drop last_commit info
401 $pat =~ s/([_%\\])/\\$1/g;
402 $self->{oidx}->dbh->do('PRAGMA case_sensitive_like = ON');
403 my $lc_i = $self->{oidx}->dbh->prepare(<<'');
404 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
406 $lc_i->execute("lc-%:$pat//%", '\\');
407 while (my ($key) = $lc_i->fetchrow_array) {
408 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
409 warn "I: removing $key\n";
410 $self->{oidx}->dbh->do(<<'', undef, $key);
411 DELETE FROM eidx_meta WHERE key = ?
414 warn "I: $eidx_key removed\n";
418 sub eidx_gc_scan_shards ($$) { # TODO: use for lei/store
419 my ($self, $sync) = @_;
420 my $nr = $self->{oidx}->dbh->do(<<'');
421 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
423 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
424 reindex_checkpoint($self, $sync) if checkpoint_due($sync);
426 # fixup from old bugs:
427 $nr = $self->{oidx}->dbh->do(<<'');
428 DELETE FROM over WHERE num > 0 AND num NOT IN (SELECT docid FROM xref3)
430 warn "I: eliminated $nr stale over entries\n" if $nr != 0;
431 reindex_checkpoint($self, $sync) if checkpoint_due($sync);
433 my ($cur) = $self->{oidx}->dbh->selectrow_array(<<EOM);
434 SELECT MIN(num) FROM over WHERE num > 0
436 $cur // return; # empty
437 my ($r, $n, %active_shards);
440 $r = $self->{oidx}->dbh->selectcol_arrayref(<<"", undef, $cur);
441 SELECT num FROM over WHERE num >= ? ORDER BY num ASC LIMIT 10000
443 last unless scalar(@$r);
444 while (defined($n = shift @$r)) {
445 for my $i ($cur..($n - 1)) {
446 my $idx = idx_shard($self, $i);
447 $idx->ipc_do('xdb_remove_quiet', $i);
448 $active_shards{$idx} = $idx;
452 if (checkpoint_due($sync)) {
453 for my $idx (values %active_shards) {
454 $nr += $idx->ipc_do('nr_quiet_rm')
457 reindex_checkpoint($self, $sync);
460 warn "I: eliminated $nr stale Xapian documents\n" if $nr != 0;
464 my ($self, $opt) = @_;
465 $self->{cfg} or die "E: GC requires ->attach_config\n";
468 need_checkpoint => \(my $need_checkpoint = 0),
470 next_check => now() + 10,
471 checkpoint_unlocks => 1,
474 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
475 eidx_gc_scan_inboxes($self, $sync);
476 eidx_gc_scan_shards($self, $sync);
481 my ($self, $sync, $smsg) = @_;
482 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
483 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
484 $self->{-ibx_ary_known}->[$pos] //
485 die "BUG: ibx for $smsg->{blob} not mapped"
488 sub _fd_constrained ($) {
490 $self->{-fd_constrained} //= do {
492 if (eval { require BSD::Resource; 1 }) {
493 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
494 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
496 chomp($soft = `sh -c 'ulimit -n'`);
498 if (defined($soft)) {
499 # $want is an estimate
500 my $want = scalar(@{$self->{ibx_active}}) + 64;
501 my $ret = $want > $soft;
504 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
509 warn "Unable to determine RLIMIT_NOFILE: $@\n";
515 sub _reindex_finalize ($$$) {
516 my ($req, $smsg, $eml) = @_;
517 my $sync = $req->{sync};
518 my $self = $sync->{self};
519 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
520 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
521 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
522 my $docid = $smsg->{num} = $orig_smsg->{num};
523 $self->{oidx}->add_overview($eml, $smsg); # may rethread
524 check_batch_limit({ %$sync, new_smsg => $smsg });
525 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
526 my $stable = delete($by_chash->{$chash0}) //
527 die "BUG: $smsg->{blob} chash missing";
528 my $idx = $self->idx_shard($docid);
529 my $top_smsg = pop @$stable;
530 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
531 my $ibx = _ibx_for($self, $sync, $smsg);
532 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
533 for my $x (reverse @$stable) {
534 $ibx = _ibx_for($self, $sync, $x);
535 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
536 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
538 return if $nr == 1; # likely, all good
540 warn "W: #$docid split into $nr due to deduplication change\n";
542 for my $ary (values %$by_chash) {
543 for my $x (reverse @$ary) {
544 warn "removing #$docid xref3 $x->{blob}\n";
545 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
546 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
548 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
549 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
550 $ibx = _ibx_for($self, $sync, $x);
551 if (my $over = $ibx->over) {
552 my $e = $over->get_art($x->{num});
553 $e->{blob} eq $x->{blob} or die <<EOF;
554 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
556 push @todo, $ibx, $e;
557 $over->dbh_close if _fd_constrained($self);
559 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
563 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
564 reindex_unseen($self, $sync, $ibx, $e);
568 sub _reindex_oid { # git->cat_async callback
569 my ($bref, $oid, $type, $size, $req) = @_;
570 my $sync = $req->{sync};
571 my $self = $sync->{self};
572 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
573 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
574 my $docid = $orig_smsg->{num};
575 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
576 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
578 warn "W: #$docid gone or corrupted\n";
579 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
580 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
581 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
583 warn "BUG: #$docid gone (UNEXPECTED)\n";
584 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
588 my $ci = $self->{current_info};
589 local $self->{current_info} = "$ci #$docid $oid";
590 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
591 $re_smsg->set_bytes($$bref, $size);
592 my $eml = PublicInbox::Eml->new($bref);
593 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
594 cotime => $orig_smsg->{ts} });
595 my $chash = content_hash($eml);
596 $re_smsg->{chash} = $chash;
597 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
598 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
599 $re_smsg->{hdr} = $eml->header_obj;
600 push @{$req->{by_chash}->{$chash}}, $re_smsg;
601 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
602 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
603 } else { # last $re_smsg is the highest priority xref3
604 local $self->{current_info} = "$ci #$docid";
605 _reindex_finalize($req, $re_smsg, $eml);
609 sub _reindex_smsg ($$$) {
610 my ($self, $sync, $smsg) = @_;
611 my $docid = $smsg->{num};
612 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
613 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
615 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
617 $self->{oidx}->delete_by_num($docid);
618 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
622 # we sort {xr3r} in the reverse order of ibx_sorted so we can
623 # hit the common case in _reindex_finalize without rereading
624 # from git (or holding multiple messages in memory).
625 my $id2pos = $sync->{id2pos}; # index in ibx_sorted
627 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
629 $b->[1] <=> $a->[1] # break ties with {xnum}
631 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
632 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
633 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
636 sub checkpoint_due ($) {
638 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
642 # I've copied FS images and only changed the hostname before,
643 # so prepend hostname. Use `state' since these a BOFH can change
644 # these while this process is running and we always want to be
645 # able to release locks taken by this process.
646 state $retval = hostname . '-' . do {
647 my $m; # machine-id(5) is systemd
648 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
649 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
650 chomp($m ||= `{ sysctl -n kern.hostid ||
651 hostid || ghostid; } 2>/dev/null`
652 || "no-machine-id-or-hostid-on-$^O");
659 my $expect = delete($self->{-eidxq_locked}) or return;
660 my ($owner_pid, undef) = split(/-/, $expect);
661 return if $owner_pid != $$; # shards may fork
662 my $oidx = $self->{oidx};
664 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
665 if ($cur eq $expect) {
666 $oidx->eidx_meta('eidxq_lock', '');
668 } elsif ($cur ne '') {
669 warn "E: eidxq_lock($expect) stolen by $cur\n";
671 warn "E: eidxq_lock($expect) released by another process\n";
678 eidxq_release($self) and $self->{oidx}->commit_lazy;
681 sub _eidxq_take ($) {
683 my $val = "$$-${\time}-$>-".host_ident;
684 $self->{oidx}->eidx_meta('eidxq_lock', $val);
685 $self->{-eidxq_locked} = $val;
688 sub eidxq_lock_acquire ($) {
690 my $oidx = $self->{oidx};
692 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
693 if (my $locked = $self->{-eidxq_locked}) { # be lazy
694 return $locked if $locked eq $cur;
696 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
697 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
698 if ($euid == $> && $ident eq host_ident) {
701 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
705 warn "I: eidxq_lock is stale ($cur), clobbering\n";
706 return _eidxq_take($self);
708 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
710 my $fn = $oidx->dbh->sqlite_db_filename;
712 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
713 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
714 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
719 sub ibx_sorted ($$) {
720 my ($self, $type) = @_;
721 $self->{"-ibx_ary_$type"} //= do {
722 # highest boost first, stable for config-ordering tiebreaker
725 ($b->{boost} // 0) <=> ($a->{boost} // 0)
726 } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
730 sub prep_id2pos ($) {
734 $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
738 sub eidxq_process ($$) { # for reindexing
739 my ($self, $sync) = @_;
740 return unless $self->{cfg};
742 return unless eidxq_lock_acquire($self);
743 my $dbh = $self->{oidx}->dbh;
744 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
746 local $sync->{-regen_fmt} = "%u/$tot\n";
747 my $pr = $sync->{-opt}->{-progress};
749 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
750 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
751 $pr->("Xapian indexing $min..$max (total=$tot)\n");
753 $sync->{id2pos} //= prep_id2pos($self);
756 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
757 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
759 while (defined(my $docid = $iter->fetchrow_array)) {
760 last if $sync->{quit};
761 if (my $smsg = $self->{oidx}->get_art($docid)) {
762 _reindex_smsg($self, $sync, $smsg);
764 warn "E: #$docid does not exist in over\n";
766 $del->execute($docid);
769 if (checkpoint_due($sync)) {
770 $dbh = $del = $iter = undef;
771 reindex_checkpoint($self, $sync); # release lock
772 $dbh = $self->{oidx}->dbh;
776 $self->git->async_wait_all;
777 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
780 sub _reindex_unseen { # git->cat_async callback
781 my ($bref, $oid, $type, $size, $req) = @_;
782 return if is_bad_blob($oid, $type, $size, $req->{oid});
783 my $self = $req->{self} // die 'BUG: {self} unset';
784 local $self->{current_info} = "$self->{current_info} $oid";
785 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
786 $new_smsg->set_bytes($$bref, $size);
787 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
788 $req->{new_smsg} = $new_smsg;
789 $req->{chash} = content_hash($eml);
790 $req->{mids} = mids($eml); # do_step iterates through this
791 do_step($req); # enter the normal indexing flow
794 # --reindex may catch totally unseen messages, this handles them
795 sub reindex_unseen ($$$$) {
796 my ($self, $sync, $ibx, $xsmsg) = @_;
799 autime => $xsmsg->{ds},
800 cotime => $xsmsg->{ts},
801 oid => $xsmsg->{blob},
803 xnum => $xsmsg->{num},
804 # {mids} and {chash} will be filled in at _reindex_unseen
806 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
807 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
810 sub _unref_stale ($$$$$) {
811 my ($sync, $docid, $ibx, $xnum, $oidbin) = @_;
812 my $del = $sync->{self}->{oidx}->dbh->prepare_cached(<<'');
813 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
815 $del->bind_param(1, $ibx->{-ibx_id});
816 $del->bind_param(2, $xnum);
817 $del->bind_param(3, $oidbin, SQL_BLOB);
819 my $xr3 = $sync->{self}->{oidx}->get_xref3($docid, 1);
820 my $idx = $sync->{self}->idx_shard($docid);
821 if (scalar(@$xr3) == 0) { # all gone
822 $sync->{self}->{oidx}->delete_by_num($docid);
823 $sync->{self}->{oidx}->eidxq_del($docid);
824 $idx->ipc_do('xdb_remove', $docid);
825 } else { # enqueue for reindex of remaining messages
826 $idx->ipc_do('remove_eidx_info', $docid, $ibx->eidx_key);
827 $sync->{self}->{oidx}->eidxq_add($docid); # yes, add
831 sub _unref_stale_range ($$$) {
832 my ($sync, $ibx, $lt_or_gt) = @_;
836 $r = $sync->{self}->{oidx}->dbh->selectall_arrayref(
837 <<EOS, undef, $ibx->{-ibx_id});
838 SELECT docid,xnum,oidbin FROM xref3
839 WHERE ibx_id = ? AND xnum $lt_or_gt LIMIT $lim
841 return if $sync->{quit};
842 for (@$r) { # hopefully rare, not worth optimizing:
843 my ($docid, $xnum, $oidbin) = @$_;
844 my $hex = unpack('H*', $oidbin);
845 warn("# $xnum:$hex (#$docid): stale\n");
846 _unref_stale($sync, $docid, $ibx, $xnum, $oidbin);
848 } while (scalar(@$r) == $lim);
852 sub _reindex_check_ibx ($$$) {
853 my ($self, $sync, $ibx) = @_;
854 my $ibx_id = $ibx->{-ibx_id};
856 my $opt = { limit => $slice };
857 my ($beg, $end) = (1, $slice);
858 my $err = sync_inbox($self, $sync, $ibx) and return;
859 my $max = $ibx->over->max;
860 $end = $max if $end > $max;
862 # first, check if we missed any messages in target $ibx
864 my $pr = $sync->{-opt}->{-progress};
865 my $ekey = $ibx->eidx_key;
866 local $sync->{-regen_fmt} = "$ekey checking %u/$max\n";
868 my $fast = $sync->{-opt}->{fast};
869 my $dsu; # _unref_stale_range (< $lo) called
871 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end, $opt)})) {
872 ${$sync->{nr}} = $beg;
873 $beg = $msgs->[-1]->{num} + 1;
874 $end = $beg + $slice;
875 $end = $max if $end > $max;
876 if (checkpoint_due($sync)) {
877 reindex_checkpoint($self, $sync); # release lock
879 ($lo, $hi) = ($msgs->[0]->{num}, $msgs->[-1]->{num});
880 $dsu //= _unref_stale_range($sync, $ibx, "< $lo");
881 my $x3a = $self->{oidx}->dbh->selectall_arrayref(
882 <<"", undef, $ibx_id, $lo, $hi);
883 SELECT xnum,oidbin,docid FROM xref3 WHERE
884 ibx_id = ? AND xnum >= ? AND xnum <= ?
888 my $k = pack('J', $_->[0]) . $_->[1];
889 push @{$x3m{$k}}, $_->[2];
892 for my $xsmsg (@$msgs) {
893 my $k = pack('JH*', $xsmsg->{num}, $xsmsg->{blob});
894 my $docids = delete($x3m{$k});
895 if (!defined($docids)) {
896 reindex_unseen($self, $sync, $ibx, $xsmsg);
898 for my $num (@$docids) {
899 $self->{oidx}->eidxq_add($num);
901 return if $sync->{quit};
904 return if $sync->{quit};
905 next unless scalar keys %x3m;
907 # eliminate stale/mismatched entries
908 my %mismatch = map { $_->{num} => $_->{blob} } @$msgs;
909 while (my ($k, $docids) = each %x3m) {
910 my ($xnum, $hex) = unpack('JH*', $k);
911 my $bin = pack('H*', $hex);
912 my $exp = $mismatch{$xnum};
913 my $m = defined($exp) ? "mismatch (!= $exp)" : 'stale';
914 warn("# $xnum:$hex (#@$docids): $m\n");
915 for my $i (@$docids) {
916 _unref_stale($sync, $i, $ibx, $xnum, $bin);
920 _unref_stale_range($sync, $ibx, "> $hi") if defined($hi);
923 sub _reindex_inbox ($$$) {
924 my ($self, $sync, $ibx) = @_;
925 my $ekey = $ibx->eidx_key;
926 local $self->{current_info} = $ekey;
927 if (defined(my $err = _ibx_index_reject($ibx))) {
928 warn "W: cannot reindex $ekey ($err)\n";
930 _reindex_check_ibx($self, $sync, $ibx);
932 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
936 my ($self, $sync) = @_;
937 return unless $self->{cfg};
939 # acquire eidxq_lock early because full reindex takes forever
940 # and incremental -extindex processes can run during our checkpoints
941 if (!eidxq_lock_acquire($self)) {
942 warn "E: aborting --reindex\n";
945 for my $ibx (@{ibx_sorted($self, 'active')}) {
946 _reindex_inbox($self, $sync, $ibx);
947 last if $sync->{quit};
949 $self->git->async_wait_all; # ensure eidxq gets filled completely
950 eidxq_process($self, $sync) unless $sync->{quit};
954 my ($self, $sync, $ibx) = @_;
955 my $err = _sync_inbox($self, $sync, $ibx);
956 delete @$ibx{qw(mm over)};
957 warn $err, "\n" if defined($err);
961 sub dd_smsg { # git->cat_async callback
962 my ($bref, $oid, $type, $size, $dd) = @_;
963 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
964 my $self = $dd->{self} // die 'BUG: {self} missing';
965 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
966 if ($type eq 'missing') {
967 _blob_missing($dd, $smsg);
968 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
969 local $self->{current_info} = "$self->{current_info} $oid";
970 my $chash = content_hash(PublicInbox::Eml->new($bref));
971 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
973 return if $per_mid->{last_smsg} != $smsg;
974 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
975 my $keep = shift @$ary;
976 next if !scalar(@$ary);
977 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
979 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
980 join(', ', map { "#$_->{num}" } @$ary),"\n";
981 next if $per_mid->{sync}->{-opt}->{'dry-run'};
982 my $oidx = $self->{oidx};
983 for my $smsg (@$ary) {
984 my $gone = $smsg->{num};
985 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
986 $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
987 $oidx->delete_by_num($gone);
992 sub eidx_dedupe ($$$) {
993 my ($self, $sync, $msgids) = @_;
994 $sync->{dedupe_cull} = 0;
997 return unless eidxq_lock_acquire($self);
998 my ($iter, $cur_mid);
1001 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
1002 SELECT MAX(id) FROM msgid
1004 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
1006 # note: we could write this query more intelligently,
1007 # but that causes lock contention with read-only processes
1009 $cur_mid = $msgids->[$idx];
1010 if ($cur_mid eq '') { # all Message-IDs
1011 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1012 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
1014 $iter->execute($min_id);
1016 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1017 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
1019 $iter->execute($cur_mid, $min_id);
1021 while (my ($mid, $id) = $iter->fetchrow_array) {
1022 last if $sync->{quit};
1023 $self->{current_info} = "dedupe $mid";
1024 ${$sync->{nr}} = $min_id = $id;
1026 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
1029 next if scalar(@smsg) < 2;
1031 dd_chash => {}, # chash => [ary of smsgs]
1032 last_smsg => $smsg[-1],
1036 $candidates += scalar(@smsg) - 1;
1037 for my $smsg (@smsg) {
1039 per_mid => $per_mid,
1043 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
1045 # need to wait on every single one @smsg contents can get
1046 # invalidated inside dd_smsg for messages with multiple
1048 $self->git->async_wait_all;
1050 if (checkpoint_due($sync)) {
1052 reindex_checkpoint($self, $sync);
1053 goto dedupe_restart;
1056 goto dedupe_restart if defined($msgids->[++$idx]);
1058 my $n = delete $sync->{dedupe_cull};
1059 if (my $pr = $sync->{-opt}->{-progress}) {
1060 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1065 sub eidx_sync { # main entry point
1066 my ($self, $opt) = @_;
1068 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1069 local $self->{current_info} = '';
1070 local $SIG{__WARN__} = sub {
1071 return if PublicInbox::Eml::warn_ignore(@_);
1072 $warn_cb->($self->{current_info}, ': ', @_);
1074 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1075 $self->{oidx}->rethread_prepare($opt);
1077 need_checkpoint => \(my $need_checkpoint = 0),
1079 next_check => now() + 10,
1081 # DO NOT SET {reindex} here, it's incompatible with reused
1082 # V2Writable code, reindex is totally different here
1083 # compared to v1/v2 inboxes because we have multiple histories
1085 -regen_fmt => "%u/?\n",
1087 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1088 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1089 local $SIG{QUIT} = $quit;
1090 local $SIG{INT} = $quit;
1091 local $SIG{TERM} = $quit;
1092 for my $ibx (@{ibx_sorted($self, 'known')}) {
1093 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1096 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1097 $sync->{id2pos} //= prep_id2pos($self);
1098 $sync->{boost_in_use} = 1;
1101 if (my $msgids = delete($opt->{dedupe})) {
1102 local $sync->{checkpoint_unlocks} = 1;
1103 eidx_dedupe($self, $sync, $msgids);
1105 if (delete($opt->{reindex})) {
1106 local $sync->{checkpoint_unlocks} = 1;
1107 eidx_reindex($self, $sync);
1110 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1111 if ($opt->{scan} // 1) {
1112 for my $ibx (@{ibx_sorted($self, 'active')}) {
1113 last if $sync->{quit};
1114 sync_inbox($self, $sync, $ibx);
1117 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1118 eidxq_process($self, $sync) unless $sync->{quit};
1120 eidxq_release($self);
1122 $sync; # for eidx_watch
1125 sub update_last_commit { # overrides V2Writable
1126 my ($self, $sync, $stk) = @_;
1127 my $unit = $sync->{unit} // return;
1128 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1129 defined($latest_cmt) or return;
1130 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1131 my $ekey = $ibx->eidx_key;
1132 my $uv = $ibx->uidvalidity;
1133 my $epoch = $unit->{epoch};
1135 my $v = $ibx->version;
1137 die 'No {epoch} for v2 unit' unless defined $epoch;
1138 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1140 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1141 $meta_key = "lc-v1:$ekey//$uv";
1143 die "Unsupported inbox version: $v";
1145 my $last = $self->{oidx}->eidx_meta($meta_key);
1146 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1147 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1148 chomp(my $n = $unit->{git}->qx(@cmd));
1149 return if $n ne '' && $n == 0;
1151 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1154 sub _idx_init { # with_umask callback
1155 my ($self, $opt) = @_;
1156 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1157 $self->{midx} = PublicInbox::MiscIdx->new($self);
1160 sub symlink_packs ($$) {
1161 my ($ibx, $pd) = @_;
1163 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1164 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1165 my $src = substr($idx, 0, -length('.idx'));
1166 my $dst = $pd . substr($src, rindex($src, '/'));
1167 if (-f "$src.pack" and
1168 symlink("$src.pack", "$dst.pack") and
1169 symlink($idx, "$dst.idx") and
1172 # .promisor, .bitmap, .rev and .keep are optional
1173 # XXX should we symlink .keep here?
1174 for my $s (qw(promisor bitmap rev)) {
1175 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1177 } elsif (!$!{EEXIST}) {
1178 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1179 unlink "$dst.pack", "$dst.idx";
1185 sub idx_init { # similar to V2Writable
1186 my ($self, $opt) = @_;
1187 return if $self->{idx_shards};
1189 $self->git->cleanup;
1191 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1192 my ($has_new, $alt, $seen);
1193 if ($opt->{-private}) { # LeiStore
1194 my $local = "$self->{topdir}/local"; # lei/store
1195 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1196 'ALL.git', 'local');
1199 umask 077; # don't bother restoring for lei
1200 PublicInbox::Import::init_bare($ALL);
1201 $self->git->qx(qw(config core.sharedRepository 0600));
1203 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1204 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1205 } else { # extindex has no epochs
1206 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1208 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1210 PublicInbox::Import::init_bare($ALL);
1213 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1215 my $pd = "$ALL/objects/pack";
1216 if (opendir(my $dh, $pd)) { # drop stale symlinks
1217 while (defined(my $dn = readdir($dh))) {
1218 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1220 unlink($f) if -l $f && !-e $f;
1223 } elsif ($!{ENOENT}) {
1224 mkdir($pd) or die "mkdir($pd): $!";
1226 die "opendir($pd): $!";
1229 for my $ibx (@{ibx_sorted($self, 'active')}) {
1230 # create symlinks for multi-pack-index
1231 $git_midx += symlink_packs($ibx, $pd);
1232 # add new lines to our alternates file
1233 my $d = $ibx->git->{git_dir} . '/objects';
1234 next if exists $alt->{$d};
1235 if (my @st = stat($d)) {
1236 next if $seen->{"$st[0]\0$st[1]"}++;
1238 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1239 next if $opt->{-idx_gc};
1243 ($has_new || $new ne '') and
1244 $self->{mg}->write_alternates($mode, $alt, $new);
1245 $git_midx and $self->with_umask(sub {
1246 my @cmd = ('multi-pack-index');
1247 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1248 my $lk = $self->lock_for_scope;
1249 system('git', "--git-dir=$ALL", @cmd, 'write');
1250 # ignore errors, fairly new command, may not exist
1252 $self->parallel_init($self->{indexlevel});
1253 $self->with_umask(\&_idx_init, $self, $opt);
1254 $self->{oidx}->begin_lazy;
1255 $self->{oidx}->eidx_prep;
1256 $self->{midx}->create_xdb if $new ne '';
1259 sub _watch_commit { # PublicInbox::DS::add_timer callback
1261 delete $self->{-commit_timer};
1262 eidxq_process($self, $self->{-watch_sync});
1263 eidxq_release($self);
1264 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1265 reindex_checkpoint($self, $self->{-watch_sync});
1266 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1268 # call event_step => done unless commit_timer is armed
1269 PublicInbox::DS::requeue($self);
1272 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1273 my ($self, $ibx) = @_;
1274 my $opt = $self->{-watch_sync}->{-opt};
1275 my $pr = $opt->{-progress};
1276 my $ekey = $ibx->eidx_key;
1277 local $0 = "sync $ekey";
1278 $pr->("indexing $ekey\n") if $pr;
1279 $self->idx_init($opt);
1280 sync_inbox($self, $self->{-watch_sync}, $ibx);
1281 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1282 \&_watch_commit, $self);
1285 sub eidx_reload { # -extindex --watch SIGHUP handler
1286 my ($self, $idler) = @_;
1288 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1289 $pr->('reloading ...') if $pr;
1290 delete $self->{-resync_queue};
1291 delete $self->{-ibx_ary_known};
1292 delete $self->{-ibx_ary_active};
1293 $self->{ibx_known} = [];
1294 $self->{ibx_active} = [];
1295 %{$self->{ibx_map}} = ();
1296 delete $self->{-watch_sync}->{id2pos};
1297 my $cfg = PublicInbox::Config->new;
1298 attach_config($self, $cfg);
1299 $idler->refresh($cfg);
1300 $pr->(" done\n") if $pr;
1302 warn "reload not supported without --all\n";
1306 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1308 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1309 PublicInbox::DS::requeue($self); # trigger our ->event_step
1312 sub event_step { # PublicInbox::DS::requeue callback
1314 if (my $resync_queue = $self->{-resync_queue}) {
1315 if (my $ibx = shift(@$resync_queue)) {
1316 on_inbox_unlock($self, $ibx);
1317 PublicInbox::DS::requeue($self);
1319 delete $self->{-resync_queue};
1320 _watch_commit($self);
1323 done($self) unless $self->{-commit_timer};
1327 sub eidx_watch { # public-inbox-extindex --watch main loop
1328 my ($self, $opt) = @_;
1329 local @SIG{keys %SIG} = values %SIG;
1330 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1331 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1333 require PublicInbox::InboxIdle;
1334 require PublicInbox::DS;
1335 require PublicInbox::Syscall;
1336 require PublicInbox::Sigfd;
1337 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1338 if (!$self->{cfg}) {
1339 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1341 for my $ibx (@{ibx_sorted($self, 'active')}) {
1342 $ibx->subscribe_unlock(__PACKAGE__, $self)
1344 my $pr = $opt->{-progress};
1345 $pr->("performing initial scan ...\n") if $pr;
1346 my $sync = eidx_sync($self, $opt); # initial sync
1347 return if $sync->{quit};
1348 my $oldset = PublicInbox::DS::block_signals();
1349 local $self->{current_info} = '';
1350 my $cb = $SIG{__WARN__} || \&CORE::warn;
1351 local $SIG{__WARN__} = sub {
1352 return if PublicInbox::Eml::warn_ignore(@_);
1353 $cb->($self->{current_info}, ': ', @_);
1356 HUP => sub { eidx_reload($self, $idler) },
1357 USR1 => sub { eidx_resync_start($self) },
1358 TSTP => sub { kill('STOP', $$) },
1360 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1361 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1362 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1363 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1364 $pr->("initial scan complete, entering event loop\n") if $pr;
1365 # calls InboxIdle->event_step:
1366 PublicInbox::DS::event_loop($sig, $oldset);
1371 *done = \&PublicInbox::V2Writable::done;
1372 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1373 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1374 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1375 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1376 *index_todo = \&PublicInbox::V2Writable::index_todo;
1377 *count_shards = \&PublicInbox::V2Writable::count_shards;
1378 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1379 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1380 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1381 *checkpoint = \&PublicInbox::V2Writable::checkpoint;