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