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