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