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});
360 my $tg = term_generator($self);
361 $tg->set_document($doc);
362 index_headers($self, $smsg);
364 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
365 index_ids($self, $doc, $eml, $mids);
367 # by default, we maintain compatibility with v1.5.0 and earlier
368 # by writing to docdata.glass, users who never exect to downgrade can
370 if (!$self->{-skip_docdata}) {
371 # WWW doesn't need {to} or {cc}, only NNTP
372 $smsg->{to} = $smsg->{cc} = '';
373 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
374 my $data = $smsg->to_doc_data;
375 $doc->set_data($data);
378 if (my $altid = $self->{-altid}) {
379 foreach my $alt (@$altid) {
380 my $pfx = $alt->{xprefix};
381 foreach my $mid (@$mids) {
382 my $id = $alt->mid2alt($mid);
383 next unless defined $id;
384 $doc->add_boolean_term($pfx . $id);
388 $self->{xdb}->replace_document($smsg->{num}, $doc);
391 sub _msgmap_init ($) {
393 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
394 $self->{mm} //= eval {
395 require PublicInbox::Msgmap;
396 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
397 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
402 # mime = PublicInbox::Eml or Email::MIME object
403 my ($self, $mime, $smsg, $sync) = @_;
404 my $mids = mids_for_index($mime);
405 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
406 $smsg->{mid} //= $mids->[0]; # v1 compatibility
407 $smsg->{num} //= do { # v1
409 index_mm($self, $mime, $smsg->{blob}, $sync);
413 $smsg->populate($mime, $sync);
414 $smsg->{bytes} //= length($mime->as_string);
417 # order matters, overview stores every possible piece of
418 # data in doc_data (deflated). Xapian only stores a subset
419 # of the fields which exist in over.sqlite3. We may stop
420 # storing doc_data in Xapian sometime after we get multi-inbox
422 if (my $over = $self->{over}) { # v1 only
423 $over->add_overview($mime, $smsg);
425 if (need_xapian($self)) {
426 add_xapian($self, $mime, $smsg, $mids);
431 warn "failed to index message <".join('> <',@$mids).">: $@\n";
438 my ($self, $oid, @removed) = @_;
439 my $xdb = $self->{xdb} or return;
440 for my $num (@removed) {
441 my $doc = eval { $xdb->get_document($num) };
443 warn "E: $@\n" if $@;
444 warn "E: #$num $oid missing in Xapian\n";
447 my $smsg = bless {}, 'PublicInbox::Smsg';
448 $smsg->load_expand($doc);
449 my $blob = $smsg->{blob} // '(unset)';
451 $xdb->delete_document($num);
453 warn "E: #$num $oid != $blob in Xapian\n";
459 my ($self, $oid, $num) = @_;
460 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
461 $self->begin_txn_lazy;
462 xdb_remove($self, $oid, $num) if need_xapian($self);
465 sub index_git_blob_id {
466 my ($doc, $pfx, $objid) = @_;
468 my $len = length($objid);
469 for (my $len = length($objid); $len >= 7; ) {
470 $doc->add_term($pfx.$objid);
471 $objid = substr($objid, 0, --$len);
477 my ($self, $oid, $eml) = @_;
478 my $mids = mids($eml);
481 for my $mid (@$mids) {
482 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
484 warn "E: failed to remove <$mid> from overview: $@\n";
486 $nr += scalar @removed;
487 $tmp{$_}++ for @removed;
491 $mids = join('> <', @$mids);
492 warn "W: <$mids> missing for removal from overview\n";
494 while (my ($num, $nr) = each %tmp) {
495 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
498 $self->{mm}->num_delete($_) for (keys %tmp);
499 } else { # just in case msgmap and over.sqlite3 become desynched:
500 $self->{mm}->mid_delete($mids->[0]);
502 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
506 my ($self, $mime, $oid, $sync) = @_;
507 my $mids = mids($mime);
508 my $mm = $self->{mm};
509 if ($sync->{reindex}) {
510 my $over = $self->{over};
511 for my $mid (@$mids) {
512 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
513 return $num if defined $num;
515 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
517 # fallback to num_for since filters like RubyLang set the number
518 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
522 # returns the number of bytes to add if given a non-CRLF arg
523 sub crlf_adjust ($) {
524 if (index($_[0], "\r\n") < 0) {
525 # common case is LF-only, every \n needs an \r;
526 # so favor a cheap tr// over an expensive m//g
528 } else { # count number of '\n' w/o '\r', expensive:
529 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
533 sub index_both { # git->cat_async callback
534 my ($bref, $oid, $type, $size, $sync) = @_;
535 my ($nr, $max) = @$sync{qw(nr max)};
538 $size += crlf_adjust($$bref);
539 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
540 my $self = $sync->{sidx};
541 my $eml = PublicInbox::Eml->new($bref);
542 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
543 die "E: could not generate NNTP article number for $oid";
544 add_message($self, $eml, $smsg, $sync);
547 sub unindex_both { # git->cat_async callback
548 my ($bref, $oid, $type, $size, $self) = @_;
549 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
552 # called by public-inbox-index
554 my ($self, $opt) = @_;
555 delete $self->{lock_path} if $opt->{-skip_lock};
556 $self->{ibx}->with_umask(\&_index_sync, $self, $opt);
557 if ($opt->{reindex}) {
559 delete @again{qw(rethread reindex)};
560 index_sync($self, \%again);
564 sub check_size { # check_async cb for -index --max-size=...
565 my ($oid, $type, $size, $arg, $git) = @_;
566 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
567 if ($size <= $arg->{max_size}) {
568 $git->cat_async($oid, $arg->{index_oid}, $arg);
570 warn "W: skipping $oid ($size > $arg->{max_size})\n";
574 sub v1_checkpoint ($$;$) {
575 my ($self, $sync, $stk) = @_;
576 $self->{ibx}->git->check_async_wait;
577 $self->{ibx}->git->cat_async_wait;
579 # latest_cmt may be undef
580 my $newest = $stk ? $stk->{latest_cmt} : undef;
582 my $cur = $self->{mm}->last_commit || '';
583 if (need_update($self, $cur, $newest)) {
584 $self->{mm}->last_commit($newest);
587 ${$sync->{max}} = $self->{batch_bytes};
590 $self->{mm}->{dbh}->commit;
591 if ($newest && need_xapian($self)) {
592 my $cur = $self->{xdb}->get_metadata('last_commit');
593 if (need_update($self, $cur, $newest)) {
594 $self->{xdb}->set_metadata('last_commit', $newest);
598 $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
599 commit_txn_lazy($self);
600 $self->{ibx}->git->cleanup;
601 my $nr = ${$sync->{nr}};
602 idx_release($self, $nr);
603 # let another process do some work...
604 if (my $pr = $sync->{-opt}->{-progress}) {
605 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
607 if (!$stk) { # more to come
608 begin_txn_lazy($self);
609 $self->{mm}->{dbh}->begin_work;
615 my ($self, $sync, $stk) = @_;
616 my $git = $self->{ibx}->git;
617 my $max = $self->{batch_bytes};
620 $sync->{max} = \$max;
621 $sync->{sidx} = $self;
623 $self->{mm}->{dbh}->begin_work;
624 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
625 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
626 for my $oid (@leftovers) {
627 $oid = unpack('H*', $oid);
628 $git->cat_async($oid, \&unindex_both, $self);
631 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
632 $sync->{index_oid} = \&index_both;
634 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
636 my $arg = { %$sync, autime => $at, cotime => $ct };
637 if ($sync->{max_size}) {
638 $git->check_async($oid, \&check_size, $arg);
640 $git->cat_async($oid, \&index_both, $arg);
642 v1_checkpoint($self, $sync) if $max <= 0;
643 } elsif ($f eq 'd') {
644 $git->cat_async($oid, \&unindex_both, $self);
647 v1_checkpoint($self, $sync, $stk);
650 sub log2stack ($$$$) {
651 my ($sync, $git, $range, $ibx) = @_;
652 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
654 if ($ibx->version == 1) {
655 my $path = $hex.'{2}/'.$hex.'{38}';
656 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
657 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
659 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
660 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
663 # Count the new files so they can be added newest to oldest
664 # and still have numbers increasing from oldest to newest
665 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
666 --no-notes --no-color --no-renames --no-abbrev),
670 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
671 ($at, $ct) = ($1 + 0, $2 + 0);
672 $stk //= PublicInbox::IdxStack->new($3);
675 if ($D) { # reindex case
676 $D->{pack('H*', $oid)}++;
677 } else { # non-reindex case:
678 $stk->push_rec('d', $at, $ct, $oid);
683 my $oid_bin = pack('H*', $oid);
684 my $nr = --$D->{$oid_bin};
685 delete($D->{$oid_bin}) if $nr <= 0;
687 # nr < 0 (-1) means it never existed
688 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
690 $stk->push_rec('m', $at, $ct, $oid);
694 close $fh or die "git log failed: \$?=$?";
695 $stk //= PublicInbox::IdxStack->new;
699 sub prepare_stack ($$$) {
700 my ($self, $sync, $range) = @_;
701 my $git = $self->{ibx}->git;
703 if (index($range, '..') < 0) {
704 # don't show annoying git errors to users who run -index
706 $git->qx(qw(rev-parse -q --verify), "$range^0");
707 return PublicInbox::IdxStack->new->read_prepare if $?;
709 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
710 log2stack($sync, $git, $range, $self->{ibx});
713 # --is-ancestor requires git 1.8.0+
714 sub is_ancestor ($$$) {
715 my ($git, $cur, $tip) = @_;
716 return 0 unless $git->check($cur);
717 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
718 qw(merge-base --is-ancestor), $cur, $tip ];
719 my $pid = spawn($cmd);
720 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
724 sub need_update ($$$) {
725 my ($self, $cur, $new) = @_;
726 my $git = $self->{ibx}->git;
727 return 1 if $cur && !is_ancestor($git, $cur, $new);
728 my $range = $cur eq '' ? $new : "$cur..$new";
729 chomp(my $n = $git->qx(qw(rev-list --count), $range));
730 ($n eq '' || $n > 0);
733 # The last git commit we indexed with Xapian or SQLite (msgmap)
734 # This needs to account for cases where Xapian or SQLite is
735 # out-of-date with respect to the other.
737 my ($self, $mm) = @_;
738 my $lm = $mm->last_commit || '';
740 if (need_xapian($self)) {
741 $lx = $self->{xdb}->get_metadata('last_commit') || '';
745 # Use last_commit from msgmap if it is older or unset
746 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
752 sub reindex_from ($$) {
753 my ($reindex, $last_commit) = @_;
754 return $last_commit unless $reindex;
755 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
758 # indexes all unindexed messages (v1 only)
760 my ($self, $opt) = @_;
761 my $tip = $opt->{ref} || 'HEAD';
762 my $git = $self->{ibx}->git;
763 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
765 my $pr = $opt->{-progress};
766 my $sync = { reindex => $opt->{reindex}, -opt => $opt };
767 my $xdb = $self->begin_txn_lazy;
768 $self->{over}->rethread_prepare($opt);
769 my $mm = _msgmap_init($self);
770 if ($sync->{reindex}) {
771 my $last = $mm->last_commit;
775 # somebody just blindly added --reindex when indexing
776 # for the first time, allow it:
777 undef $sync->{reindex};
780 my $last_commit = _last_x_commit($self, $mm);
781 my $lx = reindex_from($sync->{reindex}, $last_commit);
782 my $range = $lx eq '' ? $tip : "$lx..$tip";
783 $pr->("counting changes\n\t$range ... ") if $pr;
784 my $stk = prepare_stack($self, $sync, $range);
785 $sync->{ntodo} = $stk ? $stk->num_records : 0;
786 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
787 process_stack($self, $sync, $stk);
791 # order matters for unlocking
792 $_[0]->{xdb} = undef;
793 $_[0]->{lockfh} = undef;
796 # remote_* subs are only used by SearchIdxPart
799 if (my $w = $self->{w}) {
800 print $w "commit\n" or die "failed to write commit: $!";
802 $self->commit_txn_lazy;
808 if (my $w = delete $self->{w}) {
809 my $pid = delete $self->{pid} or die "no process to wait on\n";
810 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
811 close $w or die "failed to close pipe for pid:$pid: $!\n";
812 waitpid($pid, 0) == $pid or die "remote process did not finish";
813 $? == 0 or die ref($self)." pid:$pid exited with: $?";
815 die "transaction in progress $self\n" if $self->{txn};
816 idx_release($self) if $self->{xdb};
821 my ($self, $oid, $num) = @_;
822 if (my $w = $self->{w}) {
823 # triggers remove_by_oid in a shard
824 print $w "D $oid $num\n" or die "failed to write remove $!";
826 $self->remove_by_oid($oid, $num);
832 my $xdb = $self->{xdb} || idx_acquire($self);
833 $self->{over}->begin_lazy if $self->{over};
834 $xdb->begin_transaction if $xdb;
841 $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
844 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
845 # This metadata is read by Admin::detect_indexlevel:
846 sub set_metadata_once {
849 return if $self->{shard}; # only continue if undef or 0, not >0
850 my $xdb = $self->{xdb};
852 if (delete($self->{-set_indexlevel_once})) {
853 my $level = $xdb->get_metadata('indexlevel');
854 if (!$level || $level ne 'medium') {
855 $xdb->set_metadata('indexlevel', 'medium');
858 if (delete($self->{-set_skip_docdata_once})) {
859 $xdb->get_metadata('skip_docdata') or
860 $xdb->set_metadata('skip_docdata', '1');
866 if (my $xdb = $self->{xdb}) {
867 set_metadata_once($self);
868 $xdb->commit_transaction;
870 $self->{over}->commit_lazy if $self->{over};
873 sub commit_txn_lazy {
875 delete($self->{txn}) and
876 $self->{ibx}->with_umask(\&_commit_txn, $self);
881 if (need_xapian($self)) {
882 die "$$ $0 xdb not released\n" if $self->{xdb};
884 die "$$ $0 still in transaction\n" if $self->{txn};