]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
use both Date: and Received: times
[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::MID qw/mid_clean id_compress mid_mime mids references/;
15 use PublicInbox::MsgIter;
16 use Carp qw(croak);
17 use POSIX qw(strftime);
18 require PublicInbox::Git;
19
20 use constant {
21         PERM_UMASK => 0,
22         OLD_PERM_GROUP => 1,
23         OLD_PERM_EVERYBODY => 2,
24         PERM_GROUP => 0660,
25         PERM_EVERYBODY => 0664,
26         BATCH_BYTES => 1_000_000,
27         DEBUG => !!$ENV{DEBUG},
28 };
29
30 my %GIT_ESC = (
31         a => "\a",
32         b => "\b",
33         f => "\f",
34         n => "\n",
35         r => "\r",
36         t => "\t",
37         v => "\013",
38 );
39
40 sub git_unquote ($) {
41         my ($s) = @_;
42         return $s unless ($s =~ /\A"(.*)"\z/);
43         $s = $1;
44         $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
45         $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
46         $s;
47 }
48
49 sub new {
50         my ($class, $ibx, $creat, $part) = @_;
51         my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
52         my $git_dir = $mainrepo;
53         my ($altid, $git);
54         my $version = 1;
55         if (ref $ibx) {
56                 $mainrepo = $ibx->{mainrepo};
57                 $altid = $ibx->{altid};
58                 $version = $ibx->{version} || 1;
59                 if ($altid) {
60                         require PublicInbox::AltId;
61                         $altid = [ map {
62                                 PublicInbox::AltId->new($ibx, $_);
63                         } @$altid ];
64                 }
65                 $git = $ibx->git;
66         } else {
67                 $git = PublicInbox::Git->new($git_dir); # v1 only
68         }
69         require Search::Xapian::WritableDatabase;
70         my $self = bless {
71                 mainrepo => $mainrepo,
72                 git => $git,
73                 -altid => $altid,
74                 version => $version,
75         }, $class;
76         my $perm = $self->_git_config_perm;
77         my $umask = _umask_for($perm);
78         $self->{umask} = $umask;
79         if ($version == 1) {
80                 $self->{lock_path} = "$mainrepo/ssoma.lock";
81         } elsif ($version == 2) {
82                 defined $part or die "partition is required for v2\n";
83                 # partition is a number or "all"
84                 $self->{partition} = $part;
85                 $self->{lock_path} = undef;
86                 $self->{msgmap_path} = "$mainrepo/msgmap.sqlite3";
87         } else {
88                 die "unsupported inbox version=$version\n";
89         }
90         $self->{creat} = ($creat || 0) == 1;
91         $self;
92 }
93
94 sub _xdb_release {
95         my ($self) = @_;
96         my $xdb = delete $self->{xdb} or croak 'not acquired';
97         $xdb->close;
98         $self->lock_release if $self->{creat};
99         undef;
100 }
101
102 sub _xdb_acquire {
103         my ($self) = @_;
104         croak 'already acquired' if $self->{xdb};
105         my $dir = $self->xdir;
106         my $flag = Search::Xapian::DB_OPEN;
107         if ($self->{creat}) {
108                 require File::Path;
109                 $self->lock_acquire;
110                 File::Path::mkpath($dir);
111                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
112         }
113         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
114 }
115
116 sub add_val ($$$) {
117         my ($doc, $col, $num) = @_;
118         $num = Search::Xapian::sortable_serialise($num);
119         $doc->add_value($col, $num);
120 }
121
122 sub add_values ($$) {
123         my ($doc, $values) = @_;
124
125         my $ts = $values->[PublicInbox::Search::TS];
126         add_val($doc, PublicInbox::Search::TS, $ts);
127
128         my $num = $values->[PublicInbox::Search::NUM];
129         defined($num) and add_val($doc, PublicInbox::Search::NUM, $num);
130
131         my $bytes = $values->[PublicInbox::Search::BYTES];
132         defined($bytes) and add_val($doc, PublicInbox::Search::BYTES, $bytes);
133
134         my $lines = $values->[PublicInbox::Search::LINES];
135         add_val($doc, PublicInbox::Search::LINES, $lines);
136
137         my $ds = $values->[PublicInbox::Search::DS];
138         add_val($doc, PublicInbox::Search::DS, $ds);
139         my $yyyymmdd = strftime('%Y%m%d', gmtime($ds));
140         add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
141 }
142
143 sub index_users ($$) {
144         my ($tg, $smsg) = @_;
145
146         my $from = $smsg->from;
147         my $to = $smsg->to;
148         my $cc = $smsg->cc;
149
150         $tg->index_text($from, 1, 'A'); # A - author
151         $tg->increase_termpos;
152         $tg->index_text($to, 1, 'XTO') if $to ne '';
153         $tg->increase_termpos;
154         $tg->index_text($cc, 1, 'XCC') if $cc ne '';
155         $tg->increase_termpos;
156 }
157
158 sub index_diff_inc ($$$$) {
159         my ($tg, $text, $pfx, $xnq) = @_;
160         if (@$xnq) {
161                 $tg->index_text(join("\n", @$xnq), 1, 'XNQ');
162                 $tg->increase_termpos;
163                 @$xnq = ();
164         }
165         $tg->index_text($text, 1, $pfx);
166         $tg->increase_termpos;
167 }
168
169 sub index_old_diff_fn {
170         my ($tg, $seen, $fa, $fb, $xnq) = @_;
171
172         # no renames or space support for traditional diffs,
173         # find the number of leading common paths to strip:
174         my @fa = split('/', $fa);
175         my @fb = split('/', $fb);
176         while (scalar(@fa) && scalar(@fb)) {
177                 $fa = join('/', @fa);
178                 $fb = join('/', @fb);
179                 if ($fa eq $fb) {
180                         unless ($seen->{$fa}++) {
181                                 index_diff_inc($tg, $fa, 'XDFN', $xnq);
182                         }
183                         return 1;
184                 }
185                 shift @fa;
186                 shift @fb;
187         }
188         0;
189 }
190
191 sub index_diff ($$$) {
192         my ($tg, $lines, $doc) = @_;
193         my %seen;
194         my $in_diff;
195         my @xnq;
196         my $xnq = \@xnq;
197         foreach (@$lines) {
198                 if ($in_diff && s/^ //) { # diff context
199                         index_diff_inc($tg, $_, 'XDFCTX', $xnq);
200                 } elsif (/^-- $/) { # email signature begins
201                         $in_diff = undef;
202                 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
203                         my ($fa, $fb) = ($1, $2);
204                         my $fn = (split('/', git_unquote($fa), 2))[1];
205                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
206                         $fn = (split('/', git_unquote($fb), 2))[1];
207                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
208                         $in_diff = 1;
209                 # traditional diff:
210                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
211                         my ($opt, $fa, $fb) = ($1, $2, $3);
212                         push @xnq, $_;
213                         # only support unified:
214                         next unless $opt =~ /[uU]/;
215                         $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb,
216                                                         $xnq);
217                 } elsif (m!^--- ("?a/.+)!) {
218                         my $fn = (split('/', git_unquote($1), 2))[1];
219                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
220                         $in_diff = 1;
221                 } elsif (m!^\+\+\+ ("?b/.+)!)  {
222                         my $fn = (split('/', git_unquote($1), 2))[1];
223                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
224                         $in_diff = 1;
225                 } elsif (/^--- (\S+)/) {
226                         $in_diff = $1;
227                         push @xnq, $_;
228                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
229                         $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1,
230                                                         $xnq);
231                 } elsif ($in_diff && s/^\+//) { # diff added
232                         index_diff_inc($tg, $_, 'XDFB', $xnq);
233                 } elsif ($in_diff && s/^-//) { # diff removed
234                         index_diff_inc($tg, $_, 'XDFA', $xnq);
235                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
236                         my ($ba, $bb) = ($1, $2);
237                         index_git_blob_id($doc, 'XDFPRE', $ba);
238                         index_git_blob_id($doc, 'XDFPOST', $bb);
239                         $in_diff = 1;
240                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
241                         # traditional diff w/o -p
242                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
243                         # hunk header context
244                         index_diff_inc($tg, $1, 'XDFHH', $xnq);
245                 # ignore the following lines:
246                 } elsif (/^(?:dis)similarity index/ ||
247                                 /^(?:old|new) mode/ ||
248                                 /^(?:deleted|new) file mode/ ||
249                                 /^(?:copy|rename) (?:from|to) / ||
250                                 /^(?:dis)?similarity index / ||
251                                 /^\\ No newline at end of file/ ||
252                                 /^Binary files .* differ/) {
253                         push @xnq, $_;
254                 } elsif ($_ eq '') {
255                         $in_diff = undef;
256                 } else {
257                         push @xnq, $_;
258                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
259                         $in_diff = undef;
260                 }
261         }
262
263         $tg->index_text(join("\n", @xnq), 1, 'XNQ');
264         $tg->increase_termpos;
265 }
266
267 sub index_body ($$$) {
268         my ($tg, $lines, $doc) = @_;
269         my $txt = join("\n", @$lines);
270         if ($doc) {
271                 # does it look like a diff?
272                 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
273                         $txt = undef;
274                         index_diff($tg, $lines, $doc);
275                 } else {
276                         $tg->index_text($txt, 1, 'XNQ');
277                 }
278         } else {
279                 $tg->index_text($txt, 0, 'XQUOT');
280         }
281         $tg->increase_termpos;
282         @$lines = ();
283 }
284
285 sub add_message {
286         # mime = Email::MIME object
287         my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
288         my $doc_id;
289         my $mids = mids($mime->header_obj);
290         my $skel = $self->{skeleton};
291
292         eval {
293                 my $smsg = PublicInbox::SearchMsg->new($mime);
294                 my $doc = $smsg->{doc};
295                 my $subj = $smsg->subject;
296                 my $xpath;
297                 if ($subj ne '') {
298                         $xpath = $self->subject_path($subj);
299                         $xpath = id_compress($xpath);
300                 }
301
302                 my $lines = $mime->body_raw =~ tr!\n!\n!;
303                 my @values = ($smsg->ds, $num, $bytes, $lines, $smsg->ts);
304                 add_values($doc, \@values);
305
306                 my $tg = $self->term_generator;
307
308                 $tg->set_document($doc);
309                 $tg->index_text($subj, 1, 'S') if $subj;
310                 $tg->increase_termpos;
311
312                 index_users($tg, $smsg);
313
314                 msg_iter($mime, sub {
315                         my ($part, $depth, @idx) = @{$_[0]};
316                         my $ct = $part->content_type || 'text/plain';
317                         my $fn = $part->filename;
318                         if (defined $fn && $fn ne '') {
319                                 $tg->index_text($fn, 1, 'XFN');
320                         }
321
322                         return if $ct =~ m!\btext/x?html\b!i;
323
324                         my $s = eval { $part->body_str };
325                         if ($@) {
326                                 if ($ct =~ m!\btext/plain\b!i) {
327                                         # Try to assume UTF-8 because Alpine
328                                         # seems to do wacky things and set
329                                         # charset=X-UNKNOWN
330                                         $part->charset_set('UTF-8');
331                                         $s = eval { $part->body_str };
332                                         $s = $part->body if $@;
333                                 }
334                         }
335                         defined $s or return;
336
337                         my (@orig, @quot);
338                         my $body = $part->body;
339                         my @lines = split(/\n/, $body);
340                         while (defined(my $l = shift @lines)) {
341                                 if ($l =~ /^>/) {
342                                         index_body($tg, \@orig, $doc) if @orig;
343                                         push @quot, $l;
344                                 } else {
345                                         index_body($tg, \@quot, 0) if @quot;
346                                         push @orig, $l;
347                                 }
348                         }
349                         index_body($tg, \@quot, 0) if @quot;
350                         index_body($tg, \@orig, $doc) if @orig;
351                 });
352
353                 # populates smsg->references for smsg->to_doc_data
354                 my $refs = parse_references($smsg);
355                 $mid0 = $mids->[0] unless defined $mid0;
356                 my $data = $smsg->to_doc_data($oid, $mid0);
357                 foreach my $mid (@$mids) {
358                         $tg->index_text($mid, 1, 'XM');
359                 }
360                 $doc->set_data($data);
361                 if (my $altid = $self->{-altid}) {
362                         foreach my $alt (@$altid) {
363                                 my $pfx = $alt->{xprefix};
364                                 foreach my $mid (@$mids) {
365                                         my $id = $alt->mid2alt($mid);
366                                         next unless defined $id;
367                                         $doc->add_boolean_term($pfx . $id);
368                                 }
369                         }
370                 }
371
372                 if ($skel) {
373                         push @values, $mids, $xpath, $data;
374                         $skel->index_skeleton(\@values);
375                         $doc->add_boolean_term('Q' . $_) foreach @$mids;
376                         $doc_id = $self->{xdb}->add_document($doc);
377                 } else {
378                         $doc_id = link_and_save($self, $doc, $mids, $refs,
379                                                 $num, $xpath);
380                 }
381         };
382
383         if ($@) {
384                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
385                 return undef;
386         }
387         $doc_id;
388 }
389
390 sub batch_do {
391         my ($self, $termval, $cb) = @_;
392         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
393         while (1) {
394                 my ($head, $tail) = $self->find_doc_ids($termval);
395                 return if $head == $tail;
396                 my @ids;
397                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
398                         push @ids, $head->get_docid;
399                 }
400                 $cb->(\@ids);
401         }
402 }
403
404 sub remove_message {
405         my ($self, $mid) = @_;
406         my $db = $self->{xdb};
407         my $called;
408         $mid = mid_clean($mid);
409
410         eval {
411                 batch_do($self, 'Q' . $mid, sub {
412                         my ($ids) = @_;
413                         $db->delete_document($_) for @$ids;
414                         $called = 1;
415                 });
416         };
417         if ($@) {
418                 warn "failed to remove message <$mid>: $@\n";
419         } elsif (!$called) {
420                 warn "cannot remove non-existent <$mid>\n";
421         }
422 }
423
424 # MID is a hint in V2
425 sub remove_by_oid {
426         my ($self, $oid, $mid) = @_;
427         my $db = $self->{xdb};
428
429         # XXX careful, we cannot use batch_do here since we conditionally
430         # delete documents based on other factors, so we cannot call
431         # find_doc_ids twice.
432         my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
433         return if $head == $tail;
434
435         # there is only ONE element in @delete unless we
436         # have bugs in our v2writable deduplication check
437         my @delete;
438         for (; $head != $tail; $head->inc) {
439                 my $docid = $head->get_docid;
440                 my $doc = $db->get_document($docid);
441                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
442                 $smsg->load_expand;
443                 push(@delete, $docid) if $smsg->{blob} eq $oid;
444         }
445         $db->delete_document($_) foreach @delete;
446         scalar(@delete);
447 }
448
449 sub term_generator { # write-only
450         my ($self) = @_;
451
452         my $tg = $self->{term_generator};
453         return $tg if $tg;
454
455         $tg = Search::Xapian::TermGenerator->new;
456         $tg->set_stemmer($self->stemmer);
457
458         $self->{term_generator} = $tg;
459 }
460
461 # increments last_thread_id counter
462 # returns a 64-bit integer represented as a decimal string
463 sub next_thread_id {
464         my ($self) = @_;
465         my $db = $self->{xdb};
466         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
467
468         $db->set_metadata('last_thread_id', ++$last_thread_id);
469
470         $last_thread_id;
471 }
472
473 sub parse_references ($) {
474         my ($smsg) = @_;
475         my $mime = $smsg->{mime};
476         my $hdr = $mime->header_obj;
477         my $refs = references($hdr);
478         return $refs if scalar(@$refs) == 0;
479
480         # prevent circular references via References here:
481         my %mids = map { $_ => 1 } @{mids($hdr)};
482         my @keep;
483         foreach my $ref (@$refs) {
484                 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
485                         warn "References: <$ref> too long, ignoring\n";
486                         next;
487                 }
488                 next if $mids{$ref};
489                 push @keep, $ref;
490         }
491         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
492         \@keep;
493 }
494
495 sub link_doc {
496         my ($self, $doc, $refs, $old_tid) = @_;
497         my $tid;
498
499         if (@$refs) {
500                 # first ref *should* be the thread root,
501                 # but we can never trust clients to do the right thing
502                 my $ref = shift @$refs;
503                 $tid = resolve_mid_to_tid($self, $ref);
504                 merge_threads($self, $tid, $old_tid) if defined $old_tid;
505
506                 # the rest of the refs should point to this tid:
507                 foreach $ref (@$refs) {
508                         my $ptid = resolve_mid_to_tid($self, $ref);
509                         merge_threads($self, $tid, $ptid);
510                 }
511         } else {
512                 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
513         }
514         $doc->add_boolean_term('G' . $tid);
515         $tid;
516 }
517
518 sub link_and_save {
519         my ($self, $doc, $mids, $refs, $num, $xpath) = @_;
520         my $db = $self->{xdb};
521         my $old_tid;
522         my $doc_id;
523         $doc->add_boolean_term('XNUM' . $num) if defined $num;
524         $doc->add_boolean_term('XPATH' . $xpath) if defined $xpath;
525         $doc->add_boolean_term('Q' . $_) foreach @$mids;
526
527         my $vivified = 0;
528         $self->{skel} and die "Should not have read-only skel here\n";;
529         foreach my $mid (@$mids) {
530                 $self->each_smsg_by_mid($mid, sub {
531                         my ($cur) = @_;
532                         my $type = $cur->type;
533                         my $cur_tid = $cur->thread_id;
534                         $old_tid = $cur_tid unless defined $old_tid;
535                         if ($type eq 'mail') {
536                                 # do not break existing mail messages,
537                                 # just merge the threads
538                                 merge_threads($self, $old_tid, $cur_tid);
539                                 return 1;
540                         }
541                         if ($type ne 'ghost') {
542                                 die "<$mid> has a bad type: $type\n";
543                         }
544                         my $tid = link_doc($self, $doc, $refs, $old_tid);
545                         $old_tid = $tid unless defined $old_tid;
546                         $doc_id = $cur->{doc_id};
547                         $self->{xdb}->replace_document($doc_id, $doc);
548                         ++$vivified;
549                         1;
550                 });
551         }
552         # not really important, but we return any vivified ghost docid, here:
553         return $doc_id if defined $doc_id;
554         link_doc($self, $doc, $refs, $old_tid);
555         $self->{xdb}->add_document($doc);
556 }
557
558 sub index_git_blob_id {
559         my ($doc, $pfx, $objid) = @_;
560
561         my $len = length($objid);
562         for (my $len = length($objid); $len >= 7; ) {
563                 $doc->add_term($pfx.$objid);
564                 $objid = substr($objid, 0, --$len);
565         }
566 }
567
568 sub unindex_blob {
569         my ($self, $mime) = @_;
570         my $mid = eval { mid_clean(mid_mime($mime)) };
571         $self->remove_message($mid) if defined $mid;
572 }
573
574 sub index_mm {
575         my ($self, $mime) = @_;
576         my $mid = mid_clean(mid_mime($mime));
577         my $mm = $self->{mm};
578         my $num = $mm->mid_insert($mid);
579         return $num if defined $num;
580
581         # fallback to num_for since filters like RubyLang set the number
582         $mm->num_for($mid);
583 }
584
585 sub unindex_mm {
586         my ($self, $mime) = @_;
587         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
588 }
589
590 sub index_mm2 {
591         my ($self, $mime, $bytes, $blob) = @_;
592         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
593         add_message($self, $mime, $bytes, $num, $blob);
594 }
595
596 sub unindex_mm2 {
597         my ($self, $mime) = @_;
598         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
599         unindex_blob($self, $mime);
600 }
601
602 sub index_both {
603         my ($self, $mime, $bytes, $blob) = @_;
604         my $num = index_mm($self, $mime);
605         add_message($self, $mime, $bytes, $num, $blob);
606 }
607
608 sub unindex_both {
609         my ($self, $mime) = @_;
610         unindex_blob($self, $mime);
611         unindex_mm($self, $mime);
612 }
613
614 sub do_cat_mail {
615         my ($git, $blob, $sizeref) = @_;
616         my $mime = eval {
617                 my $str = $git->cat_file($blob, $sizeref);
618                 # fixup bugs from import:
619                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
620                 PublicInbox::MIME->new($str);
621         };
622         $@ ? undef : $mime;
623 }
624
625 sub index_sync {
626         my ($self, $opts) = @_;
627         with_umask($self, sub { $self->_index_sync($opts) });
628 }
629
630 sub batch_adjust ($$$$) {
631         my ($max, $bytes, $batch_cb, $latest) = @_;
632         $$max -= $bytes;
633         if ($$max <= 0) {
634                 $$max = BATCH_BYTES;
635                 $batch_cb->($latest, 1);
636         }
637 }
638
639 # only for v1
640 sub rlog {
641         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
642         my $hex = '[a-f0-9]';
643         my $h40 = $hex .'{40}';
644         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
645         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
646         my $git = $self->{git};
647         my $latest;
648         my $bytes;
649         my $max = BATCH_BYTES;
650         local $/ = "\n";
651         my $line;
652         while (defined($line = <$log>)) {
653                 if ($line =~ /$addmsg/o) {
654                         my $blob = $1;
655                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
656                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
657                         $add_cb->($self, $mime, $bytes, $blob);
658                 } elsif ($line =~ /$delmsg/o) {
659                         my $blob = $1;
660                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
661                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
662                         $del_cb->($self, $mime);
663                 } elsif ($line =~ /^commit ($h40)/o) {
664                         $latest = $1;
665                 }
666         }
667         $batch_cb->($latest, 0);
668 }
669
670 sub _msgmap_init {
671         my ($self) = @_;
672         $self->{mm} ||= eval {
673                 require PublicInbox::Msgmap;
674                 my $msgmap_path = $self->{msgmap_path};
675                 if (defined $msgmap_path) { # v2
676                         PublicInbox::Msgmap->new_file($msgmap_path, 1);
677                 } else {
678                         PublicInbox::Msgmap->new($self->{mainrepo}, 1);
679                 }
680         };
681 }
682
683 sub _git_log {
684         my ($self, $range) = @_;
685         $self->{git}->popen(qw/log --reverse --no-notes --no-color
686                                 --raw -r --no-abbrev/, $range);
687 }
688
689 # indexes all unindexed messages
690 sub _index_sync {
691         my ($self, $opts) = @_;
692         my $tip = $opts->{ref} || 'HEAD';
693         my $reindex = $opts->{reindex};
694         my ($mkey, $last_commit, $lx, $xlog);
695         $self->{git}->batch_prepare;
696         my $xdb = _xdb_acquire($self);
697         $xdb->begin_transaction;
698         do {
699                 $xlog = undef;
700                 $mkey = 'last_commit';
701                 $last_commit = $xdb->get_metadata('last_commit');
702                 $lx = $last_commit;
703                 if ($reindex) {
704                         $lx = '';
705                         $mkey = undef if $last_commit ne '';
706                 }
707                 $xdb->cancel_transaction;
708                 $xdb = _xdb_release($self);
709
710                 # ensure we leak no FDs to "git log"
711                 my $range = $lx eq '' ? $tip : "$lx..$tip";
712                 $xlog = _git_log($self, $range);
713
714                 $xdb = _xdb_acquire($self);
715                 $xdb->begin_transaction;
716         } while ($xdb->get_metadata('last_commit') ne $last_commit);
717
718         my $mm = _msgmap_init($self);
719         my $dbh = $mm->{dbh} if $mm;
720         my $mm_only;
721         my $cb = sub {
722                 my ($commit, $more) = @_;
723                 if ($dbh) {
724                         $mm->last_commit($commit) if $commit;
725                         $dbh->commit;
726                 }
727                 if (!$mm_only) {
728                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
729                         $xdb->commit_transaction;
730                         $xdb = _xdb_release($self);
731                 }
732                 # let another process do some work... <
733                 if ($more) {
734                         if (!$mm_only) {
735                                 $xdb = _xdb_acquire($self);
736                                 $xdb->begin_transaction;
737                         }
738                         $dbh->begin_work if $dbh;
739                 }
740         };
741
742         if ($mm) {
743                 $dbh->begin_work;
744                 my $lm = $mm->last_commit || '';
745                 if ($lm eq $lx) {
746                         # Common case is the indexes are synced,
747                         # we only need to run git-log once:
748                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
749                 } else {
750                         # Uncommon case, msgmap and xapian are out-of-sync
751                         # do not care for performance (but git is fast :>)
752                         # This happens if we have to reindex Xapian since
753                         # msgmap is a frozen format and our Xapian format
754                         # is evolving.
755                         my $r = $lm eq '' ? $tip : "$lm..$tip";
756
757                         # first, ensure msgmap is up-to-date:
758                         my $mkey_prev = $mkey;
759                         $mkey = undef; # ignore xapian, for now
760                         my $mlog = _git_log($self, $r);
761                         $mm_only = 1;
762                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
763                         $mm_only = $mlog = undef;
764
765                         # now deal with Xapian
766                         $mkey = $mkey_prev;
767                         $dbh = undef;
768                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
769                 }
770         } else {
771                 # user didn't install DBD::SQLite and DBI
772                 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
773         }
774 }
775
776 # this will create a ghost as necessary
777 sub resolve_mid_to_tid {
778         my ($self, $mid) = @_;
779         my $tid;
780         $self->each_smsg_by_mid($mid, sub {
781                 my ($smsg) = @_;
782                 my $cur_tid = $smsg->thread_id;
783                 if (defined $tid) {
784                         merge_threads($self, $tid, $cur_tid);
785                 } else {
786                         $tid = $smsg->thread_id;
787                 }
788                 1;
789         });
790         return $tid if defined $tid;
791
792         $self->create_ghost($mid)->thread_id;
793 }
794
795 sub create_ghost {
796         my ($self, $mid) = @_;
797
798         my $tid = $self->next_thread_id;
799         my $doc = Search::Xapian::Document->new;
800         $doc->add_boolean_term('Q' . $mid);
801         $doc->add_boolean_term('G' . $tid);
802         $doc->add_boolean_term('T' . 'ghost');
803
804         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
805         $self->{xdb}->add_document($doc);
806
807         $smsg;
808 }
809
810 sub merge_threads {
811         my ($self, $winner_tid, $loser_tid) = @_;
812         return if $winner_tid == $loser_tid;
813         my $db = $self->{xdb};
814         batch_do($self, 'G' . $loser_tid, sub {
815                 my ($ids) = @_;
816                 foreach my $docid (@$ids) {
817                         my $doc = $db->get_document($docid);
818                         $doc->remove_term('G' . $loser_tid);
819                         $doc->add_boolean_term('G' . $winner_tid);
820                         $db->replace_document($docid, $doc);
821                 }
822         });
823 }
824
825 sub _read_git_config_perm {
826         my ($self) = @_;
827         my @cmd = qw(config);
828         if ($self->{version} == 2) {
829                 push @cmd, "--file=$self->{mainrepo}/all.git/config";
830         }
831         my $fh = $self->{git}->popen(@cmd, 'core.sharedRepository');
832         local $/ = "\n";
833         my $perm = <$fh>;
834         chomp $perm if defined $perm;
835         $perm;
836 }
837
838 sub _git_config_perm {
839         my $self = shift;
840         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
841         return PERM_GROUP if (!defined($perm) || $perm eq '');
842         return PERM_UMASK if ($perm eq 'umask');
843         return PERM_GROUP if ($perm eq 'group');
844         if ($perm =~ /\A(?:all|world|everybody)\z/) {
845                 return PERM_EVERYBODY;
846         }
847         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
848         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
849
850         my $i = oct($perm);
851         return PERM_UMASK if ($i == PERM_UMASK);
852         return PERM_GROUP if ($i == OLD_PERM_GROUP);
853         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
854
855         if (($i & 0600) != 0600) {
856                 die "core.sharedRepository mode invalid: ".
857                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
858         }
859         ($i & 0666);
860 }
861
862 sub _umask_for {
863         my ($perm) = @_; # _git_config_perm return value
864         my $rv = $perm;
865         return umask if $rv == 0;
866
867         # set +x bit if +r or +w were set
868         $rv |= 0100 if ($rv & 0600);
869         $rv |= 0010 if ($rv & 0060);
870         $rv |= 0001 if ($rv & 0006);
871         (~$rv & 0777);
872 }
873
874 sub with_umask {
875         my ($self, $cb) = @_;
876         my $old = umask $self->{umask};
877         my $rv = eval { $cb->() };
878         my $err = $@;
879         umask $old;
880         die $err if $err;
881         $rv;
882 }
883
884 sub DESTROY {
885         # order matters for unlocking
886         $_[0]->{xdb} = undef;
887         $_[0]->{lockfh} = undef;
888 }
889
890 # remote_* subs are only used by SearchIdxPart and SearchIdxSkeleton
891 sub remote_commit {
892         my ($self) = @_;
893         if (my $w = $self->{w}) {
894                 print $w "commit\n" or die "failed to write commit: $!";
895         } else {
896                 $self->commit_txn_lazy;
897                 if (my $skel = $self->{skeleton}) {
898                         $skel->commit_txn_lazy;
899                 }
900         }
901 }
902
903 sub remote_close {
904         my ($self) = @_;
905         if (my $w = delete $self->{w}) {
906                 my $pid = delete $self->{pid} or die "no process to wait on\n";
907                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
908                 close $w or die "failed to close pipe for pid:$pid: $!\n";
909                 waitpid($pid, 0) == $pid or die "remote process did not finish";
910                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
911         } else {
912                 die "transaction in progress $self\n" if $self->{txn};
913                 $self->_xdb_release if $self->{xdb};
914         }
915 }
916
917 sub remote_remove {
918         my ($self, $oid, $mid) = @_;
919         if (my $w = $self->{w}) {
920                 # triggers remove_by_oid in partition or skeleton
921                 print $w "D $oid $mid\n" or die "failed to write remove $!";
922         } else {
923                 $self->begin_txn_lazy;
924                 $self->remove_by_oid($oid, $mid);
925         }
926 }
927
928 sub begin_txn_lazy {
929         my ($self) = @_;
930         return if $self->{txn};
931         my $xdb = $self->{xdb} || $self->_xdb_acquire;
932         $xdb->begin_transaction;
933         $self->{txn} = 1;
934 }
935
936 sub commit_txn_lazy {
937         my ($self) = @_;
938         delete $self->{txn} or return;
939         $self->{xdb}->commit_transaction;
940 }
941
942 sub worker_done {
943         my ($self) = @_;
944         die "$$ $0 xdb not released\n" if $self->{xdb};
945         die "$$ $0 still in transaction\n" if $self->{txn};
946 }
947
948 1;