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 $self->{index_max_size} = $ibx->{index_max_size};
71 } elsif ($version == 2) {
72 defined $shard or die "shard is required for v2\n";
74 $self->{shard} = $shard;
75 $self->{lock_path} = undef;
77 die "unsupported inbox version=$version\n";
79 $self->{creat} = ($creat || 0) == 1;
83 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
86 my ($self, $wake) = @_;
87 if (need_xapian($self)) {
88 my $xdb = delete $self->{xdb} or croak 'not acquired';
91 $self->lock_release($wake) if $self->{creat};
95 sub load_xapian_writable () {
96 return 1 if $X->{WritableDatabase};
97 PublicInbox::Search::load_xapian() or return;
98 my $xap = $PublicInbox::Search::Xap;
99 for (qw(Document TermGenerator WritableDatabase)) {
100 $X->{$_} = $xap.'::'.$_;
102 eval 'require '.$X->{WritableDatabase} or die;
103 *sortable_serialise = $xap.'::sortable_serialise';
104 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
105 $DB_OPEN = eval($xap.'::DB_OPEN()');
106 my $ver = (eval($xap.'::major_version()') << 16) |
107 (eval($xap.'::minor_version()') << 8);
108 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
115 my $dir = $self->xdir;
116 if (need_xapian($self)) {
117 croak 'already acquired' if $self->{xdb};
118 load_xapian_writable();
119 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
121 if ($self->{creat}) {
125 # don't create empty Xapian directories if we don't need Xapian
126 my $is_shard = defined($self->{shard});
127 if (!-d $dir && (!$is_shard ||
128 ($is_shard && need_xapian($self)))) {
129 File::Path::mkpath($dir);
133 return unless defined $flag;
134 $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_fsync};
135 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
137 die "Failed opening $dir: ", $@;
143 my ($doc, $col, $num) = @_;
144 $num = sortable_serialise($num);
145 $doc->add_value($col, $num);
148 sub term_generator ($) { # write-only
151 $self->{term_generator} //= do {
152 my $tg = $X->{TermGenerator}->new;
153 $tg->set_stemmer($self->stemmer);
158 sub index_text ($$$$) {
159 my ($self, $text, $wdf_inc, $prefix) = @_;
160 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
162 if ($self->{indexlevel} eq 'full') {
163 $tg->index_text($text, $wdf_inc, $prefix);
164 $tg->increase_termpos;
166 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
170 sub index_headers ($$) {
171 my ($self, $smsg) = @_;
172 my @x = (from => 'A', # Author
173 subject => 'S', to => 'XTO', cc => 'XCC');
174 while (my ($field, $pfx) = splice(@x, 0, 2)) {
175 my $val = $smsg->{$field};
176 index_text($self, $val, 1, $pfx) if $val ne '';
180 sub index_diff_inc ($$$$) {
181 my ($self, $text, $pfx, $xnq) = @_;
183 index_text($self, join("\n", @$xnq), 1, 'XNQ');
186 index_text($self, $text, 1, $pfx);
189 sub index_old_diff_fn {
190 my ($self, $seen, $fa, $fb, $xnq) = @_;
192 # no renames or space support for traditional diffs,
193 # find the number of leading common paths to strip:
194 my @fa = split('/', $fa);
195 my @fb = split('/', $fb);
196 while (scalar(@fa) && scalar(@fb)) {
197 $fa = join('/', @fa);
198 $fb = join('/', @fb);
200 unless ($seen->{$fa}++) {
201 index_diff_inc($self, $fa, 'XDFN', $xnq);
211 sub index_diff ($$$) {
212 my ($self, $txt, $doc) = @_;
217 foreach (split(/\n/, $txt)) {
218 if ($in_diff && s/^ //) { # diff context
219 index_diff_inc($self, $_, 'XDFCTX', $xnq);
220 } elsif (/^-- $/) { # email signature begins
222 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
223 # wait until "---" and "+++" to capture filenames
226 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
227 my ($opt, $fa, $fb) = ($1, $2, $3);
229 # only support unified:
230 next unless $opt =~ /[uU]/;
231 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
233 } elsif (m!^--- ("?[^/]+/.+)!) {
235 $fn = (split('/', git_unquote($fn), 2))[1];
236 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
238 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
240 $fn = (split('/', git_unquote($fn), 2))[1];
241 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
243 } elsif (/^--- (\S+)/) {
246 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
247 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
249 } elsif ($in_diff && s/^\+//) { # diff added
250 index_diff_inc($self, $_, 'XDFB', $xnq);
251 } elsif ($in_diff && s/^-//) { # diff removed
252 index_diff_inc($self, $_, 'XDFA', $xnq);
253 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
254 my ($ba, $bb) = ($1, $2);
255 index_git_blob_id($doc, 'XDFPRE', $ba);
256 index_git_blob_id($doc, 'XDFPOST', $bb);
258 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
259 # traditional diff w/o -p
260 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
261 # hunk header context
262 index_diff_inc($self, $1, 'XDFHH', $xnq);
263 # ignore the following lines:
264 } elsif (/^(?:dis)similarity index/ ||
265 /^(?:old|new) mode/ ||
266 /^(?:deleted|new) file mode/ ||
267 /^(?:copy|rename) (?:from|to) / ||
268 /^(?:dis)?similarity index / ||
269 /^\\ No newline at end of file/ ||
270 /^Binary files .* differ/) {
273 # possible to be in diff context, some mail may be
274 # stripped by MUA or even GNU diff(1). "git apply"
275 # treats a bare "\n" as diff context, too
278 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
283 index_text($self, join("\n", @xnq), 1, 'XNQ');
286 sub index_xapian { # msg_iter callback
287 my $part = $_[0]->[0]; # ignore $depth and $idx
288 my ($self, $doc) = @{$_[1]};
289 my $ct = $part->content_type || 'text/plain';
290 my $fn = $part->filename;
291 if (defined $fn && $fn ne '') {
292 index_text($self, $fn, 1, 'XFN');
294 if ($part->{is_submsg}) {
295 my $mids = mids_for_index($part);
296 index_ids($self, $doc, $part, $mids);
297 my $smsg = bless {}, 'PublicInbox::Smsg';
298 $smsg->populate($part);
299 index_headers($self, $smsg);
302 my ($s, undef) = msg_part_text($part, $ct);
303 defined $s or return;
304 $_[0]->[0] = $part = undef; # free memory
306 # split off quoted and unquoted blocks:
307 my @sections = PublicInbox::MsgIter::split_quotes($s);
308 undef $s; # free memory
309 for my $txt (@sections) {
311 index_text($self, $txt, 0, 'XQUOT');
313 # does it look like a diff?
314 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
315 index_diff($self, $txt, $doc);
317 index_text($self, $txt, 1, 'XNQ');
320 undef $txt; # free memory
324 sub index_ids ($$$$) {
325 my ($self, $doc, $hdr, $mids) = @_;
326 for my $mid (@$mids) {
327 index_text($self, $mid, 1, 'XM');
329 # because too many Message-IDs are prefixed with
331 if ($mid =~ /\w{12,}/) {
332 my @long = ($mid =~ /(\w{3,}+)/g);
333 index_text($self, join(' ', @long), 1, 'XM');
336 $doc->add_boolean_term('Q' . $_) for @$mids;
337 for my $l ($hdr->header_raw('List-Id')) {
338 $l =~ /<([^>]+)>/ or next;
340 $doc->add_boolean_term('G' . $lid);
341 index_text($self, $lid, 1, 'XL'); # probabilistic
345 sub add_xapian ($$$$) {
346 my ($self, $eml, $smsg, $mids) = @_;
347 my $doc = $X->{Document}->new;
348 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
349 my @ds = gmtime($smsg->{ds});
350 my $yyyymmdd = strftime('%Y%m%d', @ds);
351 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
352 my $dt = strftime('%Y%m%d%H%M%S', @ds);
353 add_val($doc, PublicInbox::Search::DT(), $dt);
354 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
355 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
357 my $tg = term_generator($self);
358 $tg->set_document($doc);
359 index_headers($self, $smsg);
361 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
362 index_ids($self, $doc, $eml, $mids);
363 $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
364 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
365 my $data = $smsg->to_doc_data;
366 $doc->set_data($data);
367 if (my $altid = $self->{-altid}) {
368 foreach my $alt (@$altid) {
369 my $pfx = $alt->{xprefix};
370 foreach my $mid (@$mids) {
371 my $id = $alt->mid2alt($mid);
372 next unless defined $id;
373 $doc->add_boolean_term($pfx . $id);
377 $self->{xdb}->replace_document($smsg->{num}, $doc);
380 sub _msgmap_init ($) {
382 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
383 $self->{mm} //= eval {
384 require PublicInbox::Msgmap;
385 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
386 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
391 # mime = PublicInbox::Eml or Email::MIME object
392 my ($self, $mime, $smsg, $sync) = @_;
393 my $mids = mids_for_index($mime);
394 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
395 $smsg->{mid} //= $mids->[0]; # v1 compatibility
396 $smsg->{num} //= do { # v1
398 index_mm($self, $mime, $smsg->{blob}, $sync);
402 $smsg->populate($mime, $sync);
403 $smsg->{bytes} //= length($mime->as_string);
406 # order matters, overview stores every possible piece of
407 # data in doc_data (deflated). Xapian only stores a subset
408 # of the fields which exist in over.sqlite3. We may stop
409 # storing doc_data in Xapian sometime after we get multi-inbox
411 if (my $over = $self->{over}) { # v1 only
412 $over->add_overview($mime, $smsg);
414 if (need_xapian($self)) {
415 add_xapian($self, $mime, $smsg, $mids);
420 warn "failed to index message <".join('> <',@$mids).">: $@\n";
427 my ($self, $oid, @removed) = @_;
428 my $xdb = $self->{xdb} or return;
429 for my $num (@removed) {
430 my $doc = eval { $xdb->get_document($num) };
432 warn "E: $@\n" if $@;
433 warn "E: #$num $oid missing in Xapian\n";
436 my $smsg = bless {}, 'PublicInbox::Smsg';
437 $smsg->load_expand($doc);
438 my $blob = $smsg->{blob} // '(unset)';
440 $xdb->delete_document($num);
442 warn "E: #$num $oid != $blob in Xapian\n";
448 my ($self, $oid, $num) = @_;
449 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
450 $self->begin_txn_lazy;
451 xdb_remove($self, $oid, $num) if need_xapian($self);
454 sub index_git_blob_id {
455 my ($doc, $pfx, $objid) = @_;
457 my $len = length($objid);
458 for (my $len = length($objid); $len >= 7; ) {
459 $doc->add_term($pfx.$objid);
460 $objid = substr($objid, 0, --$len);
466 my ($self, $oid, $eml) = @_;
467 my $mids = mids($eml);
470 for my $mid (@$mids) {
471 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
473 warn "E: failed to remove <$mid> from overview: $@\n";
475 $nr += scalar @removed;
476 $tmp{$_}++ for @removed;
480 $mids = join('> <', @$mids);
481 warn "W: <$mids> missing for removal from overview\n";
483 while (my ($num, $nr) = each %tmp) {
484 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
487 $self->{mm}->num_delete($_) for (keys %tmp);
488 } else { # just in case msgmap and over.sqlite3 become desynched:
489 $self->{mm}->mid_delete($mids->[0]);
491 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
495 my ($self, $mime, $oid, $sync) = @_;
496 my $mids = mids($mime);
497 my $mm = $self->{mm};
498 if ($sync->{reindex}) {
499 my $over = $self->{over};
500 for my $mid (@$mids) {
501 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
502 return $num if defined $num;
504 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
506 # fallback to num_for since filters like RubyLang set the number
507 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
511 # returns the number of bytes to add if given a non-CRLF arg
512 sub crlf_adjust ($) {
513 if (index($_[0], "\r\n") < 0) {
514 # common case is LF-only, every \n needs an \r;
515 # so favor a cheap tr// over an expensive m//g
517 } else { # count number of '\n' w/o '\r', expensive:
518 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
522 sub index_both { # git->cat_async callback
523 my ($bref, $oid, $type, $size, $sync) = @_;
524 my ($nr, $max) = @$sync{qw(nr max)};
527 $size += crlf_adjust($$bref);
528 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
529 my $self = $sync->{sidx};
530 my $eml = PublicInbox::Eml->new($bref);
531 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
532 die "E: could not generate NNTP article number for $oid";
533 add_message($self, $eml, $smsg, $sync);
536 sub unindex_both { # git->cat_async callback
537 my ($bref, $oid, $type, $size, $self) = @_;
538 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
541 # called by public-inbox-index
543 my ($self, $opts) = @_;
544 delete $self->{lock_path} if $opts->{-skip_lock};
545 $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
546 if ($opts->{reindex}) {
548 delete @again{qw(rethread reindex)};
549 index_sync($self, \%again);
553 sub check_size { # check_async cb for -index --max-size=...
554 my ($oid, $type, $size, $arg, $git) = @_;
555 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
556 if ($size <= $arg->{index_max_size}) {
557 $git->cat_async($oid, $arg->{index_oid}, $arg);
559 warn "W: skipping $oid ($size > $arg->{index_max_size})\n";
563 sub v1_checkpoint ($$;$) {
564 my ($self, $sync, $stk) = @_;
565 $self->{ibx}->git->check_async_wait;
566 $self->{ibx}->git->cat_async_wait;
568 # latest_cmt may be undef
569 my $newest = $stk ? $stk->{latest_cmt} : undef;
571 my $cur = $self->{mm}->last_commit || '';
572 if (need_update($self, $cur, $newest)) {
573 $self->{mm}->last_commit($newest);
576 ${$sync->{max}} = $BATCH_BYTES;
579 $self->{mm}->{dbh}->commit;
580 if ($newest && need_xapian($self)) {
581 my $cur = $self->{xdb}->get_metadata('last_commit');
582 if (need_update($self, $cur, $newest)) {
583 $self->{xdb}->set_metadata('last_commit', $newest);
587 $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
588 commit_txn_lazy($self);
589 $self->{ibx}->git->cleanup;
590 my $nr = ${$sync->{nr}};
591 idx_release($self, $nr);
592 # let another process do some work...
593 if (my $pr = $sync->{-opt}->{-progress}) {
594 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
596 if (!$stk) { # more to come
597 begin_txn_lazy($self);
598 $self->{mm}->{dbh}->begin_work;
604 my ($self, $sync, $stk) = @_;
605 my $git = $self->{ibx}->git;
606 my $max = $BATCH_BYTES;
609 $sync->{max} = \$max;
610 $sync->{sidx} = $self;
612 $self->{mm}->{dbh}->begin_work;
613 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
614 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
615 for my $oid (@leftovers) {
616 $oid = unpack('H*', $oid);
617 $git->cat_async($oid, \&unindex_both, $self);
620 if ($sync->{index_max_size} = $self->{ibx}->{index_max_size}) {
621 $sync->{index_oid} = \&index_both;
623 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
625 my $arg = { %$sync, autime => $at, cotime => $ct };
626 if ($sync->{index_max_size}) {
627 $git->check_async($oid, \&check_size, $arg);
629 $git->cat_async($oid, \&index_both, $arg);
631 v1_checkpoint($self, $sync) if $max <= 0;
632 } elsif ($f eq 'd') {
633 $git->cat_async($oid, \&unindex_both, $self);
636 v1_checkpoint($self, $sync, $stk);
639 sub log2stack ($$$$) {
640 my ($sync, $git, $range, $ibx) = @_;
641 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
643 if ($ibx->version == 1) {
644 my $path = $hex.'{2}/'.$hex.'{38}';
645 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
646 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
648 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
649 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
652 # Count the new files so they can be added newest to oldest
653 # and still have numbers increasing from oldest to newest
654 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
655 --no-notes --no-color --no-renames --no-abbrev),
659 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
660 ($at, $ct) = ($1 + 0, $2 + 0);
661 $stk //= PublicInbox::IdxStack->new($3);
664 if ($D) { # reindex case
665 $D->{pack('H*', $oid)}++;
666 } else { # non-reindex case:
667 $stk->push_rec('d', $at, $ct, $oid);
672 my $oid_bin = pack('H*', $oid);
673 my $nr = --$D->{$oid_bin};
674 delete($D->{$oid_bin}) if $nr <= 0;
676 # nr < 0 (-1) means it never existed
677 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
679 $stk->push_rec('m', $at, $ct, $oid);
683 close $fh or die "git log failed: \$?=$?";
684 $stk //= PublicInbox::IdxStack->new;
688 sub prepare_stack ($$$) {
689 my ($self, $sync, $range) = @_;
690 my $git = $self->{ibx}->git;
692 if (index($range, '..') < 0) {
693 # don't show annoying git errors to users who run -index
695 $git->qx(qw(rev-parse -q --verify), "$range^0");
696 return PublicInbox::IdxStack->new->read_prepare if $?;
698 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
699 log2stack($sync, $git, $range, $self->{ibx});
702 # --is-ancestor requires git 1.8.0+
703 sub is_ancestor ($$$) {
704 my ($git, $cur, $tip) = @_;
705 return 0 unless $git->check($cur);
706 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
707 qw(merge-base --is-ancestor), $cur, $tip ];
708 my $pid = spawn($cmd);
709 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
713 sub need_update ($$$) {
714 my ($self, $cur, $new) = @_;
715 my $git = $self->{ibx}->git;
716 return 1 if $cur && !is_ancestor($git, $cur, $new);
717 my $range = $cur eq '' ? $new : "$cur..$new";
718 chomp(my $n = $git->qx(qw(rev-list --count), $range));
719 ($n eq '' || $n > 0);
722 # The last git commit we indexed with Xapian or SQLite (msgmap)
723 # This needs to account for cases where Xapian or SQLite is
724 # out-of-date with respect to the other.
726 my ($self, $mm) = @_;
727 my $lm = $mm->last_commit || '';
729 if (need_xapian($self)) {
730 $lx = $self->{xdb}->get_metadata('last_commit') || '';
734 # Use last_commit from msgmap if it is older or unset
735 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
741 sub reindex_from ($$) {
742 my ($reindex, $last_commit) = @_;
743 return $last_commit unless $reindex;
744 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
747 # indexes all unindexed messages (v1 only)
749 my ($self, $opts) = @_;
750 my $tip = $opts->{ref} || 'HEAD';
751 my $git = $self->{ibx}->git;
753 my $pr = $opts->{-progress};
754 my $sync = { reindex => $opts->{reindex}, -opt => $opts };
755 my $xdb = $self->begin_txn_lazy;
756 $self->{over}->rethread_prepare($opts);
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};