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