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::MiscIdx;
25 use PublicInbox::MID qw(mids);
26 use PublicInbox::V2Writable;
27 use PublicInbox::InboxWritable;
28 use PublicInbox::ContentHash qw(content_hash);
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";
40 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
42 creat => $opt->{creat},
43 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
50 lock_path => "$dir/ei.lock",
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;
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";
67 if (!defined($ibx->uidvalidity)) {
68 warn "W: skipping $key (no UIDVALIDITY)\n";
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;
76 $ibx = PublicInbox::InboxWritable->new($ibx);
77 $self->{ibx_map}->{$key} //= do {
78 push @{$self->{ibx_list}}, $ibx;
83 sub _ibx_attach { # each_inbox callback
84 my ($ibx, $self) = @_;
85 attach_inbox($self, $ibx);
89 my ($self, $cfg) = @_;
90 $cfg->each_inbox(\&_ibx_attach, $self);
93 sub git_blob_digest ($) {
95 my $dig = Digest::SHA->new(1); # XXX SHA256 later
96 $dig->add('blob '.length($$bref)."\0");
101 sub is_bad_blob ($$$$) {
102 my ($oid, $type, $size, $expect_oid) = @_;
103 if ($type ne 'blob') {
104 carp "W: $expect_oid is not a blob (type=$type)";
107 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
108 $size == 0 ? 1 : 0; # size == 0 means purged
111 sub check_batch_limit ($) {
113 my $self = $req->{self};
114 my $new_smsg = $req->{new_smsg};
116 # {raw_bytes} may be unset, so just use {bytes}
117 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
119 # set flag for PublicInbox::V2Writable::index_todo:
120 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
124 my ($req, $smsg) = @_;
125 my $self = $req->{self};
126 my $docid = $smsg->{num};
127 my $idx = $self->idx_shard($docid);
128 my $oid = $req->{oid};
129 my $xibx = $req->{ibx};
130 my $eml = $req->{eml};
131 my $eidx_key = $xibx->eidx_key;
132 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
133 my $xnum = $req->{xnum};
134 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
135 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
136 check_batch_limit($req);
139 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
142 $idx->shard_remove($oid, $docid);
143 } elsif ($rm_eidx_info) {
144 $idx->shard_remove_eidx_info($docid, $oid, $xibx, $eml);
149 # called by V2Writable::sync_prepare
150 sub artnum_max { $_[0]->{oidx}->eidx_max }
152 sub index_unseen ($) {
154 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
155 my $eml = delete $req->{eml};
156 $new_smsg->populate($eml, $req);
157 my $self = $req->{self};
158 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
159 $new_smsg->{num} = $docid;
160 my $idx = $self->idx_shard($docid);
161 $self->{oidx}->add_overview($eml, $new_smsg);
162 my $oid = $new_smsg->{blob};
163 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
164 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
165 $idx->index_raw(undef, $eml, $new_smsg, $ibx);
166 check_batch_limit($req);
169 sub do_finalize ($) {
171 if (my $indexed = $req->{indexed}) {
172 do_xpost($req, $_) for @$indexed;
173 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
176 # `d' message was already unindexed in the v1/v2 inboxes,
177 # so it's too noisy to warn, here.
179 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
180 if (defined(my $cur_cmt = $req->{cur_cmt})) {
181 ${$req->{latest_cmt}} = $cur_cmt;
185 sub do_step ($) { # main iterator for adding messages to the index
187 my $self = $req->{self};
189 if (my $next_arg = $req->{next_arg}) {
190 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
191 $req->{cur_smsg} = $smsg;
192 $self->git->cat_async($smsg->{blob},
193 \&ck_existing, $req);
194 return; # ck_existing calls do_step
196 delete $req->{cur_smsg};
197 delete $req->{next_arg};
199 my $mid = shift(@{$req->{mids}});
200 last unless defined $mid;
202 $req->{next_arg} = [ $mid, \$id, \$prev ];
208 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
210 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
211 my $self = $req->{self};
212 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
213 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
215 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
216 die "BUG: xref $keep[0] has no OID";
218 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
219 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
220 my $saved = $self->{oidx}->get_art($smsg->{num});
222 $self->{oidx}->delete_by_num($smsg->{num});
226 sub ck_existing { # git->cat_async callback
227 my ($bref, $oid, $type, $size, $req) = @_;
228 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
229 if ($type eq 'missing') {
231 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
232 my $cur = PublicInbox::Eml->new($bref);
233 if (content_hash($cur) eq $req->{chash}) {
234 push @{$req->{indexed}}, $smsg; # for do_xpost
235 } # else { index_unseen later }
240 # is the messages visible in the inbox currently being indexed?
241 # return the number if so
242 sub cur_ibx_xnum ($$) {
243 my ($req, $bref) = @_;
244 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
247 git_blob_digest($bref)->hexdigest eq $req->{oid} or die
248 "BUG: blob mismatch $req->{oid}";
250 $req->{eml} = PublicInbox::Eml->new($bref);
251 $req->{chash} = content_hash($req->{eml});
252 $req->{mids} = mids($req->{eml});
253 my @q = @{$req->{mids}}; # copy
254 while (defined(my $mid = shift @q)) {
256 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
257 return $x->{num} if $x->{blob} eq $req->{oid};
263 sub index_oid { # git->cat_async callback for 'm'
264 my ($bref, $oid, $type, $size, $req) = @_;
265 my $self = $req->{self};
266 local $self->{current_info} = "$self->{current_info} $oid";
267 return if is_bad_blob($oid, $type, $size, $req->{oid});
268 my $new_smsg = $req->{new_smsg} = bless {
270 }, 'PublicInbox::Smsg';
271 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
272 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
277 sub unindex_oid { # git->cat_async callback for 'd'
278 my ($bref, $oid, $type, $size, $req) = @_;
279 my $self = $req->{self};
280 local $self->{current_info} = "$self->{current_info} $oid";
281 return if is_bad_blob($oid, $type, $size, $req->{oid});
282 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
286 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
288 my ($self, $sync) = @_;
290 my $ekey = $sync->{ibx}->eidx_key;
291 my $uv = $sync->{ibx}->uidvalidity;
292 for my $i (0..$sync->{epoch_max}) {
293 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
298 sub _sync_inbox ($$$) {
299 my ($self, $sync, $ibx) = @_;
301 $sync->{nr} = \(my $nr = 0);
302 my $v = $ibx->version;
303 my $ekey = $ibx->eidx_key;
306 defined($ibx->git_dir_latest(\$epoch_max)) or return;
307 $sync->{epoch_max} = $epoch_max;
308 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
310 my $uv = $ibx->uidvalidity;
311 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
312 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
313 my $unit = { stack => $stk, git => $ibx->git };
314 push @{$sync->{todo}}, $unit;
316 warn "E: $ekey unsupported inbox version (v$v)\n";
319 for my $unit (@{delete($sync->{todo}) // []}) {
320 last if $sync->{quit};
321 index_todo($self, $sync, $unit);
323 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
324 $ibx->git->cleanup; # done with this inbox, now
327 sub eidx_sync { # main entry point
328 my ($self, $opt) = @_;
329 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
330 $self->{oidx}->rethread_prepare($opt);
332 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
333 local $self->{current_info} = '';
334 local $SIG{__WARN__} = sub {
335 $warn_cb->($self->{current_info}, ': ', @_);
338 need_checkpoint => \(my $need_checkpoint = 0),
339 reindex => $opt->{reindex},
342 -regen_fmt => "%u/?\n",
344 local $SIG{USR1} = sub { $need_checkpoint = 1 };
345 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
346 local $SIG{QUIT} = $quit;
347 local $SIG{INT} = $quit;
348 local $SIG{TERM} = $quit;
350 # don't use $_ here, it'll get clobbered by reindex_checkpoint
351 for my $ibx (@{$self->{ibx_list}}) {
352 last if $sync->{quit};
353 _sync_inbox($self, $sync, $ibx);
355 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
357 PublicInbox::V2Writable::done($self);
360 sub update_last_commit { # overrides V2Writable
361 my ($self, $sync, $stk) = @_;
362 my $unit = $sync->{unit} // return;
363 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
364 defined($latest_cmt) or return;
365 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
366 my $ekey = $ibx->eidx_key;
367 my $uv = $ibx->uidvalidity;
368 my $epoch = $unit->{epoch};
370 my $v = $ibx->version;
372 die 'No {epoch} for v2 unit' unless defined $epoch;
373 $meta_key = "lc-v2:$ekey//$uv;$epoch";
375 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
376 $meta_key = "lc-v1:$ekey//$uv";
378 die "Unsupported inbox version: $v";
380 my $last = $self->{oidx}->eidx_meta($meta_key);
381 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
382 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
383 chomp(my $n = $unit->{git}->qx(@cmd));
384 return if $n ne '' && $n == 0;
386 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
389 sub _idx_init { # with_umask callback
390 my ($self, $opt) = @_;
391 PublicInbox::V2Writable::_idx_init($self, $opt);
392 $self->{midx} = PublicInbox::MiscIdx->new($self);
395 sub idx_init { # similar to V2Writable
396 my ($self, $opt) = @_;
397 return if $self->{idx_shards};
401 my $ALL = $self->git->{git_dir}; # ALL.git
402 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
403 my $info_dir = "$ALL/objects/info";
404 my $alt = "$info_dir/alternates";
406 my (@old, @new, %seen); # seen: st_dev + st_ino
408 open(my $fh, '<', $alt) or die "open $alt: $!";
409 $mode = (stat($fh))[2] & 07777;
410 while (my $line = <$fh>) {
411 chomp(my $d = $line);
412 if (my @st = stat($d)) {
413 next if $seen{"$st[0]\0$st[1]"}++;
415 warn "W: stat($d) failed (from $alt): $!\n";
420 for my $ibx (@{$self->{ibx_list}}) {
421 my $line = $ibx->git->{git_dir} . "/objects\n";
422 chomp(my $d = $line);
423 if (my @st = stat($d)) {
424 next if $seen{"$st[0]\0$st[1]"}++;
426 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
433 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
435 $self->parallel_init($self->{indexlevel});
436 $self->umask_prepare;
437 $self->with_umask(\&_idx_init, $self, $opt);
438 $self->{oidx}->begin_lazy;
439 $self->{oidx}->eidx_prep;
440 $self->{midx}->begin_txn;
444 *done = \&PublicInbox::V2Writable::done;
445 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
446 *with_umask = \&PublicInbox::InboxWritable::with_umask;
447 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
448 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
449 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
450 *index_todo = \&PublicInbox::V2Writable::index_todo;
451 *count_shards = \&PublicInbox::V2Writable::count_shards;
452 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
453 *idx_shard = \&PublicInbox::V2Writable::idx_shard;