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