]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
msgmap: use TRUNCATE for journal_mode, for now
[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 warnings;
13 use DBI;
14 use DBD::SQLite;
15 use File::Temp qw(tempfile);
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 dbh_new {
28         my ($f, $writable) = @_;
29         if ($writable && !-f $f) { # SQLite defaults mode to 0644, we want 0666
30                 open my $fh, '+>>', $f or die "failed to open $f: $!";
31         }
32         my $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
33                 AutoCommit => 1,
34                 RaiseError => 1,
35                 PrintError => 0,
36                 ReadOnly => !$writable,
37                 sqlite_use_immediate_transaction => 1,
38         });
39         $dbh;
40 }
41
42 sub new_file {
43         my ($class, $f, $writable) = @_;
44         return if !$writable && !-r $f;
45
46         my $dbh = dbh_new($f, $writable);
47         my $self = bless { dbh => $dbh }, $class;
48
49         if ($writable) {
50                 create_tables($dbh);
51
52                 # TRUNCATE reduces I/O compared to the default (DELETE)
53                 $dbh->do('PRAGMA journal_mode = TRUNCATE');
54
55                 $dbh->begin_work;
56                 $self->created_at(time) unless $self->created_at;
57
58                 my (undef, $max) = $self->minmax();
59                 $max ||= 0;
60                 $self->num_highwater($max);
61                 $dbh->commit;
62         }
63         $self;
64 }
65
66 # used to keep track of used numeric mappings for v2 reindex
67 sub tmp_clone {
68         my ($self) = @_;
69         my ($fh, $fn) = tempfile('msgmap-XXXXXXXX', EXLOCK => 0, TMPDIR => 1);
70         $self->{dbh}->sqlite_backup_to_file($fn);
71         my $tmp = ref($self)->new_file($fn, 1);
72         $tmp->{dbh}->do('PRAGMA synchronous = OFF');
73         $tmp->{tmp_name} = $fn; # SQLite won't work if unlinked, apparently
74         $tmp->{pid} = $$;
75         close $fh or die "failed to close $fn: $!";
76         $tmp;
77 }
78
79 # n.b. invoked directly by scripts/xhdr-num2mid
80 sub meta_accessor {
81         my ($self, $key, $value) = @_;
82
83         my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
84         my $dbh = $self->{dbh};
85         my $prev;
86         defined $value or return $dbh->selectrow_array($sql, undef, $key);
87
88         $prev = $dbh->selectrow_array($sql, undef, $key);
89
90         if (defined $prev) {
91                 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
92                 $dbh->do($sql, undef, $value, $key);
93         } else {
94                 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
95                 $dbh->do($sql, undef, $key, $value);
96         }
97         $prev;
98 }
99
100 sub last_commit {
101         my ($self, $commit) = @_;
102         $self->meta_accessor('last_commit', $commit);
103 }
104
105 # v2 uses this to keep track of how up-to-date Xapian is
106 # old versions may be automatically GC'ed away in the future,
107 # but it's a trivial amount of storage.
108 sub last_commit_xap {
109         my ($self, $version, $i, $commit) = @_;
110         $self->meta_accessor("last_xap$version-$i", $commit);
111 }
112
113 sub created_at {
114         my ($self, $second) = @_;
115         $self->meta_accessor('created_at', $second);
116 }
117
118 sub num_highwater {
119         my ($self, $num) = @_;
120         my $high = $self->{num_highwater} ||=
121             $self->meta_accessor('num_highwater');
122         if (defined($num) && (!defined($high) || ($num > $high))) {
123                 $self->{num_highwater} = $num;
124                 $self->meta_accessor('num_highwater', $num);
125         }
126         $self->{num_highwater};
127 }
128
129 sub mid_insert {
130         my ($self, $mid) = @_;
131         my $dbh = $self->{dbh};
132         my $sth = $dbh->prepare_cached(<<'');
133 INSERT INTO msgmap (mid) VALUES (?)
134
135         return unless eval { $sth->execute($mid) };
136         my $num = $dbh->last_insert_id(undef, undef, 'msgmap', 'num');
137         $self->num_highwater($num) if defined($num);
138         $num;
139 }
140
141 sub mid_for {
142         my ($self, $num) = @_;
143         my $dbh = $self->{dbh};
144         my $sth = $self->{mid_for} ||=
145                 $dbh->prepare('SELECT mid FROM msgmap WHERE num = ? LIMIT 1');
146         $sth->bind_param(1, $num);
147         $sth->execute;
148         $sth->fetchrow_array;
149 }
150
151 sub num_for {
152         my ($self, $mid) = @_;
153         my $dbh = $self->{dbh};
154         my $sth = $self->{num_for} ||=
155                 $dbh->prepare('SELECT num FROM msgmap WHERE mid = ? LIMIT 1');
156         $sth->bind_param(1, $mid);
157         $sth->execute;
158         $sth->fetchrow_array;
159 }
160
161 sub minmax {
162         my ($self) = @_;
163         my $dbh = $self->{dbh};
164         # breaking MIN and MAX into separate queries speeds up from 250ms
165         # to around 700us with 2.7million messages.
166         my $sth = $dbh->prepare_cached('SELECT MIN(num) FROM msgmap', undef, 1);
167         $sth->execute;
168         my $min = $sth->fetchrow_array;
169         $sth = $dbh->prepare_cached('SELECT MAX(num) FROM msgmap', undef, 1);
170         $sth->execute;
171         ($min, $sth->fetchrow_array);
172 }
173
174 sub mid_delete {
175         my ($self, $mid) = @_;
176         my $dbh = $self->{dbh};
177         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
178         $sth->bind_param(1, $mid);
179         $sth->execute;
180 }
181
182 sub num_delete {
183         my ($self, $num) = @_;
184         my $dbh = $self->{dbh};
185         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
186         $sth->bind_param(1, $num);
187         $sth->execute;
188 }
189
190 sub create_tables {
191         my ($dbh) = @_;
192         my $e;
193
194         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM msgmap;') };
195         defined $e or $dbh->do('CREATE TABLE msgmap (' .
196                         'num INTEGER PRIMARY KEY AUTOINCREMENT, '.
197                         'mid VARCHAR(1000) NOT NULL, ' .
198                         'UNIQUE (mid) )');
199
200         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM meta') };
201         defined $e or $dbh->do('CREATE TABLE meta (' .
202                         'key VARCHAR(32) PRIMARY KEY, '.
203                         'val VARCHAR(255) NOT NULL)');
204 }
205
206 # used by NNTP.pm
207 sub ids_after {
208         my ($self, $num) = @_;
209         my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
210 SELECT num FROM msgmap WHERE num > ?
211 ORDER BY num ASC LIMIT 1000
212
213         $$num = $ids->[-1] if @$ids;
214         $ids;
215 }
216
217 sub msg_range {
218         my ($self, $beg, $end, $cols) = @_;
219         $cols //= 'num,mid';
220         my $dbh = $self->{dbh};
221         my $attr = { Columns => [] };
222         my $mids = $dbh->selectall_arrayref(<<"", $attr, $$beg, $end);
223 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
224 ORDER BY num ASC LIMIT 1000
225
226         $$beg = $mids->[-1]->[0] + 1 if @$mids;
227         $mids
228 }
229
230 # only used for mapping external serial numbers (e.g. articles from gmane)
231 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
232 sub mid_set {
233         my ($self, $num, $mid) = @_;
234         my $sth = $self->{mid_set} ||= do {
235                 $self->{dbh}->prepare(
236                         'INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)');
237         };
238         my $result = $sth->execute($num, $mid);
239         $self->num_highwater($num) if (defined($result) && $result == 1);
240         $result;
241 }
242
243 sub DESTROY {
244         my ($self) = @_;
245         delete $self->{dbh};
246         my $f = delete $self->{tmp_name};
247         if (defined $f && $self->{pid} == $$) {
248                 unlink $f or warn "failed to unlink $f: $!\n";
249         }
250 }
251
252 sub atfork_parent {
253         my ($self) = @_;
254         my $f = $self->{tmp_name} or die "not a temporary clone\n";
255         delete $self->{dbh} and die "tmp_clone dbh not prepared for parent";
256         my $dbh = $self->{dbh} = dbh_new($f, 1);
257         $dbh->do('PRAGMA synchronous = OFF');
258 }
259
260 sub atfork_prepare {
261         my ($self) = @_;
262         my $f = $self->{tmp_name} or die "not a temporary clone\n";
263         $self->{pid} == $$ or
264                 die "BUG: atfork_prepare not called from $self->{pid}\n";
265         $self->{dbh} or die "temporary clone not open\n";
266         # must clobber prepared statements
267         %$self = (tmp_name => $f, pid => $$);
268 }
269
270 1;