]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
over+msgmap: respect WAL journal_mode if set
[public-inbox.git] / lib / PublicInbox / Msgmap.pm
1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # bidirectional Message-ID <-> Article Number mapping for the NNTP
5 # and web interfaces.  This is required for implementing stable article
6 # numbers for NNTP and allows prefix lookups for partial Message-IDs
7 # in case URLs get truncated from copy-n-paste errors by users.
8 #
9 # This is maintained by ::SearchIdx
10 package PublicInbox::Msgmap;
11 use strict;
12 use DBI;
13 use DBD::SQLite;
14 use PublicInbox::Over;
15 use PublicInbox::Spawn;
16
17 sub new {
18         my ($class, $git_dir, $writable) = @_;
19         my $d = "$git_dir/public-inbox";
20         if ($writable && !-d $d && !mkdir $d) {
21                 my $err = $!;
22                 -d $d or die "$d not created: $err";
23         }
24         new_file($class, "$d/msgmap.sqlite3", $writable);
25 }
26
27 sub new_file {
28         my ($class, $f, $rw) = @_;
29         return if !$rw && !-r $f;
30
31         my $self = bless { filename => $f }, $class;
32         my $dbh = $self->{dbh} = PublicInbox::Over::dbh_new($self, $rw);
33         if ($rw) {
34                 $dbh->begin_work;
35                 create_tables($dbh);
36                 $self->created_at(time) unless $self->created_at;
37
38                 my $max = $self->max // 0;
39                 $self->num_highwater($max);
40                 $dbh->commit;
41         }
42         $self;
43 }
44
45 # used to keep track of used numeric mappings for v2 reindex
46 sub tmp_clone {
47         my ($self, $dir) = @_;
48         require File::Temp;
49         my $tmp = "mm_tmp-$$-XXXXXX";
50         my ($fh, $fn) = File::Temp::tempfile($tmp, EXLOCK => 0, DIR => $dir);
51         PublicInbox::Spawn::nodatacow_fd(fileno($fh));
52         $self->{dbh}->sqlite_backup_to_file($fn);
53         $tmp = ref($self)->new_file($fn, 2);
54         $tmp->{dbh}->do('PRAGMA journal_mode = MEMORY');
55         $tmp->{pid} = $$;
56         $tmp;
57 }
58
59 # n.b. invoked directly by scripts/xhdr-num2mid
60 sub meta_accessor {
61         my ($self, $key, $value) = @_;
62
63         my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
64         my $dbh = $self->{dbh};
65         my $prev;
66         defined $value or return $dbh->selectrow_array($sql, undef, $key);
67
68         $prev = $dbh->selectrow_array($sql, undef, $key);
69
70         if (defined $prev) {
71                 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
72                 $dbh->do($sql, undef, $value, $key);
73         } else {
74                 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
75                 $dbh->do($sql, undef, $key, $value);
76         }
77         $prev;
78 }
79
80 sub last_commit {
81         my ($self, $commit) = @_;
82         $self->meta_accessor('last_commit', $commit);
83 }
84
85 # v2 uses this to keep track of how up-to-date Xapian is
86 # old versions may be automatically GC'ed away in the future,
87 # but it's a trivial amount of storage.
88 sub last_commit_xap {
89         my ($self, $version, $i, $commit) = @_;
90         $self->meta_accessor("last_xap$version-$i", $commit);
91 }
92
93 sub created_at {
94         my ($self, $second) = @_;
95         $self->meta_accessor('created_at', $second);
96 }
97
98 sub num_highwater {
99         my ($self, $num) = @_;
100         my $high = $self->{num_highwater} ||=
101             $self->meta_accessor('num_highwater');
102         if (defined($num) && (!defined($high) || ($num > $high))) {
103                 $self->{num_highwater} = $num;
104                 $self->meta_accessor('num_highwater', $num);
105         }
106         $self->{num_highwater};
107 }
108
109 sub mid_insert {
110         my ($self, $mid) = @_;
111         my $dbh = $self->{dbh};
112         my $sth = $dbh->prepare_cached(<<'');
113 INSERT INTO msgmap (mid) VALUES (?)
114
115         return unless eval { $sth->execute($mid) };
116         my $num = $dbh->last_insert_id(undef, undef, 'msgmap', 'num');
117         $self->num_highwater($num) if defined($num);
118         $num;
119 }
120
121 sub mid_for {
122         my ($self, $num) = @_;
123         my $dbh = $self->{dbh};
124         my $sth = $self->{mid_for} ||=
125                 $dbh->prepare('SELECT mid FROM msgmap WHERE num = ? LIMIT 1');
126         $sth->bind_param(1, $num);
127         $sth->execute;
128         $sth->fetchrow_array;
129 }
130
131 sub num_for {
132         my ($self, $mid) = @_;
133         my $dbh = $self->{dbh};
134         my $sth = $self->{num_for} ||=
135                 $dbh->prepare('SELECT num FROM msgmap WHERE mid = ? LIMIT 1');
136         $sth->bind_param(1, $mid);
137         $sth->execute;
138         $sth->fetchrow_array;
139 }
140
141 sub max {
142         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
143                                                 undef, 1);
144         $sth->execute;
145         $sth->fetchrow_array;
146 }
147
148 sub minmax {
149         # breaking MIN and MAX into separate queries speeds up from 250ms
150         # to around 700us with 2.7million messages.
151         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MIN(num) FROM msgmap',
152                                                 undef, 1);
153         $sth->execute;
154         ($sth->fetchrow_array, max($_[0]));
155 }
156
157 sub mid_delete {
158         my ($self, $mid) = @_;
159         my $dbh = $self->{dbh};
160         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
161         $sth->bind_param(1, $mid);
162         $sth->execute;
163 }
164
165 sub num_delete {
166         my ($self, $num) = @_;
167         my $dbh = $self->{dbh};
168         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
169         $sth->bind_param(1, $num);
170         $sth->execute;
171 }
172
173 sub create_tables {
174         my ($dbh) = @_;
175
176         $dbh->do(<<'');
177 CREATE TABLE IF NOT EXISTS msgmap (
178         num INTEGER PRIMARY KEY AUTOINCREMENT,
179         mid VARCHAR(1000) NOT NULL,
180         UNIQUE (mid)
181 )
182
183         $dbh->do(<<'');
184 CREATE TABLE IF NOT EXISTS meta (
185         key VARCHAR(32) PRIMARY KEY,
186         val VARCHAR(255) NOT NULL
187 )
188
189 }
190
191 # used by NNTP.pm
192 sub ids_after {
193         my ($self, $num) = @_;
194         my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
195 SELECT num FROM msgmap WHERE num > ?
196 ORDER BY num ASC LIMIT 1000
197
198         $$num = $ids->[-1] if @$ids;
199         $ids;
200 }
201
202 sub msg_range {
203         my ($self, $beg, $end, $cols) = @_;
204         $cols //= 'num,mid';
205         my $dbh = $self->{dbh};
206         my $attr = { Columns => [] };
207         my $mids = $dbh->selectall_arrayref(<<"", $attr, $$beg, $end);
208 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
209 ORDER BY num ASC LIMIT 1000
210
211         $$beg = $mids->[-1]->[0] + 1 if @$mids;
212         $mids
213 }
214
215 # only used for mapping external serial numbers (e.g. articles from gmane)
216 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
217 sub mid_set {
218         my ($self, $num, $mid) = @_;
219         my $sth = $self->{mid_set} ||= do {
220                 $self->{dbh}->prepare(
221                         'INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)');
222         };
223         my $result = $sth->execute($num, $mid);
224         $self->num_highwater($num) if (defined($result) && $result == 1);
225         $result;
226 }
227
228 sub DESTROY {
229         my ($self) = @_;
230         my $dbh = $self->{dbh} or return;
231         if (($self->{pid} // 0) == $$) {
232                 my $f = $dbh->sqlite_db_filename;
233                 unlink $f or warn "failed to unlink $f: $!\n";
234         }
235 }
236
237 sub atfork_parent {
238         my ($self) = @_;
239         $self->{pid} or die 'BUG: not a temporary clone';
240         $self->{dbh} and die 'BUG: tmp_clone dbh not prepared for parent';
241         defined($self->{filename}) or die 'BUG: {filename} not defined';
242         $self->{dbh} = PublicInbox::Over::dbh_new($self, 2);
243         $self->{dbh}->do('PRAGMA journal_mode = MEMORY');
244 }
245
246 sub atfork_prepare {
247         my ($self) = @_;
248         my $pid = $self->{pid} or die 'BUG: not a temporary clone';
249         $pid == $$ or die "BUG: atfork_prepare not called by $pid";
250         my $dbh = $self->{dbh} or die 'BUG: temporary clone not open';
251
252         # must clobber prepared statements
253         %$self = (filename => $dbh->sqlite_db_filename, pid => $pid);
254 }
255
256 sub skip_artnum {
257         my ($self, $skip_artnum) = @_;
258         return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
259
260         my $cur = num_highwater($self) // 0;
261         if ($skip_artnum < $cur) {
262                 die "E: current article number $cur ",
263                         "exceeds --skip-artnum=$skip_artnum\n";
264         } else {
265                 my $ok;
266                 for (1..10) {
267                         my $mid = 'skip'.rand.'@'.rand.'.example.com';
268                         $ok = mid_set($self, $skip_artnum, $mid);
269                         if ($ok) {
270                                 mid_delete($self, $mid);
271                                 last;
272                         }
273                 }
274                 $ok or die '--skip-artnum failed';
275
276                 # in the future, the indexer may use this value for
277                 # new messages in old epochs
278                 meta_accessor($self, 'skip_artnum', $skip_artnum);
279         }
280 }
281
282 sub check_inodes {
283         my ($self) = @_;
284         # no filename if in-:memory:
285         my $f = $self->{dbh}->sqlite_db_filename // return;
286         if (my @st = stat($f)) { # did st_dev, st_ino change?
287                 my $st = pack('dd', $st[0], $st[1]);
288                 if ($st ne ($self->{st} // $st)) {
289                         my $tmp = eval { ref($self)->new_file($f) };
290                         if ($@) {
291                                 warn "E: DBI->connect($f): $@\n";
292                         } else {
293                                 %$self = %$tmp;
294                         }
295                 }
296         } else {
297                 warn "W: stat $f: $!\n";
298         }
299 }
300
301 1;