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