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 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
436 $cur // return; # empty
437 my ($r, $n, %active);
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{$idx} = $idx;
452 if (checkpoint_due($sync)) {
453 for my $idx (values %active) {
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 _reindex_check_unseen ($$$) {
811 my ($self, $sync, $ibx) = @_;
812 my $ibx_id = $ibx->{-ibx_id};
814 my ($beg, $end) = (1, $slice);
816 # first, check if we missed any messages in target $ibx
818 my $pr = $sync->{-opt}->{-progress};
819 my $ekey = $ibx->eidx_key;
820 local $sync->{-regen_fmt} =
821 "$ekey checking unseen %u/".$ibx->over->max."\n";
823 my $fast = $sync->{-opt}->{fast};
824 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
825 ${$sync->{nr}} = $beg;
826 $beg = $msgs->[-1]->{num} + 1;
827 $end = $beg + $slice;
828 if (checkpoint_due($sync)) {
829 reindex_checkpoint($self, $sync); # release lock
832 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
833 SELECT DISTINCT(docid) FROM xref3 WHERE
834 ibx_id = ? AND xnum = ? AND oidbin = ?
836 for my $xsmsg (@$msgs) {
837 my $oidbin = pack('H*', $xsmsg->{blob});
838 $inx3->bind_param(1, $ibx_id);
839 $inx3->bind_param(2, $xsmsg->{num});
840 $inx3->bind_param(3, $oidbin, SQL_BLOB);
842 my $docids = $inx3->fetchall_arrayref;
843 # index messages which were totally missed
844 # the first time around ASAP:
845 if (scalar(@$docids) == 0) {
846 reindex_unseen($self, $sync, $ibx, $xsmsg);
847 } elsif (!$fast) { # already seen, reindex later
848 for my $r (@$docids) {
849 $self->{oidx}->eidxq_add($r->[0]);
852 last if $sync->{quit};
854 last if $sync->{quit};
858 sub _reindex_check_stale ($$$) {
859 my ($self, $sync, $ibx) = @_;
861 my $pr = $sync->{-opt}->{-progress};
863 my $ekey = $ibx->eidx_key;
864 local $sync->{-regen_fmt} =
865 "$ekey checking stale/missing %u/".$ibx->over->max."\n";
868 if (checkpoint_due($sync)) {
869 reindex_checkpoint($self, $sync); # release lock
871 # now, check if there's stale xrefs
872 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
873 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
874 ORDER BY docid,xnum ASC LIMIT 10000
876 $iter->execute($ibx->{-ibx_id}, $min);
879 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
880 return if $sync->{quit};
881 ${$sync->{nr}} = $xnum;
883 $fetching = $min = $docid;
884 my $smsg = $ibx->over->get_art($xnum);
888 } elsif (pack('H*', $smsg->{blob}) ne $oidbin) {
889 $err = "mismatch (!= $smsg->{blob})";
891 next; # likely, all good
893 # current_info already has eidx_key
894 my $oidhex = unpack('H*', $oidbin);
895 warn "$xnum:$oidhex (#$docid): $err\n";
896 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
897 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
899 $del->bind_param(1, $ibx->{-ibx_id});
900 $del->bind_param(2, $xnum);
901 $del->bind_param(3, $oidbin, SQL_BLOB);
904 # get_xref3 over-fetches, but this is a rare path:
905 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
906 my $idx = $self->idx_shard($docid);
907 if (scalar(@$xr3) == 0) { # all gone
908 $self->{oidx}->delete_by_num($docid);
909 $self->{oidx}->eidxq_del($docid);
910 $idx->ipc_do('xdb_remove', $docid);
911 } else { # enqueue for reindex of remaining messages
912 $idx->ipc_do('remove_eidx_info', $docid, $ekey);
913 $self->{oidx}->eidxq_add($docid); # yes, add
916 } while (defined $fetching);
919 sub _reindex_inbox ($$$) {
920 my ($self, $sync, $ibx) = @_;
921 my $ekey = $ibx->eidx_key;
922 local $self->{current_info} = $ekey;
923 if (defined(my $err = _ibx_index_reject($ibx))) {
924 warn "W: cannot reindex $ekey ($err)\n";
926 _reindex_check_unseen($self, $sync, $ibx);
927 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
929 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
933 my ($self, $sync) = @_;
934 return unless $self->{cfg};
936 # acquire eidxq_lock early because full reindex takes forever
937 # and incremental -extindex processes can run during our checkpoints
938 if (!eidxq_lock_acquire($self)) {
939 warn "E: aborting --reindex\n";
942 for my $ibx (@{ibx_sorted($self, 'active')}) {
943 _reindex_inbox($self, $sync, $ibx);
944 last if $sync->{quit};
946 $self->git->async_wait_all; # ensure eidxq gets filled completely
947 eidxq_process($self, $sync) unless $sync->{quit};
951 my ($self, $sync, $ibx) = @_;
952 my $err = _sync_inbox($self, $sync, $ibx);
953 delete @$ibx{qw(mm over)};
954 warn $err, "\n" if defined($err);
957 sub dd_smsg { # git->cat_async callback
958 my ($bref, $oid, $type, $size, $dd) = @_;
959 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
960 my $self = $dd->{self} // die 'BUG: {self} missing';
961 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
962 if ($type eq 'missing') {
963 _blob_missing($dd, $smsg);
964 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
965 local $self->{current_info} = "$self->{current_info} $oid";
966 my $chash = content_hash(PublicInbox::Eml->new($bref));
967 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
969 return if $per_mid->{last_smsg} != $smsg;
970 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
971 my $keep = shift @$ary;
972 next if !scalar(@$ary);
973 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
975 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
976 join(', ', map { "#$_->{num}" } @$ary),"\n";
977 next if $per_mid->{sync}->{-opt}->{'dry-run'};
978 my $oidx = $self->{oidx};
979 for my $smsg (@$ary) {
980 my $gone = $smsg->{num};
981 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
982 $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
983 $oidx->delete_by_num($gone);
988 sub eidx_dedupe ($$$) {
989 my ($self, $sync, $msgids) = @_;
990 $sync->{dedupe_cull} = 0;
993 return unless eidxq_lock_acquire($self);
994 my ($iter, $cur_mid);
997 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
998 SELECT MAX(id) FROM msgid
1000 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
1002 # note: we could write this query more intelligently,
1003 # but that causes lock contention with read-only processes
1005 $cur_mid = $msgids->[$idx];
1006 if ($cur_mid eq '') { # all Message-IDs
1007 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1008 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
1010 $iter->execute($min_id);
1012 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1013 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
1015 $iter->execute($cur_mid, $min_id);
1017 while (my ($mid, $id) = $iter->fetchrow_array) {
1018 last if $sync->{quit};
1019 $self->{current_info} = "dedupe $mid";
1020 ${$sync->{nr}} = $min_id = $id;
1022 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
1025 next if scalar(@smsg) < 2;
1027 dd_chash => {}, # chash => [ary of smsgs]
1028 last_smsg => $smsg[-1],
1032 $candidates += scalar(@smsg) - 1;
1033 for my $smsg (@smsg) {
1035 per_mid => $per_mid,
1039 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
1041 # need to wait on every single one @smsg contents can get
1042 # invalidated inside dd_smsg for messages with multiple
1044 $self->git->async_wait_all;
1046 if (checkpoint_due($sync)) {
1048 reindex_checkpoint($self, $sync);
1049 goto dedupe_restart;
1052 goto dedupe_restart if defined($msgids->[++$idx]);
1054 my $n = delete $sync->{dedupe_cull};
1055 if (my $pr = $sync->{-opt}->{-progress}) {
1056 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1061 sub eidx_sync { # main entry point
1062 my ($self, $opt) = @_;
1064 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1065 local $self->{current_info} = '';
1066 local $SIG{__WARN__} = sub {
1067 return if PublicInbox::Eml::warn_ignore(@_);
1068 $warn_cb->($self->{current_info}, ': ', @_);
1070 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1071 $self->{oidx}->rethread_prepare($opt);
1073 need_checkpoint => \(my $need_checkpoint = 0),
1075 next_check => now() + 10,
1077 # DO NOT SET {reindex} here, it's incompatible with reused
1078 # V2Writable code, reindex is totally different here
1079 # compared to v1/v2 inboxes because we have multiple histories
1081 -regen_fmt => "%u/?\n",
1083 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1084 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1085 local $SIG{QUIT} = $quit;
1086 local $SIG{INT} = $quit;
1087 local $SIG{TERM} = $quit;
1088 for my $ibx (@{ibx_sorted($self, 'known')}) {
1089 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1092 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1093 $sync->{id2pos} //= prep_id2pos($self);
1094 $sync->{boost_in_use} = 1;
1097 if (my $msgids = delete($opt->{dedupe})) {
1098 local $sync->{checkpoint_unlocks} = 1;
1099 eidx_dedupe($self, $sync, $msgids);
1101 if (delete($opt->{reindex})) {
1102 local $sync->{checkpoint_unlocks} = 1;
1103 eidx_reindex($self, $sync);
1106 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1107 if ($opt->{scan} // 1) {
1108 for my $ibx (@{ibx_sorted($self, 'active')}) {
1109 last if $sync->{quit};
1110 sync_inbox($self, $sync, $ibx);
1113 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1114 eidxq_process($self, $sync) unless $sync->{quit};
1116 eidxq_release($self);
1118 $sync; # for eidx_watch
1121 sub update_last_commit { # overrides V2Writable
1122 my ($self, $sync, $stk) = @_;
1123 my $unit = $sync->{unit} // return;
1124 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1125 defined($latest_cmt) or return;
1126 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1127 my $ekey = $ibx->eidx_key;
1128 my $uv = $ibx->uidvalidity;
1129 my $epoch = $unit->{epoch};
1131 my $v = $ibx->version;
1133 die 'No {epoch} for v2 unit' unless defined $epoch;
1134 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1136 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1137 $meta_key = "lc-v1:$ekey//$uv";
1139 die "Unsupported inbox version: $v";
1141 my $last = $self->{oidx}->eidx_meta($meta_key);
1142 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1143 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1144 chomp(my $n = $unit->{git}->qx(@cmd));
1145 return if $n ne '' && $n == 0;
1147 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1150 sub _idx_init { # with_umask callback
1151 my ($self, $opt) = @_;
1152 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1153 $self->{midx} = PublicInbox::MiscIdx->new($self);
1156 sub symlink_packs ($$) {
1157 my ($ibx, $pd) = @_;
1159 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1160 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1161 my $src = substr($idx, 0, -length('.idx'));
1162 my $dst = $pd . substr($src, rindex($src, '/'));
1163 if (-f "$src.pack" and
1164 symlink("$src.pack", "$dst.pack") and
1165 symlink($idx, "$dst.idx") and
1168 # .promisor, .bitmap, .rev and .keep are optional
1169 # XXX should we symlink .keep here?
1170 for my $s (qw(promisor bitmap rev)) {
1171 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1173 } elsif (!$!{EEXIST}) {
1174 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1175 unlink "$dst.pack", "$dst.idx";
1181 sub idx_init { # similar to V2Writable
1182 my ($self, $opt) = @_;
1183 return if $self->{idx_shards};
1185 $self->git->cleanup;
1187 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1188 my ($has_new, $alt, $seen);
1189 if ($opt->{-private}) { # LeiStore
1190 my $local = "$self->{topdir}/local"; # lei/store
1191 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1192 'ALL.git', 'local');
1195 umask 077; # don't bother restoring for lei
1196 PublicInbox::Import::init_bare($ALL);
1197 $self->git->qx(qw(config core.sharedRepository 0600));
1199 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1200 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1201 } else { # extindex has no epochs
1202 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1204 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1206 PublicInbox::Import::init_bare($ALL);
1209 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1211 my $pd = "$ALL/objects/pack";
1212 if (opendir(my $dh, $pd)) { # drop stale symlinks
1213 while (defined(my $dn = readdir($dh))) {
1214 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1216 unlink($f) if -l $f && !-e $f;
1219 } elsif ($!{ENOENT}) {
1220 mkdir($pd) or die "mkdir($pd): $!";
1222 die "opendir($pd): $!";
1225 for my $ibx (@{ibx_sorted($self, 'active')}) {
1226 # create symlinks for multi-pack-index
1227 $git_midx += symlink_packs($ibx, $pd);
1228 # add new lines to our alternates file
1229 my $d = $ibx->git->{git_dir} . '/objects';
1230 next if exists $alt->{$d};
1231 if (my @st = stat($d)) {
1232 next if $seen->{"$st[0]\0$st[1]"}++;
1234 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1235 next if $opt->{-idx_gc};
1239 ($has_new || $new ne '') and
1240 $self->{mg}->write_alternates($mode, $alt, $new);
1241 $git_midx and $self->with_umask(sub {
1242 my @cmd = ('multi-pack-index');
1243 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1244 my $lk = $self->lock_for_scope;
1245 system('git', "--git-dir=$ALL", @cmd, 'write');
1246 # ignore errors, fairly new command, may not exist
1248 $self->parallel_init($self->{indexlevel});
1249 $self->with_umask(\&_idx_init, $self, $opt);
1250 $self->{oidx}->begin_lazy;
1251 $self->{oidx}->eidx_prep;
1252 $self->{midx}->create_xdb if $new ne '';
1255 sub _watch_commit { # PublicInbox::DS::add_timer callback
1257 delete $self->{-commit_timer};
1258 eidxq_process($self, $self->{-watch_sync});
1259 eidxq_release($self);
1260 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1261 reindex_checkpoint($self, $self->{-watch_sync});
1262 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1264 # call event_step => done unless commit_timer is armed
1265 PublicInbox::DS::requeue($self);
1268 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1269 my ($self, $ibx) = @_;
1270 my $opt = $self->{-watch_sync}->{-opt};
1271 my $pr = $opt->{-progress};
1272 my $ekey = $ibx->eidx_key;
1273 local $0 = "sync $ekey";
1274 $pr->("indexing $ekey\n") if $pr;
1275 $self->idx_init($opt);
1276 sync_inbox($self, $self->{-watch_sync}, $ibx);
1277 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1278 \&_watch_commit, $self);
1281 sub eidx_reload { # -extindex --watch SIGHUP handler
1282 my ($self, $idler) = @_;
1284 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1285 $pr->('reloading ...') if $pr;
1286 delete $self->{-resync_queue};
1287 delete $self->{-ibx_ary_known};
1288 delete $self->{-ibx_ary_active};
1289 $self->{ibx_known} = [];
1290 $self->{ibx_active} = [];
1291 %{$self->{ibx_map}} = ();
1292 delete $self->{-watch_sync}->{id2pos};
1293 my $cfg = PublicInbox::Config->new;
1294 attach_config($self, $cfg);
1295 $idler->refresh($cfg);
1296 $pr->(" done\n") if $pr;
1298 warn "reload not supported without --all\n";
1302 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1304 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1305 PublicInbox::DS::requeue($self); # trigger our ->event_step
1308 sub event_step { # PublicInbox::DS::requeue callback
1310 if (my $resync_queue = $self->{-resync_queue}) {
1311 if (my $ibx = shift(@$resync_queue)) {
1312 on_inbox_unlock($self, $ibx);
1313 PublicInbox::DS::requeue($self);
1315 delete $self->{-resync_queue};
1316 _watch_commit($self);
1319 done($self) unless $self->{-commit_timer};
1323 sub eidx_watch { # public-inbox-extindex --watch main loop
1324 my ($self, $opt) = @_;
1325 local @SIG{keys %SIG} = values %SIG;
1326 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1327 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1329 require PublicInbox::InboxIdle;
1330 require PublicInbox::DS;
1331 require PublicInbox::Syscall;
1332 require PublicInbox::Sigfd;
1333 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1334 if (!$self->{cfg}) {
1335 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1337 for my $ibx (@{ibx_sorted($self, 'active')}) {
1338 $ibx->subscribe_unlock(__PACKAGE__, $self)
1340 my $pr = $opt->{-progress};
1341 $pr->("performing initial scan ...\n") if $pr;
1342 my $sync = eidx_sync($self, $opt); # initial sync
1343 return if $sync->{quit};
1344 my $oldset = PublicInbox::DS::block_signals();
1345 local $self->{current_info} = '';
1346 my $cb = $SIG{__WARN__} || \&CORE::warn;
1347 local $SIG{__WARN__} = sub {
1348 return if PublicInbox::Eml::warn_ignore(@_);
1349 $cb->($self->{current_info}, ': ', @_);
1352 HUP => sub { eidx_reload($self, $idler) },
1353 USR1 => sub { eidx_resync_start($self) },
1354 TSTP => sub { kill('STOP', $$) },
1356 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1357 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1358 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1359 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1360 $pr->("initial scan complete, entering event loop\n") if $pr;
1361 # calls InboxIdle->event_step:
1362 PublicInbox::DS::event_loop($sig, $oldset);
1367 *done = \&PublicInbox::V2Writable::done;
1368 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1369 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1370 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1371 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1372 *index_todo = \&PublicInbox::V2Writable::index_todo;
1373 *count_shards = \&PublicInbox::V2Writable::count_shards;
1374 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1375 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1376 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1377 *checkpoint = \&PublicInbox::V2Writable::checkpoint;