]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
searchidx: support indexing multiple MIDs
[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 mids references/;
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 (Xapian limitation) - length('Q')
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 ($doc, $values) = @_;
146
147         my $ts = $values->[PublicInbox::Search::TS];
148         add_val($doc, PublicInbox::Search::TS, $ts);
149
150         my $num = $values->[PublicInbox::Search::NUM];
151         defined($num) and add_val($doc, PublicInbox::Search::NUM, $num);
152
153         my $bytes = $values->[PublicInbox::Search::BYTES];
154         defined($bytes) and add_val($doc, PublicInbox::Search::BYTES, $bytes);
155
156         my $lines = $values->[PublicInbox::Search::LINES];
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 $doc_id;
285         my $mids = mids($mime->header_obj);
286         my $skel = $self->{skeleton};
287
288         eval {
289                 my $smsg = PublicInbox::SearchMsg->new($mime);
290                 my $doc = $smsg->{doc};
291                 foreach my $mid (@$mids) {
292                         # FIXME: may be abused to prevent archival
293                         length($mid) > MAX_MID_SIZE and
294                                 die 'Message-ID too long';
295                         $doc->add_term('Q' . $mid);
296                 }
297                 my $subj = $smsg->subject;
298                 my $xpath;
299                 if ($subj ne '') {
300                         $xpath = $self->subject_path($subj);
301                         $xpath = id_compress($xpath);
302                         $doc->add_term('XPATH' . $xpath);
303                 }
304
305                 my $lines = $mime->body_raw =~ tr!\n!\n!;
306                 my @values = ($smsg->ts, $num, $bytes, $lines);
307                 add_values($doc, \@values);
308
309                 my $tg = $self->term_generator;
310
311                 $tg->set_document($doc);
312                 $tg->index_text($subj, 1, 'S') if $subj;
313                 $tg->increase_termpos;
314
315                 index_users($tg, $smsg);
316
317                 msg_iter($mime, sub {
318                         my ($part, $depth, @idx) = @{$_[0]};
319                         my $ct = $part->content_type || 'text/plain';
320                         my $fn = $part->filename;
321                         if (defined $fn && $fn ne '') {
322                                 $tg->index_text($fn, 1, 'XFN');
323                         }
324
325                         return if $ct =~ m!\btext/x?html\b!i;
326
327                         my $s = eval { $part->body_str };
328                         if ($@) {
329                                 if ($ct =~ m!\btext/plain\b!i) {
330                                         # Try to assume UTF-8 because Alpine
331                                         # seems to do wacky things and set
332                                         # charset=X-UNKNOWN
333                                         $part->charset_set('UTF-8');
334                                         $s = eval { $part->body_str };
335                                         $s = $part->body if $@;
336                                 }
337                         }
338                         defined $s or return;
339
340                         my (@orig, @quot);
341                         my $body = $part->body;
342                         my @lines = split(/\n/, $body);
343                         while (defined(my $l = shift @lines)) {
344                                 if ($l =~ /^>/) {
345                                         index_body($tg, \@orig, $doc) if @orig;
346                                         push @quot, $l;
347                                 } else {
348                                         index_body($tg, \@quot, 0) if @quot;
349                                         push @orig, $l;
350                                 }
351                         }
352                         index_body($tg, \@quot, 0) if @quot;
353                         index_body($tg, \@orig, $doc) if @orig;
354                 });
355
356                 # populates smsg->references for smsg->to_doc_data
357                 my $refs = parse_references($smsg);
358                 my $data = $smsg->to_doc_data($blob);
359                 foreach my $mid (@$mids) {
360                         $tg->index_text($mid, 1, 'XM');
361                 }
362                 $doc->set_data($data);
363                 if (my $altid = $self->{-altid}) {
364                         foreach my $alt (@$altid) {
365                                 foreach my $mid (@$mids) {
366                                         my $id = $alt->mid2alt($mid);
367                                         next unless defined $id;
368                                         $doc->add_term($alt->{xprefix} . $id);
369                                 }
370                         }
371                 }
372                 if ($skel) {
373                         push @values, $mids, $xpath, $data;
374                         $skel->index_skeleton(\@values);
375                         $doc_id = $self->{xdb}->add_document($doc);
376                 } else {
377                         $doc_id = link_and_save($self, $doc, $mids, $refs);
378                 }
379         };
380
381         if ($@) {
382                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
383                 return undef;
384         }
385         $doc_id;
386 }
387
388 # returns deleted doc_id on success, undef on missing
389 sub remove_message {
390         my ($self, $mid) = @_;
391         my $db = $self->{xdb};
392         my $doc_id;
393         $mid = mid_clean($mid);
394
395         eval {
396                 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
397                 if ($head->equal($tail)) {
398                         warn "cannot remove non-existent <$mid>\n";
399                 }
400                 for (; $head != $tail; $head->inc) {
401                         my $docid = $head->get_docid;
402                         $db->delete_document($docid);
403                 }
404         };
405
406         if ($@) {
407                 warn "failed to remove message <$mid>: $@\n";
408                 return undef;
409         }
410         $doc_id;
411 }
412
413 sub term_generator { # write-only
414         my ($self) = @_;
415
416         my $tg = $self->{term_generator};
417         return $tg if $tg;
418
419         $tg = Search::Xapian::TermGenerator->new;
420         $tg->set_stemmer($self->stemmer);
421
422         $self->{term_generator} = $tg;
423 }
424
425 # increments last_thread_id counter
426 # returns a 64-bit integer represented as a decimal string
427 sub next_thread_id {
428         my ($self) = @_;
429         my $db = $self->{xdb};
430         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
431
432         $db->set_metadata('last_thread_id', ++$last_thread_id);
433
434         $last_thread_id;
435 }
436
437 sub parse_references ($) {
438         my ($smsg) = @_;
439         my $mime = $smsg->{mime};
440         my $hdr = $mime->header_obj;
441         my $refs = references($hdr);
442         return $refs if scalar(@$refs) == 0;
443
444         # prevent circular references via References here:
445         my %mids = map { $_ => 1 } @{mids($hdr)};
446         my @keep;
447         foreach my $ref (@$refs) {
448                 # FIXME: this is an archive-prevention vector like X-No-Archive
449                 if (length($ref) > MAX_MID_SIZE) {
450                         warn "References: <$ref> too long, ignoring\n";
451                 }
452                 next if $mids{$ref};
453                 push @keep, $ref;
454         }
455         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
456         \@keep;
457 }
458
459 sub link_doc {
460         my ($self, $doc, $refs, $old_tid) = @_;
461         my $tid;
462
463         if (@$refs) {
464                 # first ref *should* be the thread root,
465                 # but we can never trust clients to do the right thing
466                 my $ref = shift @$refs;
467                 $tid = resolve_mid_to_tid($self, $ref);
468                 merge_threads($self, $tid, $old_tid) if defined $old_tid;
469
470                 # the rest of the refs should point to this tid:
471                 foreach $ref (@$refs) {
472                         my $ptid = resolve_mid_to_tid($self, $ref);
473                         merge_threads($self, $tid, $ptid);
474                 }
475         } else {
476                 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
477         }
478         $doc->add_term('G' . $tid);
479         $tid;
480 }
481
482 sub link_and_save {
483         my ($self, $doc, $mids, $refs) = @_;
484         my $db = $self->{xdb};
485         my $old_tid;
486         my $doc_id;
487         my $vivified = 0;
488         foreach my $mid (@$mids) {
489                 $self->each_smsg_by_mid($mid, sub {
490                         my ($cur) = @_;
491                         my $type = $cur->type;
492                         my $cur_tid = $cur->thread_id;
493                         $old_tid = $cur_tid unless defined $old_tid;
494                         if ($type eq 'mail') {
495                                 # do not break existing mail messages,
496                                 # just merge the threads
497                                 merge_threads($self, $old_tid, $cur_tid);
498                                 return 1;
499                         }
500                         if ($type ne 'ghost') {
501                                 die "<$mid> has a bad type: $type\n";
502                         }
503                         my $tid = link_doc($self, $doc, $refs, $old_tid);
504                         $old_tid = $tid unless defined $old_tid;
505                         $doc_id = $cur->{doc_id};
506                         $self->{xdb}->replace_document($doc_id, $doc);
507                         ++$vivified;
508                         1;
509                 });
510         }
511         # not really important, but we return any vivified ghost docid, here:
512         return $doc_id if defined $doc_id;
513         link_doc($self, $doc, $refs, $old_tid);
514         $self->{xdb}->add_document($doc);
515 }
516
517 sub index_git_blob_id {
518         my ($doc, $pfx, $objid) = @_;
519
520         my $len = length($objid);
521         for (my $len = length($objid); $len >= 7; ) {
522                 $doc->add_term($pfx.$objid);
523                 $objid = substr($objid, 0, --$len);
524         }
525 }
526
527 sub unindex_blob {
528         my ($self, $mime) = @_;
529         my $mid = eval { mid_clean(mid_mime($mime)) };
530         $self->remove_message($mid) if defined $mid;
531 }
532
533 sub index_mm {
534         my ($self, $mime) = @_;
535         my $mid = mid_clean(mid_mime($mime));
536         my $mm = $self->{mm};
537         my $num = $mm->mid_insert($mid);
538         return $num if defined $num;
539
540         # fallback to num_for since filters like RubyLang set the number
541         $mm->num_for($mid);
542 }
543
544 sub unindex_mm {
545         my ($self, $mime) = @_;
546         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
547 }
548
549 sub index_mm2 {
550         my ($self, $mime, $bytes, $blob) = @_;
551         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
552         add_message($self, $mime, $bytes, $num, $blob);
553 }
554
555 sub unindex_mm2 {
556         my ($self, $mime) = @_;
557         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
558         unindex_blob($self, $mime);
559 }
560
561 sub index_both {
562         my ($self, $mime, $bytes, $blob) = @_;
563         my $num = index_mm($self, $mime);
564         add_message($self, $mime, $bytes, $num, $blob);
565 }
566
567 sub unindex_both {
568         my ($self, $mime) = @_;
569         unindex_blob($self, $mime);
570         unindex_mm($self, $mime);
571 }
572
573 sub do_cat_mail {
574         my ($git, $blob, $sizeref) = @_;
575         my $mime = eval {
576                 my $str = $git->cat_file($blob, $sizeref);
577                 # fixup bugs from import:
578                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
579                 PublicInbox::MIME->new($str);
580         };
581         $@ ? undef : $mime;
582 }
583
584 sub index_sync {
585         my ($self, $opts) = @_;
586         with_umask($self, sub { $self->_index_sync($opts) });
587 }
588
589 sub batch_adjust ($$$$) {
590         my ($max, $bytes, $batch_cb, $latest) = @_;
591         $$max -= $bytes;
592         if ($$max <= 0) {
593                 $$max = BATCH_BYTES;
594                 $batch_cb->($latest, 1);
595         }
596 }
597
598 # only for v1
599 sub rlog {
600         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
601         my $hex = '[a-f0-9]';
602         my $h40 = $hex .'{40}';
603         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
604         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
605         my $git = $self->{git};
606         my $latest;
607         my $bytes;
608         my $max = BATCH_BYTES;
609         local $/ = "\n";
610         my $line;
611         while (defined($line = <$log>)) {
612                 if ($line =~ /$addmsg/o) {
613                         my $blob = $1;
614                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
615                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
616                         $add_cb->($self, $mime, $bytes, $blob);
617                 } elsif ($line =~ /$delmsg/o) {
618                         my $blob = $1;
619                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
620                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
621                         $del_cb->($self, $mime);
622                 } elsif ($line =~ /^commit ($h40)/o) {
623                         $latest = $1;
624                 }
625         }
626         $batch_cb->($latest, 0);
627 }
628
629 sub _msgmap_init {
630         my ($self) = @_;
631         $self->{mm} ||= eval {
632                 require PublicInbox::Msgmap;
633                 my $msgmap_path = $self->{msgmap_path};
634                 if (defined $msgmap_path) { # v2
635                         PublicInbox::Msgmap->new_file($msgmap_path, 1);
636                 } else {
637                         PublicInbox::Msgmap->new($self->{mainrepo}, 1);
638                 }
639         };
640 }
641
642 sub _git_log {
643         my ($self, $range) = @_;
644         $self->{git}->popen(qw/log --reverse --no-notes --no-color
645                                 --raw -r --no-abbrev/, $range);
646 }
647
648 # indexes all unindexed messages
649 sub _index_sync {
650         my ($self, $opts) = @_;
651         my $tip = $opts->{ref} || 'HEAD';
652         my $reindex = $opts->{reindex};
653         my ($mkey, $last_commit, $lx, $xlog);
654         $self->{git}->batch_prepare;
655         my $xdb = _xdb_acquire($self);
656         $xdb->begin_transaction;
657         do {
658                 $xlog = undef;
659                 $mkey = 'last_commit';
660                 $last_commit = $xdb->get_metadata('last_commit');
661                 $lx = $last_commit;
662                 if ($reindex) {
663                         $lx = '';
664                         $mkey = undef if $last_commit ne '';
665                 }
666                 $xdb->cancel_transaction;
667                 $xdb = _xdb_release($self);
668
669                 # ensure we leak no FDs to "git log"
670                 my $range = $lx eq '' ? $tip : "$lx..$tip";
671                 $xlog = _git_log($self, $range);
672
673                 $xdb = _xdb_acquire($self);
674                 $xdb->begin_transaction;
675         } while ($xdb->get_metadata('last_commit') ne $last_commit);
676
677         my $mm = _msgmap_init($self);
678         my $dbh = $mm->{dbh} if $mm;
679         my $mm_only;
680         my $cb = sub {
681                 my ($commit, $more) = @_;
682                 if ($dbh) {
683                         $mm->last_commit($commit) if $commit;
684                         $dbh->commit;
685                 }
686                 if (!$mm_only) {
687                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
688                         $xdb->commit_transaction;
689                         $xdb = _xdb_release($self);
690                 }
691                 # let another process do some work... <
692                 if ($more) {
693                         if (!$mm_only) {
694                                 $xdb = _xdb_acquire($self);
695                                 $xdb->begin_transaction;
696                         }
697                         $dbh->begin_work if $dbh;
698                 }
699         };
700
701         if ($mm) {
702                 $dbh->begin_work;
703                 my $lm = $mm->last_commit || '';
704                 if ($lm eq $lx) {
705                         # Common case is the indexes are synced,
706                         # we only need to run git-log once:
707                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
708                 } else {
709                         # Uncommon case, msgmap and xapian are out-of-sync
710                         # do not care for performance (but git is fast :>)
711                         # This happens if we have to reindex Xapian since
712                         # msgmap is a frozen format and our Xapian format
713                         # is evolving.
714                         my $r = $lm eq '' ? $tip : "$lm..$tip";
715
716                         # first, ensure msgmap is up-to-date:
717                         my $mkey_prev = $mkey;
718                         $mkey = undef; # ignore xapian, for now
719                         my $mlog = _git_log($self, $r);
720                         $mm_only = 1;
721                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
722                         $mm_only = $mlog = undef;
723
724                         # now deal with Xapian
725                         $mkey = $mkey_prev;
726                         $dbh = undef;
727                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
728                 }
729         } else {
730                 # user didn't install DBD::SQLite and DBI
731                 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
732         }
733 }
734
735 # this will create a ghost as necessary
736 sub resolve_mid_to_tid {
737         my ($self, $mid) = @_;
738         my $tid;
739         $self->each_smsg_by_mid($mid, sub {
740                 my ($smsg) = @_;
741                 my $cur_tid = $smsg->thread_id;
742                 if (defined $tid) {
743                         merge_threads($self, $tid, $cur_tid);
744                 } else {
745                         $tid = $smsg->thread_id;
746                 }
747                 1;
748         });
749         return $tid if defined $tid;
750
751         $self->create_ghost($mid)->thread_id;
752 }
753
754 sub create_ghost {
755         my ($self, $mid) = @_;
756
757         my $tid = $self->next_thread_id;
758         my $doc = Search::Xapian::Document->new;
759         $doc->add_term('Q' . $mid);
760         $doc->add_term('G' . $tid);
761         $doc->add_term('T' . 'ghost');
762
763         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
764         $self->{xdb}->add_document($doc);
765
766         $smsg;
767 }
768
769 sub merge_threads {
770         my ($self, $winner_tid, $loser_tid) = @_;
771         return if $winner_tid == $loser_tid;
772         my $db = $self->{xdb};
773
774         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
775         while (1) {
776                 my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
777                 return if $head == $tail;
778                 my @ids;
779                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
780                         push @ids, $head->get_docid;
781                 }
782                 foreach my $docid (@ids) {
783                         my $doc = $db->get_document($docid);
784                         $doc->remove_term('G' . $loser_tid);
785                         $doc->add_term('G' . $winner_tid);
786                         $db->replace_document($docid, $doc);
787                 }
788         }
789 }
790
791 sub _read_git_config_perm {
792         my ($self) = @_;
793         my @cmd = qw(config);
794         if ($self->{version} == 2) {
795                 push @cmd, "--file=$self->{mainrepo}/inbox-config";
796         }
797         my $fh = $self->{git}->popen(@cmd, 'core.sharedRepository');
798         local $/ = "\n";
799         my $perm = <$fh>;
800         chomp $perm if defined $perm;
801         $perm;
802 }
803
804 sub _git_config_perm {
805         my $self = shift;
806         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
807         return PERM_GROUP if (!defined($perm) || $perm eq '');
808         return PERM_UMASK if ($perm eq 'umask');
809         return PERM_GROUP if ($perm eq 'group');
810         if ($perm =~ /\A(?:all|world|everybody)\z/) {
811                 return PERM_EVERYBODY;
812         }
813         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
814         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
815
816         my $i = oct($perm);
817         return PERM_UMASK if ($i == PERM_UMASK);
818         return PERM_GROUP if ($i == OLD_PERM_GROUP);
819         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
820
821         if (($i & 0600) != 0600) {
822                 die "core.sharedRepository mode invalid: ".
823                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
824         }
825         ($i & 0666);
826 }
827
828 sub _umask_for {
829         my ($perm) = @_; # _git_config_perm return value
830         my $rv = $perm;
831         return umask if $rv == 0;
832
833         # set +x bit if +r or +w were set
834         $rv |= 0100 if ($rv & 0600);
835         $rv |= 0010 if ($rv & 0060);
836         $rv |= 0001 if ($rv & 0006);
837         (~$rv & 0777);
838 }
839
840 sub with_umask {
841         my ($self, $cb) = @_;
842         my $old = umask $self->{umask};
843         my $rv = eval { $cb->() };
844         my $err = $@;
845         umask $old;
846         die $err if $err;
847         $rv;
848 }
849
850 sub DESTROY {
851         # order matters for unlocking
852         $_[0]->{xdb} = undef;
853         $_[0]->{lockfh} = undef;
854 }
855
856 # remote_* subs are only used by SearchIdxPart and SearchIdxSkeleton
857 sub remote_commit {
858         my ($self) = @_;
859         print { $self->{w} } "commit\n" or die "failed to write commit: $!";
860 }
861
862 sub remote_close {
863         my ($self) = @_;
864         my $pid = delete $self->{pid} or die "no process to wait on\n";
865         my $w = delete $self->{w} or die "no pipe to write to\n";
866         print $w "close\n" or die "failed to write to pid:$pid: $!\n";
867         close $w or die "failed to close pipe for pid:$pid: $!\n";
868         waitpid($pid, 0) == $pid or die "remote process did not finish";
869         $? == 0 or die ref($self)." pid:$pid exited with: $?";
870 }
871
872 1;