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