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