]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/SearchIdx.pm
wwwstream: subclass off GzipFilter
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
index 4e951bbedc7449d899a683b8ce6f965f3d291e5e..4caa66d3751d175f1a22e6685b173b66e800dec6 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (C) 2015-2019 all contributors <meta@public-inbox.org>
+# Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 # based on notmuch, but with no concept of folders, files or flags
 #
@@ -10,7 +10,7 @@ package PublicInbox::SearchIdx;
 use strict;
 use warnings;
 use base qw(PublicInbox::Search PublicInbox::Lock);
-use PublicInbox::MIME;
+use PublicInbox::Eml;
 use PublicInbox::InboxWritable;
 use PublicInbox::MID qw/mid_clean mid_mime mids_for_index/;
 use PublicInbox::MsgIter;
@@ -19,13 +19,12 @@ use POSIX qw(strftime);
 use PublicInbox::OverIdx;
 use PublicInbox::Spawn qw(spawn);
 use PublicInbox::Git qw(git_unquote);
+use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
 my $X = \%PublicInbox::Search::X;
 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
-use constant {
-       BATCH_BYTES => defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
-                       0x7fffffff : 1_000_000,
-       DEBUG => !!$ENV{DEBUG},
-};
+our $BATCH_BYTES = defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
+                       0x7fffffff : 1_000_000;
+use constant DEBUG => !!$ENV{DEBUG};
 
 my $xapianlevels = qr/\A(?:full|medium)\z/;
 
@@ -54,14 +53,16 @@ sub new {
                -inbox => $ibx,
                git => $ibx->git,
                -altid => $altid,
-               version => $version,
+               ibx_ver => $version,
                indexlevel => $indexlevel,
        }, $class;
+       $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
        $ibx->umask_prepare;
        if ($version == 1) {
                $self->{lock_path} = "$inboxdir/ssoma.lock";
                my $dir = $self->xdir;
                $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
+               $self->{index_max_size} = $ibx->{index_max_size};
        } elsif ($version == 2) {
                defined $shard or die "shard is required for v2\n";
                # shard is a number
@@ -77,12 +78,12 @@ sub new {
 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
 
 sub _xdb_release {
-       my ($self) = @_;
+       my ($self, $wake) = @_;
        if (need_xapian($self)) {
                my $xdb = delete $self->{xdb} or croak 'not acquired';
                $xdb->close;
        }
-       $self->lock_release if $self->{creat};
+       $self->lock_release($wake) if $self->{creat};
        undef;
 }
 
@@ -155,16 +156,14 @@ sub index_text ($$$$) {
        }
 }
 
-sub index_users ($$) {
+sub index_headers ($$) {
        my ($self, $smsg) = @_;
-
-       my $from = $smsg->from;
-       my $to = $smsg->to;
-       my $cc = $smsg->cc;
-
-       index_text($self, $from, 1, 'A'); # A - author
-       index_text($self, $to, 1, 'XTO') if $to ne '';
-       index_text($self, $cc, 1, 'XCC') if $cc ne '';
+       my @x = (from => 'A', # Author
+               subject => 'S', to => 'XTO', cc => 'XCC');
+       while (my ($field, $pfx) = splice(@x, 0, 2)) {
+               my $val = $smsg->{$field};
+               index_text($self, $val, 1, $pfx) if $val ne '';
+       }
 }
 
 sub index_diff_inc ($$$$) {
@@ -209,12 +208,8 @@ sub index_diff ($$$) {
                        index_diff_inc($self, $_, 'XDFCTX', $xnq);
                } elsif (/^-- $/) { # email signature begins
                        $in_diff = undef;
-               } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
-                       my ($fa, $fb) = ($1, $2);
-                       my $fn = (split('/', git_unquote($fa), 2))[1];
-                       $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
-                       $fn = (split('/', git_unquote($fb), 2))[1];
-                       $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
+               } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
+                       # wait until "---" and "+++" to capture filenames
                        $in_diff = 1;
                # traditional diff:
                } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
@@ -224,12 +219,12 @@ sub index_diff ($$$) {
                        next unless $opt =~ /[uU]/;
                        $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
                                                        $xnq);
-               } elsif (m!^--- ("?a/.+)!) {
+               } elsif (m!^--- ("?[^/]+/.+)!) {
                        my $fn = $1;
                        $fn = (split('/', git_unquote($fn), 2))[1];
                        $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
                        $in_diff = 1;
-               } elsif (m!^\+\+\+ ("?b/.+)!)  {
+               } elsif (m!^\+\+\+ ("?[^/]+/.+)!)  {
                        my $fn = $1;
                        $fn = (split('/', git_unquote($fn), 2))[1];
                        $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
@@ -277,70 +272,87 @@ sub index_diff ($$$) {
        index_text($self, join("\n", @xnq), 1, 'XNQ');
 }
 
-sub index_body ($$$) {
-       my ($self, $txt, $doc) = @_;
-       if ($doc) {
-               # does it look like a diff?
-               if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
-                       index_diff($self, $txt, $doc);
-               } else {
-                       index_text($self, $txt, 1, 'XNQ');
-               }
-       } else {
-               index_text($self, $txt, 0, 'XQUOT');
-       }
-}
-
 sub index_xapian { # msg_iter callback
-       my ($part, $depth, @idx) = @{$_[0]};
+       my $part = $_[0]->[0]; # ignore $depth and $idx
        my ($self, $doc) = @{$_[1]};
        my $ct = $part->content_type || 'text/plain';
        my $fn = $part->filename;
        if (defined $fn && $fn ne '') {
                index_text($self, $fn, 1, 'XFN');
        }
+       if ($part->{is_submsg}) {
+               my $mids = mids_for_index($part);
+               index_ids($self, $doc, $part, $mids);
+               my $smsg = bless {}, 'PublicInbox::Smsg';
+               $smsg->populate($part);
+               index_headers($self, $smsg);
+       }
 
        my ($s, undef) = msg_part_text($part, $ct);
        defined $s or return;
+       $_[0]->[0] = $part = undef; # free memory
 
        # split off quoted and unquoted blocks:
-       my @sections = split(/((?:^>[^\n]*\n)+)/sm, $s);
-       $part = $s = undef;
-       index_body($self, $_, /\A>/ ? 0 : $doc) for @sections;
+       my @sections = PublicInbox::MsgIter::split_quotes($s);
+       undef $s; # free memory
+       for my $txt (@sections) {
+               if ($txt =~ /\A>/) {
+                       index_text($self, $txt, 0, 'XQUOT');
+               } else {
+                       # does it look like a diff?
+                       if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
+                               index_diff($self, $txt, $doc);
+                       } else {
+                               index_text($self, $txt, 1, 'XNQ');
+                       }
+               }
+               undef $txt; # free memory
+       }
 }
 
-sub add_xapian ($$$$$$) {
-       my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
-       my $smsg = PublicInbox::SearchMsg->new($mime);
+sub index_ids ($$$$) {
+       my ($self, $doc, $hdr, $mids) = @_;
+       for my $mid (@$mids) {
+               index_text($self, $mid, 1, 'XM');
+
+               # because too many Message-IDs are prefixed with
+               # "Pine.LNX."...
+               if ($mid =~ /\w{12,}/) {
+                       my @long = ($mid =~ /(\w{3,}+)/g);
+                       index_text($self, join(' ', @long), 1, 'XM');
+               }
+       }
+       $doc->add_boolean_term('Q' . $_) for @$mids;
+       for my $l ($hdr->header_raw('List-Id')) {
+               $l =~ /<([^>]+)>/ or next;
+               my $lid = $1;
+               $doc->add_boolean_term('G' . $lid);
+               index_text($self, $lid, 1, 'XL'); # probabilistic
+       }
+}
+
+sub add_xapian ($$$$) {
+       my ($self, $mime, $smsg, $mids) = @_;
+       my $hdr = $mime->header_obj;
        my $doc = $X->{Document}->new;
-       my $subj = $smsg->subject;
-       add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
-       my @ds = gmtime($smsg->ds);
+       add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
+       my @ds = gmtime($smsg->{ds});
        my $yyyymmdd = strftime('%Y%m%d', @ds);
        add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
        my $dt = strftime('%Y%m%d%H%M%S', @ds);
        add_val($doc, PublicInbox::Search::DT(), $dt);
+       add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
+       add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
 
        my $tg = term_generator($self);
-
        $tg->set_document($doc);
-       index_text($self, $subj, 1, 'S') if $subj;
-       index_users($self, $smsg);
+       index_headers($self, $smsg);
 
        msg_iter($mime, \&index_xapian, [ $self, $doc ]);
-       foreach my $mid (@$mids) {
-               index_text($self, $mid, 1, 'XM');
-
-               # because too many Message-IDs are prefixed with
-               # "Pine.LNX."...
-               if ($mid =~ /\w{12,}/) {
-                       my @long = ($mid =~ /(\w{3,}+)/g);
-                       index_text($self, join(' ', @long), 1, 'XM');
-               }
-       }
-       $smsg->{to} = $smsg->{cc} = '';
-       PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
-       my $data = $smsg->to_doc_data($oid, $mid0);
+       index_ids($self, $doc, $hdr, $mids);
+       $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
+       PublicInbox::OverIdx::parse_references($smsg, $hdr, $mids);
+       my $data = $smsg->to_doc_data;
        $doc->set_data($data);
        if (my $altid = $self->{-altid}) {
                foreach my $alt (@$altid) {
@@ -352,13 +364,12 @@ sub add_xapian ($$$$$$) {
                        }
                }
        }
-       $doc->add_boolean_term('Q' . $_) foreach @$mids;
-       $self->{xdb}->replace_document($num, $doc);
+       $self->{xdb}->replace_document($smsg->{num}, $doc);
 }
 
 sub _msgmap_init ($) {
        my ($self) = @_;
-       die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
+       die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
        $self->{mm} //= eval {
                require PublicInbox::Msgmap;
                PublicInbox::Msgmap->new($self->{inboxdir}, 1);
@@ -366,20 +377,32 @@ sub _msgmap_init ($) {
 }
 
 sub add_message {
-       # mime = Email::MIME object
-       my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
-       my $mids = mids_for_index($mime->header_obj);
-       $mid0 //= $mids->[0]; # v1 compatibility
-       $num //= do { # v1
+       # mime = PublicInbox::Eml or Email::MIME object
+       my ($self, $mime, $smsg, $sync) = @_;
+       my $hdr = $mime->header_obj;
+       my $mids = mids_for_index($hdr);
+       $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
+       $smsg->{mid} //= $mids->[0]; # v1 compatibility
+       $smsg->{num} //= do { # v1
                _msgmap_init($self);
                index_mm($self, $mime);
        };
+
+       # v1 and tests only:
+       $smsg->populate($hdr, $sync);
+       $smsg->{bytes} //= length($mime->as_string);
+
        eval {
-               if (need_xapian($self)) {
-                       add_xapian($self, $mime, $num, $oid, $mids, $mid0);
+               # order matters, overview stores every possible piece of
+               # data in doc_data (deflated).  Xapian only stores a subset
+               # of the fields which exist in over.sqlite3.  We may stop
+               # storing doc_data in Xapian sometime after we get multi-inbox
+               # search working.
+               if (my $over = $self->{over}) { # v1 only
+                       $over->add_overview($mime, $smsg);
                }
-               if (my $over = $self->{over}) {
-                       $over->add_overview($mime, $bytes, $num, $oid, $mid0);
+               if (need_xapian($self)) {
+                       add_xapian($self, $mime, $smsg, $mids);
                }
        };
 
@@ -387,7 +410,7 @@ sub add_message {
                warn "failed to index message <".join('> <',@$mids).">: $@\n";
                return undef;
        }
-       $num;
+       $smsg->{num};
 }
 
 # returns begin and end PostingIterator
@@ -464,7 +487,7 @@ sub remove_by_oid {
        for (; $head != $tail; $head++) {
                my $docid = $head->get_docid;
                my $doc = $db->get_document($docid);
-               my $smsg = PublicInbox::SearchMsg->wrap($mid);
+               my $smsg = bless { mid => $mid }, 'PublicInbox::Smsg';
                $smsg->load_expand($doc);
                if ($smsg->{blob} eq $oid) {
                        push(@delete, $docid);
@@ -486,13 +509,13 @@ sub index_git_blob_id {
 
 sub unindex_blob {
        my ($self, $mime) = @_;
-       my $mid = eval { mid_clean(mid_mime($mime)) };
+       my $mid = eval { mid_mime($mime) };
        $self->remove_message($mid) if defined $mid;
 }
 
 sub index_mm {
        my ($self, $mime) = @_;
-       my $mid = mid_clean(mid_mime($mime));
+       my $mid = mid_mime($mime);
        my $mm = $self->{mm};
        my $num;
 
@@ -523,30 +546,39 @@ sub index_mm {
 
 sub unindex_mm {
        my ($self, $mime) = @_;
-       $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
+       $self->{mm}->mid_delete(mid_mime($mime));
 }
 
-sub index_both {
-       my ($self, $mime, $bytes, $blob) = @_;
-       my $num = index_mm($self, $mime);
-       add_message($self, $mime, $bytes, $num, $blob);
+# returns the number of bytes to add if given a non-CRLF arg
+sub crlf_adjust ($) {
+       if (index($_[0], "\r\n") < 0) {
+               # common case is LF-only, every \n needs an \r;
+               # so favor a cheap tr// over an expensive m//g
+               $_[0] =~ tr/\n/\n/;
+       } else { # count number of '\n' w/o '\r', expensive:
+               scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
+       }
 }
 
-sub unindex_both {
-       my ($self, $mime) = @_;
-       unindex_blob($self, $mime);
-       unindex_mm($self, $mime);
+sub index_both { # git->cat_async callback
+       my ($bref, $oid, $type, $size, $sync) = @_;
+       my ($nr, $max) = @$sync{qw(nr max)};
+       ++$$nr;
+       $$max -= $size;
+       $size += crlf_adjust($$bref);
+       my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
+       my $self = $sync->{sidx};
+       my $eml = PublicInbox::Eml->new($bref);
+       my $num = index_mm($self, $eml);
+       $smsg->{num} = $num;
+       add_message($self, $eml, $smsg, $sync);
 }
 
-sub do_cat_mail {
-       my ($git, $blob, $sizeref) = @_;
-       my $mime = eval {
-               my $str = $git->cat_file($blob, $sizeref);
-               # fixup bugs from import:
-               $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
-               PublicInbox::MIME->new($str);
-       };
-       $@ ? undef : $mime;
+sub unindex_both { # git->cat_async callback
+       my ($bref, $oid, $type, $size, $self) = @_;
+       my $eml = PublicInbox::Eml->new($bref);
+       unindex_blob($self, $eml);
+       unindex_mm($self, $eml);
 }
 
 # called by public-inbox-index
@@ -556,58 +588,71 @@ sub index_sync {
        $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
 }
 
-sub batch_adjust ($$$$$) {
-       my ($max, $bytes, $batch_cb, $latest, $nr) = @_;
-       $$max -= $bytes;
-       if ($$max <= 0) {
-               $$max = BATCH_BYTES;
-               $batch_cb->($nr, $latest);
-       }
+sub too_big ($$$) {
+       my ($self, $git, $oid) = @_;
+       my $max_size = $self->{index_max_size} or return;
+       my (undef, undef, $size) = $git->check($oid);
+       die "E: bad $oid in $git->{git_dir}\n" if !defined($size);
+       return if $size <= $max_size;
+       warn "W: skipping $oid ($size > $max_size)\n";
+       1;
 }
 
 # only for v1
 sub read_log {
-       my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
+       my ($self, $log, $batch_cb) = @_;
        my $hex = '[a-f0-9]';
        my $h40 = $hex .'{40}';
        my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
        my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
        my $git = $self->{git};
        my $latest;
-       my $bytes;
-       my $max = BATCH_BYTES;
+       my $max = $BATCH_BYTES;
        local $/ = "\n";
        my %D;
        my $line;
        my $newest;
        my $nr = 0;
+       my $sync = { sidx => $self, nr => \$nr, max => \$max };
        while (defined($line = <$log>)) {
                if ($line =~ /$addmsg/o) {
                        my $blob = $1;
                        if (delete $D{$blob}) {
+                               # make sure pending index writes are done
+                               # before writing to ->mm
+                               $git->cat_async_wait;
+
                                if (defined $self->{regen_down}) {
                                        my $num = $self->{regen_down}--;
                                        $self->{mm}->num_highwater($num);
                                }
                                next;
                        }
-                       my $mime = do_cat_mail($git, $blob, \$bytes) or next;
-                       batch_adjust(\$max, $bytes, $batch_cb, $latest, ++$nr);
-                       $add_cb->($self, $mime, $bytes, $blob);
+                       next if too_big($self, $git, $blob);
+                       $git->cat_async($blob, \&index_both, { %$sync });
+                       if ($max <= 0) {
+                               $git->cat_async_wait;
+                               $max = $BATCH_BYTES;
+                               $batch_cb->($nr, $latest);
+                       }
                } elsif ($line =~ /$delmsg/o) {
                        my $blob = $1;
-                       $D{$blob} = 1;
+                       $D{$blob} = 1 unless too_big($self, $git, $blob);
                } elsif ($line =~ /^commit ($h40)/o) {
                        $latest = $1;
                        $newest ||= $latest;
+               } elsif ($line =~ /^author .*? ([0-9]+) [\-\+][0-9]+$/) {
+                       $sync->{autime} = $1;
+               } elsif ($line =~ /^committer .*? ([0-9]+) [\-\+][0-9]+$/) {
+                       $sync->{cotime} = $1;
                }
        }
        close($log) or die "git log failed: \$?=$?";
        # get the leftovers
        foreach my $blob (keys %D) {
-               my $mime = do_cat_mail($git, $blob, \$bytes) or next;
-               $del_cb->($self, $mime);
+               $git->cat_async($blob, \&unindex_both, $self);
        }
+       $git->cat_async_wait;
        $batch_cb->($nr, $latest, $newest);
 }
 
@@ -616,7 +661,7 @@ sub _git_log {
        my $git = $self->{git};
 
        if (index($range, '..') < 0) {
-               # don't show annoying git errrors to users who run -index
+               # don't show annoying git errors to users who run -index
                # on empty inboxes
                $git->qx(qw(rev-parse -q --verify), "$range^0");
                if ($?) {
@@ -649,13 +694,14 @@ sub _git_log {
                } else {
                        # normal regen is for for fresh data
                        $self->{regen_down} = $fcount;
+                       $self->{regen_down} += $high unless $opts->{reindex};
                }
        } else {
                # Give oldest messages the smallest numbers
                $self->{regen_down} = $high + $fcount;
        }
 
-       $git->popen(qw/log --no-notes --no-color --no-renames
+       $git->popen(qw/log --pretty=raw --no-notes --no-color --no-renames
                                --raw -r --no-abbrev/, $range);
 }
 
@@ -716,10 +762,7 @@ sub _index_sync {
        my $xdb = $self->begin_txn_lazy;
        my $mm = _msgmap_init($self);
        do {
-               if ($xlog) {
-                       close($xlog) or die "git log failed: \$?=$?";
-                       $xlog = undef;
-               }
+               $xlog = undef; # stop previous git-log via SIGPIPE
                $last_commit = _last_x_commit($self, $mm);
                $lx = reindex_from($opts->{reindex}, $last_commit);
 
@@ -738,7 +781,7 @@ sub _index_sync {
        } while (_last_x_commit($self, $mm) ne $last_commit);
 
        my $dbh = $mm->{dbh} if $mm;
-       my $cb = sub {
+       my $batch_cb = sub {
                my ($nr, $commit, $newest) = @_;
                if ($dbh) {
                        if ($newest) {
@@ -757,7 +800,7 @@ sub _index_sync {
                }
                $self->commit_txn_lazy;
                $git->cleanup;
-               $xdb = _xdb_release($self);
+               $xdb = _xdb_release($self, $nr);
                # let another process do some work... <
                $pr->("indexed $nr/$self->{ntodo}\n") if $pr && $nr;
                if (!$newest) {
@@ -767,7 +810,7 @@ sub _index_sync {
        };
 
        $dbh->begin_work;
-       read_log($self, $xlog, *index_both, *unindex_both, $cb);
+       read_log($self, $xlog, $batch_cb);
 }
 
 sub DESTROY {
@@ -824,20 +867,27 @@ sub begin_txn_lazy {
        });
 }
 
+# store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
+# This metadata is read by Admin::detect_indexlevel:
+sub set_indexlevel {
+       my ($self) = @_;
+
+       if (!$self->{shard} && # undef or 0, not >0
+                       delete($self->{-set_indexlevel_once})) {
+               my $xdb = $self->{xdb};
+               my $level = $xdb->get_metadata('indexlevel');
+               if (!$level || $level ne 'medium') {
+                       $xdb->set_metadata('indexlevel', 'medium');
+               }
+       }
+}
+
 sub commit_txn_lazy {
        my ($self) = @_;
        delete $self->{txn} or return;
        $self->{-inbox}->with_umask(sub {
                if (my $xdb = $self->{xdb}) {
-
-                       # store 'indexlevel=medium' in v2 shard=0 and
-                       # v1 (only one shard)
-                       # This metadata is read by Admin::detect_indexlevel:
-                       if (!$self->{shard} # undef or 0, not >0
-                           && $self->{indexlevel} eq 'medium') {
-                               $xdb->set_metadata('indexlevel', 'medium');
-                       }
-
+                       set_indexlevel($self);
                        $xdb->commit_transaction;
                }
                $self->{over}->commit_lazy if $self->{over};