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