1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
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.
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)
16 package PublicInbox::ExtSearchIdx;
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);
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";
39 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
41 creat => $opt->{creat},
42 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
49 lock_path => "$dir/ei.lock",
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;
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";
66 if (!defined($ibx->uidvalidity)) {
67 warn "W: skipping $key (no UIDVALIDITY)\n";
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;
75 $ibx = PublicInbox::InboxWritable->new($ibx);
76 $self->{ibx_map}->{$key} //= do {
77 push @{$self->{ibx_list}}, $ibx;
82 sub _ibx_attach { # each_inbox callback
83 my ($ibx, $self) = @_;
84 attach_inbox($self, $ibx);
88 my ($self, $cfg) = @_;
89 $cfg->each_inbox(\&_ibx_attach, $self);
92 sub git_blob_digest ($) {
94 my $dig = Digest::SHA->new(1); # XXX SHA256 later
95 $dig->add('blob '.length($$bref)."\0");
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)";
106 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
107 $size == 0 ? 1 : 0; # size == 0 means purged
110 sub check_batch_limit ($) {
112 my $self = $req->{self};
113 my $new_smsg = $req->{new_smsg};
115 # {raw_bytes} may be unset, so just use {bytes}
116 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
118 # set flag for PublicInbox::V2Writable::index_todo:
119 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
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);
136 $self->{oidx}->remove_xref3($docid, $oid, $xibx->eidx_key);
137 $idx->shard_remove_eidx_info($docid, $oid, $xibx, $eml);
141 # called by V2Writable::sync_prepare
142 sub artnum_max { $_[0]->{oidx}->eidx_max }
144 sub index_unseen ($) {
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);
161 sub do_finalize ($) {
163 if (my $indexed = $req->{indexed}) {
164 do_xpost($req, $_) for @$indexed;
165 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
168 # `d' message was already unindexed in the v1/v2 inboxes,
169 # so it's too noisy to warn, here.
173 sub do_step ($) { # main iterator for adding messages to the index
175 my $self = $req->{self};
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
184 delete $req->{cur_smsg};
185 delete $req->{next_arg};
187 my $mid = shift(@{$req->{mids}});
188 last unless defined $mid;
190 $req->{next_arg} = [ $mid, \$id, \$prev ];
196 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
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);
203 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
204 die "BUG: xref $keep[0] has no OID";
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});
210 $self->{oidx}->delete_by_num($smsg->{num});
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') {
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 }
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';
235 git_blob_digest($bref)->hexdigest eq $req->{oid} or die
236 "BUG: blob mismatch $req->{oid}";
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)) {
244 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
245 return $x->{num} if $x->{blob} eq $req->{oid};
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 {
256 }, 'PublicInbox::Smsg';
257 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
258 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
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
269 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
271 my ($self, $sync) = @_;
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");
281 sub _sync_inbox ($$$) {
282 my ($self, $opt, $ibx) = @_;
284 need_checkpoint => \(my $bool = 0),
285 reindex => $opt->{reindex},
290 my $v = $ibx->version;
291 my $ekey = $ibx->eidx_key;
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}
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;
304 warn "E: $ekey unsupported inbox version (v$v)\n";
307 index_todo($self, $sync, $_) for @{$sync->{todo}};
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);
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}, ': ', @_);
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);
326 $self->{oidx}->rethread_done($opt);
328 PublicInbox::V2Writable::done($self);
331 sub update_last_commit { # overrides V2Writable
332 my ($self, $sync, $unit, $latest_cmt) = @_;
333 return unless defined $latest_cmt;
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};
341 my $v = $ibx->version;
343 die 'No {epoch} for v2 unit' unless defined $epoch;
344 $meta_key = "lc-v2:$ekey//$uv;$epoch";
346 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
347 $meta_key = "lc-v1:$ekey//$uv";
349 die "Unsupported inbox version: $v";
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;
357 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
360 sub idx_init { # similar to V2Writable
361 my ($self, $opt) = @_;
362 return if $self->{idx_shards};
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";
371 my (%old, @old, %new, @new);
373 open(my $fh, '<', $alt) or die "open $alt: $!";
374 $mode = (stat($fh))[2] & 07777;
376 push @old, $_ if !$old{$_}++;
379 for my $ibx (@{$self->{ibx_list}}) {
380 my $line = $ibx->git->{git_dir} . "/objects\n";
388 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
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;
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;