]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extindex: SIGUSR1 supports checkpoint
[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         my $self = $req->{self};
254         local $self->{current_info} = "$self->{current_info} $oid";
255         return if is_bad_blob($oid, $type, $size, $req->{oid});
256         my $new_smsg = $req->{new_smsg} = bless {
257                 blob => $oid,
258         }, 'PublicInbox::Smsg';
259         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
260         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
261         ++${$req->{nr}};
262         do_step($req);
263 }
264
265 sub unindex_oid { # git->cat_async callback for 'd'
266         my ($bref, $oid, $type, $size, $req) = @_;
267         my $self = $req->{self};
268         local $self->{current_info} = "$self->{current_info} $oid";
269         return if is_bad_blob($oid, $type, $size, $req->{oid});
270         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
271         do_step($req);
272 }
273
274 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
275 sub last_commits {
276         my ($self, $sync) = @_;
277         my $heads = [];
278         my $ekey = $sync->{ibx}->eidx_key;
279         my $uv = $sync->{ibx}->uidvalidity;
280         for my $i (0..$sync->{epoch_max}) {
281                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
282         }
283         $heads;
284 }
285
286 sub _sync_inbox ($$$) {
287         my ($self, $sync, $ibx) = @_;
288         $sync->{ibx} = $ibx;
289         $sync->{nr} = \(my $nr = 0);
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         my $sync = {
321                 need_checkpoint => \(my $need_checkpoint = 0),
322                 reindex => $opt->{reindex},
323                 -opt => $opt,
324                 self => $self,
325                 -regen_fmt => "%u/?\n",
326         };
327         local $SIG{USR1} = sub { $need_checkpoint = 1 };
328
329         # don't use $_ here, it'll get clobbered by reindex_checkpoint
330         for my $ibx (@{$self->{ibx_list}}) {
331                 _sync_inbox($self, $sync, $ibx);
332         }
333
334         $self->{oidx}->rethread_done($opt);
335
336         PublicInbox::V2Writable::done($self);
337 }
338
339 sub update_last_commit { # overrides V2Writable
340         my ($self, $sync, $unit, $latest_cmt) = @_;
341         return unless defined $latest_cmt;
342
343         $self->git->async_wait_all;
344         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
345         my $ekey = $ibx->eidx_key;
346         my $uv = $ibx->uidvalidity;
347         my $epoch = $unit->{epoch};
348         my $meta_key;
349         my $v = $ibx->version;
350         if ($v == 2) {
351                 die 'No {epoch} for v2 unit' unless defined $epoch;
352                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
353         } elsif ($v == 1) {
354                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
355                 $meta_key = "lc-v1:$ekey//$uv";
356         } else {
357                 die "Unsupported inbox version: $v";
358         }
359         my $last = $self->{oidx}->eidx_meta($meta_key);
360         if (defined $last && is_ancestor($unit->{git}, $last, $latest_cmt)) {
361                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
362                 chomp(my $n = $unit->{git}->qx(@cmd));
363                 return if $n ne '' && $n == 0;
364         }
365         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
366 }
367
368 sub idx_init { # similar to V2Writable
369         my ($self, $opt) = @_;
370         return if $self->{idx_shards};
371
372         $self->git->cleanup;
373
374         my $ALL = $self->git->{git_dir}; # ALL.git
375         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
376         my $info_dir = "$ALL/objects/info";
377         my $alt = "$info_dir/alternates";
378         my $mode = 0644;
379         my (%old, @old, %new, @new);
380         if (-e $alt) {
381                 open(my $fh, '<', $alt) or die "open $alt: $!";
382                 $mode = (stat($fh))[2] & 07777;
383                 while (<$fh>) {
384                         push @old, $_ if !$old{$_}++;
385                 }
386         }
387         for my $ibx (@{$self->{ibx_list}}) {
388                 my $line = $ibx->git->{git_dir} . "/objects\n";
389                 next if $old{$line};
390                 $new{$line} = 1;
391                 push @new, $line;
392         }
393         if (scalar @new) {
394                 push @old, @new;
395                 my $o = \@old;
396                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
397         }
398         $self->parallel_init($self->{indexlevel});
399         $self->umask_prepare;
400         $self->with_umask(\&PublicInbox::V2Writable::_idx_init, $self, $opt);
401         $self->{oidx}->begin_lazy;
402         $self->{oidx}->eidx_prep;
403 }
404
405 no warnings 'once';
406 *done = \&PublicInbox::V2Writable::done;
407 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
408 *with_umask = \&PublicInbox::InboxWritable::with_umask;
409 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
410 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
411 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
412 *index_todo = \&PublicInbox::V2Writable::index_todo;
413 *count_shards = \&PublicInbox::V2Writable::count_shards;
414 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
415 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
416
417 1;