]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
Merge remote-tracking branch 'origin/xap-optional' into master
[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 sub index_sync {
546         my ($self, $opts) = @_;
547         $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
548 }
549
550 sub batch_adjust ($$$$) {
551         my ($max, $bytes, $batch_cb, $latest) = @_;
552         $$max -= $bytes;
553         if ($$max <= 0) {
554                 $$max = BATCH_BYTES;
555                 $batch_cb->($latest);
556         }
557 }
558
559 # only for v1
560 sub read_log {
561         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
562         my $hex = '[a-f0-9]';
563         my $h40 = $hex .'{40}';
564         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
565         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
566         my $git = $self->{git};
567         my $latest;
568         my $bytes;
569         my $max = BATCH_BYTES;
570         local $/ = "\n";
571         my %D;
572         my $line;
573         my $newest;
574         while (defined($line = <$log>)) {
575                 if ($line =~ /$addmsg/o) {
576                         my $blob = $1;
577                         if (delete $D{$blob}) {
578                                 if (defined $self->{regen_down}) {
579                                         my $num = $self->{regen_down}--;
580                                         $self->{mm}->num_highwater($num);
581                                 }
582                                 next;
583                         }
584                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
585                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
586                         $add_cb->($self, $mime, $bytes, $blob);
587                 } elsif ($line =~ /$delmsg/o) {
588                         my $blob = $1;
589                         $D{$blob} = 1;
590                 } elsif ($line =~ /^commit ($h40)/o) {
591                         $latest = $1;
592                         $newest ||= $latest;
593                 }
594         }
595         # get the leftovers
596         foreach my $blob (keys %D) {
597                 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
598                 $del_cb->($self, $mime);
599         }
600         $batch_cb->($latest, $newest);
601 }
602
603 sub _msgmap_init {
604         my ($self) = @_;
605         die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
606         $self->{mm} ||= eval {
607                 require PublicInbox::Msgmap;
608                 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
609         };
610 }
611
612 sub _git_log {
613         my ($self, $range) = @_;
614         my $git = $self->{git};
615
616         if (index($range, '..') < 0) {
617                 # don't show annoying git errrors to users who run -index
618                 # on empty inboxes
619                 $git->qx(qw(rev-parse -q --verify), "$range^0");
620                 if ($?) {
621                         open my $fh, '<', '/dev/null' or
622                                 die "failed to open /dev/null: $!\n";
623                         return $fh;
624                 }
625         }
626
627         # Count the new files so they can be added newest to oldest
628         # and still have numbers increasing from oldest to newest
629         my $fcount = 0;
630         # can't use 'rev-list --count' if we use --diff-filter
631         my $fh = $git->popen(qw(log --pretty=tformat:%h
632                              --no-notes --no-color --no-renames
633                              --diff-filter=AM), $range);
634         ++$fcount while <$fh>;
635         my $high = $self->{mm}->num_highwater;
636
637         if (index($range, '..') < 0) {
638                 if ($high && $high == $fcount) {
639                         # fix up old bugs in full indexes which caused messages to
640                         # not appear in Msgmap
641                         $self->{regen_up} = $high;
642                 } else {
643                         # normal regen is for for fresh data
644                         $self->{regen_down} = $fcount;
645                 }
646         } else {
647                 # Give oldest messages the smallest numbers
648                 $self->{regen_down} = $high + $fcount;
649         }
650
651         $git->popen(qw/log --no-notes --no-color --no-renames
652                                 --raw -r --no-abbrev/, $range);
653 }
654
655 # --is-ancestor requires git 1.8.0+
656 sub is_ancestor ($$$) {
657         my ($git, $cur, $tip) = @_;
658         return 0 unless $git->check($cur);
659         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
660                 qw(merge-base --is-ancestor), $cur, $tip ];
661         my $pid = spawn($cmd);
662         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
663         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
664         $? == 0;
665 }
666
667 sub need_update ($$$) {
668         my ($self, $cur, $new) = @_;
669         my $git = $self->{git};
670         return 1 if $cur && !is_ancestor($git, $cur, $new);
671         my $range = $cur eq '' ? $new : "$cur..$new";
672         chomp(my $n = $git->qx(qw(rev-list --count), $range));
673         ($n eq '' || $n > 0);
674 }
675
676 # The last git commit we indexed with Xapian or SQLite (msgmap)
677 # This needs to account for cases where Xapian or SQLite is
678 # out-of-date with respect to the other.
679 sub _last_x_commit {
680         my ($self, $mm) = @_;
681         my $lm = $mm->last_commit || '';
682         my $lx = '';
683         if (need_xapian($self)) {
684                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
685         } else {
686                 $lx = $lm;
687         }
688         # Use last_commit from msgmap if it is older or unset
689         if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
690                 $lx = $lm;
691         }
692         $lx;
693 }
694
695 # indexes all unindexed messages (v1 only)
696 sub _index_sync {
697         my ($self, $opts) = @_;
698         my $tip = $opts->{ref} || 'HEAD';
699         my ($last_commit, $lx, $xlog);
700         my $git = $self->{git};
701         $git->batch_prepare;
702
703         my $xdb = $self->begin_txn_lazy;
704         my $mm = _msgmap_init($self);
705         do {
706                 $xlog = undef;
707                 $last_commit = _last_x_commit($self, $mm);
708                 $lx = $opts->{reindex} ? '' : $last_commit;
709
710                 $self->{over}->rollback_lazy;
711                 $self->{over}->disconnect;
712                 $git->cleanup;
713                 delete $self->{txn};
714                 $xdb->cancel_transaction if $xdb;
715                 $xdb = _xdb_release($self);
716
717                 # ensure we leak no FDs to "git log" with Xapian <= 1.2
718                 my $range = $lx eq '' ? $tip : "$lx..$tip";
719                 $xlog = _git_log($self, $range);
720
721                 $xdb = $self->begin_txn_lazy;
722         } while (_last_x_commit($self, $mm) ne $last_commit);
723
724         my $dbh = $mm->{dbh} if $mm;
725         my $cb = sub {
726                 my ($commit, $newest) = @_;
727                 if ($dbh) {
728                         if ($newest) {
729                                 my $cur = $mm->last_commit || '';
730                                 if (need_update($self, $cur, $newest)) {
731                                         $mm->last_commit($newest);
732                                 }
733                         }
734                         $dbh->commit;
735                 }
736                 if ($newest && need_xapian($self)) {
737                         my $cur = $xdb->get_metadata('last_commit');
738                         if (need_update($self, $cur, $newest)) {
739                                 $xdb->set_metadata('last_commit', $newest);
740                         }
741                 }
742                 $self->commit_txn_lazy;
743                 $git->cleanup;
744                 $xdb = _xdb_release($self);
745                 # let another process do some work... <
746                 if (!$newest) {
747                         $xdb = $self->begin_txn_lazy;
748                         $dbh->begin_work if $dbh;
749                 }
750         };
751
752         $dbh->begin_work;
753         read_log($self, $xlog, *index_both, *unindex_both, $cb);
754 }
755
756 sub DESTROY {
757         # order matters for unlocking
758         $_[0]->{xdb} = undef;
759         $_[0]->{lockfh} = undef;
760 }
761
762 # remote_* subs are only used by SearchIdxPart
763 sub remote_commit {
764         my ($self) = @_;
765         if (my $w = $self->{w}) {
766                 print $w "commit\n" or die "failed to write commit: $!";
767         } else {
768                 $self->commit_txn_lazy;
769         }
770 }
771
772 sub remote_close {
773         my ($self) = @_;
774         if (my $w = delete $self->{w}) {
775                 my $pid = delete $self->{pid} or die "no process to wait on\n";
776                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
777                 close $w or die "failed to close pipe for pid:$pid: $!\n";
778                 waitpid($pid, 0) == $pid or die "remote process did not finish";
779                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
780         } else {
781                 die "transaction in progress $self\n" if $self->{txn};
782                 $self->_xdb_release if $self->{xdb};
783         }
784 }
785
786 sub remote_remove {
787         my ($self, $oid, $mid) = @_;
788         if (my $w = $self->{w}) {
789                 # triggers remove_by_oid in a partition
790                 print $w "D $oid $mid\n" or die "failed to write remove $!";
791         } else {
792                 $self->begin_txn_lazy;
793                 $self->remove_by_oid($oid, $mid);
794         }
795 }
796
797 sub begin_txn_lazy {
798         my ($self) = @_;
799         return if $self->{txn};
800
801         $self->{-inbox}->with_umask(sub {
802                 my $xdb = $self->{xdb} || $self->_xdb_acquire;
803                 $self->{over}->begin_lazy if $self->{over};
804                 $xdb->begin_transaction if $xdb;
805                 $self->{txn} = 1;
806                 $xdb;
807         });
808 }
809
810 sub commit_txn_lazy {
811         my ($self) = @_;
812         delete $self->{txn} or return;
813         $self->{-inbox}->with_umask(sub {
814                 if (my $xdb = $self->{xdb}) {
815                         $xdb->commit_transaction;
816                 }
817                 $self->{over}->commit_lazy if $self->{over};
818         });
819 }
820
821 sub worker_done {
822         my ($self) = @_;
823         if (need_xapian($self)) {
824                 die "$$ $0 xdb not released\n" if $self->{xdb};
825         }
826         die "$$ $0 still in transaction\n" if $self->{txn};
827 }
828
829 1;