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';
64 if ($ibx->{-skip_docdata}) {
65 $self->{-set_skip_docdata_once} = 1;
66 $self->{-skip_docdata} = 1;
70 $self->{lock_path} = "$inboxdir/ssoma.lock";
71 my $dir = $self->xdir;
72 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
73 $self->{over}->{-no_fsync} = 1 if $ibx->{-no_fsync};
74 } elsif ($version == 2) {
75 defined $shard or die "shard is required for v2\n";
77 $self->{shard} = $shard;
78 $self->{lock_path} = undef;
80 die "unsupported inbox version=$version\n";
82 $self->{creat} = ($creat || 0) == 1;
86 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
89 my ($self, $wake) = @_;
90 if (need_xapian($self)) {
91 my $xdb = delete $self->{xdb} or croak 'not acquired';
94 $self->lock_release($wake) if $self->{creat};
98 sub load_xapian_writable () {
99 return 1 if $X->{WritableDatabase};
100 PublicInbox::Search::load_xapian() or return;
101 my $xap = $PublicInbox::Search::Xap;
102 for (qw(Document TermGenerator WritableDatabase)) {
103 $X->{$_} = $xap.'::'.$_;
105 eval 'require '.$X->{WritableDatabase} or die;
106 *sortable_serialise = $xap.'::sortable_serialise';
107 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
108 $DB_OPEN = eval($xap.'::DB_OPEN()');
109 my $ver = (eval($xap.'::major_version()') << 16) |
110 (eval($xap.'::minor_version()') << 8);
111 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
118 my $dir = $self->xdir;
119 if (need_xapian($self)) {
120 croak 'already acquired' if $self->{xdb};
121 load_xapian_writable();
122 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
124 if ($self->{creat}) {
128 # don't create empty Xapian directories if we don't need Xapian
129 my $is_shard = defined($self->{shard});
130 if (!-d $dir && (!$is_shard ||
131 ($is_shard && need_xapian($self)))) {
132 File::Path::mkpath($dir);
136 return unless defined $flag;
137 $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_fsync};
138 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
140 die "Failed opening $dir: ", $@;
146 my ($doc, $col, $num) = @_;
147 $num = sortable_serialise($num);
148 $doc->add_value($col, $num);
151 sub term_generator ($) { # write-only
154 $self->{term_generator} //= do {
155 my $tg = $X->{TermGenerator}->new;
156 $tg->set_stemmer($self->stemmer);
161 sub index_text ($$$$) {
162 my ($self, $text, $wdf_inc, $prefix) = @_;
163 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
165 if ($self->{indexlevel} eq 'full') {
166 $tg->index_text($text, $wdf_inc, $prefix);
167 $tg->increase_termpos;
169 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
173 sub index_headers ($$) {
174 my ($self, $smsg) = @_;
175 my @x = (from => 'A', # Author
176 subject => 'S', to => 'XTO', cc => 'XCC');
177 while (my ($field, $pfx) = splice(@x, 0, 2)) {
178 my $val = $smsg->{$field};
179 index_text($self, $val, 1, $pfx) if $val ne '';
183 sub index_diff_inc ($$$$) {
184 my ($self, $text, $pfx, $xnq) = @_;
186 index_text($self, join("\n", @$xnq), 1, 'XNQ');
189 index_text($self, $text, 1, $pfx);
192 sub index_old_diff_fn {
193 my ($self, $seen, $fa, $fb, $xnq) = @_;
195 # no renames or space support for traditional diffs,
196 # find the number of leading common paths to strip:
197 my @fa = split('/', $fa);
198 my @fb = split('/', $fb);
199 while (scalar(@fa) && scalar(@fb)) {
200 $fa = join('/', @fa);
201 $fb = join('/', @fb);
203 unless ($seen->{$fa}++) {
204 index_diff_inc($self, $fa, 'XDFN', $xnq);
214 sub index_diff ($$$) {
215 my ($self, $txt, $doc) = @_;
220 foreach (split(/\n/, $txt)) {
221 if ($in_diff && s/^ //) { # diff context
222 index_diff_inc($self, $_, 'XDFCTX', $xnq);
223 } elsif (/^-- $/) { # email signature begins
225 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
226 # wait until "---" and "+++" to capture filenames
229 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
230 my ($opt, $fa, $fb) = ($1, $2, $3);
232 # only support unified:
233 next unless $opt =~ /[uU]/;
234 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
236 } elsif (m!^--- ("?[^/]+/.+)!) {
238 $fn = (split('/', git_unquote($fn), 2))[1];
239 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
241 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
243 $fn = (split('/', git_unquote($fn), 2))[1];
244 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
246 } elsif (/^--- (\S+)/) {
249 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
250 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
252 } elsif ($in_diff && s/^\+//) { # diff added
253 index_diff_inc($self, $_, 'XDFB', $xnq);
254 } elsif ($in_diff && s/^-//) { # diff removed
255 index_diff_inc($self, $_, 'XDFA', $xnq);
256 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
257 my ($ba, $bb) = ($1, $2);
258 index_git_blob_id($doc, 'XDFPRE', $ba);
259 index_git_blob_id($doc, 'XDFPOST', $bb);
261 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
262 # traditional diff w/o -p
263 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
264 # hunk header context
265 index_diff_inc($self, $1, 'XDFHH', $xnq);
266 # ignore the following lines:
267 } elsif (/^(?:dis)similarity index/ ||
268 /^(?:old|new) mode/ ||
269 /^(?:deleted|new) file mode/ ||
270 /^(?:copy|rename) (?:from|to) / ||
271 /^(?:dis)?similarity index / ||
272 /^\\ No newline at end of file/ ||
273 /^Binary files .* differ/) {
276 # possible to be in diff context, some mail may be
277 # stripped by MUA or even GNU diff(1). "git apply"
278 # treats a bare "\n" as diff context, too
281 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
286 index_text($self, join("\n", @xnq), 1, 'XNQ');
289 sub index_xapian { # msg_iter callback
290 my $part = $_[0]->[0]; # ignore $depth and $idx
291 my ($self, $doc) = @{$_[1]};
292 my $ct = $part->content_type || 'text/plain';
293 my $fn = $part->filename;
294 if (defined $fn && $fn ne '') {
295 index_text($self, $fn, 1, 'XFN');
297 if ($part->{is_submsg}) {
298 my $mids = mids_for_index($part);
299 index_ids($self, $doc, $part, $mids);
300 my $smsg = bless {}, 'PublicInbox::Smsg';
301 $smsg->populate($part);
302 index_headers($self, $smsg);
305 my ($s, undef) = msg_part_text($part, $ct);
306 defined $s or return;
307 $_[0]->[0] = $part = undef; # free memory
309 # split off quoted and unquoted blocks:
310 my @sections = PublicInbox::MsgIter::split_quotes($s);
311 undef $s; # free memory
312 for my $txt (@sections) {
314 index_text($self, $txt, 0, 'XQUOT');
316 # does it look like a diff?
317 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
318 index_diff($self, $txt, $doc);
320 index_text($self, $txt, 1, 'XNQ');
323 undef $txt; # free memory
327 sub index_ids ($$$$) {
328 my ($self, $doc, $hdr, $mids) = @_;
329 for my $mid (@$mids) {
330 index_text($self, $mid, 1, 'XM');
332 # because too many Message-IDs are prefixed with
334 if ($mid =~ /\w{12,}/) {
335 my @long = ($mid =~ /(\w{3,}+)/g);
336 index_text($self, join(' ', @long), 1, 'XM');
339 $doc->add_boolean_term('Q' . $_) for @$mids;
340 for my $l ($hdr->header_raw('List-Id')) {
341 $l =~ /<([^>]+)>/ or next;
343 $doc->add_boolean_term('G' . $lid);
344 index_text($self, $lid, 1, 'XL'); # probabilistic
348 sub add_xapian ($$$$) {
349 my ($self, $eml, $smsg, $mids) = @_;
350 my $doc = $X->{Document}->new;
351 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
352 my @ds = gmtime($smsg->{ds});
353 my $yyyymmdd = strftime('%Y%m%d', @ds);
354 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
355 my $dt = strftime('%Y%m%d%H%M%S', @ds);
356 add_val($doc, PublicInbox::Search::DT(), $dt);
357 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
358 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
359 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
361 my $tg = term_generator($self);
362 $tg->set_document($doc);
363 index_headers($self, $smsg);
365 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
366 index_ids($self, $doc, $eml, $mids);
368 # by default, we maintain compatibility with v1.5.0 and earlier
369 # by writing to docdata.glass, users who never exect to downgrade can
371 if (!$self->{-skip_docdata}) {
372 # WWW doesn't need {to} or {cc}, only NNTP
373 $smsg->{to} = $smsg->{cc} = '';
374 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
375 my $data = $smsg->to_doc_data;
376 $doc->set_data($data);
379 if (my $altid = $self->{-altid}) {
380 foreach my $alt (@$altid) {
381 my $pfx = $alt->{xprefix};
382 foreach my $mid (@$mids) {
383 my $id = $alt->mid2alt($mid);
384 next unless defined $id;
385 $doc->add_boolean_term($pfx . $id);
389 $self->{xdb}->replace_document($smsg->{num}, $doc);
392 sub _msgmap_init ($) {
394 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
395 $self->{mm} //= eval {
396 require PublicInbox::Msgmap;
397 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
398 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
403 # mime = PublicInbox::Eml or Email::MIME object
404 my ($self, $mime, $smsg, $sync) = @_;
405 my $mids = mids_for_index($mime);
406 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
407 $smsg->{mid} //= $mids->[0]; # v1 compatibility
408 $smsg->{num} //= do { # v1
410 index_mm($self, $mime, $smsg->{blob}, $sync);
414 $smsg->populate($mime, $sync);
415 $smsg->{bytes} //= length($mime->as_string);
418 # order matters, overview stores every possible piece of
419 # data in doc_data (deflated). Xapian only stores a subset
420 # of the fields which exist in over.sqlite3. We may stop
421 # storing doc_data in Xapian sometime after we get multi-inbox
423 if (my $over = $self->{over}) { # v1 only
424 $over->add_overview($mime, $smsg);
426 if (need_xapian($self)) {
427 add_xapian($self, $mime, $smsg, $mids);
432 warn "failed to index message <".join('> <',@$mids).">: $@\n";
439 my ($self, $oid, @removed) = @_;
440 my $xdb = $self->{xdb} or return;
441 for my $num (@removed) {
442 my $doc = eval { $xdb->get_document($num) };
444 warn "E: $@\n" if $@;
445 warn "E: #$num $oid missing in Xapian\n";
448 my $smsg = bless {}, 'PublicInbox::Smsg';
449 $smsg->load_expand($doc);
450 my $blob = $smsg->{blob} // '(unset)';
452 $xdb->delete_document($num);
454 warn "E: #$num $oid != $blob in Xapian\n";
460 my ($self, $oid, $num) = @_;
461 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
462 $self->begin_txn_lazy;
463 xdb_remove($self, $oid, $num) if need_xapian($self);
466 sub index_git_blob_id {
467 my ($doc, $pfx, $objid) = @_;
469 my $len = length($objid);
470 for (my $len = length($objid); $len >= 7; ) {
471 $doc->add_term($pfx.$objid);
472 $objid = substr($objid, 0, --$len);
478 my ($self, $oid, $eml) = @_;
479 my $mids = mids($eml);
482 for my $mid (@$mids) {
483 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
485 warn "E: failed to remove <$mid> from overview: $@\n";
487 $nr += scalar @removed;
488 $tmp{$_}++ for @removed;
492 $mids = join('> <', @$mids);
493 warn "W: <$mids> missing for removal from overview\n";
495 while (my ($num, $nr) = each %tmp) {
496 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
499 $self->{mm}->num_delete($_) for (keys %tmp);
500 } else { # just in case msgmap and over.sqlite3 become desynched:
501 $self->{mm}->mid_delete($mids->[0]);
503 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
507 my ($self, $mime, $oid, $sync) = @_;
508 my $mids = mids($mime);
509 my $mm = $self->{mm};
510 if ($sync->{reindex}) {
511 my $over = $self->{over};
512 for my $mid (@$mids) {
513 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
514 return $num if defined $num;
516 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
518 # fallback to num_for since filters like RubyLang set the number
519 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
523 # returns the number of bytes to add if given a non-CRLF arg
524 sub crlf_adjust ($) {
525 if (index($_[0], "\r\n") < 0) {
526 # common case is LF-only, every \n needs an \r;
527 # so favor a cheap tr// over an expensive m//g
529 } else { # count number of '\n' w/o '\r', expensive:
530 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
534 sub index_both { # git->cat_async callback
535 my ($bref, $oid, $type, $size, $sync) = @_;
536 my ($nr, $max) = @$sync{qw(nr max)};
539 $size += crlf_adjust($$bref);
540 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
541 my $self = $sync->{sidx};
542 my $eml = PublicInbox::Eml->new($bref);
543 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
544 die "E: could not generate NNTP article number for $oid";
545 add_message($self, $eml, $smsg, $sync);
548 sub unindex_both { # git->cat_async callback
549 my ($bref, $oid, $type, $size, $self) = @_;
550 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
553 # called by public-inbox-index
555 my ($self, $opt) = @_;
556 delete $self->{lock_path} if $opt->{-skip_lock};
557 $self->{ibx}->with_umask(\&_index_sync, $self, $opt);
558 if ($opt->{reindex}) {
560 delete @again{qw(rethread reindex)};
561 index_sync($self, \%again);
565 sub check_size { # check_async cb for -index --max-size=...
566 my ($oid, $type, $size, $arg, $git) = @_;
567 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
568 if ($size <= $arg->{max_size}) {
569 $git->cat_async($oid, $arg->{index_oid}, $arg);
571 warn "W: skipping $oid ($size > $arg->{max_size})\n";
575 sub v1_checkpoint ($$;$) {
576 my ($self, $sync, $stk) = @_;
577 $self->{ibx}->git->check_async_wait;
578 $self->{ibx}->git->cat_async_wait;
580 # latest_cmt may be undef
581 my $newest = $stk ? $stk->{latest_cmt} : undef;
583 my $cur = $self->{mm}->last_commit || '';
584 if (need_update($self, $cur, $newest)) {
585 $self->{mm}->last_commit($newest);
588 ${$sync->{max}} = $self->{batch_bytes};
591 $self->{mm}->{dbh}->commit;
592 if ($newest && need_xapian($self)) {
593 my $cur = $self->{xdb}->get_metadata('last_commit');
594 if (need_update($self, $cur, $newest)) {
595 $self->{xdb}->set_metadata('last_commit', $newest);
599 $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
600 commit_txn_lazy($self);
601 $self->{ibx}->git->cleanup;
602 my $nr = ${$sync->{nr}};
603 idx_release($self, $nr);
604 # let another process do some work...
605 if (my $pr = $sync->{-opt}->{-progress}) {
606 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
608 if (!$stk) { # more to come
609 begin_txn_lazy($self);
610 $self->{mm}->{dbh}->begin_work;
616 my ($self, $sync, $stk) = @_;
617 my $git = $self->{ibx}->git;
618 my $max = $self->{batch_bytes};
621 $sync->{max} = \$max;
622 $sync->{sidx} = $self;
624 $self->{mm}->{dbh}->begin_work;
625 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
626 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
627 for my $oid (@leftovers) {
628 $oid = unpack('H*', $oid);
629 $git->cat_async($oid, \&unindex_both, $self);
632 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
633 $sync->{index_oid} = \&index_both;
635 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
637 my $arg = { %$sync, autime => $at, cotime => $ct };
638 if ($sync->{max_size}) {
639 $git->check_async($oid, \&check_size, $arg);
641 $git->cat_async($oid, \&index_both, $arg);
643 v1_checkpoint($self, $sync) if $max <= 0;
644 } elsif ($f eq 'd') {
645 $git->cat_async($oid, \&unindex_both, $self);
648 v1_checkpoint($self, $sync, $stk);
651 sub log2stack ($$$$) {
652 my ($sync, $git, $range, $ibx) = @_;
653 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
655 if ($ibx->version == 1) {
656 my $path = $hex.'{2}/'.$hex.'{38}';
657 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
658 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
660 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
661 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
664 # Count the new files so they can be added newest to oldest
665 # and still have numbers increasing from oldest to newest
666 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
667 --no-notes --no-color --no-renames --no-abbrev),
671 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
672 ($at, $ct) = ($1 + 0, $2 + 0);
673 $stk //= PublicInbox::IdxStack->new($3);
676 if ($D) { # reindex case
677 $D->{pack('H*', $oid)}++;
678 } else { # non-reindex case:
679 $stk->push_rec('d', $at, $ct, $oid);
684 my $oid_bin = pack('H*', $oid);
685 my $nr = --$D->{$oid_bin};
686 delete($D->{$oid_bin}) if $nr <= 0;
688 # nr < 0 (-1) means it never existed
689 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
691 $stk->push_rec('m', $at, $ct, $oid);
695 close $fh or die "git log failed: \$?=$?";
696 $stk //= PublicInbox::IdxStack->new;
700 sub prepare_stack ($$$) {
701 my ($self, $sync, $range) = @_;
702 my $git = $self->{ibx}->git;
704 if (index($range, '..') < 0) {
705 # don't show annoying git errors to users who run -index
707 $git->qx(qw(rev-parse -q --verify), "$range^0");
708 return PublicInbox::IdxStack->new->read_prepare if $?;
710 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
711 log2stack($sync, $git, $range, $self->{ibx});
714 # --is-ancestor requires git 1.8.0+
715 sub is_ancestor ($$$) {
716 my ($git, $cur, $tip) = @_;
717 return 0 unless $git->check($cur);
718 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
719 qw(merge-base --is-ancestor), $cur, $tip ];
720 my $pid = spawn($cmd);
721 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
725 sub need_update ($$$) {
726 my ($self, $cur, $new) = @_;
727 my $git = $self->{ibx}->git;
728 return 1 if $cur && !is_ancestor($git, $cur, $new);
729 my $range = $cur eq '' ? $new : "$cur..$new";
730 chomp(my $n = $git->qx(qw(rev-list --count), $range));
731 ($n eq '' || $n > 0);
734 # The last git commit we indexed with Xapian or SQLite (msgmap)
735 # This needs to account for cases where Xapian or SQLite is
736 # out-of-date with respect to the other.
738 my ($self, $mm) = @_;
739 my $lm = $mm->last_commit || '';
741 if (need_xapian($self)) {
742 $lx = $self->{xdb}->get_metadata('last_commit') || '';
746 # Use last_commit from msgmap if it is older or unset
747 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
753 sub reindex_from ($$) {
754 my ($reindex, $last_commit) = @_;
755 return $last_commit unless $reindex;
756 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
759 # indexes all unindexed messages (v1 only)
761 my ($self, $opt) = @_;
762 my $tip = $opt->{ref} || 'HEAD';
763 my $git = $self->{ibx}->git;
764 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
766 my $pr = $opt->{-progress};
767 my $sync = { reindex => $opt->{reindex}, -opt => $opt };
768 my $xdb = $self->begin_txn_lazy;
769 $self->{over}->rethread_prepare($opt);
770 my $mm = _msgmap_init($self);
771 if ($sync->{reindex}) {
772 my $last = $mm->last_commit;
776 # somebody just blindly added --reindex when indexing
777 # for the first time, allow it:
778 undef $sync->{reindex};
781 my $last_commit = _last_x_commit($self, $mm);
782 my $lx = reindex_from($sync->{reindex}, $last_commit);
783 my $range = $lx eq '' ? $tip : "$lx..$tip";
784 $pr->("counting changes\n\t$range ... ") if $pr;
785 my $stk = prepare_stack($self, $sync, $range);
786 $sync->{ntodo} = $stk ? $stk->num_records : 0;
787 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
788 process_stack($self, $sync, $stk);
792 # order matters for unlocking
793 $_[0]->{xdb} = undef;
794 $_[0]->{lockfh} = undef;
799 my $xdb = $self->{xdb} || idx_acquire($self);
800 $self->{over}->begin_lazy if $self->{over};
801 $xdb->begin_transaction if $xdb;
808 $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
811 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
812 # This metadata is read by Admin::detect_indexlevel:
813 sub set_metadata_once {
816 return if $self->{shard}; # only continue if undef or 0, not >0
817 my $xdb = $self->{xdb};
819 if (delete($self->{-set_indexlevel_once})) {
820 my $level = $xdb->get_metadata('indexlevel');
821 if (!$level || $level ne 'medium') {
822 $xdb->set_metadata('indexlevel', 'medium');
825 if (delete($self->{-set_skip_docdata_once})) {
826 $xdb->get_metadata('skip_docdata') or
827 $xdb->set_metadata('skip_docdata', '1');
833 if (my $xdb = $self->{xdb}) {
834 set_metadata_once($self);
835 $xdb->commit_transaction;
837 $self->{over}->commit_lazy if $self->{over};
840 sub commit_txn_lazy {
842 delete($self->{txn}) and
843 $self->{ibx}->with_umask(\&_commit_txn, $self);
848 if (need_xapian($self)) {
849 die "$$ $0 xdb not released\n" if $self->{xdb};
851 die "$$ $0 still in transaction\n" if $self->{txn};