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