]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
b0a12bcabce0e97e04f6e8fb13de346f91439f90
[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 $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
295                 my $unit = { stack => $stk, git => $ibx->git };
296                 push @{$sync->{todo}}, $unit;
297         } else {
298                 warn "E: $ekey unsupported inbox version (v$v)\n";
299                 return;
300         }
301         for my $unit (@{delete($sync->{todo}) // []}) {
302                 last if $sync->{quit};
303                 index_todo($self, $sync, $unit);
304         }
305         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
306         $ibx->git->cleanup; # done with this inbox, now
307 }
308
309 sub unref_doc ($$$$) {
310         my ($self, $ibx_id, $eidx_key, $docid) = @_;
311         my $dbh = $self->{oidx}->dbh;
312
313         # for debug/info purposes, oids may no longer be accessible
314         my $sth = $dbh->prepare_cached(<<'', undef, 1);
315 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
316
317         $sth->execute($docid, $ibx_id);
318         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
319
320         $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
321 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
322
323         my $remain = $self->{oidx}->get_xref3($docid);
324         my $idx = $self->idx_shard($docid);
325         if (@$remain) {
326                 for my $oid (@oid) {
327                         warn "I: unref #$docid $eidx_key $oid\n";
328                         $idx->shard_remove_eidx_info($docid, $eidx_key);
329                 }
330         } else {
331                 warn "I: remove #$docid $eidx_key @oid\n";
332                 $idx->shard_remove($docid);
333         }
334 }
335
336 sub eidx_gc {
337         my ($self, $opt) = @_;
338         $self->{cfg} or die "E: GC requires ->attach_config\n";
339         $opt->{-idx_gc} = 1;
340         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
341
342         my $dbh = $self->{oidx}->dbh;
343         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
344         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
345         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
346
347         $ibx_ck->execute;
348         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
349                 next if $self->{ibx_map}->{$eidx_key};
350                 $self->{midx}->remove_eidx_key($eidx_key);
351                 warn "I: deleting messages for $eidx_key...\n";
352                 $x3_doc->execute($ibx_id);
353                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
354                         unref_doc($self, $ibx_id, $eidx_key, $docid);
355                 }
356                 $dbh->prepare_cached(<<'')->execute($ibx_id);
357 DELETE FROM inboxes WHERE ibx_id = ?
358
359                 # drop last_commit info
360                 my $pat = $eidx_key;
361                 $pat =~ s/([_%])/\\$1/g;
362                 $lc_i->execute("lc-%:$pat//%");
363                 while (my ($key) = $lc_i->fetchrow_array) {
364                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
365                         warn "I: removing $key\n";
366                         $dbh->prepare_cached(<<'')->execute($key);
367 DELETE FROM eidx_meta WHERE key = ?
368
369                 }
370
371                 warn "I: $eidx_key removed\n";
372         }
373
374         # it's not real unless it's in `over', we use parallelism here,
375         # shards will be reading directly from over, so commit
376         $self->{oidx}->commit_lazy;
377         $self->{oidx}->begin_lazy;
378
379         for my $idx (@{$self->{idx_shards}}) {
380                 warn "I: cleaning up shard #$idx->{shard}\n";
381                 $idx->shard_over_check($self->{oidx});
382         }
383         my $nr = $dbh->do(<<'');
384 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
385
386         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
387
388         done($self);
389 }
390
391 sub eidx_sync { # main entry point
392         my ($self, $opt) = @_;
393         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
394         $self->{oidx}->rethread_prepare($opt);
395
396         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
397         local $self->{current_info} = '';
398         local $SIG{__WARN__} = sub {
399                 $warn_cb->($self->{current_info}, ': ', @_);
400         };
401         my $sync = {
402                 need_checkpoint => \(my $need_checkpoint = 0),
403                 reindex => $opt->{reindex},
404                 -opt => $opt,
405                 self => $self,
406                 -regen_fmt => "%u/?\n",
407         };
408         local $SIG{USR1} = sub { $need_checkpoint = 1 };
409         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
410         local $SIG{QUIT} = $quit;
411         local $SIG{INT} = $quit;
412         local $SIG{TERM} = $quit;
413
414         # don't use $_ here, it'll get clobbered by reindex_checkpoint
415         for my $ibx (@{$self->{ibx_list}}) {
416                 last if $sync->{quit};
417                 _sync_inbox($self, $sync, $ibx);
418         }
419         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
420
421         PublicInbox::V2Writable::done($self);
422 }
423
424 sub update_last_commit { # overrides V2Writable
425         my ($self, $sync, $stk) = @_;
426         my $unit = $sync->{unit} // return;
427         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
428         defined($latest_cmt) or return;
429         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
430         my $ekey = $ibx->eidx_key;
431         my $uv = $ibx->uidvalidity;
432         my $epoch = $unit->{epoch};
433         my $meta_key;
434         my $v = $ibx->version;
435         if ($v == 2) {
436                 die 'No {epoch} for v2 unit' unless defined $epoch;
437                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
438         } elsif ($v == 1) {
439                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
440                 $meta_key = "lc-v1:$ekey//$uv";
441         } else {
442                 die "Unsupported inbox version: $v";
443         }
444         my $last = $self->{oidx}->eidx_meta($meta_key);
445         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
446                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
447                 chomp(my $n = $unit->{git}->qx(@cmd));
448                 return if $n ne '' && $n == 0;
449         }
450         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
451 }
452
453 sub _idx_init { # with_umask callback
454         my ($self, $opt) = @_;
455         PublicInbox::V2Writable::_idx_init($self, $opt);
456         $self->{midx} = PublicInbox::MiscIdx->new($self);
457 }
458
459 sub idx_init { # similar to V2Writable
460         my ($self, $opt) = @_;
461         return if $self->{idx_shards};
462
463         $self->git->cleanup;
464
465         my $ALL = $self->git->{git_dir}; # ALL.git
466         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
467         my $info_dir = "$ALL/objects/info";
468         my $alt = "$info_dir/alternates";
469         my $mode = 0644;
470         my (@old, @new, %seen); # seen: st_dev + st_ino
471         if (-e $alt) {
472                 open(my $fh, '<', $alt) or die "open $alt: $!";
473                 $mode = (stat($fh))[2] & 07777;
474                 while (my $line = <$fh>) {
475                         chomp(my $d = $line);
476                         if (my @st = stat($d)) {
477                                 next if $seen{"$st[0]\0$st[1]"}++;
478                         } else {
479                                 warn "W: stat($d) failed (from $alt): $!\n";
480                                 next if $opt->{-idx_gc};
481                         }
482                         push @old, $line;
483                 }
484         }
485         for my $ibx (@{$self->{ibx_list}}) {
486                 my $line = $ibx->git->{git_dir} . "/objects\n";
487                 chomp(my $d = $line);
488                 if (my @st = stat($d)) {
489                         next if $seen{"$st[0]\0$st[1]"}++;
490                 } else {
491                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
492                         next if $opt->{-idx_gc};
493                 }
494                 push @new, $line;
495         }
496         if (scalar @new) {
497                 push @old, @new;
498                 my $o = \@old;
499                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
500         }
501         $self->parallel_init($self->{indexlevel});
502         $self->umask_prepare;
503         $self->with_umask(\&_idx_init, $self, $opt);
504         $self->{oidx}->begin_lazy;
505         $self->{oidx}->eidx_prep;
506         $self->{midx}->begin_txn;
507 }
508
509 no warnings 'once';
510 *done = \&PublicInbox::V2Writable::done;
511 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
512 *with_umask = \&PublicInbox::InboxWritable::with_umask;
513 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
514 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
515 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
516 *index_todo = \&PublicInbox::V2Writable::index_todo;
517 *count_shards = \&PublicInbox::V2Writable::count_shards;
518 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
519 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
520
521 1;