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