]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
search: avoid mindlessly calling body_set
[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 Mail::Thread.  This writes to the search
8 # index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use warnings;
12 use Fcntl qw(:flock :DEFAULT);
13 use Email::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 *xpfx = *PublicInbox::Search::xpfx;
23
24 use constant MAX_MID_SIZE => 244; # max term size - 1 in Xapian
25 use constant {
26         PERM_UMASK => 0,
27         OLD_PERM_GROUP => 1,
28         OLD_PERM_EVERYBODY => 2,
29         PERM_GROUP => 0660,
30         PERM_EVERYBODY => 0664,
31 };
32
33 sub new {
34         my ($class, $inbox, $creat) = @_;
35         my $git_dir = $inbox;
36         my $altid;
37         if (ref $inbox) {
38                 $git_dir = $inbox->{mainrepo};
39                 $altid = $inbox->{altid};
40                 if ($altid) {
41                         require PublicInbox::AltId;
42                         $altid = [ map {
43                                 PublicInbox::AltId->new($inbox, $_);
44                         } @$altid ];
45                 }
46         }
47         require Search::Xapian::WritableDatabase;
48         my $self = bless { git_dir => $git_dir, -altid => $altid }, $class;
49         my $perm = $self->_git_config_perm;
50         my $umask = _umask_for($perm);
51         $self->{umask} = $umask;
52         $self->{lock_path} = "$git_dir/ssoma.lock";
53         $self->{git} = PublicInbox::Git->new($git_dir);
54         $self->{creat} = ($creat || 0) == 1;
55         $self;
56 }
57
58 sub _xdb_release {
59         my ($self) = @_;
60         my $xdb = delete $self->{xdb} or croak 'not acquired';
61         $xdb->close;
62         _lock_release($self) if $self->{creat};
63         undef;
64 }
65
66 sub _xdb_acquire {
67         my ($self) = @_;
68         croak 'already acquired' if $self->{xdb};
69         my $dir = PublicInbox::Search->xdir($self->{git_dir});
70         my $flag = Search::Xapian::DB_OPEN;
71         if ($self->{creat}) {
72                 require File::Path;
73                 _lock_acquire($self);
74                 File::Path::mkpath($dir);
75                 $self->{batch_size} = 100;
76                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
77         }
78         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
79 }
80
81 # we only acquire the flock if creating or reindexing;
82 # PublicInbox::Import already has the lock on its own.
83 sub _lock_acquire {
84         my ($self) = @_;
85         croak 'already locked' if $self->{lockfh};
86         sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
87                 die "failed to open lock $self->{lock_path}: $!\n";
88         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
89         $self->{lockfh} = $lockfh;
90 }
91
92 sub _lock_release {
93         my ($self) = @_;
94         my $lockfh = delete $self->{lockfh} or croak 'not locked';
95         flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
96         close $lockfh or die "close failed: $!\n";
97 }
98
99 sub add_val ($$$) {
100         my ($doc, $col, $num) = @_;
101         $num = Search::Xapian::sortable_serialise($num);
102         $doc->add_value($col, $num);
103 }
104
105 sub add_values ($$$) {
106         my ($smsg, $bytes, $num) = @_;
107
108         my $ts = $smsg->ts;
109         my $doc = $smsg->{doc};
110         add_val($doc, &PublicInbox::Search::TS, $ts);
111
112         defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
113
114         defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
115
116         add_val($doc, &PublicInbox::Search::LINES,
117                         $smsg->{mime}->body_raw =~ tr!\n!\n!);
118
119         my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
120         add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
121 }
122
123 sub index_users ($$) {
124         my ($tg, $smsg) = @_;
125
126         my $from = $smsg->from;
127         my $to = $smsg->to;
128         my $cc = $smsg->cc;
129
130         $tg->index_text($from, 1, 'A'); # A - author
131         $tg->increase_termpos;
132         $tg->index_text($to, 1, 'XTO') if $to ne '';
133         $tg->increase_termpos;
134         $tg->index_text($cc, 1, 'XCC') if $cc ne '';
135         $tg->increase_termpos;
136 }
137
138 sub index_body ($$$) {
139         my ($tg, $lines, $inc) = @_;
140         $tg->index_text(join("\n", @$lines), $inc, $inc ? 'XNQ' : 'XQUOT');
141         @$lines = ();
142         $tg->increase_termpos;
143 }
144
145 sub add_message {
146         my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
147         my $db = $self->{xdb};
148
149         my ($doc_id, $old_tid);
150         my $mid = mid_clean(mid_mime($mime));
151         my $ct_msg = $mime->header('Content-Type') || 'text/plain';
152
153         eval {
154                 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
155                 my $smsg = $self->lookup_message($mid);
156                 if ($smsg) {
157                         # convert a ghost to a regular message
158                         # it will also clobber any existing regular message
159                         $doc_id = $smsg->doc_id;
160                         $old_tid = $smsg->thread_id;
161                 }
162                 $smsg = PublicInbox::SearchMsg->new($mime);
163                 my $doc = $smsg->{doc};
164                 $doc->add_term(xpfx('mid') . $mid);
165
166                 my $subj = $smsg->subject;
167                 if ($subj ne '') {
168                         my $path = $self->subject_path($subj);
169                         $doc->add_term(xpfx('path') . id_compress($path));
170                 }
171
172                 add_values($smsg, $bytes, $num);
173
174                 my $tg = $self->term_generator;
175
176                 $tg->set_document($doc);
177                 $tg->index_text($subj, 1, 'S') if $subj;
178                 $tg->increase_termpos;
179
180                 index_users($tg, $smsg);
181
182                 msg_iter($mime, sub {
183                         my ($part, $depth, @idx) = @{$_[0]};
184                         my $ct = $part->content_type || $ct_msg;
185
186                         # account for filter bugs...
187                         $ct =~ m!\btext/plain\b!i or return;
188
189                         my (@orig, @quot);
190                         my $body = $part->body;
191                         my @lines = split(/\n/, $body);
192                         while (defined(my $l = shift @lines)) {
193                                 if ($l =~ /^>/) {
194                                         index_body($tg, \@orig, 1) if @orig;
195                                         push @quot, $l;
196                                 } else {
197                                         index_body($tg, \@quot, 0) if @quot;
198                                         push @orig, $l;
199                                 }
200                         }
201                         index_body($tg, \@quot, 0) if @quot;
202                         index_body($tg, \@orig, 1) if @orig;
203                 });
204
205                 link_message($self, $smsg, $old_tid);
206                 $tg->index_text($mid, 1, 'XMID');
207                 $doc->set_data($smsg->to_doc_data($blob));
208
209                 if (my $altid = $self->{-altid}) {
210                         foreach my $alt (@$altid) {
211                                 my $id = $alt->mid2alt($mid);
212                                 next unless defined $id;
213                                 $doc->add_term($alt->{xprefix} . $id);
214                         }
215                 }
216                 if (defined $doc_id) {
217                         $db->replace_document($doc_id, $doc);
218                 } else {
219                         $doc_id = $db->add_document($doc);
220                 }
221         };
222
223         if ($@) {
224                 warn "failed to index message <$mid>: $@\n";
225                 return undef;
226         }
227         $doc_id;
228 }
229
230 # returns deleted doc_id on success, undef on missing
231 sub remove_message {
232         my ($self, $mid) = @_;
233         my $db = $self->{xdb};
234         my $doc_id;
235         $mid = mid_clean($mid);
236
237         eval {
238                 $doc_id = $self->find_unique_doc_id('mid', $mid);
239                 $db->delete_document($doc_id) if defined $doc_id;
240         };
241
242         if ($@) {
243                 warn "failed to remove message <$mid>: $@\n";
244                 return undef;
245         }
246         $doc_id;
247 }
248
249 sub term_generator { # write-only
250         my ($self) = @_;
251
252         my $tg = $self->{term_generator};
253         return $tg if $tg;
254
255         $tg = Search::Xapian::TermGenerator->new;
256         $tg->set_stemmer($self->stemmer);
257
258         $self->{term_generator} = $tg;
259 }
260
261 # increments last_thread_id counter
262 # returns a 64-bit integer represented as a hex string
263 sub next_thread_id {
264         my ($self) = @_;
265         my $db = $self->{xdb};
266         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
267
268         $db->set_metadata('last_thread_id', ++$last_thread_id);
269
270         $last_thread_id;
271 }
272
273 sub link_message {
274         my ($self, $smsg, $old_tid) = @_;
275         my $doc = $smsg->{doc};
276         my $mid = $smsg->mid;
277         my $mime = $smsg->mime;
278         my $hdr = $mime->header_obj;
279         my $refs = $hdr->header_raw('References');
280         my @refs = $refs ? ($refs =~ /<([^>]+)>/g) : ();
281         if (my $irt = $hdr->header_raw('In-Reply-To')) {
282                 # last References should be $irt
283                 # we will de-dupe later
284                 push @refs, mid_clean($irt);
285         }
286
287         my $tid;
288         if (@refs) {
289                 my %uniq = ($mid => 1);
290                 my @orig_refs = @refs;
291                 @refs = ();
292
293                 # prevent circular references via References: here:
294                 foreach my $ref (@orig_refs) {
295                         if (length($ref) > MAX_MID_SIZE) {
296                                 warn "References: <$ref> too long, ignoring\n";
297                         }
298                         next if $uniq{$ref};
299                         $uniq{$ref} = 1;
300                         push @refs, $ref;
301                 }
302         }
303         if (@refs) {
304                 $smsg->{references} = '<'.join('> <', @refs).'>';
305
306                 # first ref *should* be the thread root,
307                 # but we can never trust clients to do the right thing
308                 my $ref = shift @refs;
309                 $tid = $self->_resolve_mid_to_tid($ref);
310                 $self->merge_threads($tid, $old_tid) if defined $old_tid;
311
312                 # the rest of the refs should point to this tid:
313                 foreach $ref (@refs) {
314                         my $ptid = $self->_resolve_mid_to_tid($ref);
315                         merge_threads($self, $tid, $ptid);
316                 }
317         } else {
318                 $tid = $self->next_thread_id;
319         }
320         $doc->add_term(xpfx('thread') . $tid);
321 }
322
323 sub index_blob {
324         my ($self, $mime, $bytes, $num, $blob) = @_;
325         $self->add_message($mime, $bytes, $num, $blob);
326 }
327
328 sub unindex_blob {
329         my ($self, $mime) = @_;
330         my $mid = eval { mid_clean(mid_mime($mime)) };
331         $self->remove_message($mid) if defined $mid;
332 }
333
334 sub index_mm {
335         my ($self, $mime) = @_;
336         $self->{mm}->mid_insert(mid_clean(mid_mime($mime)));
337 }
338
339 sub unindex_mm {
340         my ($self, $mime) = @_;
341         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
342 }
343
344 sub index_mm2 {
345         my ($self, $mime, $bytes, $blob) = @_;
346         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
347         index_blob($self, $mime, $bytes, $num, $blob);
348 }
349
350 sub unindex_mm2 {
351         my ($self, $mime) = @_;
352         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
353         unindex_blob($self, $mime);
354 }
355
356 sub index_both {
357         my ($self, $mime, $bytes, $blob) = @_;
358         my $num = index_mm($self, $mime);
359         index_blob($self, $mime, $bytes, $num, $blob);
360 }
361
362 sub unindex_both {
363         my ($self, $mime) = @_;
364         unindex_blob($self, $mime);
365         unindex_mm($self, $mime);
366 }
367
368 sub do_cat_mail {
369         my ($git, $blob, $sizeref) = @_;
370         my $mime = eval {
371                 my $str = $git->cat_file($blob, $sizeref);
372                 # fixup bugs from import:
373                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
374                 Email::MIME->new($str);
375         };
376         $@ ? undef : $mime;
377 }
378
379 sub index_sync {
380         my ($self, $opts) = @_;
381         with_umask($self, sub { $self->_index_sync($opts) });
382 }
383
384 sub rlog {
385         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
386         my $hex = '[a-f0-9]';
387         my $h40 = $hex .'{40}';
388         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
389         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
390         my $git = $self->{git};
391         my $latest;
392         my $bytes;
393         my $max = $self->{batch_size}; # may be undef
394         local $/ = "\n";
395         my $line;
396         while (defined($line = <$log>)) {
397                 if ($line =~ /$addmsg/o) {
398                         my $blob = $1;
399                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
400                         $add_cb->($self, $mime, $bytes, $blob);
401                 } elsif ($line =~ /$delmsg/o) {
402                         my $blob = $1;
403                         my $mime = do_cat_mail($git, $blob) or next;
404                         $del_cb->($self, $mime);
405                 } elsif ($line =~ /^commit ($h40)/o) {
406                         if (defined $max && --$max <= 0) {
407                                 $max = $self->{batch_size};
408                                 $batch_cb->($latest, 1);
409                         }
410                         $latest = $1;
411                 }
412         }
413         $batch_cb->($latest, 0);
414 }
415
416 sub _msgmap_init {
417         my ($self) = @_;
418         $self->{mm} = eval {
419                 require PublicInbox::Msgmap;
420                 PublicInbox::Msgmap->new($self->{git_dir}, 1);
421         };
422 }
423
424 sub _git_log {
425         my ($self, $range) = @_;
426         $self->{git}->popen(qw/log --reverse --no-notes --no-color
427                                 --raw -r --no-abbrev/, $range);
428 }
429
430 # indexes all unindexed messages
431 sub _index_sync {
432         my ($self, $opts) = @_;
433         my $tip = $opts->{ref} || 'HEAD';
434         my $reindex = $opts->{reindex};
435         my ($mkey, $last_commit, $lx, $xlog);
436         $self->{git}->batch_prepare;
437         my $xdb = _xdb_acquire($self);
438         $xdb->begin_transaction;
439         do {
440                 $xlog = undef;
441                 $mkey = 'last_commit';
442                 $last_commit = $xdb->get_metadata('last_commit');
443                 $lx = $last_commit;
444                 if ($reindex) {
445                         $lx = '';
446                         $mkey = undef if $last_commit ne '';
447                 }
448                 $xdb->cancel_transaction;
449                 $xdb = _xdb_release($self);
450
451                 # ensure we leak no FDs to "git log"
452                 my $range = $lx eq '' ? $tip : "$lx..$tip";
453                 $xlog = _git_log($self, $range);
454
455                 $xdb = _xdb_acquire($self);
456                 $xdb->begin_transaction;
457         } while ($xdb->get_metadata('last_commit') ne $last_commit);
458
459         my $mm = _msgmap_init($self);
460         my $dbh = $mm->{dbh} if $mm;
461         my $mm_only;
462         my $cb = sub {
463                 my ($commit, $more) = @_;
464                 if ($dbh) {
465                         $mm->last_commit($commit) if $commit;
466                         $dbh->commit;
467                 }
468                 if (!$mm_only) {
469                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
470                         $xdb->commit_transaction;
471                         $xdb = _xdb_release($self);
472                 }
473                 # let another process do some work... <
474                 if ($more) {
475                         if (!$mm_only) {
476                                 $xdb = _xdb_acquire($self);
477                                 $xdb->begin_transaction;
478                         }
479                         $dbh->begin_work if $dbh;
480                 }
481         };
482
483         if ($mm) {
484                 $dbh->begin_work;
485                 my $lm = $mm->last_commit || '';
486                 if ($lm eq $lx) {
487                         # Common case is the indexes are synced,
488                         # we only need to run git-log once:
489                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
490                 } else {
491                         # Uncommon case, msgmap and xapian are out-of-sync
492                         # do not care for performance (but git is fast :>)
493                         # This happens if we have to reindex Xapian since
494                         # msgmap is a frozen format and our Xapian format
495                         # is evolving.
496                         my $r = $lm eq '' ? $tip : "$lm..$tip";
497
498                         # first, ensure msgmap is up-to-date:
499                         my $mkey_prev = $mkey;
500                         $mkey = undef; # ignore xapian, for now
501                         my $mlog = _git_log($self, $r);
502                         $mm_only = 1;
503                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
504                         $mm_only = $mlog = undef;
505
506                         # now deal with Xapian
507                         $mkey = $mkey_prev;
508                         $dbh = undef;
509                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
510                 }
511         } else {
512                 # user didn't install DBD::SQLite and DBI
513                 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
514         }
515 }
516
517 # this will create a ghost as necessary
518 sub _resolve_mid_to_tid {
519         my ($self, $mid) = @_;
520
521         my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
522         $smsg->thread_id;
523 }
524
525 sub create_ghost {
526         my ($self, $mid) = @_;
527
528         my $tid = $self->next_thread_id;
529         my $doc = Search::Xapian::Document->new;
530         $doc->add_term(xpfx('mid') . $mid);
531         $doc->add_term(xpfx('thread') . $tid);
532         $doc->add_term(xpfx('type') . 'ghost');
533
534         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
535         $self->{xdb}->add_document($doc);
536
537         $smsg;
538 }
539
540 sub merge_threads {
541         my ($self, $winner_tid, $loser_tid) = @_;
542         return if $winner_tid == $loser_tid;
543         my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
544         my $thread_pfx = xpfx('thread');
545         my $db = $self->{xdb};
546
547         for (; $head != $tail; $head->inc) {
548                 my $docid = $head->get_docid;
549                 my $doc = $db->get_document($docid);
550                 $doc->remove_term($thread_pfx . $loser_tid);
551                 $doc->add_term($thread_pfx . $winner_tid);
552                 $db->replace_document($docid, $doc);
553         }
554 }
555
556 sub _read_git_config_perm {
557         my ($self) = @_;
558         my @cmd = qw(config core.sharedRepository);
559         my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
560         local $/ = "\n";
561         my $perm = <$fh>;
562         chomp $perm if defined $perm;
563         $perm;
564 }
565
566 sub _git_config_perm {
567         my $self = shift;
568         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
569         return PERM_GROUP if (!defined($perm) || $perm eq '');
570         return PERM_UMASK if ($perm eq 'umask');
571         return PERM_GROUP if ($perm eq 'group');
572         if ($perm =~ /\A(?:all|world|everybody)\z/) {
573                 return PERM_EVERYBODY;
574         }
575         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
576         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
577
578         my $i = oct($perm);
579         return PERM_UMASK if ($i == PERM_UMASK);
580         return PERM_GROUP if ($i == OLD_PERM_GROUP);
581         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
582
583         if (($i & 0600) != 0600) {
584                 die "core.sharedRepository mode invalid: ".
585                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
586         }
587         ($i & 0666);
588 }
589
590 sub _umask_for {
591         my ($perm) = @_; # _git_config_perm return value
592         my $rv = $perm;
593         return umask if $rv == 0;
594
595         # set +x bit if +r or +w were set
596         $rv |= 0100 if ($rv & 0600);
597         $rv |= 0010 if ($rv & 0060);
598         $rv |= 0001 if ($rv & 0006);
599         (~$rv & 0777);
600 }
601
602 sub with_umask {
603         my ($self, $cb) = @_;
604         my $old = umask $self->{umask};
605         my $rv = eval { $cb->() };
606         my $err = $@;
607         umask $old;
608         die $err if $@;
609         $rv;
610 }
611
612 sub DESTROY {
613         # order matters for unlocking
614         $_[0]->{xdb} = undef;
615         $_[0]->{lockfh} = undef;
616 }
617
618 1;