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