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