]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearchidx: ck_existing: set $OID for warning context
[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 $self = $req->{self} // die 'BUG: {self} missing';
226                 local $self->{current_info} = "$self->{current_info} $oid";
227                 my $cur = PublicInbox::Eml->new($bref);
228                 if (content_hash($cur) eq $req->{chash}) {
229                         push @{$req->{indexed}}, $smsg; # for do_xpost
230                 } # else { index_unseen later }
231         }
232         do_step($req);
233 }
234
235 # is the messages visible in the inbox currently being indexed?
236 # return the number if so
237 sub cur_ibx_xnum ($$) {
238         my ($req, $bref) = @_;
239         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
240
241         $req->{eml} = PublicInbox::Eml->new($bref);
242         $req->{chash} = content_hash($req->{eml});
243         $req->{mids} = mids($req->{eml});
244         my @q = @{$req->{mids}}; # copy
245         while (defined(my $mid = shift @q)) {
246                 my ($id, $prev);
247                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
248                         return $x->{num} if $x->{blob} eq $req->{oid};
249                 }
250         }
251         undef;
252 }
253
254 sub index_oid { # git->cat_async callback for 'm'
255         my ($bref, $oid, $type, $size, $req) = @_;
256         my $self = $req->{self};
257         local $self->{current_info} = "$self->{current_info} $oid";
258         return if is_bad_blob($oid, $type, $size, $req->{oid});
259         my $new_smsg = $req->{new_smsg} = bless {
260                 blob => $oid,
261         }, 'PublicInbox::Smsg';
262         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
263         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
264         ++${$req->{nr}};
265         do_step($req);
266 }
267
268 sub unindex_oid { # git->cat_async callback for 'd'
269         my ($bref, $oid, $type, $size, $req) = @_;
270         my $self = $req->{self};
271         local $self->{current_info} = "$self->{current_info} $oid";
272         return if is_bad_blob($oid, $type, $size, $req->{oid});
273         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
274         do_step($req);
275 }
276
277 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
278 sub last_commits {
279         my ($self, $sync) = @_;
280         my $heads = [];
281         my $ekey = $sync->{ibx}->eidx_key;
282         my $uv = $sync->{ibx}->uidvalidity;
283         for my $i (0..$sync->{epoch_max}) {
284                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
285         }
286         $heads;
287 }
288
289 sub _sync_inbox ($$$) {
290         my ($self, $sync, $ibx) = @_;
291         $sync->{ibx} = $ibx;
292         $sync->{nr} = \(my $nr = 0);
293         my $v = $ibx->version;
294         my $ekey = $ibx->eidx_key;
295         if ($v == 2) {
296                 my $epoch_max;
297                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
298                 $sync->{epoch_max} = $epoch_max;
299                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
300         } elsif ($v == 1) {
301                 my $uv = $ibx->uidvalidity;
302                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
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 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         my $idx = $self->idx_shard($docid);
334         if (@$remain) {
335                 for my $oid (@oid) {
336                         warn "I: unref #$docid $eidx_key $oid\n";
337                         $idx->shard_remove_eidx_info($docid, $eidx_key);
338                 }
339         } else {
340                 warn "I: remove #$docid $eidx_key @oid\n";
341                 $idx->shard_remove($docid);
342         }
343 }
344
345 sub eidx_gc {
346         my ($self, $opt) = @_;
347         $self->{cfg} or die "E: GC requires ->attach_config\n";
348         $opt->{-idx_gc} = 1;
349         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
350
351         my $dbh = $self->{oidx}->dbh;
352         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
353         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
354         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
355
356         $ibx_ck->execute;
357         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
358                 next if $self->{ibx_map}->{$eidx_key};
359                 $self->{midx}->remove_eidx_key($eidx_key);
360                 warn "I: deleting messages for $eidx_key...\n";
361                 $x3_doc->execute($ibx_id);
362                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
363                         unref_doc($self, $ibx_id, $eidx_key, $docid);
364                 }
365                 $dbh->prepare_cached(<<'')->execute($ibx_id);
366 DELETE FROM inboxes WHERE ibx_id = ?
367
368                 # drop last_commit info
369                 my $pat = $eidx_key;
370                 $pat =~ s/([_%])/\\$1/g;
371                 $lc_i->execute("lc-%:$pat//%");
372                 while (my ($key) = $lc_i->fetchrow_array) {
373                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
374                         warn "I: removing $key\n";
375                         $dbh->prepare_cached(<<'')->execute($key);
376 DELETE FROM eidx_meta WHERE key = ?
377
378                 }
379
380                 warn "I: $eidx_key removed\n";
381         }
382
383         # it's not real unless it's in `over', we use parallelism here,
384         # shards will be reading directly from over, so commit
385         $self->{oidx}->commit_lazy;
386         $self->{oidx}->begin_lazy;
387
388         for my $idx (@{$self->{idx_shards}}) {
389                 warn "I: cleaning up shard #$idx->{shard}\n";
390                 $idx->shard_over_check($self->{oidx});
391         }
392         my $nr = $dbh->do(<<'');
393 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
394
395         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
396
397         done($self);
398 }
399
400 sub eidx_sync { # main entry point
401         my ($self, $opt) = @_;
402         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
403         $self->{oidx}->rethread_prepare($opt);
404
405         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
406         local $self->{current_info} = '';
407         local $SIG{__WARN__} = sub {
408                 $warn_cb->($self->{current_info}, ': ', @_);
409         };
410         my $sync = {
411                 need_checkpoint => \(my $need_checkpoint = 0),
412                 reindex => $opt->{reindex},
413                 -opt => $opt,
414                 self => $self,
415                 -regen_fmt => "%u/?\n",
416         };
417         local $SIG{USR1} = sub { $need_checkpoint = 1 };
418         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
419         local $SIG{QUIT} = $quit;
420         local $SIG{INT} = $quit;
421         local $SIG{TERM} = $quit;
422
423         # don't use $_ here, it'll get clobbered by reindex_checkpoint
424         for my $ibx (@{$self->{ibx_list}}) {
425                 last if $sync->{quit};
426                 _sync_inbox($self, $sync, $ibx);
427         }
428         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
429
430         PublicInbox::V2Writable::done($self);
431 }
432
433 sub update_last_commit { # overrides V2Writable
434         my ($self, $sync, $stk) = @_;
435         my $unit = $sync->{unit} // return;
436         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
437         defined($latest_cmt) or return;
438         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
439         my $ekey = $ibx->eidx_key;
440         my $uv = $ibx->uidvalidity;
441         my $epoch = $unit->{epoch};
442         my $meta_key;
443         my $v = $ibx->version;
444         if ($v == 2) {
445                 die 'No {epoch} for v2 unit' unless defined $epoch;
446                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
447         } elsif ($v == 1) {
448                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
449                 $meta_key = "lc-v1:$ekey//$uv";
450         } else {
451                 die "Unsupported inbox version: $v";
452         }
453         my $last = $self->{oidx}->eidx_meta($meta_key);
454         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
455                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
456                 chomp(my $n = $unit->{git}->qx(@cmd));
457                 return if $n ne '' && $n == 0;
458         }
459         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
460 }
461
462 sub _idx_init { # with_umask callback
463         my ($self, $opt) = @_;
464         PublicInbox::V2Writable::_idx_init($self, $opt);
465         $self->{midx} = PublicInbox::MiscIdx->new($self);
466 }
467
468 sub idx_init { # similar to V2Writable
469         my ($self, $opt) = @_;
470         return if $self->{idx_shards};
471
472         $self->git->cleanup;
473
474         my $ALL = $self->git->{git_dir}; # ALL.git
475         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
476         my $info_dir = "$ALL/objects/info";
477         my $alt = "$info_dir/alternates";
478         my $mode = 0644;
479         my (@old, @new, %seen); # seen: st_dev + st_ino
480         if (-e $alt) {
481                 open(my $fh, '<', $alt) or die "open $alt: $!";
482                 $mode = (stat($fh))[2] & 07777;
483                 while (my $line = <$fh>) {
484                         chomp(my $d = $line);
485                         if (my @st = stat($d)) {
486                                 next if $seen{"$st[0]\0$st[1]"}++;
487                         } else {
488                                 warn "W: stat($d) failed (from $alt): $!\n";
489                                 next if $opt->{-idx_gc};
490                         }
491                         push @old, $line;
492                 }
493         }
494         for my $ibx (@{$self->{ibx_list}}) {
495                 my $line = $ibx->git->{git_dir} . "/objects\n";
496                 chomp(my $d = $line);
497                 if (my @st = stat($d)) {
498                         next if $seen{"$st[0]\0$st[1]"}++;
499                 } else {
500                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
501                         next if $opt->{-idx_gc};
502                 }
503                 push @new, $line;
504         }
505         if (scalar @new) {
506                 push @old, @new;
507                 my $o = \@old;
508                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
509         }
510         $self->parallel_init($self->{indexlevel});
511         $self->umask_prepare;
512         $self->with_umask(\&_idx_init, $self, $opt);
513         $self->{oidx}->begin_lazy;
514         $self->{oidx}->eidx_prep;
515         $self->{midx}->begin_txn;
516 }
517
518 no warnings 'once';
519 *done = \&PublicInbox::V2Writable::done;
520 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
521 *with_umask = \&PublicInbox::InboxWritable::with_umask;
522 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
523 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
524 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
525 *index_todo = \&PublicInbox::V2Writable::index_todo;
526 *count_shards = \&PublicInbox::V2Writable::count_shards;
527 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
528 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
529
530 1;