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