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