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