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