]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
inbox: simplify v2 epoch counting
[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 Sys::Hostname qw(hostname);
22 use POSIX qw(strftime);
23 use PublicInbox::Search;
24 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor
25         is_bad_blob);
26 use PublicInbox::OverIdx;
27 use PublicInbox::MiscIdx;
28 use PublicInbox::MID qw(mids);
29 use PublicInbox::V2Writable;
30 use PublicInbox::InboxWritable;
31 use PublicInbox::ContentHash qw(content_hash);
32 use PublicInbox::Eml;
33 use File::Spec;
34 use PublicInbox::DS qw(now);
35 use DBI qw(:sql_types); # SQL_BLOB
36
37 sub new {
38         my (undef, $dir, $opt) = @_;
39         $dir = File::Spec->canonpath($dir);
40         my $l = $opt->{indexlevel} // 'full';
41         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
42                 die "invalid indexlevel=$l\n";
43         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
44         my $self = bless {
45                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
46                 topdir => $dir,
47                 creat => $opt->{creat},
48                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
49                 ibx_list => [],
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 || nproc_shards($opt->{creat});
58         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
59         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
60         $self->{oidx} = $oidx;
61         $self
62 }
63
64 sub attach_inbox {
65         my ($self, $ibx) = @_;
66         $ibx = PublicInbox::InboxWritable->new($ibx);
67         my $key = $ibx->eidx_key;
68         if (!$ibx->over || !$ibx->mm) {
69                 warn "W: skipping $key (unindexed)\n";
70                 return;
71         }
72         if (!defined($ibx->uidvalidity)) {
73                 warn "W: skipping $key (no UIDVALIDITY)\n";
74                 return;
75         }
76         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
77         if ($ibxdir ne $ibx->{inboxdir}) {
78                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
79                 $ibx->{inboxdir} = $ibxdir;
80         }
81         $ibx = PublicInbox::InboxWritable->new($ibx);
82         $self->{ibx_map}->{$key} //= do {
83                 push @{$self->{ibx_list}}, $ibx;
84                 $ibx;
85         }
86 }
87
88 sub _ibx_attach { # each_inbox callback
89         my ($ibx, $self) = @_;
90         attach_inbox($self, $ibx);
91 }
92
93 sub attach_config {
94         my ($self, $cfg) = @_;
95         $self->{cfg} = $cfg;
96         $cfg->each_inbox(\&_ibx_attach, $self);
97 }
98
99 sub check_batch_limit ($) {
100         my ($req) = @_;
101         my $self = $req->{self};
102         my $new_smsg = $req->{new_smsg};
103
104         # {raw_bytes} may be unset, so just use {bytes}
105         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
106
107         # set flag for PublicInbox::V2Writable::index_todo:
108         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
109 }
110
111 sub do_xpost ($$) {
112         my ($req, $smsg) = @_;
113         my $self = $req->{self};
114         my $docid = $smsg->{num};
115         my $idx = $self->idx_shard($docid);
116         my $oid = $req->{oid};
117         my $xibx = $req->{ibx};
118         my $eml = $req->{eml};
119         my $eidx_key = $xibx->eidx_key;
120         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
121                 my $xnum = $req->{xnum};
122                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
123                 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
124                 check_batch_limit($req);
125         } else { # 'd'
126                 my $rm_eidx_info;
127                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
128                                                         \$rm_eidx_info);
129                 if ($nr == 0) {
130                         $self->{oidx}->eidxq_del($docid);
131                         $idx->shard_remove($docid);
132                 } elsif ($rm_eidx_info) {
133                         $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
134                         $self->{oidx}->eidxq_add($docid); # yes, add
135                 }
136         }
137 }
138
139 # called by V2Writable::sync_prepare
140 sub artnum_max { $_[0]->{oidx}->eidx_max }
141
142 sub index_unseen ($) {
143         my ($req) = @_;
144         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
145         my $eml = delete $req->{eml};
146         $new_smsg->populate($eml, $req);
147         my $self = $req->{self};
148         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
149         $new_smsg->{num} = $docid;
150         my $idx = $self->idx_shard($docid);
151         $self->{oidx}->add_overview($eml, $new_smsg);
152         my $oid = $new_smsg->{blob};
153         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
154         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
155         $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
156         check_batch_limit($req);
157 }
158
159 sub do_finalize ($) {
160         my ($req) = @_;
161         if (my $indexed = $req->{indexed}) {
162                 do_xpost($req, $_) for @$indexed;
163         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
164                 index_unseen($req);
165         } else {
166                 # `d' message was already unindexed in the v1/v2 inboxes,
167                 # so it's too noisy to warn, here.
168         }
169         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
170         if (defined(my $cur_cmt = $req->{cur_cmt})) {
171                 ${$req->{latest_cmt}} = $cur_cmt;
172         }
173 }
174
175 sub do_step ($) { # main iterator for adding messages to the index
176         my ($req) = @_;
177         my $self = $req->{self} // die 'BUG: {self} missing';
178         while (1) {
179                 if (my $next_arg = $req->{next_arg}) {
180                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
181                                 $req->{cur_smsg} = $smsg;
182                                 $self->git->cat_async($smsg->{blob},
183                                                         \&ck_existing, $req);
184                                 return; # ck_existing calls do_step
185                         }
186                         delete $req->{cur_smsg};
187                         delete $req->{next_arg};
188                 }
189                 my $mid = shift(@{$req->{mids}});
190                 last unless defined $mid;
191                 my ($id, $prev);
192                 $req->{next_arg} = [ $mid, \$id, \$prev ];
193                 # loop again
194         }
195         do_finalize($req);
196 }
197
198 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
199         my ($req) = @_;
200         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
201         my $self = $req->{self};
202         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
203         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
204         if (@keep) {
205                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
206                         die "BUG: xref $keep[0] has no OID";
207                 my $oidhex = $1;
208                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
209                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
210                 my $saved = $self->{oidx}->get_art($smsg->{num});
211         } else {
212                 $self->{oidx}->delete_by_num($smsg->{num});
213         }
214 }
215
216 sub ck_existing { # git->cat_async callback
217         my ($bref, $oid, $type, $size, $req) = @_;
218         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
219         if ($type eq 'missing') {
220                 _blob_missing($req);
221         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
222                 my $self = $req->{self} // die 'BUG: {self} missing';
223                 local $self->{current_info} = "$self->{current_info} $oid";
224                 my $cur = PublicInbox::Eml->new($bref);
225                 if (content_hash($cur) eq $req->{chash}) {
226                         push @{$req->{indexed}}, $smsg; # for do_xpost
227                 } # else { index_unseen later }
228         }
229         do_step($req);
230 }
231
232 # is the messages visible in the inbox currently being indexed?
233 # return the number if so
234 sub cur_ibx_xnum ($$) {
235         my ($req, $bref) = @_;
236         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
237
238         $req->{eml} = PublicInbox::Eml->new($bref);
239         $req->{chash} = content_hash($req->{eml});
240         $req->{mids} = mids($req->{eml});
241         my @q = @{$req->{mids}}; # copy
242         while (defined(my $mid = shift @q)) {
243                 my ($id, $prev);
244                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
245                         return $x->{num} if $x->{blob} eq $req->{oid};
246                 }
247         }
248         undef;
249 }
250
251 sub index_oid { # git->cat_async callback for 'm'
252         my ($bref, $oid, $type, $size, $req) = @_;
253         my $self = $req->{self};
254         local $self->{current_info} = "$self->{current_info} $oid";
255         return if is_bad_blob($oid, $type, $size, $req->{oid});
256         my $new_smsg = $req->{new_smsg} = bless {
257                 blob => $oid,
258         }, 'PublicInbox::Smsg';
259         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
260         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
261         ++${$req->{nr}};
262         do_step($req);
263 }
264
265 sub unindex_oid { # git->cat_async callback for 'd'
266         my ($bref, $oid, $type, $size, $req) = @_;
267         my $self = $req->{self};
268         local $self->{current_info} = "$self->{current_info} $oid";
269         return if is_bad_blob($oid, $type, $size, $req->{oid});
270         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
271         do_step($req);
272 }
273
274 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
275 sub last_commits {
276         my ($self, $sync) = @_;
277         my $heads = [];
278         my $ekey = $sync->{ibx}->eidx_key;
279         my $uv = $sync->{ibx}->uidvalidity;
280         for my $i (0..$sync->{epoch_max}) {
281                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
282         }
283         $heads;
284 }
285
286 sub _sync_inbox ($$$) {
287         my ($self, $sync, $ibx) = @_;
288         $sync->{ibx} = $ibx;
289         $sync->{nr} = \(my $nr = 0);
290         my $v = $ibx->version;
291         my $ekey = $ibx->eidx_key;
292         if ($v == 2) {
293                 $sync->{epoch_max} = $ibx->max_git_epoch // return;
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 host_ident () {
528         # I've copied FS images and only changed the hostname before,
529         # so prepend hostname.  Use `state' since these a BOFH can change
530         # these while this process is running and we always want to be
531         # able to release locks taken by this process.
532         state $retval = hostname . '-' . do {
533                 my $m; # machine-id(5) is systemd
534                 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
535                 # hostid(1) is in GNU coreutils, kern.hostid is FreeBSD
536                 chomp($m ||= `hostid` || `sysctl -n kern.hostid`);
537                 $m;
538         };
539 }
540
541 sub eidxq_release {
542         my ($self) = @_;
543         my $expect = delete($self->{-eidxq_locked}) or return;
544         my ($owner_pid, undef) = split(/-/, $expect);
545         return if $owner_pid != $$; # shards may fork
546         my $oidx = $self->{oidx};
547         $oidx->begin_lazy;
548         my $cur = $oidx->eidx_meta('eidxq_lock') // '';
549         if ($cur eq $expect) {
550                 $oidx->eidx_meta('eidxq_lock', '');
551                 return 1;
552         } elsif ($cur ne '') {
553                 warn "E: eidxq_lock($expect) stolen by $cur\n";
554         } else {
555                 warn "E: eidxq_lock($expect) released by another process\n";
556         }
557         undef;
558 }
559
560 sub DESTROY {
561         my ($self) = @_;
562         eidxq_release($self) and $self->{oidx}->commit_lazy;
563 }
564
565 sub _eidxq_take ($) {
566         my ($self) = @_;
567         my $val = "$$-${\time}-$>-".host_ident;
568         $self->{oidx}->eidx_meta('eidxq_lock', $val);
569         $self->{-eidxq_locked} = $val;
570 }
571
572 sub eidxq_lock_acquire ($) {
573         my ($self) = @_;
574         my $oidx = $self->{oidx};
575         $oidx->begin_lazy;
576         my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
577         if (my $locked = $self->{-eidxq_locked}) { # be lazy
578                 return $locked if $locked eq $cur;
579         }
580         my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
581         my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
582         if ($euid == $> && $ident eq host_ident) {
583                 if (kill(0, $pid)) {
584                         warn <<EOM; return;
585 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
586 EOM
587                 }
588                 if ($!{ESRCH}) {
589                         warn "I: eidxq_lock is stale ($cur), clobbering\n";
590                         return _eidxq_take($self);
591                 }
592                 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
593         }
594         my $fn = $oidx->dbh->sqlite_db_filename;
595         warn <<EOF;
596 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
597 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
598 W:      sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
599 EOF
600         undef;
601 }
602
603 sub eidxq_process ($$) { # for reindexing
604         my ($self, $sync) = @_;
605
606         return unless eidxq_lock_acquire($self);
607         my $dbh = $self->{oidx}->dbh;
608         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
609         ${$sync->{nr}} = 0;
610         $sync->{-regen_fmt} = "%u/$tot\n";
611         my $pr = $sync->{-opt}->{-progress};
612         if ($pr) {
613                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
614                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
615                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
616         }
617         $sync->{id2pos} //= do {
618                 my %id2pos;
619                 my $pos = 0;
620                 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
621                 \%id2pos;
622         };
623         my ($del, $iter);
624 restart:
625         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
626         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
627         $iter->execute;
628         while (defined(my $docid = $iter->fetchrow_array)) {
629                 last if $sync->{quit};
630                 if (my $smsg = $self->{oidx}->get_art($docid)) {
631                         _reindex_smsg($self, $sync, $smsg);
632                 } else {
633                         warn "E: #$docid does not exist in over\n";
634                 }
635                 $del->execute($docid);
636                 ++${$sync->{nr}};
637
638                 if (checkpoint_due($sync)) {
639                         $dbh = $del = $iter = undef;
640                         reindex_checkpoint($self, $sync); # release lock
641                         $dbh = $self->{oidx}->dbh;
642                         goto restart;
643                 }
644         }
645         $self->git->async_wait_all;
646         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
647 }
648
649 sub _reindex_unseen { # git->cat_async callback
650         my ($bref, $oid, $type, $size, $req) = @_;
651         return if is_bad_blob($oid, $type, $size, $req->{oid});
652         my $self = $req->{self} // die 'BUG: {self} unset';
653         local $self->{current_info} = "$self->{current_info} $oid";
654         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
655         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
656         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
657         $req->{new_smsg} = $new_smsg;
658         $req->{chash} = content_hash($eml);
659         $req->{mids} = mids($eml); # do_step iterates through this
660         do_step($req); # enter the normal indexing flow
661 }
662
663 # --reindex may catch totally unseen messages, this handles them
664 sub reindex_unseen ($$$$) {
665         my ($self, $sync, $ibx, $xsmsg) = @_;
666         my $req = {
667                 %$sync, # has {self}
668                 autime => $xsmsg->{ds},
669                 cotime => $xsmsg->{ts},
670                 oid => $xsmsg->{blob},
671                 ibx => $ibx,
672                 xnum => $xsmsg->{num},
673                 # {mids} and {chash} will be filled in at _reindex_unseen
674         };
675         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
676         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
677 }
678
679 sub _reindex_check_unseen ($$$) {
680         my ($self, $sync, $ibx) = @_;
681         my $ibx_id = $ibx->{-ibx_id};
682         my $slice = 1000;
683         my ($beg, $end) = (1, $slice);
684
685         # first, check if we missed any messages in target $ibx
686         my $msgs;
687         my $pr = $sync->{-opt}->{-progress};
688         my $ekey = $ibx->eidx_key;
689         $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
690         ${$sync->{nr}} = 0;
691
692         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
693                 ${$sync->{nr}} = $beg;
694                 $beg = $msgs->[-1]->{num} + 1;
695                 $end = $beg + $slice;
696                 if (checkpoint_due($sync)) {
697                         reindex_checkpoint($self, $sync); # release lock
698                 }
699
700                 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
701 SELECT DISTINCT(docid) FROM xref3 WHERE
702 ibx_id = ? AND xnum = ? AND oidbin = ?
703
704                 for my $xsmsg (@$msgs) {
705                         my $oidbin = pack('H*', $xsmsg->{blob});
706                         $inx3->bind_param(1, $ibx_id);
707                         $inx3->bind_param(2, $xsmsg->{num});
708                         $inx3->bind_param(3, $oidbin, SQL_BLOB);
709                         $inx3->execute;
710                         my $docids = $inx3->fetchall_arrayref;
711                         # index messages which were totally missed
712                         # the first time around ASAP:
713                         if (scalar(@$docids) == 0) {
714                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
715                         } else { # already seen, reindex later
716                                 for my $r (@$docids) {
717                                         $self->{oidx}->eidxq_add($r->[0]);
718                                 }
719                         }
720                         last if $sync->{quit};
721                 }
722                 last if $sync->{quit};
723         }
724 }
725
726 sub _reindex_check_stale ($$$) {
727         my ($self, $sync, $ibx) = @_;
728         my $min = 0;
729         my $pr = $sync->{-opt}->{-progress};
730         my $fetching;
731         my $ekey = $ibx->eidx_key;
732         $sync->{-regen_fmt} =
733                         "$ekey check stale/missing %u/".$ibx->over->max."\n";
734         ${$sync->{nr}} = 0;
735         do {
736                 if (checkpoint_due($sync)) {
737                         reindex_checkpoint($self, $sync); # release lock
738                 }
739                 # now, check if there's stale xrefs
740                 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
741 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
742 ORDER BY docid,xnum ASC LIMIT 10000
743
744                 $iter->execute($ibx->{-ibx_id}, $min);
745                 $fetching = undef;
746
747                 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
748                         return if $sync->{quit};
749                         ${$sync->{nr}} = $xnum;
750
751                         $fetching = $min = $docid;
752                         my $smsg = $ibx->over->get_art($xnum);
753                         my $oidhex = unpack('H*', $oidbin);
754                         my $err;
755                         if (!$smsg) {
756                                 $err = 'stale';
757                         } elsif ($smsg->{blob} ne $oidhex) {
758                                 $err = "mismatch (!= $smsg->{blob})";
759                         } else {
760                                 next; # likely, all good
761                         }
762                         # current_info already has eidx_key
763                         warn "$xnum:$oidhex (#$docid): $err\n";
764                         my $del = $self->{oidx}->dbh->prepare_cached(<<'');
765 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
766
767                         $del->bind_param(1, $ibx->{-ibx_id});
768                         $del->bind_param(2, $xnum);
769                         $del->bind_param(3, $oidbin, SQL_BLOB);
770                         $del->execute;
771
772                         # get_xref3 over-fetches, but this is a rare path:
773                         my $xr3 = $self->{oidx}->get_xref3($docid);
774                         my $idx = $self->idx_shard($docid);
775                         if (scalar(@$xr3) == 0) { # all gone
776                                 $self->{oidx}->delete_by_num($docid);
777                                 $self->{oidx}->eidxq_del($docid);
778                                 $idx->shard_remove($docid);
779                         } else { # enqueue for reindex of remaining messages
780                                 $idx->shard_remove_eidx_info($docid,
781                                                         $ibx->eidx_key);
782                                 $self->{oidx}->eidxq_add($docid); # yes, add
783                         }
784                 }
785         } while (defined $fetching);
786 }
787
788 sub _reindex_inbox ($$$) {
789         my ($self, $sync, $ibx) = @_;
790         local $self->{current_info} = $ibx->eidx_key;
791         _reindex_check_unseen($self, $sync, $ibx);
792         _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
793         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
794 }
795
796 sub eidx_reindex {
797         my ($self, $sync) = @_;
798
799         # acquire eidxq_lock early because full reindex takes forever
800         # and incremental -extindex processes can run during our checkpoints
801         if (!eidxq_lock_acquire($self)) {
802                 warn "E: aborting --reindex\n";
803                 return;
804         }
805         for my $ibx (@{$self->{ibx_list}}) {
806                 _reindex_inbox($self, $sync, $ibx);
807                 last if $sync->{quit};
808         }
809         $self->git->async_wait_all; # ensure eidxq gets filled completely
810         eidxq_process($self, $sync) unless $sync->{quit};
811 }
812
813 sub eidx_sync { # main entry point
814         my ($self, $opt) = @_;
815
816         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
817         local $self->{current_info} = '';
818         local $SIG{__WARN__} = sub {
819                 $warn_cb->($self->{current_info}, ': ', @_);
820         };
821         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
822         $self->{oidx}->rethread_prepare($opt);
823         my $sync = {
824                 need_checkpoint => \(my $need_checkpoint = 0),
825                 check_intvl => 10,
826                 next_check => now() + 10,
827                 -opt => $opt,
828                 # DO NOT SET {reindex} here, it's incompatible with reused
829                 # V2Writable code, reindex is totally different here
830                 # compared to v1/v2 inboxes because we have multiple histories
831                 self => $self,
832                 -regen_fmt => "%u/?\n",
833         };
834         local $SIG{USR1} = sub { $need_checkpoint = 1 };
835         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
836         local $SIG{QUIT} = $quit;
837         local $SIG{INT} = $quit;
838         local $SIG{TERM} = $quit;
839         for my $ibx (@{$self->{ibx_list}}) {
840                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
841         }
842         if (delete($opt->{reindex})) {
843                 $sync->{checkpoint_unlocks} = 1;
844                 eidx_reindex($self, $sync);
845         }
846
847         # don't use $_ here, it'll get clobbered by reindex_checkpoint
848         for my $ibx (@{$self->{ibx_list}}) {
849                 last if $sync->{quit};
850                 _sync_inbox($self, $sync, $ibx);
851         }
852         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
853         eidxq_process($self, $sync) unless $sync->{quit};
854
855         eidxq_release($self);
856         PublicInbox::V2Writable::done($self);
857 }
858
859 sub update_last_commit { # overrides V2Writable
860         my ($self, $sync, $stk) = @_;
861         my $unit = $sync->{unit} // return;
862         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
863         defined($latest_cmt) or return;
864         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
865         my $ekey = $ibx->eidx_key;
866         my $uv = $ibx->uidvalidity;
867         my $epoch = $unit->{epoch};
868         my $meta_key;
869         my $v = $ibx->version;
870         if ($v == 2) {
871                 die 'No {epoch} for v2 unit' unless defined $epoch;
872                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
873         } elsif ($v == 1) {
874                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
875                 $meta_key = "lc-v1:$ekey//$uv";
876         } else {
877                 die "Unsupported inbox version: $v";
878         }
879         my $last = $self->{oidx}->eidx_meta($meta_key);
880         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
881                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
882                 chomp(my $n = $unit->{git}->qx(@cmd));
883                 return if $n ne '' && $n == 0;
884         }
885         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
886 }
887
888 sub _idx_init { # with_umask callback
889         my ($self, $opt) = @_;
890         PublicInbox::V2Writable::_idx_init($self, $opt);
891         $self->{midx} = PublicInbox::MiscIdx->new($self);
892 }
893
894 sub idx_init { # similar to V2Writable
895         my ($self, $opt) = @_;
896         return if $self->{idx_shards};
897
898         $self->git->cleanup;
899
900         my $ALL = $self->git->{git_dir}; # ALL.git
901         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
902         my $info_dir = "$ALL/objects/info";
903         my $alt = "$info_dir/alternates";
904         my $mode = 0644;
905         my (@old, @new, %seen); # seen: st_dev + st_ino
906         if (-e $alt) {
907                 open(my $fh, '<', $alt) or die "open $alt: $!";
908                 $mode = (stat($fh))[2] & 07777;
909                 while (my $line = <$fh>) {
910                         chomp(my $d = $line);
911                         if (my @st = stat($d)) {
912                                 next if $seen{"$st[0]\0$st[1]"}++;
913                         } else {
914                                 warn "W: stat($d) failed (from $alt): $!\n";
915                                 next if $opt->{-idx_gc};
916                         }
917                         push @old, $line;
918                 }
919         }
920         for my $ibx (@{$self->{ibx_list}}) {
921                 my $line = $ibx->git->{git_dir} . "/objects\n";
922                 chomp(my $d = $line);
923                 if (my @st = stat($d)) {
924                         next if $seen{"$st[0]\0$st[1]"}++;
925                 } else {
926                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
927                         next if $opt->{-idx_gc};
928                 }
929                 push @new, $line;
930         }
931         if (scalar @new) {
932                 push @old, @new;
933                 my $o = \@old;
934                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
935         }
936         $self->parallel_init($self->{indexlevel});
937         $self->umask_prepare;
938         $self->with_umask(\&_idx_init, $self, $opt);
939         $self->{oidx}->begin_lazy;
940         $self->{oidx}->eidx_prep;
941         $self->{midx}->begin_txn;
942 }
943
944 no warnings 'once';
945 *done = \&PublicInbox::V2Writable::done;
946 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
947 *with_umask = \&PublicInbox::InboxWritable::with_umask;
948 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
949 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
950 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
951 *index_todo = \&PublicInbox::V2Writable::index_todo;
952 *count_shards = \&PublicInbox::V2Writable::count_shards;
953 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
954 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
955 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
956
957 1;