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