]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
update copyrights for 2021
[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 PublicInbox::Search;
24 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor
25         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);
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
86         # {raw_bytes} may be unset, so just use {bytes}
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->shard_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->shard_remove($docid);
114                 } elsif ($rm_eidx_info) {
115                         $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
116                         $self->{oidx}->eidxq_add($docid); # yes, add
117                 }
118         }
119 }
120
121 # called by V2Writable::sync_prepare
122 sub artnum_max { $_[0]->{oidx}->eidx_max }
123
124 sub index_unseen ($) {
125         my ($req) = @_;
126         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
127         my $eml = delete $req->{eml};
128         $new_smsg->populate($eml, $req);
129         my $self = $req->{self};
130         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
131         $new_smsg->{num} = $docid;
132         my $idx = $self->idx_shard($docid);
133         $self->{oidx}->add_overview($eml, $new_smsg);
134         my $oid = $new_smsg->{blob};
135         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
136         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
137         $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
138         check_batch_limit($req);
139 }
140
141 sub do_finalize ($) {
142         my ($req) = @_;
143         if (my $indexed = $req->{indexed}) {
144                 do_xpost($req, $_) for @$indexed;
145         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
146                 index_unseen($req);
147         } else {
148                 # `d' message was already unindexed in the v1/v2 inboxes,
149                 # so it's too noisy to warn, here.
150         }
151         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
152         if (defined(my $cur_cmt = $req->{cur_cmt})) {
153                 ${$req->{latest_cmt}} = $cur_cmt;
154         }
155 }
156
157 sub do_step ($) { # main iterator for adding messages to the index
158         my ($req) = @_;
159         my $self = $req->{self} // die 'BUG: {self} missing';
160         while (1) {
161                 if (my $next_arg = $req->{next_arg}) {
162                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
163                                 $req->{cur_smsg} = $smsg;
164                                 $self->git->cat_async($smsg->{blob},
165                                                         \&ck_existing, $req);
166                                 return; # ck_existing calls do_step
167                         }
168                         delete $req->{cur_smsg};
169                         delete $req->{next_arg};
170                 }
171                 my $mid = shift(@{$req->{mids}});
172                 last unless defined $mid;
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 req->{cur_smsg}->{blob} is bad
181         my ($req) = @_;
182         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
183         my $self = $req->{self};
184         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
185         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
186         if (@keep) {
187                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
188                         die "BUG: xref $keep[0] has no OID";
189                 my $oidhex = $1;
190                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
191                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
192                 my $saved = $self->{oidx}->get_art($smsg->{num});
193         } else {
194                 $self->{oidx}->delete_by_num($smsg->{num});
195         }
196 }
197
198 sub ck_existing { # git->cat_async callback
199         my ($bref, $oid, $type, $size, $req) = @_;
200         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
201         if ($type eq 'missing') {
202                 _blob_missing($req);
203         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
204                 my $self = $req->{self} // die 'BUG: {self} missing';
205                 local $self->{current_info} = "$self->{current_info} $oid";
206                 my $cur = PublicInbox::Eml->new($bref);
207                 if (content_hash($cur) eq $req->{chash}) {
208                         push @{$req->{indexed}}, $smsg; # for do_xpost
209                 } # else { index_unseen later }
210         }
211         do_step($req);
212 }
213
214 # is the messages visible in the inbox currently being indexed?
215 # return the number if so
216 sub cur_ibx_xnum ($$) {
217         my ($req, $bref) = @_;
218         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
219
220         $req->{eml} = PublicInbox::Eml->new($bref);
221         $req->{chash} = content_hash($req->{eml});
222         $req->{mids} = mids($req->{eml});
223         my @q = @{$req->{mids}}; # copy
224         while (defined(my $mid = shift @q)) {
225                 my ($id, $prev);
226                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
227                         return $x->{num} if $x->{blob} eq $req->{oid};
228                 }
229         }
230         undef;
231 }
232
233 sub index_oid { # git->cat_async callback for 'm'
234         my ($bref, $oid, $type, $size, $req) = @_;
235         my $self = $req->{self};
236         local $self->{current_info} = "$self->{current_info} $oid";
237         return if is_bad_blob($oid, $type, $size, $req->{oid});
238         my $new_smsg = $req->{new_smsg} = bless {
239                 blob => $oid,
240         }, 'PublicInbox::Smsg';
241         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
242         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
243         ++${$req->{nr}};
244         do_step($req);
245 }
246
247 sub unindex_oid { # git->cat_async callback for 'd'
248         my ($bref, $oid, $type, $size, $req) = @_;
249         my $self = $req->{self};
250         local $self->{current_info} = "$self->{current_info} $oid";
251         return if is_bad_blob($oid, $type, $size, $req->{oid});
252         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
253         do_step($req);
254 }
255
256 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
257 sub last_commits {
258         my ($self, $sync) = @_;
259         my $heads = [];
260         my $ekey = $sync->{ibx}->eidx_key;
261         my $uv = $sync->{ibx}->uidvalidity;
262         for my $i (0..$sync->{epoch_max}) {
263                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
264         }
265         $heads;
266 }
267
268 sub _ibx_index_reject ($) {
269         my ($ibx) = @_;
270         $ibx->mm // return 'unindexed, no msgmap.sqlite3';
271         $ibx->uidvalidity // return 'no UIDVALIDITY';
272         $ibx->over // return 'unindexed, no over.sqlite3';
273         undef;
274 }
275
276 sub _sync_inbox ($$$) {
277         my ($self, $sync, $ibx) = @_;
278         my $ekey = $ibx->eidx_key;
279         if (defined(my $err = _ibx_index_reject($ibx))) {
280                 return "W: skipping $ekey ($err)";
281         }
282         $sync->{ibx} = $ibx;
283         $sync->{nr} = \(my $nr = 0);
284         my $v = $ibx->version;
285         if ($v == 2) {
286                 $sync->{epoch_max} = $ibx->max_git_epoch // return;
287                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
288         } elsif ($v == 1) {
289                 my $uv = $ibx->uidvalidity;
290                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
291                 my $head = $ibx->mm->last_commit //
292                         return "E: $ibx->{inboxdir} is not indexed";
293                 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
294                 my $unit = { stack => $stk, git => $ibx->git };
295                 push @{$sync->{todo}}, $unit;
296         } else {
297                 return "E: $ekey unsupported inbox version (v$v)";
298         }
299         for my $unit (@{delete($sync->{todo}) // []}) {
300                 last if $sync->{quit};
301                 index_todo($self, $sync, $unit);
302         }
303         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
304         $ibx->git->cleanup; # done with this inbox, now
305         undef;
306 }
307
308 sub gc_unref_doc ($$$$) {
309         my ($self, $ibx_id, $eidx_key, $docid) = @_;
310         my $dbh = $self->{oidx}->dbh;
311
312         # for debug/info purposes, oids may no longer be accessible
313         my $sth = $dbh->prepare_cached(<<'', undef, 1);
314 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
315
316         $sth->execute($docid, $ibx_id);
317         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
318
319         $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
320 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
321
322         my $remain = $self->{oidx}->get_xref3($docid);
323         if (scalar(@$remain)) {
324                 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
325                 for my $oid (@oid) {
326                         warn "I: unref #$docid $eidx_key $oid\n";
327                 }
328         } else {
329                 warn "I: remove #$docid $eidx_key @oid\n";
330                 $self->idx_shard($docid)->shard_remove($docid);
331         }
332 }
333
334 sub eidx_gc {
335         my ($self, $opt) = @_;
336         $self->{cfg} or die "E: GC requires ->attach_config\n";
337         $opt->{-idx_gc} = 1;
338         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
339
340         my $dbh = $self->{oidx}->dbh;
341         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
342         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
343         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
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_list}->[$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_list}}) + 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_raw(undef, $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->shard_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)->shard_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)->shard_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->{bytes} = $size + crlf_adjust($$bref);
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)->shard_remove($docid);
526                 return;
527         }
528
529         # we sort {xr3r} in the reverse order of {ibx_list} 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_list}
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 eidxq_process ($$) { # for reindexing
627         my ($self, $sync) = @_;
628
629         return unless eidxq_lock_acquire($self);
630         my $dbh = $self->{oidx}->dbh;
631         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
632         ${$sync->{nr}} = 0;
633         local $sync->{-regen_fmt} = "%u/$tot\n";
634         my $pr = $sync->{-opt}->{-progress};
635         if ($pr) {
636                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
637                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
638                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
639         }
640         $sync->{id2pos} //= do {
641                 my %id2pos;
642                 my $pos = 0;
643                 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
644                 \%id2pos;
645         };
646         my ($del, $iter);
647 restart:
648         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
649         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
650         $iter->execute;
651         while (defined(my $docid = $iter->fetchrow_array)) {
652                 last if $sync->{quit};
653                 if (my $smsg = $self->{oidx}->get_art($docid)) {
654                         _reindex_smsg($self, $sync, $smsg);
655                 } else {
656                         warn "E: #$docid does not exist in over\n";
657                 }
658                 $del->execute($docid);
659                 ++${$sync->{nr}};
660
661                 if (checkpoint_due($sync)) {
662                         $dbh = $del = $iter = undef;
663                         reindex_checkpoint($self, $sync); # release lock
664                         $dbh = $self->{oidx}->dbh;
665                         goto restart;
666                 }
667         }
668         $self->git->async_wait_all;
669         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
670 }
671
672 sub _reindex_unseen { # git->cat_async callback
673         my ($bref, $oid, $type, $size, $req) = @_;
674         return if is_bad_blob($oid, $type, $size, $req->{oid});
675         my $self = $req->{self} // die 'BUG: {self} unset';
676         local $self->{current_info} = "$self->{current_info} $oid";
677         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
678         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
679         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
680         $req->{new_smsg} = $new_smsg;
681         $req->{chash} = content_hash($eml);
682         $req->{mids} = mids($eml); # do_step iterates through this
683         do_step($req); # enter the normal indexing flow
684 }
685
686 # --reindex may catch totally unseen messages, this handles them
687 sub reindex_unseen ($$$$) {
688         my ($self, $sync, $ibx, $xsmsg) = @_;
689         my $req = {
690                 %$sync, # has {self}
691                 autime => $xsmsg->{ds},
692                 cotime => $xsmsg->{ts},
693                 oid => $xsmsg->{blob},
694                 ibx => $ibx,
695                 xnum => $xsmsg->{num},
696                 # {mids} and {chash} will be filled in at _reindex_unseen
697         };
698         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
699         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
700 }
701
702 sub _reindex_check_unseen ($$$) {
703         my ($self, $sync, $ibx) = @_;
704         my $ibx_id = $ibx->{-ibx_id};
705         my $slice = 1000;
706         my ($beg, $end) = (1, $slice);
707
708         # first, check if we missed any messages in target $ibx
709         my $msgs;
710         my $pr = $sync->{-opt}->{-progress};
711         my $ekey = $ibx->eidx_key;
712         local $sync->{-regen_fmt} =
713                         "$ekey checking unseen %u/".$ibx->over->max."\n";
714         ${$sync->{nr}} = 0;
715
716         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
717                 ${$sync->{nr}} = $beg;
718                 $beg = $msgs->[-1]->{num} + 1;
719                 $end = $beg + $slice;
720                 if (checkpoint_due($sync)) {
721                         reindex_checkpoint($self, $sync); # release lock
722                 }
723
724                 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
725 SELECT DISTINCT(docid) FROM xref3 WHERE
726 ibx_id = ? AND xnum = ? AND oidbin = ?
727
728                 for my $xsmsg (@$msgs) {
729                         my $oidbin = pack('H*', $xsmsg->{blob});
730                         $inx3->bind_param(1, $ibx_id);
731                         $inx3->bind_param(2, $xsmsg->{num});
732                         $inx3->bind_param(3, $oidbin, SQL_BLOB);
733                         $inx3->execute;
734                         my $docids = $inx3->fetchall_arrayref;
735                         # index messages which were totally missed
736                         # the first time around ASAP:
737                         if (scalar(@$docids) == 0) {
738                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
739                         } else { # already seen, reindex later
740                                 for my $r (@$docids) {
741                                         $self->{oidx}->eidxq_add($r->[0]);
742                                 }
743                         }
744                         last if $sync->{quit};
745                 }
746                 last if $sync->{quit};
747         }
748 }
749
750 sub _reindex_check_stale ($$$) {
751         my ($self, $sync, $ibx) = @_;
752         my $min = 0;
753         my $pr = $sync->{-opt}->{-progress};
754         my $fetching;
755         my $ekey = $ibx->eidx_key;
756         local $sync->{-regen_fmt} =
757                         "$ekey check stale/missing %u/".$ibx->over->max."\n";
758         ${$sync->{nr}} = 0;
759         do {
760                 if (checkpoint_due($sync)) {
761                         reindex_checkpoint($self, $sync); # release lock
762                 }
763                 # now, check if there's stale xrefs
764                 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
765 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
766 ORDER BY docid,xnum ASC LIMIT 10000
767
768                 $iter->execute($ibx->{-ibx_id}, $min);
769                 $fetching = undef;
770
771                 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
772                         return if $sync->{quit};
773                         ${$sync->{nr}} = $xnum;
774
775                         $fetching = $min = $docid;
776                         my $smsg = $ibx->over->get_art($xnum);
777                         my $oidhex = unpack('H*', $oidbin);
778                         my $err;
779                         if (!$smsg) {
780                                 $err = 'stale';
781                         } elsif ($smsg->{blob} ne $oidhex) {
782                                 $err = "mismatch (!= $smsg->{blob})";
783                         } else {
784                                 next; # likely, all good
785                         }
786                         # current_info already has eidx_key
787                         warn "$xnum:$oidhex (#$docid): $err\n";
788                         my $del = $self->{oidx}->dbh->prepare_cached(<<'');
789 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
790
791                         $del->bind_param(1, $ibx->{-ibx_id});
792                         $del->bind_param(2, $xnum);
793                         $del->bind_param(3, $oidbin, SQL_BLOB);
794                         $del->execute;
795
796                         # get_xref3 over-fetches, but this is a rare path:
797                         my $xr3 = $self->{oidx}->get_xref3($docid);
798                         my $idx = $self->idx_shard($docid);
799                         if (scalar(@$xr3) == 0) { # all gone
800                                 $self->{oidx}->delete_by_num($docid);
801                                 $self->{oidx}->eidxq_del($docid);
802                                 $idx->shard_remove($docid);
803                         } else { # enqueue for reindex of remaining messages
804                                 $idx->shard_remove_eidx_info($docid,
805                                                         $ibx->eidx_key);
806                                 $self->{oidx}->eidxq_add($docid); # yes, add
807                         }
808                 }
809         } while (defined $fetching);
810 }
811
812 sub _reindex_inbox ($$$) {
813         my ($self, $sync, $ibx) = @_;
814         my $ekey = $ibx->eidx_key;
815         local $self->{current_info} = $ekey;
816         if (defined(my $err = _ibx_index_reject($ibx))) {
817                 warn "W: cannot reindex $ekey ($err)\n";
818         } else {
819                 _reindex_check_unseen($self, $sync, $ibx);
820                 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
821         }
822         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
823 }
824
825 sub eidx_reindex {
826         my ($self, $sync) = @_;
827
828         # acquire eidxq_lock early because full reindex takes forever
829         # and incremental -extindex processes can run during our checkpoints
830         if (!eidxq_lock_acquire($self)) {
831                 warn "E: aborting --reindex\n";
832                 return;
833         }
834         for my $ibx (@{$self->{ibx_list}}) {
835                 _reindex_inbox($self, $sync, $ibx);
836                 last if $sync->{quit};
837         }
838         $self->git->async_wait_all; # ensure eidxq gets filled completely
839         eidxq_process($self, $sync) unless $sync->{quit};
840 }
841
842 sub sync_inbox {
843         my ($self, $sync, $ibx) = @_;
844         my $err = _sync_inbox($self, $sync, $ibx);
845         delete @$ibx{qw(mm over)};
846         warn $err, "\n" if defined($err);
847 }
848
849 sub eidx_sync { # main entry point
850         my ($self, $opt) = @_;
851
852         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
853         local $self->{current_info} = '';
854         local $SIG{__WARN__} = sub {
855                 $warn_cb->($self->{current_info}, ': ', @_);
856         };
857         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
858         $self->{oidx}->rethread_prepare($opt);
859         my $sync = {
860                 need_checkpoint => \(my $need_checkpoint = 0),
861                 check_intvl => 10,
862                 next_check => now() + 10,
863                 -opt => $opt,
864                 # DO NOT SET {reindex} here, it's incompatible with reused
865                 # V2Writable code, reindex is totally different here
866                 # compared to v1/v2 inboxes because we have multiple histories
867                 self => $self,
868                 -regen_fmt => "%u/?\n",
869         };
870         local $SIG{USR1} = sub { $need_checkpoint = 1 };
871         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
872         local $SIG{QUIT} = $quit;
873         local $SIG{INT} = $quit;
874         local $SIG{TERM} = $quit;
875         for my $ibx (@{$self->{ibx_list}}) {
876                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
877         }
878         if (delete($opt->{reindex})) {
879                 local $sync->{checkpoint_unlocks} = 1;
880                 eidx_reindex($self, $sync);
881         }
882
883         # don't use $_ here, it'll get clobbered by reindex_checkpoint
884         if ($opt->{scan} // 1) {
885                 for my $ibx (@{$self->{ibx_list}}) {
886                         last if $sync->{quit};
887                         sync_inbox($self, $sync, $ibx);
888                 }
889         }
890         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
891         eidxq_process($self, $sync) unless $sync->{quit};
892
893         eidxq_release($self);
894         done($self);
895         $sync; # for eidx_watch
896 }
897
898 sub update_last_commit { # overrides V2Writable
899         my ($self, $sync, $stk) = @_;
900         my $unit = $sync->{unit} // return;
901         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
902         defined($latest_cmt) or return;
903         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
904         my $ekey = $ibx->eidx_key;
905         my $uv = $ibx->uidvalidity;
906         my $epoch = $unit->{epoch};
907         my $meta_key;
908         my $v = $ibx->version;
909         if ($v == 2) {
910                 die 'No {epoch} for v2 unit' unless defined $epoch;
911                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
912         } elsif ($v == 1) {
913                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
914                 $meta_key = "lc-v1:$ekey//$uv";
915         } else {
916                 die "Unsupported inbox version: $v";
917         }
918         my $last = $self->{oidx}->eidx_meta($meta_key);
919         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
920                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
921                 chomp(my $n = $unit->{git}->qx(@cmd));
922                 return if $n ne '' && $n == 0;
923         }
924         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
925 }
926
927 sub _idx_init { # with_umask callback
928         my ($self, $opt) = @_;
929         PublicInbox::V2Writable::_idx_init($self, $opt);
930         $self->{midx} = PublicInbox::MiscIdx->new($self);
931 }
932
933 sub idx_init { # similar to V2Writable
934         my ($self, $opt) = @_;
935         return if $self->{idx_shards};
936
937         $self->git->cleanup;
938         my $mode = 0644;
939         my $ALL = $self->git->{git_dir}; # ALL.git
940         my $old = -d $ALL;
941         if ($opt->{-private}) { # LeiStore
942                 $mode = 0600;
943                 if (!$old) {
944                         umask 077; # don't bother restoring
945                         PublicInbox::Import::init_bare($ALL);
946                         $self->git->qx(qw(config core.sharedRepository 0600));
947                 }
948         } else {
949                 PublicInbox::Import::init_bare($ALL) unless $old;
950         }
951         my $info_dir = "$ALL/objects/info";
952         my $alt = "$info_dir/alternates";
953         my (@old, @new, %seen); # seen: st_dev + st_ino
954         if (-e $alt) {
955                 open(my $fh, '<', $alt) or die "open $alt: $!";
956                 $mode = (stat($fh))[2] & 07777;
957                 while (my $line = <$fh>) {
958                         chomp(my $d = $line);
959
960                         # expand relative path (/local/ stuff)
961                         substr($d, 0, 3) eq '../' and
962                                 $d = "$ALL/objects/$d";
963                         if (my @st = stat($d)) {
964                                 next if $seen{"$st[0]\0$st[1]"}++;
965                         } else {
966                                 warn "W: stat($d) failed (from $alt): $!\n";
967                                 next if $opt->{-idx_gc};
968                         }
969                         push @old, $line;
970                 }
971         }
972
973         # for LeiStore, and possibly some mirror-only state
974         if (opendir(my $dh, my $local = "$self->{topdir}/local")) {
975                 # highest numbered epoch first
976                 for my $n (sort { $b <=> $a } map { substr($_, 0, -4) + 0 }
977                                 grep(/\A[0-9]+\.git\z/, readdir($dh))) {
978                         my $d = "$local/$n.git/objects"; # absolute path
979                         if (my @st = stat($d)) {
980                                 next if $seen{"$st[0]\0$st[1]"}++;
981                                 # favor relative paths for rename-friendliness
982                                 push @new, "../../local/$n.git/objects\n";
983                         } else {
984                                 warn "W: stat($d) failed: $!\n";
985                         }
986                 }
987         }
988         for my $ibx (@{$self->{ibx_list}}) {
989                 my $line = $ibx->git->{git_dir} . "/objects\n";
990                 chomp(my $d = $line);
991                 if (my @st = stat($d)) {
992                         next if $seen{"$st[0]\0$st[1]"}++;
993                 } else {
994                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
995                         next if $opt->{-idx_gc};
996                 }
997                 push @new, $line;
998         }
999         if (scalar @new) {
1000                 push @old, @new;
1001                 my $o = \@old;
1002                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
1003         }
1004         $self->parallel_init($self->{indexlevel});
1005         $self->with_umask(\&_idx_init, $self, $opt);
1006         $self->{oidx}->begin_lazy;
1007         $self->{oidx}->eidx_prep;
1008         $self->{midx}->begin_txn;
1009 }
1010
1011 sub _watch_commit { # PublicInbox::DS::add_timer callback
1012         my ($self) = @_;
1013         delete $self->{-commit_timer};
1014         eidxq_process($self, $self->{-watch_sync});
1015         eidxq_release($self);
1016         delete local $self->{-watch_sync}->{-regen_fmt};
1017         reindex_checkpoint($self, $self->{-watch_sync});
1018
1019         # call event_step => done unless commit_timer is armed
1020         PublicInbox::DS::requeue($self);
1021 }
1022
1023 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1024         my ($self, $ibx) = @_;
1025         my $opt = $self->{-watch_sync}->{-opt};
1026         my $pr = $opt->{-progress};
1027         my $ekey = $ibx->eidx_key;
1028         local $0 = "sync $ekey";
1029         $pr->("indexing $ekey\n") if $pr;
1030         $self->idx_init($opt);
1031         sync_inbox($self, $self->{-watch_sync}, $ibx);
1032         $self->{-commit_timer} //= PublicInbox::DS::add_timer(
1033                                         $opt->{'commit-interval'} // 10,
1034                                         \&_watch_commit, $self);
1035 }
1036
1037 sub eidx_reload { # -extindex --watch SIGHUP handler
1038         my ($self, $idler) = @_;
1039         if ($self->{cfg}) {
1040                 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1041                 $pr->('reloading ...') if $pr;
1042                 delete $self->{-resync_queue};
1043                 @{$self->{ibx_list}} = ();
1044                 %{$self->{ibx_map}} = ();
1045                 delete $self->{-watch_sync}->{id2pos};
1046                 my $cfg = PublicInbox::Config->new;
1047                 attach_config($self, $cfg);
1048                 $idler->refresh($cfg);
1049                 $pr->(" done\n") if $pr;
1050         } else {
1051                 warn "reload not supported without --all\n";
1052         }
1053 }
1054
1055 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1056         my ($self) = @_;
1057         $self->{-resync_queue} //= [ @{$self->{ibx_list}} ];
1058         PublicInbox::DS::requeue($self); # trigger our ->event_step
1059 }
1060
1061 sub event_step { # PublicInbox::DS::requeue callback
1062         my ($self) = @_;
1063         if (my $resync_queue = $self->{-resync_queue}) {
1064                 if (my $ibx = shift(@$resync_queue)) {
1065                         on_inbox_unlock($self, $ibx);
1066                         PublicInbox::DS::requeue($self);
1067                 } else {
1068                         delete $self->{-resync_queue};
1069                         _watch_commit($self);
1070                 }
1071         } else {
1072                 done($self) unless $self->{-commit_timer};
1073         }
1074 }
1075
1076 sub eidx_watch { # public-inbox-extindex --watch main loop
1077         my ($self, $opt) = @_;
1078         local %SIG = %SIG;
1079         for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1080                 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1081         }
1082         require PublicInbox::InboxIdle;
1083         require PublicInbox::DS;
1084         require PublicInbox::Syscall;
1085         require PublicInbox::Sigfd;
1086         my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1087         if (!$self->{cfg}) {
1088                 $idler->watch_inbox($_) for @{$self->{ibx_list}};
1089         }
1090         $_->subscribe_unlock(__PACKAGE__, $self) for @{$self->{ibx_list}};
1091         my $pr = $opt->{-progress};
1092         $pr->("performing initial scan ...\n") if $pr;
1093         my $sync = eidx_sync($self, $opt); # initial sync
1094         return if $sync->{quit};
1095         my $oldset = PublicInbox::Sigfd::block_signals();
1096         local $self->{current_info} = '';
1097         my $cb = $SIG{__WARN__} || \&CORE::warn;
1098         local $SIG{__WARN__} = sub { $cb->($self->{current_info}, ': ', @_) };
1099         my $sig = {
1100                 HUP => sub { eidx_reload($self, $idler) },
1101                 USR1 => sub { eidx_resync_start($self) },
1102                 TSTP => sub { kill('STOP', $$) },
1103         };
1104         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1105         $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1106         my $sigfd = PublicInbox::Sigfd->new($sig,
1107                                         $PublicInbox::Syscall::SFD_NONBLOCK);
1108         %SIG = (%SIG, %$sig) if !$sigfd;
1109         local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1110         if (!$sigfd) {
1111                 # wake up every second to accept signals if we don't
1112                 # have signalfd or IO::KQueue:
1113                 PublicInbox::Sigfd::sig_setmask($oldset);
1114                 PublicInbox::DS->SetLoopTimeout(1000);
1115         }
1116         PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1117         $pr->("initial scan complete, entering event loop\n") if $pr;
1118         PublicInbox::DS->EventLoop; # calls InboxIdle->event_step
1119         done($self);
1120 }
1121
1122 no warnings 'once';
1123 *done = \&PublicInbox::V2Writable::done;
1124 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1125 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1126 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1127 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1128 *index_todo = \&PublicInbox::V2Writable::index_todo;
1129 *count_shards = \&PublicInbox::V2Writable::count_shards;
1130 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1131 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1132 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1133
1134 1;