]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearch: canonicalize topdir
[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::MID qw(mids);
25 use PublicInbox::V2Writable;
26 use PublicInbox::InboxWritable;
27 use PublicInbox::ContentHash qw(content_hash);
28 use PublicInbox::Eml;
29 use File::Spec;
30
31 sub new {
32         my (undef, $dir, $opt) = @_;
33         $dir = File::Spec->canonpath($dir);
34         my $l = $opt->{indexlevel} // 'full';
35         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
36                 die "invalid indexlevel=$l\n";
37         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
38         my $self = bless {
39                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
40                 topdir => $dir,
41                 creat => $opt->{creat},
42                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
43                 ibx_list => [],
44                 indexlevel => $l,
45                 transact_bytes => 0,
46                 total_bytes => 0,
47                 current_info => '',
48                 parallel => 1,
49                 lock_path => "$dir/ei.lock",
50         }, __PACKAGE__;
51         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
52         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
53         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
54         $self->{oidx} = $oidx;
55         $self
56 }
57
58 sub attach_inbox {
59         my ($self, $ibx) = @_;
60         $ibx = PublicInbox::InboxWritable->new($ibx);
61         my $key = $ibx->eidx_key;
62         if (!$ibx->over || !$ibx->mm) {
63                 warn "W: skipping $key (unindexed)\n";
64                 return;
65         }
66         if (!defined($ibx->uidvalidity)) {
67                 warn "W: skipping $key (no UIDVALIDITY)\n";
68                 return;
69         }
70         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
71         if ($ibxdir ne $ibx->{inboxdir}) {
72                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
73                 $ibx->{inboxdir} = $ibxdir;
74         }
75         $ibx = PublicInbox::InboxWritable->new($ibx);
76         $self->{ibx_map}->{$key} //= do {
77                 push @{$self->{ibx_list}}, $ibx;
78                 $ibx;
79         }
80 }
81
82 sub _ibx_attach { # each_inbox callback
83         my ($ibx, $self) = @_;
84         attach_inbox($self, $ibx);
85 }
86
87 sub attach_config {
88         my ($self, $cfg) = @_;
89         $cfg->each_inbox(\&_ibx_attach, $self);
90 }
91
92 sub git_blob_digest ($) {
93         my ($bref) = @_;
94         my $dig = Digest::SHA->new(1); # XXX SHA256 later
95         $dig->add('blob '.length($$bref)."\0");
96         $dig->add($$bref);
97         $dig;
98 }
99
100 sub is_bad_blob ($$$$) {
101         my ($oid, $type, $size, $expect_oid) = @_;
102         if ($type ne 'blob') {
103                 carp "W: $expect_oid is not a blob (type=$type)";
104                 return 1;
105         }
106         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
107         $size == 0 ? 1 : 0; # size == 0 means purged
108 }
109
110 sub check_batch_limit ($) {
111         my ($req) = @_;
112         my $self = $req->{self};
113         my $new_smsg = $req->{new_smsg};
114
115         # {raw_bytes} may be unset, so just use {bytes}
116         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
117
118         # set flag for PublicInbox::V2Writable::index_todo:
119         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
120 }
121
122 sub do_xpost ($$) {
123         my ($req, $smsg) = @_;
124         my $self = $req->{self};
125         my $docid = $smsg->{num};
126         my $idx = $self->idx_shard($docid);
127         my $oid = $req->{oid};
128         my $xibx = $req->{ibx};
129         my $eml = $req->{eml};
130         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
131                 my $xnum = $req->{xnum};
132                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $xibx->eidx_key);
133                 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
134                 check_batch_limit($req);
135         } else { # 'd'
136                 $self->{oidx}->remove_xref3($docid, $oid, $xibx->eidx_key);
137                 $idx->shard_remove_eidx_info($docid, $oid, $xibx, $eml);
138         }
139 }
140
141 # called by V2Writable::sync_prepare
142 sub artnum_max { $_[0]->{oidx}->eidx_max }
143
144 sub index_unseen ($) {
145         my ($req) = @_;
146         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
147         my $eml = delete $req->{eml};
148         $new_smsg->populate($eml, $req);
149         my $self = $req->{self};
150         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
151         $new_smsg->{num} = $docid;
152         my $idx = $self->idx_shard($docid);
153         $self->{oidx}->add_overview($eml, $new_smsg);
154         my $oid = $new_smsg->{blob};
155         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
156         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
157         $idx->index_raw(undef, $eml, $new_smsg, $ibx);
158         check_batch_limit($req);
159 }
160
161 sub do_finalize ($) {
162         my ($req) = @_;
163         if (my $indexed = $req->{indexed}) {
164                 do_xpost($req, $_) for @$indexed;
165         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
166                 index_unseen($req);
167         } else {
168                 # `d' message was already unindexed in the v1/v2 inboxes,
169                 # so it's too noisy to warn, here.
170         }
171 }
172
173 sub do_step ($) { # main iterator for adding messages to the index
174         my ($req) = @_;
175         my $self = $req->{self};
176         while (1) {
177                 if (my $next_arg = $req->{next_arg}) {
178                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
179                                 $req->{cur_smsg} = $smsg;
180                                 $self->git->cat_async($smsg->{blob},
181                                                         \&ck_existing, $req);
182                                 return; # ck_existing calls do_step
183                         }
184                         delete $req->{cur_smsg};
185                         delete $req->{next_arg};
186                 }
187                 my $mid = shift(@{$req->{mids}});
188                 last unless defined $mid;
189                 my ($id, $prev);
190                 $req->{next_arg} = [ $mid, \$id, \$prev ];
191                 # loop again
192         }
193         do_finalize($req);
194 }
195
196 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
197         my ($req) = @_;
198         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
199         my $self = $req->{self};
200         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
201         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
202         if (@keep) {
203                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
204                         die "BUG: xref $keep[0] has no OID";
205                 my $oidhex = $1;
206                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
207                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
208                 my $saved = $self->{oidx}->get_art($smsg->{num});
209         } else {
210                 $self->{oidx}->delete_by_num($smsg->{num});
211         }
212 }
213
214 sub ck_existing { # git->cat_async callback
215         my ($bref, $oid, $type, $size, $req) = @_;
216         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
217         if ($type eq 'missing') {
218                 _blob_missing($req);
219         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
220                 my $cur = PublicInbox::Eml->new($bref);
221                 if (content_hash($cur) eq $req->{chash}) {
222                         push @{$req->{indexed}}, $smsg; # for do_xpost
223                 } # else { index_unseen later }
224         }
225         do_step($req);
226 }
227
228 # is the messages visible in the inbox currently being indexed?
229 # return the number if so
230 sub cur_ibx_xnum ($$) {
231         my ($req, $bref) = @_;
232         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
233
234         # XXX overkill?
235         git_blob_digest($bref)->hexdigest eq $req->{oid} or die
236                 "BUG: blob mismatch $req->{oid}";
237
238         $req->{eml} = PublicInbox::Eml->new($bref);
239         $req->{chash} = content_hash($req->{eml});
240         $req->{mids} = mids($req->{eml});
241         my @q = @{$req->{mids}}; # copy
242         while (defined(my $mid = shift @q)) {
243                 my ($id, $prev);
244                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
245                         return $x->{num} if $x->{blob} eq $req->{oid};
246                 }
247         }
248         undef;
249 }
250
251 sub index_oid { # git->cat_async callback for 'm'
252         my ($bref, $oid, $type, $size, $req) = @_;
253         return if is_bad_blob($oid, $type, $size, $req->{oid});
254         my $new_smsg = $req->{new_smsg} = bless {
255                 blob => $oid,
256         }, 'PublicInbox::Smsg';
257         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
258         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
259         do_step($req);
260 }
261
262 sub unindex_oid { # git->cat_async callback for 'd'
263         my ($bref, $oid, $type, $size, $req) = @_;
264         return if is_bad_blob($oid, $type, $size, $req->{oid});
265         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
266         do_step($req);
267 }
268
269 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
270 sub last_commits {
271         my ($self, $sync) = @_;
272         my $heads = [];
273         my $ekey = $sync->{ibx}->eidx_key;
274         my $uv = $sync->{ibx}->uidvalidity;
275         for my $i (0..$sync->{epoch_max}) {
276                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
277         }
278         $heads;
279 }
280
281 sub _sync_inbox ($$$) {
282         my ($self, $opt, $ibx) = @_;
283         my $sync = {
284                 need_checkpoint => \(my $bool = 0),
285                 reindex => $opt->{reindex},
286                 -opt => $opt,
287                 self => $self,
288                 ibx => $ibx,
289         };
290         my $v = $ibx->version;
291         my $ekey = $ibx->eidx_key;
292         if ($v == 2) {
293                 my $epoch_max;
294                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
295                 $sync->{epoch_max} = $epoch_max;
296                 sync_prepare($self, $sync) or return; # fills $sync->{todo}
297         } elsif ($v == 1) {
298                 my $uv = $ibx->uidvalidity;
299                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
300                 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
301                 my $unit = { stack => $stk, git => $ibx->git };
302                 push @{$sync->{todo}}, $unit;
303         } else {
304                 warn "E: $ekey unsupported inbox version (v$v)\n";
305                 return;
306         }
307         index_todo($self, $sync, $_) for @{$sync->{todo}};
308 }
309
310 sub eidx_sync { # main entry point
311         my ($self, $opt) = @_;
312         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
313         $self->{oidx}->rethread_prepare($opt);
314
315         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
316         local $self->{current_info} = '';
317         local $SIG{__WARN__} = sub {
318                 $warn_cb->($self->{current_info}, ': ', @_);
319         };
320
321         # don't use $_ here, it'll get clobbered by reindex_checkpoint
322         for my $ibx (@{$self->{ibx_list}}) {
323                 _sync_inbox($self, $opt, $ibx);
324         }
325
326         $self->{oidx}->rethread_done($opt);
327
328         PublicInbox::V2Writable::done($self);
329 }
330
331 sub update_last_commit { # overrides V2Writable
332         my ($self, $sync, $unit, $latest_cmt) = @_;
333         return unless defined $latest_cmt;
334
335         $self->git->async_wait_all;
336         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
337         my $ekey = $ibx->eidx_key;
338         my $uv = $ibx->uidvalidity;
339         my $epoch = $unit->{epoch};
340         my $meta_key;
341         my $v = $ibx->version;
342         if ($v == 2) {
343                 die 'No {epoch} for v2 unit' unless defined $epoch;
344                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
345         } elsif ($v == 1) {
346                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
347                 $meta_key = "lc-v1:$ekey//$uv";
348         } else {
349                 die "Unsupported inbox version: $v";
350         }
351         my $last = $self->{oidx}->eidx_meta($meta_key);
352         if (defined $last && is_ancestor($unit->{git}, $last, $latest_cmt)) {
353                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
354                 chomp(my $n = $unit->{git}->qx(@cmd));
355                 return if $n ne '' && $n == 0;
356         }
357         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
358 }
359
360 sub idx_init { # similar to V2Writable
361         my ($self, $opt) = @_;
362         return if $self->{idx_shards};
363
364         $self->git->cleanup;
365
366         my $ALL = $self->git->{git_dir}; # ALL.git
367         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
368         my $info_dir = "$ALL/objects/info";
369         my $alt = "$info_dir/alternates";
370         my $mode = 0644;
371         my (%old, @old, %new, @new);
372         if (-e $alt) {
373                 open(my $fh, '<', $alt) or die "open $alt: $!";
374                 $mode = (stat($fh))[2] & 07777;
375                 while (<$fh>) {
376                         push @old, $_ if !$old{$_}++;
377                 }
378         }
379         for my $ibx (@{$self->{ibx_list}}) {
380                 my $line = $ibx->git->{git_dir} . "/objects\n";
381                 next if $old{$line};
382                 $new{$line} = 1;
383                 push @new, $line;
384         }
385         if (scalar @new) {
386                 push @old, @new;
387                 my $o = \@old;
388                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
389         }
390         $self->parallel_init($self->{indexlevel});
391         $self->umask_prepare;
392         $self->with_umask(\&PublicInbox::V2Writable::_idx_init, $self, $opt);
393         $self->{oidx}->begin_lazy;
394         $self->{oidx}->eidx_prep;
395 }
396
397 no warnings 'once';
398 *done = \&PublicInbox::V2Writable::done;
399 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
400 *with_umask = \&PublicInbox::InboxWritable::with_umask;
401 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
402 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
403 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
404 *index_todo = \&PublicInbox::V2Writable::index_todo;
405 *count_shards = \&PublicInbox::V2Writable::count_shards;
406 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
407 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
408
409 1;