]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearchidx: remove needless SHA-1 check
[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 use PublicInbox::OverIdx;
24 use PublicInbox::MiscIdx;
25 use PublicInbox::MID qw(mids);
26 use PublicInbox::V2Writable;
27 use PublicInbox::InboxWritable;
28 use PublicInbox::ContentHash qw(content_hash);
29 use PublicInbox::Eml;
30 use File::Spec;
31
32 sub new {
33         my (undef, $dir, $opt) = @_;
34         $dir = File::Spec->canonpath($dir);
35         my $l = $opt->{indexlevel} // 'full';
36         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
37                 die "invalid indexlevel=$l\n";
38         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
39         my $self = bless {
40                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
41                 topdir => $dir,
42                 creat => $opt->{creat},
43                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
44                 ibx_list => [],
45                 indexlevel => $l,
46                 transact_bytes => 0,
47                 total_bytes => 0,
48                 current_info => '',
49                 parallel => 1,
50                 lock_path => "$dir/ei.lock",
51         }, __PACKAGE__;
52         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
53         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
54         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
55         $self->{oidx} = $oidx;
56         $self
57 }
58
59 sub attach_inbox {
60         my ($self, $ibx) = @_;
61         $ibx = PublicInbox::InboxWritable->new($ibx);
62         my $key = $ibx->eidx_key;
63         if (!$ibx->over || !$ibx->mm) {
64                 warn "W: skipping $key (unindexed)\n";
65                 return;
66         }
67         if (!defined($ibx->uidvalidity)) {
68                 warn "W: skipping $key (no UIDVALIDITY)\n";
69                 return;
70         }
71         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
72         if ($ibxdir ne $ibx->{inboxdir}) {
73                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
74                 $ibx->{inboxdir} = $ibxdir;
75         }
76         $ibx = PublicInbox::InboxWritable->new($ibx);
77         $self->{ibx_map}->{$key} //= do {
78                 push @{$self->{ibx_list}}, $ibx;
79                 $ibx;
80         }
81 }
82
83 sub _ibx_attach { # each_inbox callback
84         my ($ibx, $self) = @_;
85         attach_inbox($self, $ibx);
86 }
87
88 sub attach_config {
89         my ($self, $cfg) = @_;
90         $self->{cfg} = $cfg;
91         $cfg->each_inbox(\&_ibx_attach, $self);
92 }
93
94 sub is_bad_blob ($$$$) {
95         my ($oid, $type, $size, $expect_oid) = @_;
96         if ($type ne 'blob') {
97                 carp "W: $expect_oid is not a blob (type=$type)";
98                 return 1;
99         }
100         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
101         $size == 0 ? 1 : 0; # size == 0 means purged
102 }
103
104 sub check_batch_limit ($) {
105         my ($req) = @_;
106         my $self = $req->{self};
107         my $new_smsg = $req->{new_smsg};
108
109         # {raw_bytes} may be unset, so just use {bytes}
110         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
111
112         # set flag for PublicInbox::V2Writable::index_todo:
113         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
114 }
115
116 sub do_xpost ($$) {
117         my ($req, $smsg) = @_;
118         my $self = $req->{self};
119         my $docid = $smsg->{num};
120         my $idx = $self->idx_shard($docid);
121         my $oid = $req->{oid};
122         my $xibx = $req->{ibx};
123         my $eml = $req->{eml};
124         my $eidx_key = $xibx->eidx_key;
125         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
126                 my $xnum = $req->{xnum};
127                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
128                 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
129                 check_batch_limit($req);
130         } else { # 'd'
131                 my $rm_eidx_info;
132                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
133                                                         \$rm_eidx_info);
134                 if ($nr == 0) {
135                         $idx->shard_remove($oid, $docid);
136                 } elsif ($rm_eidx_info) {
137                         $idx->shard_remove_eidx_info($docid, $oid, $eidx_key,
138                                                         $eml);
139                 }
140         }
141 }
142
143 # called by V2Writable::sync_prepare
144 sub artnum_max { $_[0]->{oidx}->eidx_max }
145
146 sub index_unseen ($) {
147         my ($req) = @_;
148         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
149         my $eml = delete $req->{eml};
150         $new_smsg->populate($eml, $req);
151         my $self = $req->{self};
152         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
153         $new_smsg->{num} = $docid;
154         my $idx = $self->idx_shard($docid);
155         $self->{oidx}->add_overview($eml, $new_smsg);
156         my $oid = $new_smsg->{blob};
157         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
158         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
159         $idx->index_raw(undef, $eml, $new_smsg, $ibx);
160         check_batch_limit($req);
161 }
162
163 sub do_finalize ($) {
164         my ($req) = @_;
165         if (my $indexed = $req->{indexed}) {
166                 do_xpost($req, $_) for @$indexed;
167         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
168                 index_unseen($req);
169         } else {
170                 # `d' message was already unindexed in the v1/v2 inboxes,
171                 # so it's too noisy to warn, here.
172         }
173         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
174         if (defined(my $cur_cmt = $req->{cur_cmt})) {
175                 ${$req->{latest_cmt}} = $cur_cmt;
176         }
177 }
178
179 sub do_step ($) { # main iterator for adding messages to the index
180         my ($req) = @_;
181         my $self = $req->{self};
182         while (1) {
183                 if (my $next_arg = $req->{next_arg}) {
184                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
185                                 $req->{cur_smsg} = $smsg;
186                                 $self->git->cat_async($smsg->{blob},
187                                                         \&ck_existing, $req);
188                                 return; # ck_existing calls do_step
189                         }
190                         delete $req->{cur_smsg};
191                         delete $req->{next_arg};
192                 }
193                 my $mid = shift(@{$req->{mids}});
194                 last unless defined $mid;
195                 my ($id, $prev);
196                 $req->{next_arg} = [ $mid, \$id, \$prev ];
197                 # loop again
198         }
199         do_finalize($req);
200 }
201
202 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
203         my ($req) = @_;
204         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
205         my $self = $req->{self};
206         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
207         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
208         if (@keep) {
209                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
210                         die "BUG: xref $keep[0] has no OID";
211                 my $oidhex = $1;
212                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
213                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
214                 my $saved = $self->{oidx}->get_art($smsg->{num});
215         } else {
216                 $self->{oidx}->delete_by_num($smsg->{num});
217         }
218 }
219
220 sub ck_existing { # git->cat_async callback
221         my ($bref, $oid, $type, $size, $req) = @_;
222         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
223         if ($type eq 'missing') {
224                 _blob_missing($req);
225         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
226                 my $cur = PublicInbox::Eml->new($bref);
227                 if (content_hash($cur) eq $req->{chash}) {
228                         push @{$req->{indexed}}, $smsg; # for do_xpost
229                 } # else { index_unseen later }
230         }
231         do_step($req);
232 }
233
234 # is the messages visible in the inbox currently being indexed?
235 # return the number if so
236 sub cur_ibx_xnum ($$) {
237         my ($req, $bref) = @_;
238         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
239
240         $req->{eml} = PublicInbox::Eml->new($bref);
241         $req->{chash} = content_hash($req->{eml});
242         $req->{mids} = mids($req->{eml});
243         my @q = @{$req->{mids}}; # copy
244         while (defined(my $mid = shift @q)) {
245                 my ($id, $prev);
246                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
247                         return $x->{num} if $x->{blob} eq $req->{oid};
248                 }
249         }
250         undef;
251 }
252
253 sub index_oid { # git->cat_async callback for 'm'
254         my ($bref, $oid, $type, $size, $req) = @_;
255         my $self = $req->{self};
256         local $self->{current_info} = "$self->{current_info} $oid";
257         return if is_bad_blob($oid, $type, $size, $req->{oid});
258         my $new_smsg = $req->{new_smsg} = bless {
259                 blob => $oid,
260         }, 'PublicInbox::Smsg';
261         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
262         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
263         ++${$req->{nr}};
264         do_step($req);
265 }
266
267 sub unindex_oid { # git->cat_async callback for 'd'
268         my ($bref, $oid, $type, $size, $req) = @_;
269         my $self = $req->{self};
270         local $self->{current_info} = "$self->{current_info} $oid";
271         return if is_bad_blob($oid, $type, $size, $req->{oid});
272         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
273         do_step($req);
274 }
275
276 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
277 sub last_commits {
278         my ($self, $sync) = @_;
279         my $heads = [];
280         my $ekey = $sync->{ibx}->eidx_key;
281         my $uv = $sync->{ibx}->uidvalidity;
282         for my $i (0..$sync->{epoch_max}) {
283                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
284         }
285         $heads;
286 }
287
288 sub _sync_inbox ($$$) {
289         my ($self, $sync, $ibx) = @_;
290         $sync->{ibx} = $ibx;
291         $sync->{nr} = \(my $nr = 0);
292         my $v = $ibx->version;
293         my $ekey = $ibx->eidx_key;
294         if ($v == 2) {
295                 my $epoch_max;
296                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
297                 $sync->{epoch_max} = $epoch_max;
298                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
299         } elsif ($v == 1) {
300                 my $uv = $ibx->uidvalidity;
301                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
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 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         my $idx = $self->idx_shard($docid);
333         if (@$remain) {
334                 for my $oid (@oid) {
335                         warn "I: unref #$docid $eidx_key $oid\n";
336                         $idx->shard_remove_eidx_info($docid, $oid, $eidx_key);
337                 }
338         } else {
339                 for my $oid (@oid) {
340                         warn "I: remove #$docid $eidx_key $oid\n";
341                         $idx->shard_remove($oid, $docid);
342                 }
343         }
344 }
345
346 sub eidx_gc {
347         my ($self, $opt) = @_;
348         $self->{cfg} or die "E: GC requires ->attach_config\n";
349         $opt->{-idx_gc} = 1;
350         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
351
352         my $dbh = $self->{oidx}->dbh;
353         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
354         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
355         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
356
357         $ibx_ck->execute;
358         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
359                 next if $self->{ibx_map}->{$eidx_key};
360                 $self->{midx}->remove_eidx_key($eidx_key);
361                 warn "I: deleting messages for $eidx_key...\n";
362                 $x3_doc->execute($ibx_id);
363                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
364                         unref_doc($self, $ibx_id, $eidx_key, $docid);
365                 }
366                 $dbh->prepare_cached(<<'')->execute($ibx_id);
367 DELETE FROM inboxes WHERE ibx_id = ?
368
369                 # drop last_commit info
370                 my $pat = $eidx_key;
371                 $pat =~ s/([_%])/\\$1/g;
372                 $lc_i->execute("lc-%:$pat//%");
373                 while (my ($key) = $lc_i->fetchrow_array) {
374                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
375                         warn "I: removing $key\n";
376                         $dbh->prepare_cached(<<'')->execute($key);
377 DELETE FROM eidx_meta WHERE key = ?
378
379                 }
380
381                 warn "I: $eidx_key removed\n";
382         }
383
384         # it's not real unless it's in `over', we use parallelism here,
385         # shards will be reading directly from over, so commit
386         $self->{oidx}->commit_lazy;
387         $self->{oidx}->begin_lazy;
388
389         for my $idx (@{$self->{idx_shards}}) {
390                 warn "I: cleaning up shard #$idx->{shard}\n";
391                 $idx->shard_over_check($self->{oidx});
392         }
393         my $nr = $dbh->do(<<'');
394 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
395
396         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
397
398         done($self);
399 }
400
401 sub eidx_sync { # main entry point
402         my ($self, $opt) = @_;
403         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
404         $self->{oidx}->rethread_prepare($opt);
405
406         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
407         local $self->{current_info} = '';
408         local $SIG{__WARN__} = sub {
409                 $warn_cb->($self->{current_info}, ': ', @_);
410         };
411         my $sync = {
412                 need_checkpoint => \(my $need_checkpoint = 0),
413                 reindex => $opt->{reindex},
414                 -opt => $opt,
415                 self => $self,
416                 -regen_fmt => "%u/?\n",
417         };
418         local $SIG{USR1} = sub { $need_checkpoint = 1 };
419         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
420         local $SIG{QUIT} = $quit;
421         local $SIG{INT} = $quit;
422         local $SIG{TERM} = $quit;
423
424         # don't use $_ here, it'll get clobbered by reindex_checkpoint
425         for my $ibx (@{$self->{ibx_list}}) {
426                 last if $sync->{quit};
427                 _sync_inbox($self, $sync, $ibx);
428         }
429         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
430
431         PublicInbox::V2Writable::done($self);
432 }
433
434 sub update_last_commit { # overrides V2Writable
435         my ($self, $sync, $stk) = @_;
436         my $unit = $sync->{unit} // return;
437         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
438         defined($latest_cmt) or return;
439         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
440         my $ekey = $ibx->eidx_key;
441         my $uv = $ibx->uidvalidity;
442         my $epoch = $unit->{epoch};
443         my $meta_key;
444         my $v = $ibx->version;
445         if ($v == 2) {
446                 die 'No {epoch} for v2 unit' unless defined $epoch;
447                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
448         } elsif ($v == 1) {
449                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
450                 $meta_key = "lc-v1:$ekey//$uv";
451         } else {
452                 die "Unsupported inbox version: $v";
453         }
454         my $last = $self->{oidx}->eidx_meta($meta_key);
455         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
456                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
457                 chomp(my $n = $unit->{git}->qx(@cmd));
458                 return if $n ne '' && $n == 0;
459         }
460         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
461 }
462
463 sub _idx_init { # with_umask callback
464         my ($self, $opt) = @_;
465         PublicInbox::V2Writable::_idx_init($self, $opt);
466         $self->{midx} = PublicInbox::MiscIdx->new($self);
467 }
468
469 sub idx_init { # similar to V2Writable
470         my ($self, $opt) = @_;
471         return if $self->{idx_shards};
472
473         $self->git->cleanup;
474
475         my $ALL = $self->git->{git_dir}; # ALL.git
476         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
477         my $info_dir = "$ALL/objects/info";
478         my $alt = "$info_dir/alternates";
479         my $mode = 0644;
480         my (@old, @new, %seen); # seen: st_dev + st_ino
481         if (-e $alt) {
482                 open(my $fh, '<', $alt) or die "open $alt: $!";
483                 $mode = (stat($fh))[2] & 07777;
484                 while (my $line = <$fh>) {
485                         chomp(my $d = $line);
486                         if (my @st = stat($d)) {
487                                 next if $seen{"$st[0]\0$st[1]"}++;
488                         } else {
489                                 warn "W: stat($d) failed (from $alt): $!\n";
490                                 next if $opt->{-idx_gc};
491                         }
492                         push @old, $line;
493                 }
494         }
495         for my $ibx (@{$self->{ibx_list}}) {
496                 my $line = $ibx->git->{git_dir} . "/objects\n";
497                 chomp(my $d = $line);
498                 if (my @st = stat($d)) {
499                         next if $seen{"$st[0]\0$st[1]"}++;
500                 } else {
501                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
502                         next if $opt->{-idx_gc};
503                 }
504                 push @new, $line;
505         }
506         if (scalar @new) {
507                 push @old, @new;
508                 my $o = \@old;
509                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
510         }
511         $self->parallel_init($self->{indexlevel});
512         $self->umask_prepare;
513         $self->with_umask(\&_idx_init, $self, $opt);
514         $self->{oidx}->begin_lazy;
515         $self->{oidx}->eidx_prep;
516         $self->{midx}->begin_txn;
517 }
518
519 no warnings 'once';
520 *done = \&PublicInbox::V2Writable::done;
521 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
522 *with_umask = \&PublicInbox::InboxWritable::with_umask;
523 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
524 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
525 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
526 *index_todo = \&PublicInbox::V2Writable::index_todo;
527 *count_shards = \&PublicInbox::V2Writable::count_shards;
528 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
529 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
530
531 1;