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