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