]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearchidx: checkpoint releases locks
[public-inbox.git] / lib / PublicInbox / ExtSearchIdx.pm
1 # Copyright (C) 2020 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 PublicInbox::Search;
22 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor
23         is_bad_blob);
24 use PublicInbox::OverIdx;
25 use PublicInbox::MiscIdx;
26 use PublicInbox::MID qw(mids);
27 use PublicInbox::V2Writable;
28 use PublicInbox::InboxWritable;
29 use PublicInbox::ContentHash qw(content_hash);
30 use PublicInbox::Eml;
31 use File::Spec;
32 use DBI qw(:sql_types); # SQL_BLOB
33
34 sub new {
35         my (undef, $dir, $opt) = @_;
36         $dir = File::Spec->canonpath($dir);
37         my $l = $opt->{indexlevel} // 'full';
38         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
39                 die "invalid indexlevel=$l\n";
40         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
41         my $self = bless {
42                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
43                 topdir => $dir,
44                 creat => $opt->{creat},
45                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
46                 ibx_list => [],
47                 indexlevel => $l,
48                 transact_bytes => 0,
49                 total_bytes => 0,
50                 current_info => '',
51                 parallel => 1,
52                 lock_path => "$dir/ei.lock",
53         }, __PACKAGE__;
54         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
55         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
56         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
57         $self->{oidx} = $oidx;
58         $self
59 }
60
61 sub attach_inbox {
62         my ($self, $ibx) = @_;
63         $ibx = PublicInbox::InboxWritable->new($ibx);
64         my $key = $ibx->eidx_key;
65         if (!$ibx->over || !$ibx->mm) {
66                 warn "W: skipping $key (unindexed)\n";
67                 return;
68         }
69         if (!defined($ibx->uidvalidity)) {
70                 warn "W: skipping $key (no UIDVALIDITY)\n";
71                 return;
72         }
73         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
74         if ($ibxdir ne $ibx->{inboxdir}) {
75                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
76                 $ibx->{inboxdir} = $ibxdir;
77         }
78         $ibx = PublicInbox::InboxWritable->new($ibx);
79         $self->{ibx_map}->{$key} //= do {
80                 push @{$self->{ibx_list}}, $ibx;
81                 $ibx;
82         }
83 }
84
85 sub _ibx_attach { # each_inbox callback
86         my ($ibx, $self) = @_;
87         attach_inbox($self, $ibx);
88 }
89
90 sub attach_config {
91         my ($self, $cfg) = @_;
92         $self->{cfg} = $cfg;
93         $cfg->each_inbox(\&_ibx_attach, $self);
94 }
95
96 sub check_batch_limit ($) {
97         my ($req) = @_;
98         my $self = $req->{self};
99         my $new_smsg = $req->{new_smsg};
100
101         # {raw_bytes} may be unset, so just use {bytes}
102         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
103
104         # set flag for PublicInbox::V2Writable::index_todo:
105         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
106 }
107
108 sub do_xpost ($$) {
109         my ($req, $smsg) = @_;
110         my $self = $req->{self};
111         my $docid = $smsg->{num};
112         my $idx = $self->idx_shard($docid);
113         my $oid = $req->{oid};
114         my $xibx = $req->{ibx};
115         my $eml = $req->{eml};
116         my $eidx_key = $xibx->eidx_key;
117         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
118                 my $xnum = $req->{xnum};
119                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
120                 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
121                 check_batch_limit($req);
122         } else { # 'd'
123                 my $rm_eidx_info;
124                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
125                                                         \$rm_eidx_info);
126                 if ($nr == 0) {
127                         $self->{oidx}->eidxq_del($docid);
128                         $idx->shard_remove($docid);
129                 } elsif ($rm_eidx_info) {
130                         $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
131                         $self->{oidx}->eidxq_add($docid); # yes, add
132                 }
133         }
134 }
135
136 # called by V2Writable::sync_prepare
137 sub artnum_max { $_[0]->{oidx}->eidx_max }
138
139 sub index_unseen ($) {
140         my ($req) = @_;
141         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
142         my $eml = delete $req->{eml};
143         $new_smsg->populate($eml, $req);
144         my $self = $req->{self};
145         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
146         $new_smsg->{num} = $docid;
147         my $idx = $self->idx_shard($docid);
148         $self->{oidx}->add_overview($eml, $new_smsg);
149         my $oid = $new_smsg->{blob};
150         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
151         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
152         $idx->index_raw(undef, $eml, $new_smsg, $ibx);
153         check_batch_limit($req);
154 }
155
156 sub do_finalize ($) {
157         my ($req) = @_;
158         if (my $indexed = $req->{indexed}) {
159                 do_xpost($req, $_) for @$indexed;
160         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
161                 index_unseen($req);
162         } else {
163                 # `d' message was already unindexed in the v1/v2 inboxes,
164                 # so it's too noisy to warn, here.
165         }
166         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
167         if (defined(my $cur_cmt = $req->{cur_cmt})) {
168                 ${$req->{latest_cmt}} = $cur_cmt;
169         }
170 }
171
172 sub do_step ($) { # main iterator for adding messages to the index
173         my ($req) = @_;
174         my $self = $req->{self} // die 'BUG: {self} missing';
175         while (1) {
176                 if (my $next_arg = $req->{next_arg}) {
177                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
178                                 $req->{cur_smsg} = $smsg;
179                                 $self->git->cat_async($smsg->{blob},
180                                                         \&ck_existing, $req);
181                                 return; # ck_existing calls do_step
182                         }
183                         delete $req->{cur_smsg};
184                         delete $req->{next_arg};
185                 }
186                 my $mid = shift(@{$req->{mids}});
187                 last unless defined $mid;
188                 my ($id, $prev);
189                 $req->{next_arg} = [ $mid, \$id, \$prev ];
190                 # loop again
191         }
192         do_finalize($req);
193 }
194
195 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
196         my ($req) = @_;
197         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
198         my $self = $req->{self};
199         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
200         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
201         if (@keep) {
202                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
203                         die "BUG: xref $keep[0] has no OID";
204                 my $oidhex = $1;
205                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
206                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
207                 my $saved = $self->{oidx}->get_art($smsg->{num});
208         } else {
209                 $self->{oidx}->delete_by_num($smsg->{num});
210         }
211 }
212
213 sub ck_existing { # git->cat_async callback
214         my ($bref, $oid, $type, $size, $req) = @_;
215         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
216         if ($type eq 'missing') {
217                 _blob_missing($req);
218         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
219                 my $self = $req->{self} // die 'BUG: {self} missing';
220                 local $self->{current_info} = "$self->{current_info} $oid";
221                 my $cur = PublicInbox::Eml->new($bref);
222                 if (content_hash($cur) eq $req->{chash}) {
223                         push @{$req->{indexed}}, $smsg; # for do_xpost
224                 } # else { index_unseen later }
225         }
226         do_step($req);
227 }
228
229 # is the messages visible in the inbox currently being indexed?
230 # return the number if so
231 sub cur_ibx_xnum ($$) {
232         my ($req, $bref) = @_;
233         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
234
235         $req->{eml} = PublicInbox::Eml->new($bref);
236         $req->{chash} = content_hash($req->{eml});
237         $req->{mids} = mids($req->{eml});
238         my @q = @{$req->{mids}}; # copy
239         while (defined(my $mid = shift @q)) {
240                 my ($id, $prev);
241                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
242                         return $x->{num} if $x->{blob} eq $req->{oid};
243                 }
244         }
245         undef;
246 }
247
248 sub index_oid { # git->cat_async callback for 'm'
249         my ($bref, $oid, $type, $size, $req) = @_;
250         my $self = $req->{self};
251         local $self->{current_info} = "$self->{current_info} $oid";
252         return if is_bad_blob($oid, $type, $size, $req->{oid});
253         my $new_smsg = $req->{new_smsg} = bless {
254                 blob => $oid,
255         }, 'PublicInbox::Smsg';
256         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
257         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
258         ++${$req->{nr}};
259         do_step($req);
260 }
261
262 sub unindex_oid { # git->cat_async callback for 'd'
263         my ($bref, $oid, $type, $size, $req) = @_;
264         my $self = $req->{self};
265         local $self->{current_info} = "$self->{current_info} $oid";
266         return if is_bad_blob($oid, $type, $size, $req->{oid});
267         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
268         do_step($req);
269 }
270
271 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
272 sub last_commits {
273         my ($self, $sync) = @_;
274         my $heads = [];
275         my $ekey = $sync->{ibx}->eidx_key;
276         my $uv = $sync->{ibx}->uidvalidity;
277         for my $i (0..$sync->{epoch_max}) {
278                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
279         }
280         $heads;
281 }
282
283 sub _sync_inbox ($$$) {
284         my ($self, $sync, $ibx) = @_;
285         $sync->{ibx} = $ibx;
286         $sync->{nr} = \(my $nr = 0);
287         my $v = $ibx->version;
288         my $ekey = $ibx->eidx_key;
289         if ($v == 2) {
290                 my $epoch_max;
291                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
292                 $sync->{epoch_max} = $epoch_max;
293                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
294         } elsif ($v == 1) {
295                 my $uv = $ibx->uidvalidity;
296                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
297                 my $head = $ibx->mm->last_commit;
298                 unless (defined $head) {
299                         warn "E: $ibx->{inboxdir} is not indexed\n";
300                         return;
301                 }
302                 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
303                 my $unit = { stack => $stk, git => $ibx->git };
304                 push @{$sync->{todo}}, $unit;
305         } else {
306                 warn "E: $ekey unsupported inbox version (v$v)\n";
307                 return;
308         }
309         for my $unit (@{delete($sync->{todo}) // []}) {
310                 last if $sync->{quit};
311                 index_todo($self, $sync, $unit);
312         }
313         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
314         $ibx->git->cleanup; # done with this inbox, now
315 }
316
317 sub gc_unref_doc ($$$$) {
318         my ($self, $ibx_id, $eidx_key, $docid) = @_;
319         my $dbh = $self->{oidx}->dbh;
320
321         # for debug/info purposes, oids may no longer be accessible
322         my $sth = $dbh->prepare_cached(<<'', undef, 1);
323 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
324
325         $sth->execute($docid, $ibx_id);
326         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
327
328         $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
329 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
330
331         my $remain = $self->{oidx}->get_xref3($docid);
332         if (scalar(@$remain)) {
333                 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
334                 for my $oid (@oid) {
335                         warn "I: unref #$docid $eidx_key $oid\n";
336                 }
337         } else {
338                 warn "I: remove #$docid $eidx_key @oid\n";
339                 $self->idx_shard($docid)->shard_remove($docid);
340         }
341 }
342
343 sub eidx_gc {
344         my ($self, $opt) = @_;
345         $self->{cfg} or die "E: GC requires ->attach_config\n";
346         $opt->{-idx_gc} = 1;
347         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
348
349         my $dbh = $self->{oidx}->dbh;
350         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
351         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
352         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
353
354         $ibx_ck->execute;
355         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
356                 next if $self->{ibx_map}->{$eidx_key};
357                 $self->{midx}->remove_eidx_key($eidx_key);
358                 warn "I: deleting messages for $eidx_key...\n";
359                 $x3_doc->execute($ibx_id);
360                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
361                         gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
362                 }
363                 $dbh->prepare_cached(<<'')->execute($ibx_id);
364 DELETE FROM inboxes WHERE ibx_id = ?
365
366                 # drop last_commit info
367                 my $pat = $eidx_key;
368                 $pat =~ s/([_%])/\\$1/g;
369                 $lc_i->execute("lc-%:$pat//%");
370                 while (my ($key) = $lc_i->fetchrow_array) {
371                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
372                         warn "I: removing $key\n";
373                         $dbh->prepare_cached(<<'')->execute($key);
374 DELETE FROM eidx_meta WHERE key = ?
375
376                 }
377
378                 warn "I: $eidx_key removed\n";
379         }
380
381         # it's not real unless it's in `over', we use parallelism here,
382         # shards will be reading directly from over, so commit
383         $self->{oidx}->commit_lazy;
384         $self->{oidx}->begin_lazy;
385
386         for my $idx (@{$self->{idx_shards}}) {
387                 warn "I: cleaning up shard #$idx->{shard}\n";
388                 $idx->shard_over_check($self->{oidx});
389         }
390         my $nr = $dbh->do(<<'');
391 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
392
393         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
394
395         done($self);
396 }
397
398 sub _reindex_finalize ($$$) {
399         my ($req, $smsg, $eml) = @_;
400         my $sync = $req->{sync};
401         my $self = $sync->{self};
402         my $by_chash = $req->{by_chash};
403         my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
404         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
405         my $docid = $smsg->{num} = $orig_smsg->{num};
406         $self->{oidx}->add_overview($eml, $smsg); # may rethread
407         check_batch_limit({ %$sync, new_smsg => $smsg });
408         if ($nr == 1) { # likely, all good
409                 $self->idx_shard($docid)->shard_reindex_docid($docid);
410                 return;
411         }
412         warn "W: #$docid split into $nr due to deduplication change\n";
413         my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
414         delete($by_chash->{$chash0}) // die "BUG: $smsg->{blob} chash missing";
415         my @todo;
416         for my $ary (values %$by_chash) {
417                 for my $x (reverse @$ary) {
418                         warn "removing #$docid xref3 $x->{blob}\n";
419                         my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
420                         die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
421                 }
422                 my $x = $ary->[-1] // die "BUG: #$docid {by_chash} empty";
423                 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
424                 my $ibx_id = delete($x->{ibx_id}) // die '{ibx_id} unset';
425                 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
426                 my $ibx = $self->{ibx_list}->[$pos] //
427                         die "BUG: ibx for $x->{blob} not mapped";
428                 my $e = $ibx->over->get_art($x->{num});
429                 $e->{blob} eq $x->{blob} or die <<EOF;
430 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
431 EOF
432                 push @todo, $ibx, $e;
433         }
434         $self->{oidx}->commit_lazy; # ensure shard workers can see xref removals
435         $self->{oidx}->begin_lazy;
436         $self->idx_shard($docid)->shard_reindex_docid($docid);
437         while (my ($ibx, $e) = splice(@todo, 0, 2)) {
438                 reindex_unseen($self, $sync, $ibx, $e);
439         }
440 }
441
442 sub _reindex_oid { # git->cat_async callback
443         my ($bref, $oid, $type, $size, $req) = @_;
444         my $sync = $req->{sync};
445         my $self = $sync->{self};
446         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
447         my $expect_oid = $req->{xr3}->[$req->{ix}]->[2];
448         my $docid = $orig_smsg->{num};
449         if (is_bad_blob($oid, $type, $size, $expect_oid)) {
450                 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
451                 if ($remain == 0) {
452                         warn "W: #$docid gone or corrupted\n";
453                         $self->idx_shard($docid)->shard_remove($docid);
454                 } elsif (my $next_oid = $req->{xr3}->[++$req->{ix}]->[2]) {
455                         $self->git->cat_async($next_oid, \&_reindex_oid, $req);
456                 } else {
457                         warn "BUG: #$docid gone (UNEXPECTED)\n";
458                         $self->idx_shard($docid)->shard_remove($docid);
459                 }
460                 return;
461         }
462         my $ci = $self->{current_info};
463         local $self->{current_info} = "$ci #$docid $oid";
464         my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
465         $re_smsg->{bytes} = $size + crlf_adjust($$bref);
466         my $eml = PublicInbox::Eml->new($bref);
467         $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
468                                 cotime => $orig_smsg->{ts} });
469         my $chash = content_hash($eml);
470         $re_smsg->{chash} = $chash;
471         $re_smsg->{xnum} = $req->{xr3}->[$req->{ix}]->[1];
472         $re_smsg->{ibx_id} = $req->{xr3}->[$req->{ix}]->[0];
473         push @{$req->{by_chash}->{$chash}}, $re_smsg;
474         if (my $next_oid = $req->{xr3}->[++$req->{ix}]->[2]) {
475                 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
476         } else { # last $re_smsg is the highest priority xref3
477                 local $self->{current_info} = "$ci #$docid";
478                 _reindex_finalize($req, $re_smsg, $eml);
479         }
480 }
481
482 sub _reindex_smsg ($$$) {
483         my ($self, $sync, $smsg) = @_;
484         my $docid = $smsg->{num};
485         my $xr3 = $self->{oidx}->get_xref3($docid, 1);
486         if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
487                 warn <<"";
488 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
489
490                 $self->{oidx}->delete_by_num($docid);
491                 $self->idx_shard($docid)->shard_remove($docid);
492                 return;
493         }
494
495         # we sort {xr3} in the reverse order of {ibx_list} so we can
496         # hit the common case in _reindex_finalize without rereading
497         # from git (or holding multiple messages in memory).
498         my $id2pos = $sync->{id2pos}; # index in {ibx_list}
499         @$xr3 = sort {
500                 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
501                                 ||
502                 $b->[1] <=> $a->[1] # break ties with {xnum}
503         } @$xr3;
504         @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
505         my $req = { orig_smsg => $smsg, sync => $sync, xr3 => $xr3, ix => 0 };
506         $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
507 }
508
509 sub eidxq_process ($$) { # for reindexing
510         my ($self, $sync) = @_;
511
512         $self->{oidx}->commit_lazy; # ensure shard workers can see it
513         $self->{oidx}->begin_lazy;
514         my $dbh = $self->{oidx}->dbh;
515         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
516         ${$sync->{nr}} = 0;
517         $sync->{-regen_fmt} = "%u/$tot\n";
518         my $pr = $sync->{-opt}->{-progress};
519         if ($pr) {
520                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
521                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
522                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
523         }
524         my %id2pos;
525         my $pos = 0;
526         $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
527         $sync->{id2pos} = \%id2pos;
528
529         my $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
530         my $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
531         $iter->execute;
532         while (defined(my $docid = $iter->fetchrow_array)) {
533                 last if $sync->{quit};
534                 if (my $smsg = $self->{oidx}->get_art($docid)) {
535                         _reindex_smsg($self, $sync, $smsg);
536                 } else {
537                         warn "E: #$docid does not exist in over\n";
538                 }
539                 $del->execute($docid);
540                 ++${$sync->{nr}};
541
542                 # this is only for SIGUSR1, shards do their own accounting:
543                 reindex_checkpoint($self, $sync) if ${$sync->{need_checkpoint}};
544         }
545         $self->git->async_wait_all;
546         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
547 }
548
549 sub _reindex_unseen { # git->cat_async callback
550         my ($bref, $oid, $type, $size, $req) = @_;
551         return if is_bad_blob($oid, $type, $size, $req->{oid});
552         my $self = $req->{self} // die 'BUG: {self} unset';
553         local $self->{current_info} = "$self->{current_info} $oid";
554         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
555         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
556         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
557         $req->{new_smsg} = $new_smsg;
558         $req->{chash} = content_hash($eml);
559         $req->{mids} = mids($eml); # do_step iterates through this
560         do_step($req); # enter the normal indexing flow
561 }
562
563 # --reindex may catch totally unseen messages, this handles them
564 sub reindex_unseen ($$$$) {
565         my ($self, $sync, $ibx, $xsmsg) = @_;
566         my $req = {
567                 %$sync, # has {self}
568                 autime => $xsmsg->{ds},
569                 cotime => $xsmsg->{ts},
570                 oid => $xsmsg->{blob},
571                 ibx => $ibx,
572                 xnum => $xsmsg->{num},
573                 # {mids} and {chash} will be filled in at _reindex_unseen
574         };
575         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
576         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
577 }
578
579 sub _reindex_check_unseen ($$$) {
580         my ($self, $sync, $ibx) = @_;
581         my $ibx_id = $ibx->{-ibx_id};
582         my ($beg, $end) = (1, 1000);
583
584         # first, check if we missed any messages in target $ibx
585         my $inx3 = $self->{oidx}->dbh->prepare(<<'');
586 SELECT DISTINCT(docid) FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
587
588         my $msgs;
589         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
590                 $beg = $msgs->[-1]->{num} + 1;
591                 $end = $beg + 1000;
592                 for my $xsmsg (@$msgs) {
593                         my $oidbin = pack('H*', $xsmsg->{blob});
594                         $inx3->bind_param(1, $ibx_id);
595                         $inx3->bind_param(2, $xsmsg->{num});
596                         $inx3->bind_param(3, $oidbin, SQL_BLOB);
597                         $inx3->execute;
598                         my $docids = $inx3->fetchall_arrayref;
599                         # index messages which were totally missed
600                         # the first time around ASAP:
601                         if (scalar(@$docids) == 0) {
602                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
603                         } else { # already seen, reindex later
604                                 for my $r (@$docids) {
605                                         $self->{oidx}->eidxq_add($r->[0]);
606                                 }
607                         }
608                         last if $sync->{quit};
609                 }
610                 last if $sync->{quit};
611         }
612 }
613
614 sub _reindex_check_stale ($$$) {
615         my ($self, $sync, $ibx) = @_;
616
617         # now, check if there's stale xrefs
618         my $get_xnum = $self->{oidx}->dbh->prepare(<<'');
619 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? ORDER BY docid ASC
620
621         $get_xnum->execute($ibx->{-ibx_id});
622         my $del_xref3 = $self->{oidx}->dbh->prepare(<<'');
623 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
624
625         while (my ($docid, $xnum, $oidbin) = $get_xnum->fetchrow_array) {
626                 last if $sync->{quit};
627                 my $smsg = $ibx->over->get_art($xnum);
628                 my $oidhex = unpack('H*', $oidbin);
629                 my $err;
630                 if (!$smsg) {
631                         $err = 'stale';
632                 } elsif ($smsg->{blob} ne $oidhex) {
633                         $err = "mismatch (!= $smsg->{blob})";
634                 } else {
635                         next; # likely, all good
636                 }
637                 warn $ibx->eidx_key . ":$xnum:$oidhex (#$docid): $err\n";
638                 $del_xref3->bind_param(1, $ibx->{-ibx_id});
639                 $del_xref3->bind_param(2, $xnum);
640                 $del_xref3->bind_param(3, $oidbin, SQL_BLOB);
641                 $del_xref3->execute;
642
643                 # get_xref3 over-fetches, but this is a rare path:
644                 my $xr3 = $self->{oidx}->get_xref3($docid);
645                 my $idx = $self->idx_shard($docid);
646                 if (scalar(@$xr3) == 0) { # all gone
647                         $self->{oidx}->delete_by_num($docid);
648                         $self->{oidx}->eidxq_del($docid);
649                         $idx->shard_remove($docid);
650                 } else { # enqueue for reindex of remaining messages
651                         $idx->shard_remove_eidx_info($docid, $ibx->eidx_key);
652                         $self->{oidx}->eidxq_add($docid); # yes, add
653                 }
654         }
655 }
656
657 sub _reindex_inbox ($$$) {
658         my ($self, $sync, $ibx) = @_;
659         _reindex_check_unseen($self, $sync, $ibx);
660         _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
661         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
662 }
663
664 sub eidx_reindex {
665         my ($self, $sync) = @_;
666
667         for my $ibx (@{$self->{ibx_list}}) {
668                 _reindex_inbox($self, $sync, $ibx);
669                 last if $sync->{quit};
670         }
671         $self->git->async_wait_all; # ensure eidxq gets filled completely
672         eidxq_process($self, $sync) unless $sync->{quit};
673 }
674
675 sub eidx_sync { # main entry point
676         my ($self, $opt) = @_;
677
678         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
679         local $self->{current_info} = '';
680         local $SIG{__WARN__} = sub {
681                 $warn_cb->($self->{current_info}, ': ', @_);
682         };
683         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
684         $self->{oidx}->rethread_prepare($opt);
685         my $sync = {
686                 need_checkpoint => \(my $need_checkpoint = 0),
687                 -opt => $opt,
688                 # DO NOT SET {reindex} here, it's incompatible with reused
689                 # V2Writable code, reindex is totally different here
690                 # compared to v1/v2 inboxes because we have multiple histories
691                 self => $self,
692                 -regen_fmt => "%u/?\n",
693         };
694         local $SIG{USR1} = sub { $need_checkpoint = 1 };
695         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
696         local $SIG{QUIT} = $quit;
697         local $SIG{INT} = $quit;
698         local $SIG{TERM} = $quit;
699         for my $ibx (@{$self->{ibx_list}}) {
700                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
701         }
702         if (delete($opt->{reindex})) {
703                 $sync->{checkpoint_unlocks} = 1;
704                 eidx_reindex($self, $sync);
705         }
706
707         # don't use $_ here, it'll get clobbered by reindex_checkpoint
708         for my $ibx (@{$self->{ibx_list}}) {
709                 last if $sync->{quit};
710                 _sync_inbox($self, $sync, $ibx);
711         }
712         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
713         eidxq_process($self, $sync) unless $sync->{quit};
714
715         PublicInbox::V2Writable::done($self);
716 }
717
718 sub update_last_commit { # overrides V2Writable
719         my ($self, $sync, $stk) = @_;
720         my $unit = $sync->{unit} // return;
721         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
722         defined($latest_cmt) or return;
723         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
724         my $ekey = $ibx->eidx_key;
725         my $uv = $ibx->uidvalidity;
726         my $epoch = $unit->{epoch};
727         my $meta_key;
728         my $v = $ibx->version;
729         if ($v == 2) {
730                 die 'No {epoch} for v2 unit' unless defined $epoch;
731                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
732         } elsif ($v == 1) {
733                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
734                 $meta_key = "lc-v1:$ekey//$uv";
735         } else {
736                 die "Unsupported inbox version: $v";
737         }
738         my $last = $self->{oidx}->eidx_meta($meta_key);
739         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
740                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
741                 chomp(my $n = $unit->{git}->qx(@cmd));
742                 return if $n ne '' && $n == 0;
743         }
744         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
745 }
746
747 sub _idx_init { # with_umask callback
748         my ($self, $opt) = @_;
749         PublicInbox::V2Writable::_idx_init($self, $opt);
750         $self->{midx} = PublicInbox::MiscIdx->new($self);
751 }
752
753 sub idx_init { # similar to V2Writable
754         my ($self, $opt) = @_;
755         return if $self->{idx_shards};
756
757         $self->git->cleanup;
758
759         my $ALL = $self->git->{git_dir}; # ALL.git
760         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
761         my $info_dir = "$ALL/objects/info";
762         my $alt = "$info_dir/alternates";
763         my $mode = 0644;
764         my (@old, @new, %seen); # seen: st_dev + st_ino
765         if (-e $alt) {
766                 open(my $fh, '<', $alt) or die "open $alt: $!";
767                 $mode = (stat($fh))[2] & 07777;
768                 while (my $line = <$fh>) {
769                         chomp(my $d = $line);
770                         if (my @st = stat($d)) {
771                                 next if $seen{"$st[0]\0$st[1]"}++;
772                         } else {
773                                 warn "W: stat($d) failed (from $alt): $!\n";
774                                 next if $opt->{-idx_gc};
775                         }
776                         push @old, $line;
777                 }
778         }
779         for my $ibx (@{$self->{ibx_list}}) {
780                 my $line = $ibx->git->{git_dir} . "/objects\n";
781                 chomp(my $d = $line);
782                 if (my @st = stat($d)) {
783                         next if $seen{"$st[0]\0$st[1]"}++;
784                 } else {
785                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
786                         next if $opt->{-idx_gc};
787                 }
788                 push @new, $line;
789         }
790         if (scalar @new) {
791                 push @old, @new;
792                 my $o = \@old;
793                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
794         }
795         $self->parallel_init($self->{indexlevel});
796         $self->umask_prepare;
797         $self->with_umask(\&_idx_init, $self, $opt);
798         $self->{oidx}->begin_lazy;
799         $self->{oidx}->eidx_prep;
800         $self->{midx}->begin_txn;
801 }
802
803 no warnings 'once';
804 *done = \&PublicInbox::V2Writable::done;
805 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
806 *with_umask = \&PublicInbox::InboxWritable::with_umask;
807 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
808 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
809 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
810 *index_todo = \&PublicInbox::V2Writable::index_todo;
811 *count_shards = \&PublicInbox::V2Writable::count_shards;
812 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
813 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
814 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
815
816 1;