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