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