]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Over.pm
smsg: reduce utf8::decode call sites
[public-inbox.git] / lib / PublicInbox / Over.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # for XOVER, OVER in NNTP, and feeds/homepage/threads in PSGI
5 # Unlike Msgmap, this is an _UNSTABLE_ database which can be
6 # tweaked/updated over time and rebuilt.
7 package PublicInbox::Over;
8 use strict;
9 use warnings;
10 use DBI;
11 use DBD::SQLite;
12 use PublicInbox::Smsg;
13 use Compress::Zlib qw(uncompress);
14 use constant DEFAULT_LIMIT => 1000;
15
16 sub dbh_new {
17         my ($self, $rw) = @_;
18         my $f = delete $self->{filename};
19         if (!-f $f) { # SQLite defaults mode to 0644, we want 0666
20                 if ($rw) {
21                         require PublicInbox::Spawn;
22                         open my $fh, '+>>', $f or die "failed to open $f: $!";
23                         PublicInbox::Spawn::nodatacow_fd(fileno($fh));
24                         my $j = "$f-journal";
25                         open $fh, '+>>', $j or die "failed to open $j: $!";
26                         PublicInbox::Spawn::nodatacow_fd(fileno($fh));
27                 } else {
28                         $self->{filename} = $f; # die on stat() below:
29                 }
30         }
31         my (@st, $st, $dbh);
32         my $tries = 0;
33         do {
34                 @st = stat($f) or die "failed to stat $f: $!";
35                 $st = pack('dd', $st[0], $st[1]); # 0: dev, 1: inode
36                 $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
37                         AutoCommit => 1,
38                         RaiseError => 1,
39                         PrintError => 0,
40                         ReadOnly => !$rw,
41                         sqlite_use_immediate_transaction => 1,
42                 });
43                 $self->{st} = $st;
44                 @st = stat($f) or die "failed to stat $f: $!";
45                 $st = pack('dd', $st[0], $st[1]);
46         } while ($st ne $self->{st} && $tries++ < 3);
47         warn "W: $f: .st_dev, .st_ino unstable\n" if $st ne $self->{st};
48         $dbh->do('PRAGMA synchronous = OFF') if ($rw // 0) > 1;
49         $dbh;
50 }
51
52 sub new {
53         my ($class, $f) = @_;
54         bless { filename => $f }, $class;
55 }
56
57 sub disconnect {
58         my ($self) = @_;
59         if (my $dbh = delete $self->{dbh}) {
60                 $self->{filename} = $dbh->sqlite_db_filename;
61         }
62 }
63
64 sub connect { $_[0]->{dbh} //= $_[0]->dbh_new }
65
66 sub load_from_row ($;$) {
67         my ($smsg, $cull) = @_;
68         bless $smsg, 'PublicInbox::Smsg';
69         if (defined(my $data = delete $smsg->{ddd})) {
70                 $data = uncompress($data);
71                 PublicInbox::Smsg::load_from_data($smsg, $data);
72
73                 # saves over 600K for 1000+ message threads
74                 PublicInbox::Smsg::psgi_cull($smsg) if $cull;
75         }
76         $smsg
77 }
78
79 sub do_get {
80         my ($self, $sql, $opts, @args) = @_;
81         my $dbh = $self->connect;
82         my $lim = (($opts->{limit} || 0) + 0) || DEFAULT_LIMIT;
83         $sql .= "LIMIT $lim";
84         my $msgs = $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
85         my $cull = $opts->{cull};
86         load_from_row($_, $cull) for @$msgs;
87         $msgs
88 }
89
90 sub query_xover {
91         my ($self, $beg, $end) = @_;
92         do_get($self, <<'', {}, $beg, $end);
93 SELECT num,ts,ds,ddd FROM over WHERE num >= ? AND num <= ?
94 ORDER BY num ASC
95
96 }
97
98 sub query_ts {
99         my ($self, $ts, $prev) = @_;
100         do_get($self, <<'', {}, $ts, $prev);
101 SELECT num,ddd FROM over WHERE ts >= ? AND num > ?
102 ORDER BY num ASC
103
104 }
105
106 sub nothing () { wantarray ? (0, []) : [] };
107
108 sub get_thread {
109         my ($self, $mid, $prev) = @_;
110         my $dbh = $self->connect;
111         my $opts = { cull => 1 };
112
113         my $id = $dbh->selectrow_array(<<'', undef, $mid);
114 SELECT id FROM msgid WHERE mid = ? LIMIT 1
115
116         defined $id or return nothing;
117
118         my $num = $dbh->selectrow_array(<<'', undef, $id);
119 SELECT num FROM id2num WHERE id = ? AND num > 0
120 ORDER BY num ASC LIMIT 1
121
122         defined $num or return nothing;
123
124         my ($tid, $sid) = $dbh->selectrow_array(<<'', undef, $num);
125 SELECT tid,sid FROM over WHERE num = ? LIMIT 1
126
127         defined $tid or return nothing; # $sid may be undef
128
129         my $cond_all = '(tid = ? OR sid = ?) AND num > ?';
130         my $sort_col = 'ds';
131         $num = 0;
132         if ($prev) { # mboxrd stream, only
133                 $num = $prev->{num} || 0;
134                 $sort_col = 'num';
135         }
136
137         my $cols = 'num,ts,ds,ddd';
138         unless (wantarray) {
139                 return do_get($self, <<"", $opts, $tid, $sid, $num);
140 SELECT $cols FROM over WHERE $cond_all
141 ORDER BY $sort_col ASC
142
143         }
144
145         # HTML view always wants an array and never uses $prev,
146         # but the mbox stream never wants an array and always has $prev
147         die '$prev not supported with wantarray' if $prev;
148         my $nr = $dbh->selectrow_array(<<"", undef, $tid, $sid, $num);
149 SELECT COUNT(num) FROM over WHERE $cond_all
150
151         # giant thread, prioritize strict (tid) matches and throw
152         # in the loose (sid) matches at the end
153         my $msgs = do_get($self, <<"", $opts, $tid, $num);
154 SELECT $cols FROM over WHERE tid = ? AND num > ?
155 ORDER BY $sort_col ASC
156
157         # do we have room for loose matches? get the most recent ones, first:
158         my $lim = DEFAULT_LIMIT - scalar(@$msgs);
159         if ($lim > 0) {
160                 $opts->{limit} = $lim;
161                 my $loose = do_get($self, <<"", $opts, $tid, $sid, $num);
162 SELECT $cols FROM over WHERE tid != ? AND sid = ? AND num > ?
163 ORDER BY $sort_col DESC
164
165                 # TODO separate strict and loose matches here once --reindex
166                 # is fixed to preserve `tid' properly
167                 push @$msgs, @$loose;
168         }
169         ($nr, $msgs);
170 }
171
172 sub recent {
173         my ($self, $opts, $after, $before) = @_;
174         my ($s, @v);
175         if (defined($before)) {
176                 if (defined($after)) {
177                         $s = '+num > 0 AND ts >= ? AND ts <= ? ORDER BY ts DESC';
178                         @v = ($after, $before);
179                 } else {
180                         $s = '+num > 0 AND ts <= ? ORDER BY ts DESC';
181                         @v = ($before);
182                 }
183         } else {
184                 if (defined($after)) {
185                         $s = '+num > 0 AND ts >= ? ORDER BY ts ASC';
186                         @v = ($after);
187                 } else {
188                         $s = '+num > 0 ORDER BY ts DESC';
189                 }
190         }
191         my $msgs = do_get($self, <<"", $opts, @v);
192 SELECT ts,ds,ddd FROM over WHERE $s
193
194         return $msgs unless wantarray;
195
196         my $nr = $self->{dbh}->selectrow_array(<<'');
197 SELECT COUNT(num) FROM over WHERE num > 0
198
199         ($nr, $msgs);
200 }
201
202 sub get_art {
203         my ($self, $num) = @_;
204         my $dbh = $self->connect;
205         my $sth = $dbh->prepare_cached(<<'', undef, 1);
206 SELECT num,ds,ts,ddd FROM over WHERE num = ? LIMIT 1
207
208         $sth->execute($num);
209         my $smsg = $sth->fetchrow_hashref;
210         $smsg ? load_from_row($smsg) : undef;
211 }
212
213 sub next_by_mid {
214         my ($self, $mid, $id, $prev) = @_;
215         my $dbh = $self->connect;
216
217         unless (defined $$id) {
218                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
219         SELECT id FROM msgid WHERE mid = ? LIMIT 1
220
221                 $sth->execute($mid);
222                 $$id = $sth->fetchrow_array;
223                 defined $$id or return;
224         }
225         my $sth = $dbh->prepare_cached(<<"", undef, 1);
226 SELECT num FROM id2num WHERE id = ? AND num > ?
227 ORDER BY num ASC LIMIT 1
228
229         $$prev ||= 0;
230         $sth->execute($$id, $$prev);
231         my $num = $sth->fetchrow_array or return;
232         $$prev = $num;
233
234         $sth = $dbh->prepare_cached(<<"", undef, 1);
235 SELECT num,ts,ds,ddd FROM over WHERE num = ? LIMIT 1
236
237         $sth->execute($num);
238         my $smsg = $sth->fetchrow_hashref or return;
239         load_from_row($smsg);
240 }
241
242 # IMAP search, this is limited by callers to UID_SLICE size (50K)
243 sub uid_range {
244         my ($self, $beg, $end, $sql) = @_;
245         my $dbh = $self->connect;
246         my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
247
248         # This is read-only, anyways; but caller should verify it's
249         # only sending \A[0-9]+\z for ds and ts column ranges
250         $q .= $$sql if $sql;
251         $q .= ' ORDER BY num ASC';
252         $dbh->selectcol_arrayref($q, undef, $beg, $end);
253 }
254
255 sub max {
256         my ($self) = @_;
257         my $sth = $self->connect->prepare_cached(<<'', undef, 1);
258 SELECT MAX(num) FROM over WHERE num > 0
259
260         $sth->execute;
261         $sth->fetchrow_array // 0;
262 }
263
264 sub imap_exists {
265         my ($self, $uid_base, $uid_end) = @_;
266         my $sth = $self->connect->prepare_cached(<<'', undef, 1);
267 SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
268
269         $sth->execute($uid_base, $uid_end);
270         $sth->fetchrow_array;
271 }
272
273 sub check_inodes {
274         my ($self) = @_;
275         my $dbh = $self->{dbh} or return;
276         my $f = $dbh->sqlite_db_filename;
277         if (my @st = stat($f)) { # did st_dev, st_ino change?
278                 my $st = pack('dd', $st[0], $st[1]);
279
280                 # don't actually reopen, just let {dbh} be recreated later
281                 if ($st ne ($self->{st} // $st)) {
282                         delete($self->{dbh});
283                         $self->{filename} = $f;
284                 }
285         } else {
286                 warn "W: stat $f: $!\n";
287         }
288 }
289
290 1;