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