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