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