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