1 # Copyright (C) 2015-2020 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 or flags
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::InboxWritable;
15 use PublicInbox::MID qw(mids_for_index mids);
16 use PublicInbox::MsgIter;
17 use PublicInbox::IdxStack;
19 use POSIX qw(strftime);
20 use PublicInbox::OverIdx;
21 use PublicInbox::Spawn qw(spawn nodatacow_dir);
22 use PublicInbox::Git qw(git_unquote);
23 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
24 our @EXPORT_OK = qw(crlf_adjust log2stack is_ancestor check_size);
25 my $X = \%PublicInbox::Search::X;
26 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
28 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
29 use constant DEBUG => !!$ENV{DEBUG};
31 my $xapianlevels = qr/\A(?:full|medium)\z/;
33 my $OID = $hex .'{40,}';
36 my ($class, $ibx, $creat, $shard) = @_;
37 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
38 my $levels = qr/\A(?:full|medium|basic)\z/;
39 my $inboxdir = $ibx->{inboxdir};
40 my $version = $ibx->version;
41 my $indexlevel = 'full';
42 my $altid = $ibx->{altid};
44 require PublicInbox::AltId;
45 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
47 if ($ibx->{indexlevel}) {
48 if ($ibx->{indexlevel} =~ $levels) {
49 $indexlevel = $ibx->{indexlevel};
51 die("Invalid indexlevel $ibx->{indexlevel}\n");
54 $ibx = PublicInbox::InboxWritable->new($ibx);
57 xpfx => $inboxdir, # for xpfx_init
60 indexlevel => $indexlevel,
63 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
66 $self->{lock_path} = "$inboxdir/ssoma.lock";
67 my $dir = $self->xdir;
68 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
69 $self->{over}->{-no_fsync} = 1 if $ibx->{-no_fsync};
70 } elsif ($version == 2) {
71 defined $shard or die "shard is required for v2\n";
73 $self->{shard} = $shard;
74 $self->{lock_path} = undef;
76 die "unsupported inbox version=$version\n";
78 $self->{creat} = ($creat || 0) == 1;
82 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
85 my ($self, $wake) = @_;
86 if (need_xapian($self)) {
87 my $xdb = delete $self->{xdb} or croak 'not acquired';
90 $self->lock_release($wake) if $self->{creat};
94 sub load_xapian_writable () {
95 return 1 if $X->{WritableDatabase};
96 PublicInbox::Search::load_xapian() or return;
97 my $xap = $PublicInbox::Search::Xap;
98 for (qw(Document TermGenerator WritableDatabase)) {
99 $X->{$_} = $xap.'::'.$_;
101 eval 'require '.$X->{WritableDatabase} or die;
102 *sortable_serialise = $xap.'::sortable_serialise';
103 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
104 $DB_OPEN = eval($xap.'::DB_OPEN()');
105 my $ver = (eval($xap.'::major_version()') << 16) |
106 (eval($xap.'::minor_version()') << 8);
107 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
114 my $dir = $self->xdir;
115 if (need_xapian($self)) {
116 croak 'already acquired' if $self->{xdb};
117 load_xapian_writable();
118 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
120 if ($self->{creat}) {
124 # don't create empty Xapian directories if we don't need Xapian
125 my $is_shard = defined($self->{shard});
126 if (!-d $dir && (!$is_shard ||
127 ($is_shard && need_xapian($self)))) {
128 File::Path::mkpath($dir);
132 return unless defined $flag;
133 $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_fsync};
134 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
136 die "Failed opening $dir: ", $@;
142 my ($doc, $col, $num) = @_;
143 $num = sortable_serialise($num);
144 $doc->add_value($col, $num);
147 sub term_generator ($) { # write-only
150 $self->{term_generator} //= do {
151 my $tg = $X->{TermGenerator}->new;
152 $tg->set_stemmer($self->stemmer);
157 sub index_text ($$$$) {
158 my ($self, $text, $wdf_inc, $prefix) = @_;
159 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
161 if ($self->{indexlevel} eq 'full') {
162 $tg->index_text($text, $wdf_inc, $prefix);
163 $tg->increase_termpos;
165 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
169 sub index_headers ($$) {
170 my ($self, $smsg) = @_;
171 my @x = (from => 'A', # Author
172 subject => 'S', to => 'XTO', cc => 'XCC');
173 while (my ($field, $pfx) = splice(@x, 0, 2)) {
174 my $val = $smsg->{$field};
175 index_text($self, $val, 1, $pfx) if $val ne '';
179 sub index_diff_inc ($$$$) {
180 my ($self, $text, $pfx, $xnq) = @_;
182 index_text($self, join("\n", @$xnq), 1, 'XNQ');
185 index_text($self, $text, 1, $pfx);
188 sub index_old_diff_fn {
189 my ($self, $seen, $fa, $fb, $xnq) = @_;
191 # no renames or space support for traditional diffs,
192 # find the number of leading common paths to strip:
193 my @fa = split('/', $fa);
194 my @fb = split('/', $fb);
195 while (scalar(@fa) && scalar(@fb)) {
196 $fa = join('/', @fa);
197 $fb = join('/', @fb);
199 unless ($seen->{$fa}++) {
200 index_diff_inc($self, $fa, 'XDFN', $xnq);
210 sub index_diff ($$$) {
211 my ($self, $txt, $doc) = @_;
216 foreach (split(/\n/, $txt)) {
217 if ($in_diff && s/^ //) { # diff context
218 index_diff_inc($self, $_, 'XDFCTX', $xnq);
219 } elsif (/^-- $/) { # email signature begins
221 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
222 # wait until "---" and "+++" to capture filenames
225 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
226 my ($opt, $fa, $fb) = ($1, $2, $3);
228 # only support unified:
229 next unless $opt =~ /[uU]/;
230 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
232 } elsif (m!^--- ("?[^/]+/.+)!) {
234 $fn = (split('/', git_unquote($fn), 2))[1];
235 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
237 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
239 $fn = (split('/', git_unquote($fn), 2))[1];
240 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
242 } elsif (/^--- (\S+)/) {
245 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
246 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
248 } elsif ($in_diff && s/^\+//) { # diff added
249 index_diff_inc($self, $_, 'XDFB', $xnq);
250 } elsif ($in_diff && s/^-//) { # diff removed
251 index_diff_inc($self, $_, 'XDFA', $xnq);
252 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
253 my ($ba, $bb) = ($1, $2);
254 index_git_blob_id($doc, 'XDFPRE', $ba);
255 index_git_blob_id($doc, 'XDFPOST', $bb);
257 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
258 # traditional diff w/o -p
259 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
260 # hunk header context
261 index_diff_inc($self, $1, 'XDFHH', $xnq);
262 # ignore the following lines:
263 } elsif (/^(?:dis)similarity index/ ||
264 /^(?:old|new) mode/ ||
265 /^(?:deleted|new) file mode/ ||
266 /^(?:copy|rename) (?:from|to) / ||
267 /^(?:dis)?similarity index / ||
268 /^\\ No newline at end of file/ ||
269 /^Binary files .* differ/) {
272 # possible to be in diff context, some mail may be
273 # stripped by MUA or even GNU diff(1). "git apply"
274 # treats a bare "\n" as diff context, too
277 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
282 index_text($self, join("\n", @xnq), 1, 'XNQ');
285 sub index_xapian { # msg_iter callback
286 my $part = $_[0]->[0]; # ignore $depth and $idx
287 my ($self, $doc) = @{$_[1]};
288 my $ct = $part->content_type || 'text/plain';
289 my $fn = $part->filename;
290 if (defined $fn && $fn ne '') {
291 index_text($self, $fn, 1, 'XFN');
293 if ($part->{is_submsg}) {
294 my $mids = mids_for_index($part);
295 index_ids($self, $doc, $part, $mids);
296 my $smsg = bless {}, 'PublicInbox::Smsg';
297 $smsg->populate($part);
298 index_headers($self, $smsg);
301 my ($s, undef) = msg_part_text($part, $ct);
302 defined $s or return;
303 $_[0]->[0] = $part = undef; # free memory
305 # split off quoted and unquoted blocks:
306 my @sections = PublicInbox::MsgIter::split_quotes($s);
307 undef $s; # free memory
308 for my $txt (@sections) {
310 index_text($self, $txt, 0, 'XQUOT');
312 # does it look like a diff?
313 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
314 index_diff($self, $txt, $doc);
316 index_text($self, $txt, 1, 'XNQ');
319 undef $txt; # free memory
323 sub index_ids ($$$$) {
324 my ($self, $doc, $hdr, $mids) = @_;
325 for my $mid (@$mids) {
326 index_text($self, $mid, 1, 'XM');
328 # because too many Message-IDs are prefixed with
330 if ($mid =~ /\w{12,}/) {
331 my @long = ($mid =~ /(\w{3,}+)/g);
332 index_text($self, join(' ', @long), 1, 'XM');
335 $doc->add_boolean_term('Q' . $_) for @$mids;
336 for my $l ($hdr->header_raw('List-Id')) {
337 $l =~ /<([^>]+)>/ or next;
339 $doc->add_boolean_term('G' . $lid);
340 index_text($self, $lid, 1, 'XL'); # probabilistic
344 sub add_xapian ($$$$) {
345 my ($self, $eml, $smsg, $mids) = @_;
346 my $doc = $X->{Document}->new;
347 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
348 my @ds = gmtime($smsg->{ds});
349 my $yyyymmdd = strftime('%Y%m%d', @ds);
350 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
351 my $dt = strftime('%Y%m%d%H%M%S', @ds);
352 add_val($doc, PublicInbox::Search::DT(), $dt);
353 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
354 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
356 my $tg = term_generator($self);
357 $tg->set_document($doc);
358 index_headers($self, $smsg);
360 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
361 index_ids($self, $doc, $eml, $mids);
362 $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
363 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
364 my $data = $smsg->to_doc_data;
365 $doc->set_data($data);
366 if (my $altid = $self->{-altid}) {
367 foreach my $alt (@$altid) {
368 my $pfx = $alt->{xprefix};
369 foreach my $mid (@$mids) {
370 my $id = $alt->mid2alt($mid);
371 next unless defined $id;
372 $doc->add_boolean_term($pfx . $id);
376 $self->{xdb}->replace_document($smsg->{num}, $doc);
379 sub _msgmap_init ($) {
381 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
382 $self->{mm} //= eval {
383 require PublicInbox::Msgmap;
384 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
385 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
390 # mime = PublicInbox::Eml or Email::MIME object
391 my ($self, $mime, $smsg, $sync) = @_;
392 my $mids = mids_for_index($mime);
393 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
394 $smsg->{mid} //= $mids->[0]; # v1 compatibility
395 $smsg->{num} //= do { # v1
397 index_mm($self, $mime, $smsg->{blob}, $sync);
401 $smsg->populate($mime, $sync);
402 $smsg->{bytes} //= length($mime->as_string);
405 # order matters, overview stores every possible piece of
406 # data in doc_data (deflated). Xapian only stores a subset
407 # of the fields which exist in over.sqlite3. We may stop
408 # storing doc_data in Xapian sometime after we get multi-inbox
410 if (my $over = $self->{over}) { # v1 only
411 $over->add_overview($mime, $smsg);
413 if (need_xapian($self)) {
414 add_xapian($self, $mime, $smsg, $mids);
419 warn "failed to index message <".join('> <',@$mids).">: $@\n";
426 my ($self, $oid, @removed) = @_;
427 my $xdb = $self->{xdb} or return;
428 for my $num (@removed) {
429 my $doc = eval { $xdb->get_document($num) };
431 warn "E: $@\n" if $@;
432 warn "E: #$num $oid missing in Xapian\n";
435 my $smsg = bless {}, 'PublicInbox::Smsg';
436 $smsg->load_expand($doc);
437 my $blob = $smsg->{blob} // '(unset)';
439 $xdb->delete_document($num);
441 warn "E: #$num $oid != $blob in Xapian\n";
447 my ($self, $oid, $num) = @_;
448 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
449 $self->begin_txn_lazy;
450 xdb_remove($self, $oid, $num) if need_xapian($self);
453 sub index_git_blob_id {
454 my ($doc, $pfx, $objid) = @_;
456 my $len = length($objid);
457 for (my $len = length($objid); $len >= 7; ) {
458 $doc->add_term($pfx.$objid);
459 $objid = substr($objid, 0, --$len);
465 my ($self, $oid, $eml) = @_;
466 my $mids = mids($eml);
469 for my $mid (@$mids) {
470 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
472 warn "E: failed to remove <$mid> from overview: $@\n";
474 $nr += scalar @removed;
475 $tmp{$_}++ for @removed;
479 $mids = join('> <', @$mids);
480 warn "W: <$mids> missing for removal from overview\n";
482 while (my ($num, $nr) = each %tmp) {
483 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
486 $self->{mm}->num_delete($_) for (keys %tmp);
487 } else { # just in case msgmap and over.sqlite3 become desynched:
488 $self->{mm}->mid_delete($mids->[0]);
490 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
494 my ($self, $mime, $oid, $sync) = @_;
495 my $mids = mids($mime);
496 my $mm = $self->{mm};
497 if ($sync->{reindex}) {
498 my $over = $self->{over};
499 for my $mid (@$mids) {
500 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
501 return $num if defined $num;
503 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
505 # fallback to num_for since filters like RubyLang set the number
506 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
510 # returns the number of bytes to add if given a non-CRLF arg
511 sub crlf_adjust ($) {
512 if (index($_[0], "\r\n") < 0) {
513 # common case is LF-only, every \n needs an \r;
514 # so favor a cheap tr// over an expensive m//g
516 } else { # count number of '\n' w/o '\r', expensive:
517 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
521 sub index_both { # git->cat_async callback
522 my ($bref, $oid, $type, $size, $sync) = @_;
523 my ($nr, $max) = @$sync{qw(nr max)};
526 $size += crlf_adjust($$bref);
527 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
528 my $self = $sync->{sidx};
529 my $eml = PublicInbox::Eml->new($bref);
530 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
531 die "E: could not generate NNTP article number for $oid";
532 add_message($self, $eml, $smsg, $sync);
535 sub unindex_both { # git->cat_async callback
536 my ($bref, $oid, $type, $size, $self) = @_;
537 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
540 # called by public-inbox-index
542 my ($self, $opt) = @_;
543 delete $self->{lock_path} if $opt->{-skip_lock};
544 $self->{ibx}->with_umask(\&_index_sync, $self, $opt);
545 if ($opt->{reindex}) {
547 delete @again{qw(rethread reindex)};
548 index_sync($self, \%again);
552 sub check_size { # check_async cb for -index --max-size=...
553 my ($oid, $type, $size, $arg, $git) = @_;
554 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
555 if ($size <= $arg->{max_size}) {
556 $git->cat_async($oid, $arg->{index_oid}, $arg);
558 warn "W: skipping $oid ($size > $arg->{max_size})\n";
562 sub v1_checkpoint ($$;$) {
563 my ($self, $sync, $stk) = @_;
564 $self->{ibx}->git->check_async_wait;
565 $self->{ibx}->git->cat_async_wait;
567 # latest_cmt may be undef
568 my $newest = $stk ? $stk->{latest_cmt} : undef;
570 my $cur = $self->{mm}->last_commit || '';
571 if (need_update($self, $cur, $newest)) {
572 $self->{mm}->last_commit($newest);
575 ${$sync->{max}} = $self->{batch_bytes};
578 $self->{mm}->{dbh}->commit;
579 if ($newest && need_xapian($self)) {
580 my $cur = $self->{xdb}->get_metadata('last_commit');
581 if (need_update($self, $cur, $newest)) {
582 $self->{xdb}->set_metadata('last_commit', $newest);
586 $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
587 commit_txn_lazy($self);
588 $self->{ibx}->git->cleanup;
589 my $nr = ${$sync->{nr}};
590 idx_release($self, $nr);
591 # let another process do some work...
592 if (my $pr = $sync->{-opt}->{-progress}) {
593 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
595 if (!$stk) { # more to come
596 begin_txn_lazy($self);
597 $self->{mm}->{dbh}->begin_work;
603 my ($self, $sync, $stk) = @_;
604 my $git = $self->{ibx}->git;
605 my $max = $self->{batch_bytes};
608 $sync->{max} = \$max;
609 $sync->{sidx} = $self;
611 $self->{mm}->{dbh}->begin_work;
612 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
613 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
614 for my $oid (@leftovers) {
615 $oid = unpack('H*', $oid);
616 $git->cat_async($oid, \&unindex_both, $self);
619 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
620 $sync->{index_oid} = \&index_both;
622 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
624 my $arg = { %$sync, autime => $at, cotime => $ct };
625 if ($sync->{max_size}) {
626 $git->check_async($oid, \&check_size, $arg);
628 $git->cat_async($oid, \&index_both, $arg);
630 v1_checkpoint($self, $sync) if $max <= 0;
631 } elsif ($f eq 'd') {
632 $git->cat_async($oid, \&unindex_both, $self);
635 v1_checkpoint($self, $sync, $stk);
638 sub log2stack ($$$$) {
639 my ($sync, $git, $range, $ibx) = @_;
640 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
642 if ($ibx->version == 1) {
643 my $path = $hex.'{2}/'.$hex.'{38}';
644 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
645 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
647 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
648 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
651 # Count the new files so they can be added newest to oldest
652 # and still have numbers increasing from oldest to newest
653 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
654 --no-notes --no-color --no-renames --no-abbrev),
658 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
659 ($at, $ct) = ($1 + 0, $2 + 0);
660 $stk //= PublicInbox::IdxStack->new($3);
663 if ($D) { # reindex case
664 $D->{pack('H*', $oid)}++;
665 } else { # non-reindex case:
666 $stk->push_rec('d', $at, $ct, $oid);
671 my $oid_bin = pack('H*', $oid);
672 my $nr = --$D->{$oid_bin};
673 delete($D->{$oid_bin}) if $nr <= 0;
675 # nr < 0 (-1) means it never existed
676 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
678 $stk->push_rec('m', $at, $ct, $oid);
682 close $fh or die "git log failed: \$?=$?";
683 $stk //= PublicInbox::IdxStack->new;
687 sub prepare_stack ($$$) {
688 my ($self, $sync, $range) = @_;
689 my $git = $self->{ibx}->git;
691 if (index($range, '..') < 0) {
692 # don't show annoying git errors to users who run -index
694 $git->qx(qw(rev-parse -q --verify), "$range^0");
695 return PublicInbox::IdxStack->new->read_prepare if $?;
697 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
698 log2stack($sync, $git, $range, $self->{ibx});
701 # --is-ancestor requires git 1.8.0+
702 sub is_ancestor ($$$) {
703 my ($git, $cur, $tip) = @_;
704 return 0 unless $git->check($cur);
705 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
706 qw(merge-base --is-ancestor), $cur, $tip ];
707 my $pid = spawn($cmd);
708 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
712 sub need_update ($$$) {
713 my ($self, $cur, $new) = @_;
714 my $git = $self->{ibx}->git;
715 return 1 if $cur && !is_ancestor($git, $cur, $new);
716 my $range = $cur eq '' ? $new : "$cur..$new";
717 chomp(my $n = $git->qx(qw(rev-list --count), $range));
718 ($n eq '' || $n > 0);
721 # The last git commit we indexed with Xapian or SQLite (msgmap)
722 # This needs to account for cases where Xapian or SQLite is
723 # out-of-date with respect to the other.
725 my ($self, $mm) = @_;
726 my $lm = $mm->last_commit || '';
728 if (need_xapian($self)) {
729 $lx = $self->{xdb}->get_metadata('last_commit') || '';
733 # Use last_commit from msgmap if it is older or unset
734 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
740 sub reindex_from ($$) {
741 my ($reindex, $last_commit) = @_;
742 return $last_commit unless $reindex;
743 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
746 # indexes all unindexed messages (v1 only)
748 my ($self, $opt) = @_;
749 my $tip = $opt->{ref} || 'HEAD';
750 my $git = $self->{ibx}->git;
751 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
753 my $pr = $opt->{-progress};
754 my $sync = { reindex => $opt->{reindex}, -opt => $opt };
755 my $xdb = $self->begin_txn_lazy;
756 $self->{over}->rethread_prepare($opt);
757 my $mm = _msgmap_init($self);
758 if ($sync->{reindex}) {
759 my $last = $mm->last_commit;
763 # somebody just blindly added --reindex when indexing
764 # for the first time, allow it:
765 undef $sync->{reindex};
768 my $last_commit = _last_x_commit($self, $mm);
769 my $lx = reindex_from($sync->{reindex}, $last_commit);
770 my $range = $lx eq '' ? $tip : "$lx..$tip";
771 $pr->("counting changes\n\t$range ... ") if $pr;
772 my $stk = prepare_stack($self, $sync, $range);
773 $sync->{ntodo} = $stk ? $stk->num_records : 0;
774 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
775 process_stack($self, $sync, $stk);
779 # order matters for unlocking
780 $_[0]->{xdb} = undef;
781 $_[0]->{lockfh} = undef;
784 # remote_* subs are only used by SearchIdxPart
787 if (my $w = $self->{w}) {
788 print $w "commit\n" or die "failed to write commit: $!";
790 $self->commit_txn_lazy;
796 if (my $w = delete $self->{w}) {
797 my $pid = delete $self->{pid} or die "no process to wait on\n";
798 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
799 close $w or die "failed to close pipe for pid:$pid: $!\n";
800 waitpid($pid, 0) == $pid or die "remote process did not finish";
801 $? == 0 or die ref($self)." pid:$pid exited with: $?";
803 die "transaction in progress $self\n" if $self->{txn};
804 idx_release($self) if $self->{xdb};
809 my ($self, $oid, $num) = @_;
810 if (my $w = $self->{w}) {
811 # triggers remove_by_oid in a shard
812 print $w "D $oid $num\n" or die "failed to write remove $!";
814 $self->remove_by_oid($oid, $num);
820 my $xdb = $self->{xdb} || idx_acquire($self);
821 $self->{over}->begin_lazy if $self->{over};
822 $xdb->begin_transaction if $xdb;
829 $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
832 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
833 # This metadata is read by Admin::detect_indexlevel:
837 if (!$self->{shard} && # undef or 0, not >0
838 delete($self->{-set_indexlevel_once})) {
839 my $xdb = $self->{xdb};
840 my $level = $xdb->get_metadata('indexlevel');
841 if (!$level || $level ne 'medium') {
842 $xdb->set_metadata('indexlevel', 'medium');
849 if (my $xdb = $self->{xdb}) {
850 set_indexlevel($self);
851 $xdb->commit_transaction;
853 $self->{over}->commit_lazy if $self->{over};
856 sub commit_txn_lazy {
858 delete($self->{txn}) and
859 $self->{ibx}->with_umask(\&_commit_txn, $self);
864 if (need_xapian($self)) {
865 die "$$ $0 xdb not released\n" if $self->{xdb};
867 die "$$ $0 still in transaction\n" if $self->{txn};