]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
xcpdb: show re-indexing progress
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015-2018 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
4 #
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;
10 use strict;
11 use warnings;
12 use base qw(PublicInbox::Search PublicInbox::Lock);
13 use PublicInbox::MIME;
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime mids/;
16 use PublicInbox::MsgIter;
17 use Carp qw(croak);
18 use POSIX qw(strftime);
19 use PublicInbox::OverIdx;
20 use PublicInbox::Spawn qw(spawn);
21 use PublicInbox::Git qw(git_unquote);
22
23 use constant {
24         BATCH_BYTES => defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
25                         0x7fffffff : 1_000_000,
26         DEBUG => !!$ENV{DEBUG},
27 };
28
29 my $xapianlevels = qr/\A(?:full|medium)\z/;
30
31 sub new {
32         my ($class, $ibx, $creat, $part) = @_;
33         my $levels = qr/\A(?:full|medium|basic)\z/;
34         my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
35         my $git_dir = $mainrepo;
36         my ($altid, $git);
37         my $version = 1;
38         my $indexlevel = 'full';
39         if (ref $ibx) {
40                 $mainrepo = $ibx->{mainrepo};
41                 $altid = $ibx->{altid};
42                 $version = $ibx->{version} || 1;
43                 if ($altid) {
44                         require PublicInbox::AltId;
45                         $altid = [ map {
46                                 PublicInbox::AltId->new($ibx, $_);
47                         } @$altid ];
48                 }
49                 if ($ibx->{indexlevel}) {
50                         if ($ibx->{indexlevel} =~ $levels) {
51                                 $indexlevel = $ibx->{indexlevel};
52                         } else {
53                                 die("Invalid indexlevel $ibx->{indexlevel}\n");
54                         }
55                 }
56         } else { # FIXME: old tests: old tests
57                 $ibx = { mainrepo => $git_dir, version => 1 };
58         }
59         $ibx = PublicInbox::InboxWritable->new($ibx);
60         my $self = bless {
61                 mainrepo => $mainrepo,
62                 -inbox => $ibx,
63                 git => $ibx->git,
64                 -altid => $altid,
65                 version => $version,
66                 indexlevel => $indexlevel,
67         }, $class;
68         $ibx->umask_prepare;
69         if ($version == 1) {
70                 $self->{lock_path} = "$mainrepo/ssoma.lock";
71                 my $dir = $self->xdir;
72                 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
73         } elsif ($version == 2) {
74                 defined $part or die "partition is required for v2\n";
75                 # partition is a number
76                 $self->{partition} = $part;
77                 $self->{lock_path} = undef;
78         } else {
79                 die "unsupported inbox version=$version\n";
80         }
81         $self->{creat} = ($creat || 0) == 1;
82         $self;
83 }
84
85 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
86
87 sub _xdb_release {
88         my ($self) = @_;
89         if (need_xapian($self)) {
90                 my $xdb = delete $self->{xdb} or croak 'not acquired';
91                 $xdb->close;
92         }
93         $self->lock_release if $self->{creat};
94         undef;
95 }
96
97 sub _xdb_acquire {
98         my ($self) = @_;
99         my $flag;
100         my $dir = $self->xdir;
101         if (need_xapian($self)) {
102                 croak 'already acquired' if $self->{xdb};
103                 PublicInbox::Search::load_xapian();
104                 require Search::Xapian::WritableDatabase;
105                 $flag = $self->{creat} ?
106                         Search::Xapian::DB_CREATE_OR_OPEN() :
107                         Search::Xapian::DB_OPEN();
108         }
109         if ($self->{creat}) {
110                 require File::Path;
111                 $self->lock_acquire;
112
113                 # don't create empty Xapian directories if we don't need Xapian
114                 my $is_part = defined($self->{partition});
115                 if (!$is_part || ($is_part && need_xapian($self))) {
116                         File::Path::mkpath($dir);
117                 }
118         }
119         return unless defined $flag;
120         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
121 }
122
123 sub add_val ($$$) {
124         my ($doc, $col, $num) = @_;
125         $num = Search::Xapian::sortable_serialise($num);
126         $doc->add_value($col, $num);
127 }
128
129 sub index_text ($$$$)
130 {
131         my ($self, $field, $n, $text) = @_;
132         my $tg = $self->term_generator;
133
134         if ($self->{indexlevel} eq 'full') {
135                 $tg->index_text($field, $n, $text);
136                 $tg->increase_termpos;
137         } else {
138                 $tg->index_text_without_positions($field, $n, $text);
139         }
140 }
141
142 sub index_users ($$) {
143         my ($self, $smsg) = @_;
144
145         my $from = $smsg->from;
146         my $to = $smsg->to;
147         my $cc = $smsg->cc;
148
149         $self->index_text($from, 1, 'A'); # A - author
150         $self->index_text($to, 1, 'XTO') if $to ne '';
151         $self->index_text($cc, 1, 'XCC') if $cc ne '';
152 }
153
154 sub index_diff_inc ($$$$) {
155         my ($self, $text, $pfx, $xnq) = @_;
156         if (@$xnq) {
157                 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
158                 @$xnq = ();
159         }
160         $self->index_text($text, 1, $pfx);
161 }
162
163 sub index_old_diff_fn {
164         my ($self, $seen, $fa, $fb, $xnq) = @_;
165
166         # no renames or space support for traditional diffs,
167         # find the number of leading common paths to strip:
168         my @fa = split('/', $fa);
169         my @fb = split('/', $fb);
170         while (scalar(@fa) && scalar(@fb)) {
171                 $fa = join('/', @fa);
172                 $fb = join('/', @fb);
173                 if ($fa eq $fb) {
174                         unless ($seen->{$fa}++) {
175                                 $self->index_diff_inc($fa, 'XDFN', $xnq);
176                         }
177                         return 1;
178                 }
179                 shift @fa;
180                 shift @fb;
181         }
182         0;
183 }
184
185 sub index_diff ($$$) {
186         my ($self, $lines, $doc) = @_;
187         my %seen;
188         my $in_diff;
189         my @xnq;
190         my $xnq = \@xnq;
191         foreach (@$lines) {
192                 if ($in_diff && s/^ //) { # diff context
193                         $self->index_diff_inc($_, 'XDFCTX', $xnq);
194                 } elsif (/^-- $/) { # email signature begins
195                         $in_diff = undef;
196                 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
197                         my ($fa, $fb) = ($1, $2);
198                         my $fn = (split('/', git_unquote($fa), 2))[1];
199                         $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
200                         $fn = (split('/', git_unquote($fb), 2))[1];
201                         $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
202                         $in_diff = 1;
203                 # traditional diff:
204                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
205                         my ($opt, $fa, $fb) = ($1, $2, $3);
206                         push @xnq, $_;
207                         # only support unified:
208                         next unless $opt =~ /[uU]/;
209                         $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
210                                                         $xnq);
211                 } elsif (m!^--- ("?a/.+)!) {
212                         my $fn = (split('/', git_unquote($1), 2))[1];
213                         $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
214                         $in_diff = 1;
215                 } elsif (m!^\+\+\+ ("?b/.+)!)  {
216                         my $fn = (split('/', git_unquote($1), 2))[1];
217                         $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
218                         $in_diff = 1;
219                 } elsif (/^--- (\S+)/) {
220                         $in_diff = $1;
221                         push @xnq, $_;
222                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
223                         $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
224                                                         $xnq);
225                 } elsif ($in_diff && s/^\+//) { # diff added
226                         $self->index_diff_inc($_, 'XDFB', $xnq);
227                 } elsif ($in_diff && s/^-//) { # diff removed
228                         $self->index_diff_inc($_, 'XDFA', $xnq);
229                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
230                         my ($ba, $bb) = ($1, $2);
231                         index_git_blob_id($doc, 'XDFPRE', $ba);
232                         index_git_blob_id($doc, 'XDFPOST', $bb);
233                         $in_diff = 1;
234                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
235                         # traditional diff w/o -p
236                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
237                         # hunk header context
238                         $self->index_diff_inc($1, 'XDFHH', $xnq);
239                 # ignore the following lines:
240                 } elsif (/^(?:dis)similarity index/ ||
241                                 /^(?:old|new) mode/ ||
242                                 /^(?:deleted|new) file mode/ ||
243                                 /^(?:copy|rename) (?:from|to) / ||
244                                 /^(?:dis)?similarity index / ||
245                                 /^\\ No newline at end of file/ ||
246                                 /^Binary files .* differ/) {
247                         push @xnq, $_;
248                 } elsif ($_ eq '') {
249                         $in_diff = undef;
250                 } else {
251                         push @xnq, $_;
252                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
253                         $in_diff = undef;
254                 }
255         }
256
257         $self->index_text(join("\n", @xnq), 1, 'XNQ');
258 }
259
260 sub index_body ($$$) {
261         my ($self, $lines, $doc) = @_;
262         my $txt = join("\n", @$lines);
263         if ($doc) {
264                 # does it look like a diff?
265                 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
266                         $txt = undef;
267                         $self->index_diff($lines, $doc);
268                 } else {
269                         $self->index_text($txt, 1, 'XNQ');
270                 }
271         } else {
272                 $self->index_text($txt, 0, 'XQUOT');
273         }
274         @$lines = ();
275 }
276
277 sub add_xapian ($$$$$) {
278         my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
279         my $smsg = PublicInbox::SearchMsg->new($mime);
280         my $doc = Search::Xapian::Document->new;
281         my $subj = $smsg->subject;
282         add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
283         my @ds = gmtime($smsg->ds);
284         my $yyyymmdd = strftime('%Y%m%d', @ds);
285         add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
286         my $dt = strftime('%Y%m%d%H%M%S', @ds);
287         add_val($doc, PublicInbox::Search::DT(), $dt);
288
289         my $tg = $self->term_generator;
290
291         $tg->set_document($doc);
292         $self->index_text($subj, 1, 'S') if $subj;
293         $self->index_users($smsg);
294
295         msg_iter($mime, sub {
296                 my ($part, $depth, @idx) = @{$_[0]};
297                 my $ct = $part->content_type || 'text/plain';
298                 my $fn = $part->filename;
299                 if (defined $fn && $fn ne '') {
300                         $self->index_text($fn, 1, 'XFN');
301                 }
302
303                 my ($s, undef) = msg_part_text($part, $ct);
304                 defined $s or return;
305
306                 my (@orig, @quot);
307                 my @lines = split(/\n/, $s);
308                 while (defined(my $l = shift @lines)) {
309                         if ($l =~ /^>/) {
310                                 $self->index_body(\@orig, $doc) if @orig;
311                                 push @quot, $l;
312                         } else {
313                                 $self->index_body(\@quot, 0) if @quot;
314                                 push @orig, $l;
315                         }
316                 }
317                 $self->index_body(\@quot, 0) if @quot;
318                 $self->index_body(\@orig, $doc) if @orig;
319         });
320
321         foreach my $mid (@$mids) {
322                 $self->index_text($mid, 1, 'XM');
323
324                 # because too many Message-IDs are prefixed with
325                 # "Pine.LNX."...
326                 if ($mid =~ /\w{12,}/) {
327                         my @long = ($mid =~ /(\w{3,}+)/g);
328                         $self->index_text(join(' ', @long), 1, 'XM');
329                 }
330         }
331         $smsg->{to} = $smsg->{cc} = '';
332         PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
333         my $data = $smsg->to_doc_data($oid, $mid0);
334         $doc->set_data($data);
335         if (my $altid = $self->{-altid}) {
336                 foreach my $alt (@$altid) {
337                         my $pfx = $alt->{xprefix};
338                         foreach my $mid (@$mids) {
339                                 my $id = $alt->mid2alt($mid);
340                                 next unless defined $id;
341                                 $doc->add_boolean_term($pfx . $id);
342                         }
343                 }
344         }
345         $doc->add_boolean_term('Q' . $_) foreach @$mids;
346         $self->{xdb}->replace_document($num, $doc);
347 }
348
349 sub add_message {
350         # mime = Email::MIME object
351         my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
352         my $mids = mids($mime->header_obj);
353         $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
354         unless (defined $num) { # v1
355                 $self->_msgmap_init;
356                 $num = index_mm($self, $mime);
357         }
358         eval {
359                 if (need_xapian($self)) {
360                         $self->add_xapian($mime, $num, $oid, $mids, $mid0)
361                 }
362                 if (my $over = $self->{over}) {
363                         $over->add_overview($mime, $bytes, $num, $oid, $mid0);
364                 }
365         };
366
367         if ($@) {
368                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
369                 return undef;
370         }
371         $num;
372 }
373
374 # returns begin and end PostingIterator
375 sub find_doc_ids {
376         my ($self, $termval) = @_;
377         my $db = $self->{xdb};
378
379         ($db->postlist_begin($termval), $db->postlist_end($termval));
380 }
381
382 # v1 only
383 sub batch_do {
384         my ($self, $termval, $cb) = @_;
385         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
386         while (1) {
387                 my ($head, $tail) = $self->find_doc_ids($termval);
388                 return if $head == $tail;
389                 my @ids;
390                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
391                         push @ids, $head->get_docid;
392                 }
393                 $cb->(\@ids);
394         }
395 }
396
397 # v1 only, where $mid is unique
398 sub remove_message {
399         my ($self, $mid) = @_;
400         $mid = mid_clean($mid);
401
402         if (my $over = $self->{over}) {
403                 my $nr = eval { $over->remove_oid(undef, $mid) };
404                 if ($@) {
405                         warn "failed to remove <$mid> from overview: $@\n";
406                 } elsif ($nr == 0) {
407                         warn "<$mid> missing for removal from overview\n";
408                 }
409         }
410         return unless need_xapian($self);
411         my $db = $self->{xdb};
412         my $nr = 0;
413         eval {
414                 batch_do($self, 'Q' . $mid, sub {
415                         my ($ids) = @_;
416                         $db->delete_document($_) for @$ids;
417                         $nr = scalar @$ids;
418                 });
419         };
420         if ($@) {
421                 warn "failed to remove <$mid> from Xapian: $@\n";
422         } elsif ($nr == 0) {
423                 warn "<$mid> missing for removal from Xapian\n";
424         }
425 }
426
427 # MID is a hint in V2
428 sub remove_by_oid {
429         my ($self, $oid, $mid) = @_;
430
431         $self->{over}->remove_oid($oid, $mid) if $self->{over};
432
433         return unless need_xapian($self);
434         my $db = $self->{xdb};
435
436         # XXX careful, we cannot use batch_do here since we conditionally
437         # delete documents based on other factors, so we cannot call
438         # find_doc_ids twice.
439         my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
440         return if $head == $tail;
441
442         # there is only ONE element in @delete unless we
443         # have bugs in our v2writable deduplication check
444         my @delete;
445         for (; $head != $tail; $head->inc) {
446                 my $docid = $head->get_docid;
447                 my $doc = $db->get_document($docid);
448                 my $smsg = PublicInbox::SearchMsg->wrap($mid);
449                 $smsg->load_expand($doc);
450                 if ($smsg->{blob} eq $oid) {
451                         push(@delete, $docid);
452                 }
453         }
454         $db->delete_document($_) foreach @delete;
455         scalar(@delete);
456 }
457
458 sub term_generator { # write-only
459         my ($self) = @_;
460
461         my $tg = $self->{term_generator};
462         return $tg if $tg;
463
464         $tg = Search::Xapian::TermGenerator->new;
465         $tg->set_stemmer($self->stemmer);
466
467         $self->{term_generator} = $tg;
468 }
469
470 sub index_git_blob_id {
471         my ($doc, $pfx, $objid) = @_;
472
473         my $len = length($objid);
474         for (my $len = length($objid); $len >= 7; ) {
475                 $doc->add_term($pfx.$objid);
476                 $objid = substr($objid, 0, --$len);
477         }
478 }
479
480 sub unindex_blob {
481         my ($self, $mime) = @_;
482         my $mid = eval { mid_clean(mid_mime($mime)) };
483         $self->remove_message($mid) if defined $mid;
484 }
485
486 sub index_mm {
487         my ($self, $mime) = @_;
488         my $mid = mid_clean(mid_mime($mime));
489         my $mm = $self->{mm};
490         my $num;
491
492         if (defined $self->{regen_down}) {
493                 $num = $mm->num_for($mid) and return $num;
494
495                 while (($num = $self->{regen_down}--) > 0) {
496                         if ($mm->mid_set($num, $mid) != 0) {
497                                 return $num;
498                         }
499                 }
500         } elsif (defined $self->{regen_up}) {
501                 $num = $mm->num_for($mid) and return $num;
502
503                 # this is to fixup old bugs due to add-remove-add
504                 while (($num = ++$self->{regen_up})) {
505                         if ($mm->mid_set($num, $mid) != 0) {
506                                 return $num;
507                         }
508                 }
509         }
510
511         $num = $mm->mid_insert($mid) and return $num;
512
513         # fallback to num_for since filters like RubyLang set the number
514         $mm->num_for($mid);
515 }
516
517 sub unindex_mm {
518         my ($self, $mime) = @_;
519         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
520 }
521
522 sub index_both {
523         my ($self, $mime, $bytes, $blob) = @_;
524         my $num = index_mm($self, $mime);
525         add_message($self, $mime, $bytes, $num, $blob);
526 }
527
528 sub unindex_both {
529         my ($self, $mime) = @_;
530         unindex_blob($self, $mime);
531         unindex_mm($self, $mime);
532 }
533
534 sub do_cat_mail {
535         my ($git, $blob, $sizeref) = @_;
536         my $mime = eval {
537                 my $str = $git->cat_file($blob, $sizeref);
538                 # fixup bugs from import:
539                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
540                 PublicInbox::MIME->new($str);
541         };
542         $@ ? undef : $mime;
543 }
544
545 # called by public-inbox-index
546 sub index_sync {
547         my ($self, $opts) = @_;
548         delete $self->{lock_path} if $opts->{-skip_lock};
549         $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
550 }
551
552 sub batch_adjust ($$$$$) {
553         my ($max, $bytes, $batch_cb, $latest, $nr) = @_;
554         $$max -= $bytes;
555         if ($$max <= 0) {
556                 $$max = BATCH_BYTES;
557                 $batch_cb->($nr, $latest);
558         }
559 }
560
561 # only for v1
562 sub read_log {
563         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
564         my $hex = '[a-f0-9]';
565         my $h40 = $hex .'{40}';
566         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
567         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
568         my $git = $self->{git};
569         my $latest;
570         my $bytes;
571         my $max = BATCH_BYTES;
572         local $/ = "\n";
573         my %D;
574         my $line;
575         my $newest;
576         my $nr = 0;
577         while (defined($line = <$log>)) {
578                 if ($line =~ /$addmsg/o) {
579                         my $blob = $1;
580                         if (delete $D{$blob}) {
581                                 if (defined $self->{regen_down}) {
582                                         my $num = $self->{regen_down}--;
583                                         $self->{mm}->num_highwater($num);
584                                 }
585                                 next;
586                         }
587                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
588                         batch_adjust(\$max, $bytes, $batch_cb, $latest, ++$nr);
589                         $add_cb->($self, $mime, $bytes, $blob);
590                 } elsif ($line =~ /$delmsg/o) {
591                         my $blob = $1;
592                         $D{$blob} = 1;
593                 } elsif ($line =~ /^commit ($h40)/o) {
594                         $latest = $1;
595                         $newest ||= $latest;
596                 }
597         }
598         # get the leftovers
599         foreach my $blob (keys %D) {
600                 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
601                 $del_cb->($self, $mime);
602         }
603         $batch_cb->($nr, $latest, $newest);
604 }
605
606 sub _msgmap_init {
607         my ($self) = @_;
608         die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
609         $self->{mm} ||= eval {
610                 require PublicInbox::Msgmap;
611                 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
612         };
613 }
614
615 sub _git_log {
616         my ($self, $opts, $range) = @_;
617         my $git = $self->{git};
618
619         if (index($range, '..') < 0) {
620                 # don't show annoying git errrors to users who run -index
621                 # on empty inboxes
622                 $git->qx(qw(rev-parse -q --verify), "$range^0");
623                 if ($?) {
624                         open my $fh, '<', '/dev/null' or
625                                 die "failed to open /dev/null: $!\n";
626                         return $fh;
627                 }
628         }
629
630         # Count the new files so they can be added newest to oldest
631         # and still have numbers increasing from oldest to newest
632         my $fcount = 0;
633         my $pr = $opts->{-progress};
634         $pr->("counting changes\n\t$range ... ") if $pr;
635         # can't use 'rev-list --count' if we use --diff-filter
636         my $fh = $git->popen(qw(log --pretty=tformat:%h
637                              --no-notes --no-color --no-renames
638                              --diff-filter=AM), $range);
639         ++$fcount while <$fh>;
640         close $fh;
641         my $high = $self->{mm}->num_highwater;
642         $pr->("$fcount\n") if $pr; # continue previous line
643         $self->{ntodo} = $fcount;
644
645         if (index($range, '..') < 0) {
646                 if ($high && $high == $fcount) {
647                         # fix up old bugs in full indexes which caused messages to
648                         # not appear in Msgmap
649                         $self->{regen_up} = $high;
650                 } else {
651                         # normal regen is for for fresh data
652                         $self->{regen_down} = $fcount;
653                 }
654         } else {
655                 # Give oldest messages the smallest numbers
656                 $self->{regen_down} = $high + $fcount;
657         }
658
659         $git->popen(qw/log --no-notes --no-color --no-renames
660                                 --raw -r --no-abbrev/, $range);
661 }
662
663 # --is-ancestor requires git 1.8.0+
664 sub is_ancestor ($$$) {
665         my ($git, $cur, $tip) = @_;
666         return 0 unless $git->check($cur);
667         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
668                 qw(merge-base --is-ancestor), $cur, $tip ];
669         my $pid = spawn($cmd);
670         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
671         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
672         $? == 0;
673 }
674
675 sub need_update ($$$) {
676         my ($self, $cur, $new) = @_;
677         my $git = $self->{git};
678         return 1 if $cur && !is_ancestor($git, $cur, $new);
679         my $range = $cur eq '' ? $new : "$cur..$new";
680         chomp(my $n = $git->qx(qw(rev-list --count), $range));
681         ($n eq '' || $n > 0);
682 }
683
684 # The last git commit we indexed with Xapian or SQLite (msgmap)
685 # This needs to account for cases where Xapian or SQLite is
686 # out-of-date with respect to the other.
687 sub _last_x_commit {
688         my ($self, $mm) = @_;
689         my $lm = $mm->last_commit || '';
690         my $lx = '';
691         if (need_xapian($self)) {
692                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
693         } else {
694                 $lx = $lm;
695         }
696         # Use last_commit from msgmap if it is older or unset
697         if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
698                 $lx = $lm;
699         }
700         $lx;
701 }
702
703 sub reindex_from ($$) {
704         my ($reindex, $last_commit) = @_;
705         return $last_commit unless $reindex;
706         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
707 }
708
709 # indexes all unindexed messages (v1 only)
710 sub _index_sync {
711         my ($self, $opts) = @_;
712         my $tip = $opts->{ref} || 'HEAD';
713         my ($last_commit, $lx, $xlog);
714         my $git = $self->{git};
715         $git->batch_prepare;
716         my $pr = $opts->{-progress};
717
718         my $xdb = $self->begin_txn_lazy;
719         my $mm = _msgmap_init($self);
720         do {
721                 $xlog = undef;
722                 $last_commit = _last_x_commit($self, $mm);
723                 $lx = reindex_from($opts->{reindex}, $last_commit);
724
725                 $self->{over}->rollback_lazy;
726                 $self->{over}->disconnect;
727                 $git->cleanup;
728                 delete $self->{txn};
729                 $xdb->cancel_transaction if $xdb;
730                 $xdb = _xdb_release($self);
731
732                 # ensure we leak no FDs to "git log" with Xapian <= 1.2
733                 my $range = $lx eq '' ? $tip : "$lx..$tip";
734                 $xlog = _git_log($self, $opts, $range);
735
736                 $xdb = $self->begin_txn_lazy;
737         } while (_last_x_commit($self, $mm) ne $last_commit);
738
739         my $dbh = $mm->{dbh} if $mm;
740         my $cb = sub {
741                 my ($nr, $commit, $newest) = @_;
742                 if ($dbh) {
743                         if ($newest) {
744                                 my $cur = $mm->last_commit || '';
745                                 if (need_update($self, $cur, $newest)) {
746                                         $mm->last_commit($newest);
747                                 }
748                         }
749                         $dbh->commit;
750                 }
751                 if ($newest && need_xapian($self)) {
752                         my $cur = $xdb->get_metadata('last_commit');
753                         if (need_update($self, $cur, $newest)) {
754                                 $xdb->set_metadata('last_commit', $newest);
755                         }
756                 }
757                 $self->commit_txn_lazy;
758                 $git->cleanup;
759                 $xdb = _xdb_release($self);
760                 # let another process do some work... <
761                 $pr->("indexed $nr/$self->{ntodo}\n") if $pr && $nr;
762                 if (!$newest) {
763                         $xdb = $self->begin_txn_lazy;
764                         $dbh->begin_work if $dbh;
765                 }
766         };
767
768         $dbh->begin_work;
769         read_log($self, $xlog, *index_both, *unindex_both, $cb);
770 }
771
772 sub DESTROY {
773         # order matters for unlocking
774         $_[0]->{xdb} = undef;
775         $_[0]->{lockfh} = undef;
776 }
777
778 # remote_* subs are only used by SearchIdxPart
779 sub remote_commit {
780         my ($self) = @_;
781         if (my $w = $self->{w}) {
782                 print $w "commit\n" or die "failed to write commit: $!";
783         } else {
784                 $self->commit_txn_lazy;
785         }
786 }
787
788 sub remote_close {
789         my ($self) = @_;
790         if (my $w = delete $self->{w}) {
791                 my $pid = delete $self->{pid} or die "no process to wait on\n";
792                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
793                 close $w or die "failed to close pipe for pid:$pid: $!\n";
794                 waitpid($pid, 0) == $pid or die "remote process did not finish";
795                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
796         } else {
797                 die "transaction in progress $self\n" if $self->{txn};
798                 $self->_xdb_release if $self->{xdb};
799         }
800 }
801
802 sub remote_remove {
803         my ($self, $oid, $mid) = @_;
804         if (my $w = $self->{w}) {
805                 # triggers remove_by_oid in a partition
806                 print $w "D $oid $mid\n" or die "failed to write remove $!";
807         } else {
808                 $self->begin_txn_lazy;
809                 $self->remove_by_oid($oid, $mid);
810         }
811 }
812
813 sub begin_txn_lazy {
814         my ($self) = @_;
815         return if $self->{txn};
816
817         $self->{-inbox}->with_umask(sub {
818                 my $xdb = $self->{xdb} || $self->_xdb_acquire;
819                 $self->{over}->begin_lazy if $self->{over};
820                 $xdb->begin_transaction if $xdb;
821                 $self->{txn} = 1;
822                 $xdb;
823         });
824 }
825
826 sub commit_txn_lazy {
827         my ($self) = @_;
828         delete $self->{txn} or return;
829         $self->{-inbox}->with_umask(sub {
830                 if (my $xdb = $self->{xdb}) {
831                         $xdb->commit_transaction;
832                 }
833                 $self->{over}->commit_lazy if $self->{over};
834         });
835 }
836
837 sub worker_done {
838         my ($self) = @_;
839         if (need_xapian($self)) {
840                 die "$$ $0 xdb not released\n" if $self->{xdb};
841         }
842         die "$$ $0 still in transaction\n" if $self->{txn};
843 }
844
845 1;