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 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
132 my $xnum = $req->{xnum};
133 $self->{oidx}->add_xref3($docid, $xnum, $oid, $xibx->eidx_key);
134 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
135 check_batch_limit($req);
137 $self->{oidx}->remove_xref3($docid, $oid, $xibx->eidx_key);
138 $idx->shard_remove_eidx_info($docid, $oid, $xibx, $eml);
142 # called by V2Writable::sync_prepare
143 sub artnum_max { $_[0]->{oidx}->eidx_max }
145 sub index_unseen ($) {
147 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
148 my $eml = delete $req->{eml};
149 $new_smsg->populate($eml, $req);
150 my $self = $req->{self};
151 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
152 $new_smsg->{num} = $docid;
153 my $idx = $self->idx_shard($docid);
154 $self->{oidx}->add_overview($eml, $new_smsg);
155 my $oid = $new_smsg->{blob};
156 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
157 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
158 $idx->index_raw(undef, $eml, $new_smsg, $ibx);
159 check_batch_limit($req);
162 sub do_finalize ($) {
164 if (my $indexed = $req->{indexed}) {
165 do_xpost($req, $_) for @$indexed;
166 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
169 # `d' message was already unindexed in the v1/v2 inboxes,
170 # so it's too noisy to warn, here.
172 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
173 if (defined(my $cur_cmt = $req->{cur_cmt})) {
174 ${$req->{latest_cmt}} = $cur_cmt;
178 sub do_step ($) { # main iterator for adding messages to the index
180 my $self = $req->{self};
182 if (my $next_arg = $req->{next_arg}) {
183 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
184 $req->{cur_smsg} = $smsg;
185 $self->git->cat_async($smsg->{blob},
186 \&ck_existing, $req);
187 return; # ck_existing calls do_step
189 delete $req->{cur_smsg};
190 delete $req->{next_arg};
192 my $mid = shift(@{$req->{mids}});
193 last unless defined $mid;
195 $req->{next_arg} = [ $mid, \$id, \$prev ];
201 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
203 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
204 my $self = $req->{self};
205 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
206 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
208 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
209 die "BUG: xref $keep[0] has no OID";
211 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
212 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
213 my $saved = $self->{oidx}->get_art($smsg->{num});
215 $self->{oidx}->delete_by_num($smsg->{num});
219 sub ck_existing { # git->cat_async callback
220 my ($bref, $oid, $type, $size, $req) = @_;
221 my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
222 if ($type eq 'missing') {
224 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
225 my $cur = PublicInbox::Eml->new($bref);
226 if (content_hash($cur) eq $req->{chash}) {
227 push @{$req->{indexed}}, $smsg; # for do_xpost
228 } # else { index_unseen later }
233 # is the messages visible in the inbox currently being indexed?
234 # return the number if so
235 sub cur_ibx_xnum ($$) {
236 my ($req, $bref) = @_;
237 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
240 git_blob_digest($bref)->hexdigest eq $req->{oid} or die
241 "BUG: blob mismatch $req->{oid}";
243 $req->{eml} = PublicInbox::Eml->new($bref);
244 $req->{chash} = content_hash($req->{eml});
245 $req->{mids} = mids($req->{eml});
246 my @q = @{$req->{mids}}; # copy
247 while (defined(my $mid = shift @q)) {
249 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
250 return $x->{num} if $x->{blob} eq $req->{oid};
256 sub index_oid { # git->cat_async callback for 'm'
257 my ($bref, $oid, $type, $size, $req) = @_;
258 my $self = $req->{self};
259 local $self->{current_info} = "$self->{current_info} $oid";
260 return if is_bad_blob($oid, $type, $size, $req->{oid});
261 my $new_smsg = $req->{new_smsg} = bless {
263 }, 'PublicInbox::Smsg';
264 $new_smsg->{bytes} = $size + crlf_adjust($$bref);
265 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
270 sub unindex_oid { # git->cat_async callback for 'd'
271 my ($bref, $oid, $type, $size, $req) = @_;
272 my $self = $req->{self};
273 local $self->{current_info} = "$self->{current_info} $oid";
274 return if is_bad_blob($oid, $type, $size, $req->{oid});
275 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
279 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
281 my ($self, $sync) = @_;
283 my $ekey = $sync->{ibx}->eidx_key;
284 my $uv = $sync->{ibx}->uidvalidity;
285 for my $i (0..$sync->{epoch_max}) {
286 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
291 sub _sync_inbox ($$$) {
292 my ($self, $sync, $ibx) = @_;
294 $sync->{nr} = \(my $nr = 0);
295 my $v = $ibx->version;
296 my $ekey = $ibx->eidx_key;
299 defined($ibx->git_dir_latest(\$epoch_max)) or return;
300 $sync->{epoch_max} = $epoch_max;
301 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
303 my $uv = $ibx->uidvalidity;
304 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
305 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
306 my $unit = { stack => $stk, git => $ibx->git };
307 push @{$sync->{todo}}, $unit;
309 warn "E: $ekey unsupported inbox version (v$v)\n";
312 unless ($sync->{quit}) {
313 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
314 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
316 $ibx->git->cleanup; # done with this inbox, now
319 sub eidx_sync { # main entry point
320 my ($self, $opt) = @_;
321 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
322 $self->{oidx}->rethread_prepare($opt);
324 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
325 local $self->{current_info} = '';
326 local $SIG{__WARN__} = sub {
327 $warn_cb->($self->{current_info}, ': ', @_);
330 need_checkpoint => \(my $need_checkpoint = 0),
331 reindex => $opt->{reindex},
334 -regen_fmt => "%u/?\n",
336 local $SIG{USR1} = sub { $need_checkpoint = 1 };
337 my $quit = sub { $sync->{quit} = 1; warn "gracefully quitting\n"; };
338 local $SIG{QUIT} = $quit;
339 local $SIG{INT} = $quit;
340 local $SIG{TERM} = $quit;
342 # don't use $_ here, it'll get clobbered by reindex_checkpoint
343 for my $ibx (@{$self->{ibx_list}}) {
344 _sync_inbox($self, $sync, $ibx);
345 last if $sync->{quit};
348 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
350 PublicInbox::V2Writable::done($self);
353 sub update_last_commit { # overrides V2Writable
354 my ($self, $sync, $stk) = @_;
355 my $unit = $sync->{unit} // return;
356 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
357 defined($latest_cmt) or return;
358 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
359 my $ekey = $ibx->eidx_key;
360 my $uv = $ibx->uidvalidity;
361 my $epoch = $unit->{epoch};
363 my $v = $ibx->version;
365 die 'No {epoch} for v2 unit' unless defined $epoch;
366 $meta_key = "lc-v2:$ekey//$uv;$epoch";
368 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
369 $meta_key = "lc-v1:$ekey//$uv";
371 die "Unsupported inbox version: $v";
373 my $last = $self->{oidx}->eidx_meta($meta_key);
374 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
375 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
376 chomp(my $n = $unit->{git}->qx(@cmd));
377 return if $n ne '' && $n == 0;
379 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
382 sub _idx_init { # with_umask callback
383 my ($self, $opt) = @_;
384 PublicInbox::V2Writable::_idx_init($self, $opt);
385 $self->{midx} = PublicInbox::MiscIdx->new($self);
388 sub idx_init { # similar to V2Writable
389 my ($self, $opt) = @_;
390 return if $self->{idx_shards};
394 my $ALL = $self->git->{git_dir}; # ALL.git
395 PublicInbox::Import::init_bare($ALL) unless -d $ALL;
396 my $info_dir = "$ALL/objects/info";
397 my $alt = "$info_dir/alternates";
399 my (@old, @new, %seen); # seen: st_dev + st_ino
401 open(my $fh, '<', $alt) or die "open $alt: $!";
402 $mode = (stat($fh))[2] & 07777;
403 while (my $line = <$fh>) {
404 chomp(my $d = $line);
405 if (my @st = stat($d)) {
406 next if $seen{"$st[0]\0$st[1]"}++;
408 warn "W: stat($d) failed (from $alt): $!\n";
413 for my $ibx (@{$self->{ibx_list}}) {
414 my $line = $ibx->git->{git_dir} . "/objects\n";
415 chomp(my $d = $line);
416 if (my @st = stat($d)) {
417 next if $seen{"$st[0]\0$st[1]"}++;
419 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
426 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
428 $self->parallel_init($self->{indexlevel});
429 $self->umask_prepare;
430 $self->with_umask(\&_idx_init, $self, $opt);
431 $self->{oidx}->begin_lazy;
432 $self->{oidx}->eidx_prep;
433 $self->{midx}->begin_txn;
437 *done = \&PublicInbox::V2Writable::done;
438 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
439 *with_umask = \&PublicInbox::InboxWritable::with_umask;
440 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
441 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
442 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
443 *index_todo = \&PublicInbox::V2Writable::index_todo;
444 *count_shards = \&PublicInbox::V2Writable::count_shards;
445 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
446 *idx_shard = \&PublicInbox::V2Writable::idx_shard;