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