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