]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearchidx: emit diagnostics for missing blobs
[public-inbox.git] / lib / PublicInbox / ExtSearchIdx.pm
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>
3
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
6 #
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.
11 #
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)
15
16 package PublicInbox::ExtSearchIdx;
17 use strict;
18 use v5.10.1;
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);
33 use PublicInbox::Eml;
34 use PublicInbox::DS qw(now add_timer);
35 use DBI qw(:sql_types); # SQL_BLOB
36
37 sub new {
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";
43         my $self = bless {
44                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
45                 topdir => $dir,
46                 creat => $opt->{creat},
47                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
48                 ibx_active => [], # by config section order
49                 ibx_known => [], # by config section order
50                 indexlevel => $l,
51                 transact_bytes => 0,
52                 total_bytes => 0,
53                 current_info => '',
54                 parallel => 1,
55                 lock_path => "$dir/ei.lock",
56         }, __PACKAGE__;
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;
62         $self
63 }
64
65 sub attach_inbox {
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) ];
71                 for my $t (@$types) {
72                         push @{$self->{"ibx_$t"}}, $ibx;
73                 }
74                 $ibx;
75         }
76 }
77
78 sub _ibx_attach { # each_inbox callback
79         my ($ibx, $self, $types) = @_;
80         attach_inbox($self, $ibx, $types);
81 }
82
83 sub attach_config {
84         my ($self, $cfg, $ibxs) = @_;
85         $self->{cfg} = $cfg;
86         my $types;
87         if ($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;
92                                 $ibx;
93                         }
94                 }
95                 # invalidate cache
96                 delete $self->{-ibx_ary_known};
97                 delete $self->{-ibx_ary_active};
98                 $types = [ 'known' ];
99         }
100         $types //= [ qw(known active) ];
101         $cfg->each_inbox(\&_ibx_attach, $self, $types);
102 }
103
104 sub check_batch_limit ($) {
105         my ($req) = @_;
106         my $self = $req->{self};
107         my $new_smsg = $req->{new_smsg};
108         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
109
110         # set flag for PublicInbox::V2Writable::index_todo:
111         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
112 }
113
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);
118         @$xr3 = sort {
119                 $id2pos->{$a->[0]} <=> $id2pos->{$b->[0]}
120                                 ||
121                 $a->[1] <=> $b->[1] # break ties with {xnum}
122         } @$xr3;
123         my $top_blob = unpack('H*', $xr3->[0]->[2]);
124         my $new_smsg = $req->{new_smsg};
125         return if $top_blob ne $new_smsg->{blob}; # loser
126
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);
131 }
132
133 sub do_xpost ($$) {
134         my ($req, $smsg) = @_;
135         my $self = $req->{self};
136         my $docid = $smsg->{num};
137         my $idx = $self->idx_shard($docid);
138         my $oid = $req->{oid};
139         my $xibx = $req->{ibx};
140         my $eml = $req->{eml};
141         my $eidx_key = $xibx->eidx_key;
142         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
143                 my $xnum = $req->{xnum};
144                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
145                 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
146                 apply_boost($req, $smsg) if $req->{boost_in_use};
147         } else { # 'd'
148                 my $rm_eidx_info;
149                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
150                                                         \$rm_eidx_info);
151                 if ($nr == 0) {
152                         $self->{oidx}->eidxq_del($docid);
153                         $idx->ipc_do('xdb_remove', $docid);
154                 } elsif ($rm_eidx_info) {
155                         $idx->ipc_do('remove_eidx_info',
156                                         $docid, $eidx_key, $eml);
157                         $self->{oidx}->eidxq_add($docid); # yes, add
158                 }
159         }
160 }
161
162 # called by V2Writable::sync_prepare
163 sub artnum_max { $_[0]->{oidx}->eidx_max }
164
165 sub index_unseen ($) {
166         my ($req) = @_;
167         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
168         my $eml = delete $req->{eml};
169         $new_smsg->populate($eml, $req);
170         my $self = $req->{self};
171         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
172         $new_smsg->{num} = $docid;
173         my $idx = $self->idx_shard($docid);
174         $self->{oidx}->add_overview($eml, $new_smsg);
175         my $oid = $new_smsg->{blob};
176         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
177         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
178         $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
179         check_batch_limit($req);
180 }
181
182 sub do_finalize ($) {
183         my ($req) = @_;
184         if (my $indexed = $req->{indexed}) { # duplicated messages
185                 do_xpost($req, $_) for @$indexed;
186         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
187                 index_unseen($req);
188         } else {
189                 # `d' message was already unindexed in the v1/v2 inboxes,
190                 # so it's too noisy to warn, here.
191         }
192         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
193         if (defined(my $cur_cmt = $req->{cur_cmt})) {
194                 ${$req->{latest_cmt}} = $cur_cmt;
195         }
196 }
197
198 sub do_step ($) { # main iterator for adding messages to the index
199         my ($req) = @_;
200         my $self = $req->{self} // die 'BUG: {self} missing';
201         while (1) {
202                 if (my $next_arg = $req->{next_arg}) {
203                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
204                                 $req->{cur_smsg} = $smsg;
205                                 $self->git->cat_async($smsg->{blob},
206                                                         \&ck_existing, $req);
207                                 return; # ck_existing calls do_step
208                         }
209                         delete $req->{next_arg};
210                 }
211                 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
212                 my $mid = shift(@{$req->{mids}}) // last;
213                 my ($id, $prev);
214                 $req->{next_arg} = [ $mid, \$id, \$prev ];
215                 # loop again
216         }
217         do_finalize($req);
218 }
219
220 sub _blob_missing ($$) { # called when $smsg->{blob} is bad
221         my ($req, $smsg) = @_;
222         my $self = $req->{self};
223         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
224         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
225         if (@keep) {
226                 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
227                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
228                         die "BUG: xref $keep[0] has no OID";
229                 my $oidhex = $1;
230                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
231                 $self->{oidx}->update_blob($smsg, $oidhex) or warn <<EOM;
232 E: #$smsg->{num} gone ($smsg->{blob} => $oidhex)
233 EOM
234         } else {
235                 warn "E: $smsg->{blob} gone, removing #$smsg->{num}\n";
236                 $self->{oidx}->delete_by_num($smsg->{num});
237         }
238 }
239
240 sub ck_existing { # git->cat_async callback
241         my ($bref, $oid, $type, $size, $req) = @_;
242         my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
243         if ($type eq 'missing') {
244                 _blob_missing($req, $smsg);
245         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
246                 my $self = $req->{self} // die 'BUG: {self} missing';
247                 local $self->{current_info} = "$self->{current_info} $oid";
248                 my $cur = PublicInbox::Eml->new($bref);
249                 if (content_hash($cur) eq $req->{chash}) {
250                         push @{$req->{indexed}}, $smsg; # for do_xpost
251                 } # else { index_unseen later }
252         }
253         do_step($req);
254 }
255
256 # is the messages visible in the inbox currently being indexed?
257 # return the number if so
258 sub cur_ibx_xnum ($$) {
259         my ($req, $bref) = @_;
260         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
261
262         $req->{eml} = PublicInbox::Eml->new($bref);
263         $req->{chash} = content_hash($req->{eml});
264         $req->{mids} = mids($req->{eml});
265         for my $mid (@{$req->{mids}}) {
266                 my ($id, $prev);
267                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
268                         return $x->{num} if $x->{blob} eq $req->{oid};
269                 }
270         }
271         undef;
272 }
273
274 sub index_oid { # git->cat_async callback for 'm'
275         my ($bref, $oid, $type, $size, $req) = @_;
276         my $self = $req->{self};
277         local $self->{current_info} = "$self->{current_info} $oid";
278         return if is_bad_blob($oid, $type, $size, $req->{oid});
279         my $new_smsg = $req->{new_smsg} = bless {
280                 blob => $oid,
281         }, 'PublicInbox::Smsg';
282         $new_smsg->set_bytes($$bref, $size);
283         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
284         ++${$req->{nr}};
285         do_step($req);
286 }
287
288 sub unindex_oid { # git->cat_async callback for 'd'
289         my ($bref, $oid, $type, $size, $req) = @_;
290         my $self = $req->{self};
291         local $self->{current_info} = "$self->{current_info} $oid";
292         return if is_bad_blob($oid, $type, $size, $req->{oid});
293         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
294         do_step($req);
295 }
296
297 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
298 sub last_commits {
299         my ($self, $sync) = @_;
300         my $heads = [];
301         my $ekey = $sync->{ibx}->eidx_key;
302         my $uv = $sync->{ibx}->uidvalidity;
303         for my $i (0..$sync->{epoch_max}) {
304                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
305         }
306         $heads;
307 }
308
309 sub _ibx_index_reject ($) {
310         my ($ibx) = @_;
311         $ibx->mm // return 'unindexed, no msgmap.sqlite3';
312         $ibx->uidvalidity // return 'no UIDVALIDITY';
313         $ibx->over // return 'unindexed, no over.sqlite3';
314         undef;
315 }
316
317 sub _sync_inbox ($$$) {
318         my ($self, $sync, $ibx) = @_;
319         my $ekey = $ibx->eidx_key;
320         if (defined(my $err = _ibx_index_reject($ibx))) {
321                 return "W: skipping $ekey ($err)";
322         }
323         $sync->{ibx} = $ibx;
324         $sync->{nr} = \(my $nr = 0);
325         my $v = $ibx->version;
326         if ($v == 2) {
327                 $sync->{epoch_max} = $ibx->max_git_epoch // return;
328                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
329         } elsif ($v == 1) {
330                 my $uv = $ibx->uidvalidity;
331                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
332                 my $head = $ibx->mm->last_commit //
333                         return "E: $ibx->{inboxdir} is not indexed";
334                 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
335                 my $unit = { stack => $stk, git => $ibx->git };
336                 push @{$sync->{todo}}, $unit;
337         } else {
338                 return "E: $ekey unsupported inbox version (v$v)";
339         }
340         for my $unit (@{delete($sync->{todo}) // []}) {
341                 last if $sync->{quit};
342                 index_todo($self, $sync, $unit);
343         }
344         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
345         $ibx->git->cleanup; # done with this inbox, now
346         undef;
347 }
348
349 sub gc_unref_doc ($$$$) {
350         my ($self, $ibx_id, $eidx_key, $docid) = @_;
351         my $remain = 0;
352         # for debug/info purposes, oids may no longer be accessible
353         my $dbh = $self->{oidx}->dbh;
354         my $sth = $dbh->prepare_cached(<<'', undef, 1);
355 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
356
357         $sth->execute($docid, $ibx_id);
358         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
359         for my $oid (@oid) {
360                 $remain += $self->{oidx}->remove_xref3($docid, $oid, $eidx_key);
361         }
362         if ($remain) {
363                 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
364                 for my $oid (@oid) {
365                         warn "I: unref #$docid $eidx_key $oid\n";
366                 }
367         } else {
368                 warn "I: remove #$docid $eidx_key @oid\n";
369                 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
370         }
371 }
372
373 sub eidx_gc {
374         my ($self, $opt) = @_;
375         $self->{cfg} or die "E: GC requires ->attach_config\n";
376         $opt->{-idx_gc} = 1;
377         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
378
379         my $dbh = $self->{oidx}->dbh;
380         $dbh->do('PRAGMA case_sensitive_like = ON'); # only place we use LIKE
381         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
382         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
383         my $lc_i = $dbh->prepare(<<'');
384 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
385
386         $ibx_ck->execute;
387         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
388                 next if $self->{ibx_map}->{$eidx_key};
389                 $self->{midx}->remove_eidx_key($eidx_key);
390                 warn "I: deleting messages for $eidx_key...\n";
391                 $x3_doc->execute($ibx_id);
392                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
393                         gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
394                 }
395                 $dbh->prepare_cached(<<'')->execute($ibx_id);
396 DELETE FROM inboxes WHERE ibx_id = ?
397
398                 # drop last_commit info
399                 my $pat = $eidx_key;
400                 $pat =~ s/([_%\\])/\\$1/g;
401                 $lc_i->execute("lc-%:$pat//%", '\\');
402                 while (my ($key) = $lc_i->fetchrow_array) {
403                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
404                         warn "I: removing $key\n";
405                         $dbh->prepare_cached(<<'')->execute($key);
406 DELETE FROM eidx_meta WHERE key = ?
407
408                 }
409
410                 warn "I: $eidx_key removed\n";
411         }
412
413         # it's not real unless it's in `over', we use parallelism here,
414         # shards will be reading directly from over, so commit
415         $self->{oidx}->commit_lazy;
416         $self->{oidx}->begin_lazy;
417
418         for my $idx (@{$self->{idx_shards}}) {
419                 warn "I: cleaning up shard #$idx->{shard}\n";
420                 $idx->shard_over_check($self->{oidx});
421         }
422         my $nr = $dbh->do(<<'');
423 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
424
425         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
426
427         # fixup from old bugs:
428         $nr = $dbh->do(<<'');
429 DELETE FROM over WHERE num NOT IN (SELECT docid FROM xref3)
430
431         warn "I: eliminated $nr stale over entries\n" if $nr != 0;
432         done($self);
433 }
434
435 sub _ibx_for ($$$) {
436         my ($self, $sync, $smsg) = @_;
437         my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
438         my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
439         $self->{-ibx_ary_known}->[$pos] //
440                 die "BUG: ibx for $smsg->{blob} not mapped"
441 }
442
443 sub _fd_constrained ($) {
444         my ($self) = @_;
445         $self->{-fd_constrained} //= do {
446                 my $soft;
447                 if (eval { require BSD::Resource; 1 }) {
448                         my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
449                         ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
450                 } else {
451                         chomp($soft = `sh -c 'ulimit -n'`);
452                 }
453                 if (defined($soft)) {
454                         # $want is an estimate
455                         my $want = scalar(@{$self->{ibx_active}}) + 64;
456                         my $ret = $want > $soft;
457                         if ($ret) {
458                                 warn <<EOF;
459 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
460 EOF
461                         }
462                         $ret;
463                 } else {
464                         warn "Unable to determine RLIMIT_NOFILE: $@\n";
465                         1;
466                 }
467         };
468 }
469
470 sub _reindex_finalize ($$$) {
471         my ($req, $smsg, $eml) = @_;
472         my $sync = $req->{sync};
473         my $self = $sync->{self};
474         my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
475         my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
476         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
477         my $docid = $smsg->{num} = $orig_smsg->{num};
478         $self->{oidx}->add_overview($eml, $smsg); # may rethread
479         check_batch_limit({ %$sync, new_smsg => $smsg });
480         my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
481         my $stable = delete($by_chash->{$chash0}) //
482                                 die "BUG: $smsg->{blob} chash missing";
483         my $idx = $self->idx_shard($docid);
484         my $top_smsg = pop @$stable;
485         $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
486         my $ibx = _ibx_for($self, $sync, $smsg);
487         $idx->index_eml($eml, $smsg, $ibx->eidx_key);
488         for my $x (reverse @$stable) {
489                 $ibx = _ibx_for($self, $sync, $x);
490                 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
491                 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
492         }
493         return if $nr == 1; # likely, all good
494
495         warn "W: #$docid split into $nr due to deduplication change\n";
496         my @todo;
497         for my $ary (values %$by_chash) {
498                 for my $x (reverse @$ary) {
499                         warn "removing #$docid xref3 $x->{blob}\n";
500                         my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
501                         die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
502                 }
503                 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
504                 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
505                 $ibx = _ibx_for($self, $sync, $x);
506                 if (my $over = $ibx->over) {
507                         my $e = $over->get_art($x->{num});
508                         $e->{blob} eq $x->{blob} or die <<EOF;
509 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
510 EOF
511                         push @todo, $ibx, $e;
512                         $over->dbh_close if _fd_constrained($self);
513                 } else {
514                         die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
515                 }
516         }
517         undef $by_chash;
518         while (my ($ibx, $e) = splice(@todo, 0, 2)) {
519                 reindex_unseen($self, $sync, $ibx, $e);
520         }
521 }
522
523 sub _reindex_oid { # git->cat_async callback
524         my ($bref, $oid, $type, $size, $req) = @_;
525         my $sync = $req->{sync};
526         my $self = $sync->{self};
527         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
528         my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
529         my $docid = $orig_smsg->{num};
530         if (is_bad_blob($oid, $type, $size, $expect_oid)) {
531                 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
532                 if ($remain == 0) {
533                         warn "W: #$docid gone or corrupted\n";
534                         $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
535                 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
536                         $self->git->cat_async($next_oid, \&_reindex_oid, $req);
537                 } else {
538                         warn "BUG: #$docid gone (UNEXPECTED)\n";
539                         $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
540                 }
541                 return;
542         }
543         my $ci = $self->{current_info};
544         local $self->{current_info} = "$ci #$docid $oid";
545         my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
546         $re_smsg->set_bytes($$bref, $size);
547         my $eml = PublicInbox::Eml->new($bref);
548         $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
549                                 cotime => $orig_smsg->{ts} });
550         my $chash = content_hash($eml);
551         $re_smsg->{chash} = $chash;
552         $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
553         $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
554         $re_smsg->{hdr} = $eml->header_obj;
555         push @{$req->{by_chash}->{$chash}}, $re_smsg;
556         if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
557                 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
558         } else { # last $re_smsg is the highest priority xref3
559                 local $self->{current_info} = "$ci #$docid";
560                 _reindex_finalize($req, $re_smsg, $eml);
561         }
562 }
563
564 sub _reindex_smsg ($$$) {
565         my ($self, $sync, $smsg) = @_;
566         my $docid = $smsg->{num};
567         my $xr3 = $self->{oidx}->get_xref3($docid, 1);
568         if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
569                 warn <<"";
570 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
571
572                 $self->{oidx}->delete_by_num($docid);
573                 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
574                 return;
575         }
576
577         # we sort {xr3r} in the reverse order of ibx_sorted so we can
578         # hit the common case in _reindex_finalize without rereading
579         # from git (or holding multiple messages in memory).
580         my $id2pos = $sync->{id2pos}; # index in ibx_sorted
581         @$xr3 = sort {
582                 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
583                                 ||
584                 $b->[1] <=> $a->[1] # break ties with {xnum}
585         } @$xr3;
586         @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
587         my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
588         $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
589 }
590
591 sub checkpoint_due ($) {
592         my ($sync) = @_;
593         ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
594 }
595
596 sub host_ident () {
597         # I've copied FS images and only changed the hostname before,
598         # so prepend hostname.  Use `state' since these a BOFH can change
599         # these while this process is running and we always want to be
600         # able to release locks taken by this process.
601         state $retval = hostname . '-' . do {
602                 my $m; # machine-id(5) is systemd
603                 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
604                 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
605                 chomp($m ||= `{ sysctl -n kern.hostid ||
606                                 hostid || ghostid; } 2>/dev/null`
607                         || "no-machine-id-or-hostid-on-$^O");
608                 $m;
609         };
610 }
611
612 sub eidxq_release {
613         my ($self) = @_;
614         my $expect = delete($self->{-eidxq_locked}) or return;
615         my ($owner_pid, undef) = split(/-/, $expect);
616         return if $owner_pid != $$; # shards may fork
617         my $oidx = $self->{oidx};
618         $oidx->begin_lazy;
619         my $cur = $oidx->eidx_meta('eidxq_lock') // '';
620         if ($cur eq $expect) {
621                 $oidx->eidx_meta('eidxq_lock', '');
622                 return 1;
623         } elsif ($cur ne '') {
624                 warn "E: eidxq_lock($expect) stolen by $cur\n";
625         } else {
626                 warn "E: eidxq_lock($expect) released by another process\n";
627         }
628         undef;
629 }
630
631 sub DESTROY {
632         my ($self) = @_;
633         eidxq_release($self) and $self->{oidx}->commit_lazy;
634 }
635
636 sub _eidxq_take ($) {
637         my ($self) = @_;
638         my $val = "$$-${\time}-$>-".host_ident;
639         $self->{oidx}->eidx_meta('eidxq_lock', $val);
640         $self->{-eidxq_locked} = $val;
641 }
642
643 sub eidxq_lock_acquire ($) {
644         my ($self) = @_;
645         my $oidx = $self->{oidx};
646         $oidx->begin_lazy;
647         my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
648         if (my $locked = $self->{-eidxq_locked}) { # be lazy
649                 return $locked if $locked eq $cur;
650         }
651         my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
652         my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
653         if ($euid == $> && $ident eq host_ident) {
654                 if (kill(0, $pid)) {
655                         warn <<EOM; return;
656 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
657 EOM
658                 }
659                 if ($!{ESRCH}) {
660                         warn "I: eidxq_lock is stale ($cur), clobbering\n";
661                         return _eidxq_take($self);
662                 }
663                 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
664         }
665         my $fn = $oidx->dbh->sqlite_db_filename;
666         warn <<EOF;
667 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
668 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
669 W:      sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
670 EOF
671         undef;
672 }
673
674 sub ibx_sorted ($$) {
675         my ($self, $type) = @_;
676         $self->{"-ibx_ary_$type"} //= do {
677                 # highest boost first, stable for config-ordering tiebreaker
678                 use sort 'stable';
679                 [ sort {
680                         ($b->{boost} // 0) <=> ($a->{boost} // 0)
681                   } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
682         }
683 }
684
685 sub prep_id2pos ($) {
686         my ($self) = @_;
687         my %id2pos;
688         my $pos = 0;
689         $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
690         \%id2pos;
691 }
692
693 sub eidxq_process ($$) { # for reindexing
694         my ($self, $sync) = @_;
695         return unless $self->{cfg};
696
697         return unless eidxq_lock_acquire($self);
698         my $dbh = $self->{oidx}->dbh;
699         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
700         ${$sync->{nr}} = 0;
701         local $sync->{-regen_fmt} = "%u/$tot\n";
702         my $pr = $sync->{-opt}->{-progress};
703         if ($pr) {
704                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
705                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
706                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
707         }
708         $sync->{id2pos} //= prep_id2pos($self);
709         my ($del, $iter);
710 restart:
711         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
712         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
713         $iter->execute;
714         while (defined(my $docid = $iter->fetchrow_array)) {
715                 last if $sync->{quit};
716                 if (my $smsg = $self->{oidx}->get_art($docid)) {
717                         _reindex_smsg($self, $sync, $smsg);
718                 } else {
719                         warn "E: #$docid does not exist in over\n";
720                 }
721                 $del->execute($docid);
722                 ++${$sync->{nr}};
723
724                 if (checkpoint_due($sync)) {
725                         $dbh = $del = $iter = undef;
726                         reindex_checkpoint($self, $sync); # release lock
727                         $dbh = $self->{oidx}->dbh;
728                         goto restart;
729                 }
730         }
731         $self->git->async_wait_all;
732         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
733 }
734
735 sub _reindex_unseen { # git->cat_async callback
736         my ($bref, $oid, $type, $size, $req) = @_;
737         return if is_bad_blob($oid, $type, $size, $req->{oid});
738         my $self = $req->{self} // die 'BUG: {self} unset';
739         local $self->{current_info} = "$self->{current_info} $oid";
740         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
741         $new_smsg->set_bytes($$bref, $size);
742         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
743         $req->{new_smsg} = $new_smsg;
744         $req->{chash} = content_hash($eml);
745         $req->{mids} = mids($eml); # do_step iterates through this
746         do_step($req); # enter the normal indexing flow
747 }
748
749 # --reindex may catch totally unseen messages, this handles them
750 sub reindex_unseen ($$$$) {
751         my ($self, $sync, $ibx, $xsmsg) = @_;
752         my $req = {
753                 %$sync, # has {self}
754                 autime => $xsmsg->{ds},
755                 cotime => $xsmsg->{ts},
756                 oid => $xsmsg->{blob},
757                 ibx => $ibx,
758                 xnum => $xsmsg->{num},
759                 # {mids} and {chash} will be filled in at _reindex_unseen
760         };
761         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
762         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
763 }
764
765 sub _reindex_check_unseen ($$$) {
766         my ($self, $sync, $ibx) = @_;
767         my $ibx_id = $ibx->{-ibx_id};
768         my $slice = 1000;
769         my ($beg, $end) = (1, $slice);
770
771         # first, check if we missed any messages in target $ibx
772         my $msgs;
773         my $pr = $sync->{-opt}->{-progress};
774         my $ekey = $ibx->eidx_key;
775         local $sync->{-regen_fmt} =
776                         "$ekey checking unseen %u/".$ibx->over->max."\n";
777         ${$sync->{nr}} = 0;
778
779         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
780                 ${$sync->{nr}} = $beg;
781                 $beg = $msgs->[-1]->{num} + 1;
782                 $end = $beg + $slice;
783                 if (checkpoint_due($sync)) {
784                         reindex_checkpoint($self, $sync); # release lock
785                 }
786
787                 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
788 SELECT DISTINCT(docid) FROM xref3 WHERE
789 ibx_id = ? AND xnum = ? AND oidbin = ?
790
791                 for my $xsmsg (@$msgs) {
792                         my $oidbin = pack('H*', $xsmsg->{blob});
793                         $inx3->bind_param(1, $ibx_id);
794                         $inx3->bind_param(2, $xsmsg->{num});
795                         $inx3->bind_param(3, $oidbin, SQL_BLOB);
796                         $inx3->execute;
797                         my $docids = $inx3->fetchall_arrayref;
798                         # index messages which were totally missed
799                         # the first time around ASAP:
800                         if (scalar(@$docids) == 0) {
801                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
802                         } else { # already seen, reindex later
803                                 for my $r (@$docids) {
804                                         $self->{oidx}->eidxq_add($r->[0]);
805                                 }
806                         }
807                         last if $sync->{quit};
808                 }
809                 last if $sync->{quit};
810         }
811 }
812
813 sub _reindex_check_stale ($$$) {
814         my ($self, $sync, $ibx) = @_;
815         my $min = 0;
816         my $pr = $sync->{-opt}->{-progress};
817         my $fetching;
818         my $ekey = $ibx->eidx_key;
819         local $sync->{-regen_fmt} =
820                         "$ekey check stale/missing %u/".$ibx->over->max."\n";
821         ${$sync->{nr}} = 0;
822         do {
823                 if (checkpoint_due($sync)) {
824                         reindex_checkpoint($self, $sync); # release lock
825                 }
826                 # now, check if there's stale xrefs
827                 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
828 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
829 ORDER BY docid,xnum ASC LIMIT 10000
830
831                 $iter->execute($ibx->{-ibx_id}, $min);
832                 $fetching = undef;
833
834                 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
835                         return if $sync->{quit};
836                         ${$sync->{nr}} = $xnum;
837
838                         $fetching = $min = $docid;
839                         my $smsg = $ibx->over->get_art($xnum);
840                         my $err;
841                         if (!$smsg) {
842                                 $err = 'stale';
843                         } elsif (pack('H*', $smsg->{blob}) ne $oidbin) {
844                                 $err = "mismatch (!= $smsg->{blob})";
845                         } else {
846                                 next; # likely, all good
847                         }
848                         # current_info already has eidx_key
849                         my $oidhex = unpack('H*', $oidbin);
850                         warn "$xnum:$oidhex (#$docid): $err\n";
851                         my $del = $self->{oidx}->dbh->prepare_cached(<<'');
852 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
853
854                         $del->bind_param(1, $ibx->{-ibx_id});
855                         $del->bind_param(2, $xnum);
856                         $del->bind_param(3, $oidbin, SQL_BLOB);
857                         $del->execute;
858
859                         # get_xref3 over-fetches, but this is a rare path:
860                         my $xr3 = $self->{oidx}->get_xref3($docid);
861                         my $idx = $self->idx_shard($docid);
862                         if (scalar(@$xr3) == 0) { # all gone
863                                 $self->{oidx}->delete_by_num($docid);
864                                 $self->{oidx}->eidxq_del($docid);
865                                 $idx->ipc_do('xdb_remove', $docid);
866                         } else { # enqueue for reindex of remaining messages
867                                 $idx->ipc_do('remove_eidx_info',
868                                                 $docid, $ibx->eidx_key);
869                                 $self->{oidx}->eidxq_add($docid); # yes, add
870                         }
871                 }
872         } while (defined $fetching);
873 }
874
875 sub _reindex_inbox ($$$) {
876         my ($self, $sync, $ibx) = @_;
877         my $ekey = $ibx->eidx_key;
878         local $self->{current_info} = $ekey;
879         if (defined(my $err = _ibx_index_reject($ibx))) {
880                 warn "W: cannot reindex $ekey ($err)\n";
881         } else {
882                 _reindex_check_unseen($self, $sync, $ibx);
883                 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
884         }
885         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
886 }
887
888 sub eidx_reindex {
889         my ($self, $sync) = @_;
890         return unless $self->{cfg};
891
892         # acquire eidxq_lock early because full reindex takes forever
893         # and incremental -extindex processes can run during our checkpoints
894         if (!eidxq_lock_acquire($self)) {
895                 warn "E: aborting --reindex\n";
896                 return;
897         }
898         for my $ibx (@{ibx_sorted($self, 'active')}) {
899                 _reindex_inbox($self, $sync, $ibx);
900                 last if $sync->{quit};
901         }
902         $self->git->async_wait_all; # ensure eidxq gets filled completely
903         eidxq_process($self, $sync) unless $sync->{quit};
904 }
905
906 sub sync_inbox {
907         my ($self, $sync, $ibx) = @_;
908         my $err = _sync_inbox($self, $sync, $ibx);
909         delete @$ibx{qw(mm over)};
910         warn $err, "\n" if defined($err);
911 }
912
913 sub dd_smsg { # git->cat_async callback
914         my ($bref, $oid, $type, $size, $dd) = @_;
915         my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
916         my $self = $dd->{self} // die 'BUG: {self} missing';
917         my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
918         if ($type eq 'missing') {
919                 _blob_missing($dd, $smsg);
920         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
921                 local $self->{current_info} = "$self->{current_info} $oid";
922                 my $chash = content_hash(PublicInbox::Eml->new($bref));
923                 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
924         }
925         return if $per_mid->{last_smsg} != $smsg;
926         while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
927                 my $keep = shift @$ary;
928                 next if !scalar(@$ary);
929                 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
930                 print STDERR
931                         "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
932                         join(', ', map { "#$_->{num}" } @$ary),"\n";
933                 next if $per_mid->{sync}->{-opt}->{'dry-run'};
934                 my $oidx = $self->{oidx};
935                 for my $smsg (@$ary) {
936                         my $gone = $smsg->{num};
937                         $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
938                         $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
939                         $oidx->delete_by_num($gone);
940                 }
941         }
942 }
943
944 sub eidx_dedupe ($$$) {
945         my ($self, $sync, $msgids) = @_;
946         $sync->{dedupe_cull} = 0;
947         my $candidates = 0;
948         my $nr_mid = 0;
949         return unless eidxq_lock_acquire($self);
950         my ($iter, $cur_mid);
951         my $min_id = 0;
952         my $idx = 0;
953         my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
954 SELECT MAX(id) FROM msgid
955 EOS
956         local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
957
958         # note: we could write this query more intelligently,
959         # but that causes lock contention with read-only processes
960 dedupe_restart:
961         $cur_mid = $msgids->[$idx];
962         if ($cur_mid eq '') { # all Message-IDs
963                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
964 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
965 EOS
966                 $iter->execute($min_id);
967         } else {
968                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
969 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
970 EOS
971                 $iter->execute($cur_mid, $min_id);
972         }
973         while (my ($mid, $id) = $iter->fetchrow_array) {
974                 last if $sync->{quit};
975                 $self->{current_info} = "dedupe $mid";
976                 ${$sync->{nr}} = $min_id = $id;
977                 my ($prv, @smsg);
978                 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
979                         push @smsg, $x;
980                 }
981                 next if scalar(@smsg) < 2;
982                 my $per_mid = {
983                         dd_chash => {}, # chash => [ary of smsgs]
984                         last_smsg => $smsg[-1],
985                         sync => $sync
986                 };
987                 $nr_mid++;
988                 $candidates += scalar(@smsg) - 1;
989                 for my $smsg (@smsg) {
990                         my $dd = {
991                                 per_mid => $per_mid,
992                                 smsg => $smsg,
993                                 self => $self,
994                         };
995                         $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
996                 }
997                 # need to wait on every single one @smsg contents can get
998                 # invalidated inside dd_smsg for messages with multiple
999                 # Message-IDs.
1000                 $self->git->async_wait_all;
1001
1002                 if (checkpoint_due($sync)) {
1003                         undef $iter;
1004                         reindex_checkpoint($self, $sync);
1005                         goto dedupe_restart;
1006                 }
1007         }
1008         goto dedupe_restart if defined($msgids->[++$idx]);
1009
1010         my $n = delete $sync->{dedupe_cull};
1011         if (my $pr = $sync->{-opt}->{-progress}) {
1012                 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1013         }
1014         ${$sync->{nr}} = 0;
1015 }
1016
1017 sub eidx_sync { # main entry point
1018         my ($self, $opt) = @_;
1019
1020         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1021         local $self->{current_info} = '';
1022         local $SIG{__WARN__} = sub {
1023                 return if PublicInbox::Eml::warn_ignore(@_);
1024                 $warn_cb->($self->{current_info}, ': ', @_);
1025         };
1026         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1027         $self->{oidx}->rethread_prepare($opt);
1028         my $sync = {
1029                 need_checkpoint => \(my $need_checkpoint = 0),
1030                 check_intvl => 10,
1031                 next_check => now() + 10,
1032                 -opt => $opt,
1033                 # DO NOT SET {reindex} here, it's incompatible with reused
1034                 # V2Writable code, reindex is totally different here
1035                 # compared to v1/v2 inboxes because we have multiple histories
1036                 self => $self,
1037                 -regen_fmt => "%u/?\n",
1038         };
1039         local $SIG{USR1} = sub { $need_checkpoint = 1 };
1040         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1041         local $SIG{QUIT} = $quit;
1042         local $SIG{INT} = $quit;
1043         local $SIG{TERM} = $quit;
1044         for my $ibx (@{ibx_sorted($self, 'known')}) {
1045                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1046         }
1047
1048         if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1049                 $sync->{id2pos} //= prep_id2pos($self);
1050                 $sync->{boost_in_use} = 1;
1051         }
1052
1053         if (my $msgids = delete($opt->{dedupe})) {
1054                 local $sync->{checkpoint_unlocks} = 1;
1055                 eidx_dedupe($self, $sync, $msgids);
1056         }
1057         if (delete($opt->{reindex})) {
1058                 local $sync->{checkpoint_unlocks} = 1;
1059                 eidx_reindex($self, $sync);
1060         }
1061
1062         # don't use $_ here, it'll get clobbered by reindex_checkpoint
1063         if ($opt->{scan} // 1) {
1064                 for my $ibx (@{ibx_sorted($self, 'active')}) {
1065                         last if $sync->{quit};
1066                         sync_inbox($self, $sync, $ibx);
1067                 }
1068         }
1069         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1070         eidxq_process($self, $sync) unless $sync->{quit};
1071
1072         eidxq_release($self);
1073         done($self);
1074         $sync; # for eidx_watch
1075 }
1076
1077 sub update_last_commit { # overrides V2Writable
1078         my ($self, $sync, $stk) = @_;
1079         my $unit = $sync->{unit} // return;
1080         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1081         defined($latest_cmt) or return;
1082         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1083         my $ekey = $ibx->eidx_key;
1084         my $uv = $ibx->uidvalidity;
1085         my $epoch = $unit->{epoch};
1086         my $meta_key;
1087         my $v = $ibx->version;
1088         if ($v == 2) {
1089                 die 'No {epoch} for v2 unit' unless defined $epoch;
1090                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1091         } elsif ($v == 1) {
1092                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1093                 $meta_key = "lc-v1:$ekey//$uv";
1094         } else {
1095                 die "Unsupported inbox version: $v";
1096         }
1097         my $last = $self->{oidx}->eidx_meta($meta_key);
1098         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1099                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1100                 chomp(my $n = $unit->{git}->qx(@cmd));
1101                 return if $n ne '' && $n == 0;
1102         }
1103         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1104 }
1105
1106 sub _idx_init { # with_umask callback
1107         my ($self, $opt) = @_;
1108         PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1109         $self->{midx} = PublicInbox::MiscIdx->new($self);
1110 }
1111
1112 sub symlink_packs ($$) {
1113         my ($ibx, $pd) = @_;
1114         my $ret = 0;
1115         my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1116         for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1117                 my $src = substr($idx, 0, -length('.idx'));
1118                 my $dst = $pd . substr($src, rindex($src, '/'));
1119                 if (-f "$src.pack" and
1120                                 symlink("$src.pack", "$dst.pack") and
1121                                 symlink($idx, "$dst.idx") and
1122                                 -f $idx) {
1123                         ++$ret;
1124                         # .promisor, .bitmap, .rev and .keep are optional
1125                         # XXX should we symlink .keep here?
1126                         for my $s (qw(promisor bitmap rev)) {
1127                                 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1128                         }
1129                 } elsif (!$!{EEXIST}) {
1130                         warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1131                         unlink "$dst.pack", "$dst.idx";
1132                 }
1133         }
1134         $ret;
1135 }
1136
1137 sub idx_init { # similar to V2Writable
1138         my ($self, $opt) = @_;
1139         return if $self->{idx_shards};
1140
1141         $self->git->cleanup;
1142         my $mode = 0644;
1143         my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1144         my ($has_new, $alt, $seen);
1145         if ($opt->{-private}) { # LeiStore
1146                 my $local = "$self->{topdir}/local"; # lei/store
1147                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1148                                                         'ALL.git', 'local');
1149                 $mode = 0600;
1150                 unless (-d $ALL) {
1151                         umask 077; # don't bother restoring for lei
1152                         PublicInbox::Import::init_bare($ALL);
1153                         $self->git->qx(qw(config core.sharedRepository 0600));
1154                 }
1155                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1156                 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1157         } else { # extindex has no epochs
1158                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1159                                                         'ALL.git');
1160                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1161                                                         $opt->{-idx_gc});
1162                 PublicInbox::Import::init_bare($ALL);
1163         }
1164
1165         # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1166         my $git_midx = 0;
1167         my $pd = "$ALL/objects/pack";
1168         if (opendir(my $dh, $pd)) { # drop stale symlinks
1169                 while (defined(my $dn = readdir($dh))) {
1170                         if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1171                                 my $f = "$pd/$dn";
1172                                 unlink($f) if -l $f && !-e $f;
1173                         }
1174                 }
1175         } elsif ($!{ENOENT}) {
1176                 mkdir($pd) or die "mkdir($pd): $!";
1177         } else {
1178                 die "opendir($pd): $!";
1179         }
1180         my $new = '';
1181         for my $ibx (@{ibx_sorted($self, 'active')}) {
1182                 # create symlinks for multi-pack-index
1183                 $git_midx += symlink_packs($ibx, $pd);
1184                 # add new lines to our alternates file
1185                 my $d = $ibx->git->{git_dir} . '/objects';
1186                 next if exists $alt->{$d};
1187                 if (my @st = stat($d)) {
1188                         next if $seen->{"$st[0]\0$st[1]"}++;
1189                 } else {
1190                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1191                         next if $opt->{-idx_gc};
1192                 }
1193                 $new .= "$d\n";
1194         }
1195         ($has_new || $new ne '') and
1196                 $self->{mg}->write_alternates($mode, $alt, $new);
1197         $git_midx and $self->with_umask(sub {
1198                 my @cmd = ('multi-pack-index');
1199                 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1200                 my $lk = $self->lock_for_scope;
1201                 system('git', "--git-dir=$ALL", @cmd, 'write');
1202                 # ignore errors, fairly new command, may not exist
1203         });
1204         $self->parallel_init($self->{indexlevel});
1205         $self->with_umask(\&_idx_init, $self, $opt);
1206         $self->{oidx}->begin_lazy;
1207         $self->{oidx}->eidx_prep;
1208         $self->{midx}->create_xdb if $new ne '';
1209 }
1210
1211 sub _watch_commit { # PublicInbox::DS::add_timer callback
1212         my ($self) = @_;
1213         delete $self->{-commit_timer};
1214         eidxq_process($self, $self->{-watch_sync});
1215         eidxq_release($self);
1216         my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1217         reindex_checkpoint($self, $self->{-watch_sync});
1218         $self->{-watch_sync}->{-regen_fmt} = $fmt;
1219
1220         # call event_step => done unless commit_timer is armed
1221         PublicInbox::DS::requeue($self);
1222 }
1223
1224 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1225         my ($self, $ibx) = @_;
1226         my $opt = $self->{-watch_sync}->{-opt};
1227         my $pr = $opt->{-progress};
1228         my $ekey = $ibx->eidx_key;
1229         local $0 = "sync $ekey";
1230         $pr->("indexing $ekey\n") if $pr;
1231         $self->idx_init($opt);
1232         sync_inbox($self, $self->{-watch_sync}, $ibx);
1233         $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1234                                         \&_watch_commit, $self);
1235 }
1236
1237 sub eidx_reload { # -extindex --watch SIGHUP handler
1238         my ($self, $idler) = @_;
1239         if ($self->{cfg}) {
1240                 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1241                 $pr->('reloading ...') if $pr;
1242                 delete $self->{-resync_queue};
1243                 delete $self->{-ibx_ary_known};
1244                 delete $self->{-ibx_ary_active};
1245                 $self->{ibx_known} = [];
1246                 $self->{ibx_active} = [];
1247                 %{$self->{ibx_map}} = ();
1248                 delete $self->{-watch_sync}->{id2pos};
1249                 my $cfg = PublicInbox::Config->new;
1250                 attach_config($self, $cfg);
1251                 $idler->refresh($cfg);
1252                 $pr->(" done\n") if $pr;
1253         } else {
1254                 warn "reload not supported without --all\n";
1255         }
1256 }
1257
1258 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1259         my ($self) = @_;
1260         $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1261         PublicInbox::DS::requeue($self); # trigger our ->event_step
1262 }
1263
1264 sub event_step { # PublicInbox::DS::requeue callback
1265         my ($self) = @_;
1266         if (my $resync_queue = $self->{-resync_queue}) {
1267                 if (my $ibx = shift(@$resync_queue)) {
1268                         on_inbox_unlock($self, $ibx);
1269                         PublicInbox::DS::requeue($self);
1270                 } else {
1271                         delete $self->{-resync_queue};
1272                         _watch_commit($self);
1273                 }
1274         } else {
1275                 done($self) unless $self->{-commit_timer};
1276         }
1277 }
1278
1279 sub eidx_watch { # public-inbox-extindex --watch main loop
1280         my ($self, $opt) = @_;
1281         local @SIG{keys %SIG} = values %SIG;
1282         for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1283                 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1284         }
1285         require PublicInbox::InboxIdle;
1286         require PublicInbox::DS;
1287         require PublicInbox::Syscall;
1288         require PublicInbox::Sigfd;
1289         my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1290         if (!$self->{cfg}) {
1291                 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1292         }
1293         for my $ibx (@{ibx_sorted($self, 'active')}) {
1294                 $ibx->subscribe_unlock(__PACKAGE__, $self)
1295         }
1296         my $pr = $opt->{-progress};
1297         $pr->("performing initial scan ...\n") if $pr;
1298         my $sync = eidx_sync($self, $opt); # initial sync
1299         return if $sync->{quit};
1300         my $oldset = PublicInbox::DS::block_signals();
1301         local $self->{current_info} = '';
1302         my $cb = $SIG{__WARN__} || \&CORE::warn;
1303         local $SIG{__WARN__} = sub {
1304                 return if PublicInbox::Eml::warn_ignore(@_);
1305                 $cb->($self->{current_info}, ': ', @_);
1306         };
1307         my $sig = {
1308                 HUP => sub { eidx_reload($self, $idler) },
1309                 USR1 => sub { eidx_resync_start($self) },
1310                 TSTP => sub { kill('STOP', $$) },
1311         };
1312         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1313         $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1314         local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1315         PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1316         $pr->("initial scan complete, entering event loop\n") if $pr;
1317         # calls InboxIdle->event_step:
1318         PublicInbox::DS::event_loop($sig, $oldset);
1319         done($self);
1320 }
1321
1322 no warnings 'once';
1323 *done = \&PublicInbox::V2Writable::done;
1324 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1325 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1326 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1327 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1328 *index_todo = \&PublicInbox::V2Writable::index_todo;
1329 *count_shards = \&PublicInbox::V2Writable::count_shards;
1330 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1331 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1332 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1333 *checkpoint = \&PublicInbox::V2Writable::checkpoint;
1334
1335 1;