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