1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces. This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
14 use PublicInbox::Search qw(xap_terms);
15 use PublicInbox::InboxWritable;
16 use PublicInbox::MID qw(mids_for_index mids);
17 use PublicInbox::MsgIter;
18 use PublicInbox::IdxStack;
19 use Carp qw(croak carp);
20 use POSIX qw(strftime);
21 use Fcntl qw(SEEK_SET);
22 use Time::Local qw(timegm);
23 use PublicInbox::OverIdx;
24 use PublicInbox::Spawn qw(spawn);
25 use PublicInbox::Git qw(git_unquote);
26 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
27 use PublicInbox::Address;
29 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
30 index_text term_generator add_val is_bad_blob);
31 my $X = \%PublicInbox::Search::X;
32 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
34 our $DB_DANGEROUS = 0;
35 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff :
36 # assume a typical 64-bit system has 8x more RAM than a
37 # typical 32-bit system:
38 (($Config{ptrsize} >= 8 ? 8192 : 1024) * 1024);
39 use constant DEBUG => !!$ENV{DEBUG};
40 my $BASE85 = qr/\A[a-zA-Z0-9\!\#\$\%\&\(\)\*\+\-;<=>\?\@\^_`\{\|\}\~]+\z/;
41 my $xapianlevels = qr/\A(?:full|medium)\z/;
43 my $OID = $hex .'{40,}';
44 my @VMD_MAP = (kw => 'K', L => 'L');
45 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
48 my ($class, $ibx, $creat, $shard) = @_;
49 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
50 my $inboxdir = $ibx->{inboxdir};
51 my $version = $ibx->version;
52 my $indexlevel = 'full';
53 my $altid = $ibx->{altid};
55 require PublicInbox::AltId;
56 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
58 if ($ibx->{indexlevel}) {
59 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
60 $indexlevel = $ibx->{indexlevel};
62 die("Invalid indexlevel $ibx->{indexlevel}\n");
65 $ibx = PublicInbox::InboxWritable->new($ibx);
66 my $self = PublicInbox::Search->new($ibx);
69 $self->{-altid} = $altid;
70 $self->{indexlevel} = $indexlevel;
71 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
72 if ($ibx->{-skip_docdata}) {
73 $self->{-set_skip_docdata_once} = 1;
74 $self->{-skip_docdata} = 1;
77 $self->{lock_path} = "$inboxdir/ssoma.lock";
78 my $dir = $self->xdir;
79 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
80 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
81 } elsif ($version == 2) {
82 defined $shard or die "shard is required for v2\n";
84 $self->{shard} = $shard;
85 $self->{lock_path} = undef;
87 die "unsupported inbox version=$version\n";
89 $self->{creat} = ($creat || 0) == 1;
93 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
96 my ($self, $wake) = @_;
97 if (need_xapian($self)) {
98 my $xdb = delete $self->{xdb} or croak '{xdb} not acquired';
101 $self->lock_release($wake) if $self->{creat};
105 sub load_xapian_writable () {
106 return 1 if $X->{WritableDatabase};
107 PublicInbox::Search::load_xapian() or die "failed to load Xapian: $@\n";
108 my $xap = $PublicInbox::Search::Xap;
109 for (qw(Document TermGenerator WritableDatabase)) {
110 $X->{$_} = $xap.'::'.$_;
112 eval 'require '.$X->{WritableDatabase} or die;
113 *sortable_serialise = $xap.'::sortable_serialise';
114 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
115 $DB_OPEN = eval($xap.'::DB_OPEN()');
116 my $ver = (eval($xap.'::major_version()') << 16) |
117 (eval($xap.'::minor_version()') << 8) |
118 eval($xap.'::revision()');
119 if ($ver >= 0x10400) {
121 $DB_DANGEROUS = 0x10;
123 # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
124 $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
131 my $dir = $self->xdir;
132 if (need_xapian($self)) {
133 croak 'already acquired' if $self->{xdb};
134 load_xapian_writable();
135 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
137 if ($self->{creat}) {
141 # don't create empty Xapian directories if we don't need Xapian
142 my $is_shard = defined($self->{shard});
143 if (!-d $dir && (!$is_shard ||
144 ($is_shard && need_xapian($self)))) {
145 File::Path::mkpath($dir);
146 require PublicInbox::Syscall;
147 PublicInbox::Syscall::nodatacow_dir($dir);
148 $self->{-set_has_threadid_once} = 1;
149 if (($self->{ibx} // $self->{eidx})->{-dangerous}) {
150 $flag |= $DB_DANGEROUS;
154 return unless defined $flag;
155 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
156 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
157 croak "Failed opening $dir: $@" if $@;
162 my ($doc, $col, $num) = @_;
163 $num = sortable_serialise($num);
164 $doc->add_value($col, $num);
167 sub term_generator ($) { # write-only
170 $self->{term_generator} //= do {
171 my $tg = $X->{TermGenerator}->new;
172 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
177 sub index_phrase ($$$$) {
178 my ($self, $text, $wdf_inc, $prefix) = @_;
180 my $tg = term_generator($self);
181 $tg->index_text($text, $wdf_inc, $prefix);
182 $tg->increase_termpos;
185 sub index_text ($$$$) {
186 my ($self, $text, $wdf_inc, $prefix) = @_;
188 if ($self->{indexlevel} eq 'full') {
189 index_phrase($self, $text, $wdf_inc, $prefix);
191 my $tg = term_generator($self);
192 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
196 sub index_headers ($$) {
197 my ($self, $smsg) = @_;
198 my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
199 while (my ($field, $pfx) = splice(@x, 0, 2)) {
200 my $val = $smsg->{$field};
202 # include "(comments)" after the address, too, so not using
203 # PublicInbox::Address::names or pairs
204 index_text($self, $val, 1, $pfx);
206 # we need positional info for email addresses since they
207 # can be considered phrases
208 if ($self->{indexlevel} eq 'medium') {
209 for my $addr (PublicInbox::Address::emails($val)) {
210 index_phrase($self, $addr, 1, $pfx);
214 @x = (subject => 'S');
215 while (my ($field, $pfx) = splice(@x, 0, 2)) {
216 my $val = $smsg->{$field};
217 index_text($self, $val, 1, $pfx) if $val ne '';
221 sub index_diff_inc ($$$$) {
222 my ($self, $text, $pfx, $xnq) = @_;
224 index_text($self, join("\n", @$xnq), 1, 'XNQ');
227 if ($pfx eq 'XDFN') {
228 index_phrase($self, $text, 1, $pfx);
230 index_text($self, $text, 1, $pfx);
234 sub index_old_diff_fn {
235 my ($self, $seen, $fa, $fb, $xnq) = @_;
237 # no renames or space support for traditional diffs,
238 # find the number of leading common paths to strip:
239 my @fa = split(m'/', $fa);
240 my @fb = split(m'/', $fb);
241 while (scalar(@fa) && scalar(@fb)) {
242 $fa = join('/', @fa);
243 $fb = join('/', @fb);
245 unless ($seen->{$fa}++) {
246 index_diff_inc($self, $fa, 'XDFN', $xnq);
256 sub index_diff ($$$) {
257 my ($self, $txt, $doc) = @_;
261 my @l = split(/\n/, $$txt);
263 while (defined($_ = shift @l)) {
264 if ($in_diff && /^GIT binary patch/) {
266 while (@l && $l[0] =~ /^(?:literal|delta) /) {
267 # TODO allow searching by size range?
268 # allows searching by exact size via:
269 # "literal $SIZE" or "delta $SIZE"
270 push @$xnq, shift(@l);
272 # skip base85 and empty lines
273 while (@l && ($l[0] =~ /$BASE85/o ||
277 # loop hits trailing "literal 0\nHcmV?d00001\n"
279 } elsif ($in_diff && s/^ //) { # diff context
280 index_diff_inc($self, $_, 'XDFCTX', $xnq);
281 } elsif (/^-- $/) { # email signature begins
283 } elsif (m!^diff --git ("?[^/]+/.+) ("?[^/]+/.+)\z!) {
284 # capture filenames here for binary diffs:
285 my ($fa, $fb) = ($1, $2);
288 $fa = (split(m'/', git_unquote($fa), 2))[1];
289 $fb = (split(m'/', git_unquote($fb), 2))[1];
290 $seen{$fa}++ or index_diff_inc($self, $fa, 'XDFN', $xnq);
291 $seen{$fb}++ or index_diff_inc($self, $fb, 'XDFN', $xnq);
293 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
294 my ($opt, $fa, $fb) = ($1, $2, $3);
296 # only support unified:
297 next unless $opt =~ /[uU]/;
298 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
300 } elsif (m!^--- ("?[^/]+/.+)!) {
302 $fn = (split(m'/', git_unquote($fn), 2))[1];
303 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
305 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
307 $fn = (split(m'/', git_unquote($fn), 2))[1];
308 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
310 } elsif (/^--- (\S+)/) {
311 $in_diff = $1; # old diff filename
313 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
314 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
316 } elsif ($in_diff && s/^\+//) { # diff added
317 index_diff_inc($self, $_, 'XDFB', $xnq);
318 } elsif ($in_diff && s/^-//) { # diff removed
319 index_diff_inc($self, $_, 'XDFA', $xnq);
320 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
321 my ($ba, $bb) = ($1, $2);
322 index_git_blob_id($doc, 'XDFPRE', $ba);
323 index_git_blob_id($doc, 'XDFPOST', $bb);
325 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
326 # traditional diff w/o -p
327 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
328 # hunk header context
329 index_diff_inc($self, $1, 'XDFHH', $xnq);
330 # ignore the following lines:
331 } elsif (/^(?:dis)similarity index/ ||
332 /^(?:old|new) mode/ ||
333 /^(?:deleted|new) file mode/ ||
334 /^(?:copy|rename) (?:from|to) / ||
335 /^(?:dis)?similarity index / ||
336 /^\\ No newline at end of file/ ||
337 /^Binary files .* differ/) {
340 # possible to be in diff context, some mail may be
341 # stripped by MUA or even GNU diff(1). "git apply"
342 # treats a bare "\n" as diff context, too
345 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
350 index_text($self, join("\n", @$xnq), 1, 'XNQ');
353 sub index_xapian { # msg_iter callback
354 my $part = $_[0]->[0]; # ignore $depth and $idx
355 my ($self, $doc) = @{$_[1]};
356 my $ct = $part->content_type || 'text/plain';
357 my $fn = $part->filename;
358 if (defined $fn && $fn ne '') {
359 index_phrase($self, $fn, 1, 'XFN');
361 if ($part->{is_submsg}) {
362 my $mids = mids_for_index($part);
363 index_ids($self, $doc, $part, $mids);
364 my $smsg = bless {}, 'PublicInbox::Smsg';
365 $smsg->populate($part);
366 index_headers($self, $smsg);
369 my ($s, undef) = msg_part_text($part, $ct);
370 defined $s or return;
371 $_[0]->[0] = $part = undef; # free memory
373 if ($s =~ /^(?:diff|---|\+\+\+) /ms) {
374 open(my $fh, '+>:utf8', undef) or die "open: $!";
375 open(my $eh, '+>', undef) or die "open: $!";
377 print $fh $s or die "print: $!";
378 sysseek($fh, 0, SEEK_SET) or die "sysseek: $!";
379 my $id = ($self->{ibx} // $self->{eidx})->git->qx(
380 [qw(patch-id --stable)],
381 {}, { 0 => $fh, 2 => $eh });
382 $id =~ /\A([a-f0-9]{40,})/ and $doc->add_term('XDFID'.$1);
383 seek($eh, 0, SEEK_SET) or die "seek: $!";
384 while (<$eh>) { warn $_ }
387 # split off quoted and unquoted blocks:
388 my @sections = PublicInbox::MsgIter::split_quotes($s);
389 undef $s; # free memory
390 for my $txt (@sections) {
392 index_text($self, $txt, 0, 'XQUOT');
394 # does it look like a diff?
395 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
396 index_diff($self, \$txt, $doc);
398 index_text($self, $txt, 1, 'XNQ');
401 undef $txt; # free memory
405 sub index_list_id ($$$) {
406 my ($self, $doc, $hdr) = @_;
407 for my $l ($hdr->header_raw('List-Id')) {
408 $l =~ /<([^>]+)>/ or next;
410 $doc->add_boolean_term('G' . $lid);
411 index_phrase($self, $lid, 1, 'XL'); # probabilistic
415 sub index_ids ($$$$) {
416 my ($self, $doc, $hdr, $mids) = @_;
417 for my $mid (@$mids) {
418 index_phrase($self, $mid, 1, 'XM');
420 # because too many Message-IDs are prefixed with
422 if ($mid =~ /\w{12,}/) {
423 my @long = ($mid =~ /(\w{3,}+)/g);
424 index_phrase($self, join(' ', @long), 1, 'XM');
427 $doc->add_boolean_term('Q' . $_) for @$mids;
428 index_list_id($self, $doc, $hdr);
431 sub eml2doc ($$$;$) {
432 my ($self, $eml, $smsg, $mids) = @_;
433 $mids //= mids_for_index($eml);
434 my $doc = $X->{Document}->new;
435 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
436 my @ds = gmtime($smsg->{ds});
437 my $yyyymmdd = strftime('%Y%m%d', @ds);
438 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
439 my $dt = strftime('%Y%m%d%H%M%S', @ds);
440 add_val($doc, PublicInbox::Search::DT(), $dt);
441 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
442 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
443 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
445 my $tg = term_generator($self);
446 $tg->set_document($doc);
447 index_headers($self, $smsg);
449 if (defined(my $eidx_key = $smsg->{eidx_key})) {
450 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
452 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
453 index_ids($self, $doc, $eml, $mids);
455 # by default, we maintain compatibility with v1.5.0 and earlier
456 # by writing to docdata.glass, users who never exect to downgrade can
458 if (!$self->{-skip_docdata}) {
459 # WWW doesn't need {to} or {cc}, only NNTP
460 $smsg->{to} = $smsg->{cc} = '';
461 $smsg->parse_references($eml, $mids);
462 my $data = $smsg->to_doc_data;
463 $doc->set_data($data);
466 if (my $altid = $self->{-altid}) {
467 foreach my $alt (@$altid) {
468 my $pfx = $alt->{xprefix};
469 foreach my $mid (@$mids) {
470 my $id = $alt->mid2alt($mid);
471 next unless defined $id;
472 $doc->add_boolean_term($pfx . $id);
479 sub add_xapian ($$$$) {
480 my ($self, $eml, $smsg, $mids) = @_;
481 begin_txn_lazy($self);
482 my $merge_vmd = delete $smsg->{-merge_vmd};
483 my $doc = eml2doc($self, $eml, $smsg, $mids);
484 if (my $old = $merge_vmd ? _get_doc($self, $smsg->{num}) : undef) {
486 while (my ($field, $pfx) = splice(@x, 0, 2)) {
487 for my $term (xap_terms($pfx, $old)) {
488 $doc->add_boolean_term($pfx.$term);
492 $self->{xdb}->replace_document($smsg->{num}, $doc);
495 sub _msgmap_init ($) {
497 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
499 require PublicInbox::Msgmap;
500 PublicInbox::Msgmap->new_file($self->{ibx}, 1);
505 # mime = PublicInbox::Eml or Email::MIME object
506 my ($self, $mime, $smsg, $sync) = @_;
507 begin_txn_lazy($self);
508 my $mids = mids_for_index($mime);
509 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
510 $smsg->{mid} //= $mids->[0]; # v1 compatibility
511 $smsg->{num} //= do { # v1
513 index_mm($self, $mime, $smsg->{blob}, $sync);
517 $smsg->populate($mime, $sync);
518 $smsg->{bytes} //= length($mime->as_string);
521 # order matters, overview stores every possible piece of
522 # data in doc_data (deflated). Xapian only stores a subset
523 # of the fields which exist in over.sqlite3. We may stop
524 # storing doc_data in Xapian sometime after we get multi-inbox
526 if (my $oidx = $self->{oidx}) { # v1 only
527 $oidx->add_overview($mime, $smsg);
529 if (need_xapian($self)) {
530 add_xapian($self, $mime, $smsg, $mids);
535 warn "failed to index message <".join('> <',@$mids).">: $@\n";
542 my ($self, $docid) = @_;
543 my $doc = eval { $self->{xdb}->get_document($docid) };
545 warn "E: $@\n" if $@;
546 warn "E: #$docid missing in Xapian\n";
552 my ($self, $docid, $eidx_key, $eml) = @_;
553 begin_txn_lazy($self);
554 my $doc = _get_doc($self, $docid) or return;
555 term_generator($self)->set_document($doc);
557 # '.' is special for lei_store
558 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
560 index_list_id($self, $doc, $eml);
561 $self->{xdb}->replace_document($docid, $doc);
565 my ($self, $pfx, $docid) = @_;
566 begin_txn_lazy($self);
567 xap_terms($pfx, $self->{xdb}, $docid);
570 sub remove_eidx_info {
571 my ($self, $docid, $eidx_key, $eml) = @_;
572 begin_txn_lazy($self);
573 my $doc = _get_doc($self, $docid) or return;
574 eval { $doc->remove_term('O'.$eidx_key) };
575 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
576 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
577 $l =~ /<([^>]+)>/ or next;
579 eval { $doc->remove_term('G' . $lid) };
580 warn "W: ->remove_term G$lid: $@\n" if $@;
582 # nb: we don't remove the XL probabilistic terms
583 # since terms may overlap if cross-posted.
585 # IOW, a message which has both <foo.example.com>
586 # and <bar.example.com> would have overlapping
587 # "XLexample" and "XLcom" as terms and which we
588 # wouldn't know if they're safe to remove if we just
589 # unindex <foo.example.com> while preserving
592 # In any case, this entire sub is will likely never
593 # be needed and users using the "l:" prefix are probably
596 $self->{xdb}->replace_document($docid, $doc);
600 my ($self, $docid, $vmd) = @_;
601 begin_txn_lazy($self);
602 my $doc = _get_doc($self, $docid) or return;
603 my ($end, @rm, @add);
605 while (my ($field, $pfx) = splice(@x, 0, 2)) {
606 my $set = $vmd->{$field} // next;
607 my %keep = map { $_ => 1 } @$set;
609 $end //= $doc->termlist_end;
610 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
612 last if $cur == $end;
613 my $v = $cur->get_termname;
614 $v =~ s/\A$pfx//s or next;
615 $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
617 push(@add, map { $pfx.$_ } keys %add);
619 return unless scalar(@rm) || scalar(@add);
620 $doc->remove_term($_) for @rm;
621 $doc->add_boolean_term($_) for @add;
622 $self->{xdb}->replace_document($docid, $doc);
625 sub apply_vmd_mod ($$) {
626 my ($doc, $vmd_mod) = @_;
629 while (my ($field, $pfx) = splice(@x, 0, 2)) {
631 for my $val (@{$vmd_mod->{"-$field"} // []}) {
633 $doc->remove_term($pfx . $val);
637 for my $val (@{$vmd_mod->{"+$field"} // []}) {
638 $doc->add_boolean_term($pfx . $val);
646 my ($self, $docid, $vmd) = @_;
647 begin_txn_lazy($self);
648 my $doc = _get_doc($self, $docid) or return;
651 while (my ($field, $pfx) = splice(@x, 0, 2)) {
652 my $add = $vmd->{$field} // next;
653 $doc->add_boolean_term($pfx . $_) for @$add;
654 $updated += scalar(@$add);
656 $updated += apply_vmd_mod($doc, $vmd);
657 $self->{xdb}->replace_document($docid, $doc) if $updated;
661 my ($self, $docid, $vmd) = @_;
662 begin_txn_lazy($self);
663 my $doc = _get_doc($self, $docid) or return;
666 while (my ($field, $pfx) = splice(@x, 0, 2)) {
667 my $rm = $vmd->{$field} // next;
670 $doc->remove_term($pfx . $_);
675 $self->{xdb}->replace_document($docid, $doc) if $replace;
679 my ($self, $docid, $vmd_mod) = @_;
680 begin_txn_lazy($self);
681 my $doc = _get_doc($self, $docid) or return;
682 my $updated = apply_vmd_mod($doc, $vmd_mod);
683 $self->{xdb}->replace_document($docid, $doc) if $updated;
688 my ($self, @docids) = @_;
689 begin_txn_lazy($self);
690 my $xdb = $self->{xdb} // die 'BUG: missing {xdb}';
691 for my $docid (@docids) {
692 eval { $xdb->delete_document($docid) };
693 warn "E: #$docid not in in Xapian? $@\n" if $@;
697 sub xdb_remove_quiet {
698 my ($self, $docid) = @_;
699 begin_txn_lazy($self);
700 my $xdb = $self->{xdb} // die 'BUG: missing {xdb}';
701 eval { $xdb->delete_document($docid) };
702 ++$self->{-quiet_rm} unless $@;
705 sub nr_quiet_rm { delete($_[0]->{-quiet_rm}) // 0 }
707 sub index_git_blob_id {
708 my ($doc, $pfx, $objid) = @_;
710 my $len = length($objid);
711 for (my $len = length($objid); $len >= 7; ) {
712 $doc->add_term($pfx.$objid);
713 $objid = substr($objid, 0, --$len);
719 my ($self, $oid, $eml) = @_;
720 my $mids = mids($eml);
723 for my $mid (@$mids) {
724 my @removed = $self->{oidx}->remove_oid($oid, $mid);
725 $nr += scalar @removed;
726 $tmp{$_}++ for @removed;
729 my $m = join('> <', @$mids);
730 warn "W: <$m> missing for removal from overview\n";
732 while (my ($num, $nr) = each %tmp) {
733 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
736 $self->{mm}->num_delete($_) for (keys %tmp);
737 } else { # just in case msgmap and over.sqlite3 become desynched:
738 $self->{mm}->mid_delete($mids->[0]);
740 xdb_remove($self, keys %tmp) if need_xapian($self);
744 my ($self, $mime, $oid, $sync) = @_;
745 my $mids = mids($mime);
746 my $mm = $self->{mm};
747 if ($sync->{reindex}) {
748 my $oidx = $self->{oidx};
749 for my $mid (@$mids) {
750 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
751 return $num if defined $num;
753 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
755 # fallback to num_for since filters like RubyLang set the number
756 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
760 sub is_bad_blob ($$$$) {
761 my ($oid, $type, $size, $expect_oid) = @_;
762 if ($type ne 'blob') {
763 carp "W: $expect_oid is not a blob (type=$type)";
766 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
767 $size == 0 ? 1 : 0; # size == 0 means purged
770 sub index_both { # git->cat_async callback
771 my ($bref, $oid, $type, $size, $sync) = @_;
772 return if is_bad_blob($oid, $type, $size, $sync->{oid});
773 my ($nr, $max) = @$sync{qw(nr max)};
776 my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
777 $smsg->set_bytes($$bref, $size);
778 my $self = $sync->{sidx};
779 local $self->{current_info} = "$self->{current_info}: $oid";
780 my $eml = PublicInbox::Eml->new($bref);
781 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
782 die "E: could not generate NNTP article number for $oid";
783 add_message($self, $eml, $smsg, $sync);
785 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
786 ${$sync->{latest_cmt}} = $cur_cmt;
789 sub unindex_both { # git->cat_async callback
790 my ($bref, $oid, $type, $size, $sync) = @_;
791 return if is_bad_blob($oid, $type, $size, $sync->{oid});
792 my $self = $sync->{sidx};
793 local $self->{current_info} = "$self->{current_info}: $oid";
794 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
795 # may be undef if leftover
796 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
797 ${$sync->{latest_cmt}} = $cur_cmt;
804 ($self->{ibx} // $self->{eidx})->with_umask(@_);
807 # called by public-inbox-index
809 my ($self, $opt) = @_;
810 delete $self->{lock_path} if $opt->{-skip_lock};
811 $self->with_umask(\&_index_sync, $self, $opt);
812 if ($opt->{reindex} && !$opt->{quit} &&
813 !grep(defined, @$opt{qw(since until)})) {
815 delete @again{qw(rethread reindex)};
816 index_sync($self, \%again);
817 $opt->{quit} = $again{quit}; # propagate to caller
821 sub check_size { # check_async cb for -index --max-size=...
822 my ($oid, $type, $size, $arg, $git) = @_;
823 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
824 if ($size <= $arg->{max_size}) {
825 $git->cat_async($oid, $arg->{index_oid}, $arg);
827 warn "W: skipping $oid ($size > $arg->{max_size})\n";
831 sub v1_checkpoint ($$;$) {
832 my ($self, $sync, $stk) = @_;
833 $self->{ibx}->git->async_wait_all;
835 # $newest may be undef
836 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
837 if (defined($newest)) {
838 my $cur = $self->{mm}->last_commit;
839 if (need_update($self, $sync, $cur, $newest)) {
840 $self->{mm}->last_commit($newest);
843 ${$sync->{max}} = $self->{batch_bytes};
845 $self->{mm}->{dbh}->commit;
846 eval { $self->{mm}->{dbh}->do('PRAGMA optimize') };
847 my $xdb = $self->{xdb};
848 if ($newest && $xdb) {
849 my $cur = $xdb->get_metadata('last_commit');
850 if (need_update($self, $sync, $cur, $newest)) {
851 $xdb->set_metadata('last_commit', $newest);
854 if ($stk) { # all done if $stk is passed
855 # let SearchView know a full --reindex was done so it can
856 # generate ->has_threadid-dependent links
857 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
858 my $n = $xdb->get_metadata('has_threadid');
859 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
861 $self->{oidx}->rethread_done($sync->{-opt}); # all done
863 commit_txn_lazy($self);
864 $sync->{ibx}->git->cleanup;
865 my $nr = ${$sync->{nr}};
866 idx_release($self, $nr);
867 # let another process do some work...
868 if (my $pr = $sync->{-opt}->{-progress}) {
869 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
871 if (!$stk && !$sync->{quit}) { # more to come
872 begin_txn_lazy($self);
873 $self->{mm}->{dbh}->begin_work;
879 my ($self, $sync, $stk) = @_;
880 my $git = $sync->{ibx}->git;
881 my $max = $self->{batch_bytes};
884 $sync->{max} = \$max;
885 $sync->{sidx} = $self;
886 $sync->{latest_cmt} = \(my $latest_cmt);
888 $self->{mm}->{dbh}->begin_work;
889 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
890 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
891 for my $oid (@leftovers) {
892 last if $sync->{quit};
893 $oid = unpack('H*', $oid);
894 $git->cat_async($oid, \&unindex_both, $sync);
897 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
898 $sync->{index_oid} = \&index_both;
900 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
901 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
902 last if $sync->{quit};
904 $arg->{autime} = $at;
905 $arg->{cotime} = $ct;
906 if ($sync->{max_size}) {
907 $git->check_async($oid, \&check_size, $arg);
909 $git->cat_async($oid, \&index_both, $arg);
911 v1_checkpoint($self, $sync) if $max <= 0;
912 } elsif ($f eq 'd') {
913 $git->cat_async($oid, \&unindex_both, $arg);
916 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
919 sub log2stack ($$$) {
920 my ($sync, $git, $range) = @_;
921 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
923 if ($sync->{ibx}->version == 1) {
924 my $path = $hex.'{2}/'.$hex.'{38}';
925 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
926 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
928 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
929 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
932 # Count the new files so they can be added newest to oldest
933 # and still have numbers increasing from oldest to newest
934 my @cmd = qw(log --raw -r --pretty=tformat:%at-%ct-%H
935 --no-notes --no-color --no-renames --no-abbrev);
936 for my $k (qw(since until)) {
937 my $v = $sync->{-opt}->{$k} // next;
938 next if !$sync->{-opt}->{reindex};
939 push @cmd, "--$k=$v";
941 my $fh = $git->popen(@cmd, $range);
942 my ($at, $ct, $stk, $cmt, $l);
943 while (defined($l = <$fh>)) {
944 return if $sync->{quit};
945 if ($l =~ /\A([0-9]+)-([0-9]+)-($OID)$/o) {
946 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
947 $stk //= PublicInbox::IdxStack->new($cmt);
948 } elsif ($l =~ /$del/) {
950 if ($D) { # reindex case
951 $D->{pack('H*', $oid)}++;
952 } else { # non-reindex case:
953 $stk->push_rec('d', $at, $ct, $oid, $cmt);
955 } elsif ($l =~ /$add/) {
958 my $oid_bin = pack('H*', $oid);
959 my $nr = --$D->{$oid_bin};
960 delete($D->{$oid_bin}) if $nr <= 0;
961 # nr < 0 (-1) means it never existed
964 $stk->push_rec('m', $at, $ct, $oid, $cmt);
967 close $fh or die "git log failed: \$?=$?";
968 $stk //= PublicInbox::IdxStack->new;
972 sub prepare_stack ($$) {
973 my ($sync, $range) = @_;
974 my $git = $sync->{ibx}->git;
976 if (index($range, '..') < 0) {
977 # don't show annoying git errors to users who run -index
979 $git->qx(qw(rev-parse -q --verify), "$range^0");
980 return PublicInbox::IdxStack->new->read_prepare if $?;
982 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
983 log2stack($sync, $git, $range);
986 # --is-ancestor requires git 1.8.0+
987 sub is_ancestor ($$$) {
988 my ($git, $cur, $tip) = @_;
989 return 0 unless $git->check($cur);
990 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
991 qw(merge-base --is-ancestor), $cur, $tip ];
992 my $pid = spawn($cmd);
993 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
997 sub need_update ($$$$) {
998 my ($self, $sync, $cur, $new) = @_;
999 my $git = $self->{ibx}->git;
1000 $cur //= ''; # XS Search::Xapian ->get_metadata doesn't give undef
1002 # don't rewind if --{since,until,before,after} are in use
1003 return if $cur ne '' &&
1004 grep(defined, @{$sync->{-opt}}{qw(since until)}) &&
1005 is_ancestor($git, $new, $cur);
1007 return 1 if $cur ne '' && !is_ancestor($git, $cur, $new);
1008 my $range = $cur eq '' ? $new : "$cur..$new";
1009 chomp(my $n = $git->qx(qw(rev-list --count), $range));
1010 ($n eq '' || $n > 0);
1013 # The last git commit we indexed with Xapian or SQLite (msgmap)
1014 # This needs to account for cases where Xapian or SQLite is
1015 # out-of-date with respect to the other.
1016 sub _last_x_commit {
1017 my ($self, $mm) = @_;
1018 my $lm = $mm->last_commit || '';
1020 if (need_xapian($self)) {
1021 $lx = $self->{xdb}->get_metadata('last_commit') || '';
1025 # Use last_commit from msgmap if it is older or unset
1026 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
1032 sub reindex_from ($$) {
1033 my ($reindex, $last_commit) = @_;
1034 return $last_commit unless $reindex;
1035 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
1041 # we set {-opt}->{quit} too, so ->index_sync callers
1042 # can abort multi-inbox loops this way
1043 $sync->{quit} = $sync->{-opt}->{quit} = 1;
1044 warn "gracefully quitting\n";
1048 # indexes all unindexed messages (v1 only)
1050 my ($self, $opt) = @_;
1051 my $tip = $opt->{ref} || 'HEAD';
1052 my $ibx = $self->{ibx};
1053 local $self->{current_info} = "$ibx->{inboxdir}";
1054 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
1055 $ibx->git->batch_prepare;
1056 my $pr = $opt->{-progress};
1057 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
1058 my $quit = quit_cb($sync);
1059 local $SIG{QUIT} = $quit;
1060 local $SIG{INT} = $quit;
1061 local $SIG{TERM} = $quit;
1062 my $xdb = $self->begin_txn_lazy;
1063 $self->{oidx}->rethread_prepare($opt);
1064 my $mm = _msgmap_init($self);
1065 if ($sync->{reindex}) {
1066 my $last = $mm->last_commit;
1070 # somebody just blindly added --reindex when indexing
1071 # for the first time, allow it:
1072 undef $sync->{reindex};
1075 my $last_commit = _last_x_commit($self, $mm);
1076 my $lx = reindex_from($sync->{reindex}, $last_commit);
1077 my $range = $lx eq '' ? $tip : "$lx..$tip";
1078 $pr->("counting changes\n\t$range ... ") if $pr;
1079 my $stk = prepare_stack($sync, $range);
1080 $sync->{ntodo} = $stk ? $stk->num_records : 0;
1081 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
1082 process_stack($self, $sync, $stk) if !$sync->{quit};
1086 # order matters for unlocking
1087 $_[0]->{xdb} = undef;
1088 $_[0]->{lockfh} = undef;
1093 my $xdb = $self->{xdb} || idx_acquire($self);
1094 $self->{oidx}->begin_lazy if $self->{oidx};
1095 $xdb->begin_transaction if $xdb;
1100 sub begin_txn_lazy {
1102 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1105 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1106 # This metadata is read by Admin::detect_indexlevel:
1107 sub set_metadata_once {
1110 return if $self->{shard}; # only continue if undef or 0, not >0
1111 my $xdb = $self->{xdb};
1113 if (delete($self->{-set_has_threadid_once})) {
1114 $xdb->set_metadata('has_threadid', '1');
1116 if (delete($self->{-set_indexlevel_once})) {
1117 my $level = $xdb->get_metadata('indexlevel');
1118 if (!$level || $level ne 'medium') {
1119 $xdb->set_metadata('indexlevel', 'medium');
1122 if (delete($self->{-set_skip_docdata_once})) {
1123 $xdb->get_metadata('skip_docdata') or
1124 $xdb->set_metadata('skip_docdata', '1');
1130 if (my $eidx = $self->{eidx}) {
1131 $eidx->git->async_wait_all;
1132 $eidx->{transact_bytes} = 0;
1134 if (my $xdb = $self->{xdb}) {
1135 set_metadata_once($self);
1136 $xdb->commit_transaction;
1138 $self->{oidx}->commit_lazy if $self->{oidx};
1141 sub commit_txn_lazy {
1143 delete($self->{txn}) and
1144 $self->with_umask(\&_commit_txn, $self);
1147 sub eidx_shard_new {
1148 my ($class, $eidx, $shard) = @_;
1151 xpfx => $eidx->{xpfx},
1152 indexlevel => $eidx->{indexlevel},
1157 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';