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