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