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