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