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