]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
wwwstream: use parent.pm and no warnings
[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 $max = $self->max // 0;
59                 $self->num_highwater($max);
60                 $dbh->commit;
61         }
62         $self;
63 }
64
65 # used to keep track of used numeric mappings for v2 reindex
66 sub tmp_clone {
67         my ($self) = @_;
68         my ($fh, $fn) = tempfile('msgmap-XXXXXXXX', EXLOCK => 0, TMPDIR => 1);
69         $self->{dbh}->sqlite_backup_to_file($fn);
70         my $tmp = ref($self)->new_file($fn, 1);
71         $tmp->{dbh}->do('PRAGMA synchronous = OFF');
72         $tmp->{dbh}->do('PRAGMA journal_mode = MEMORY');
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 max {
162         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
163                                                 undef, 1);
164         $sth->execute;
165         $sth->fetchrow_array;
166 }
167
168 sub minmax {
169         # breaking MIN and MAX into separate queries speeds up from 250ms
170         # to around 700us with 2.7million messages.
171         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MIN(num) FROM msgmap',
172                                                 undef, 1);
173         $sth->execute;
174         ($sth->fetchrow_array, max($_[0]));
175 }
176
177 sub mid_delete {
178         my ($self, $mid) = @_;
179         my $dbh = $self->{dbh};
180         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
181         $sth->bind_param(1, $mid);
182         $sth->execute;
183 }
184
185 sub num_delete {
186         my ($self, $num) = @_;
187         my $dbh = $self->{dbh};
188         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
189         $sth->bind_param(1, $num);
190         $sth->execute;
191 }
192
193 sub create_tables {
194         my ($dbh) = @_;
195         my $e;
196
197         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM msgmap;') };
198         defined $e or $dbh->do('CREATE TABLE msgmap (' .
199                         'num INTEGER PRIMARY KEY AUTOINCREMENT, '.
200                         'mid VARCHAR(1000) NOT NULL, ' .
201                         'UNIQUE (mid) )');
202
203         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM meta') };
204         defined $e or $dbh->do('CREATE TABLE meta (' .
205                         'key VARCHAR(32) PRIMARY KEY, '.
206                         'val VARCHAR(255) NOT NULL)');
207 }
208
209 # used by NNTP.pm
210 sub ids_after {
211         my ($self, $num) = @_;
212         my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
213 SELECT num FROM msgmap WHERE num > ?
214 ORDER BY num ASC LIMIT 1000
215
216         $$num = $ids->[-1] if @$ids;
217         $ids;
218 }
219
220 sub msg_range {
221         my ($self, $beg, $end, $cols) = @_;
222         $cols //= 'num,mid';
223         my $dbh = $self->{dbh};
224         my $attr = { Columns => [] };
225         my $mids = $dbh->selectall_arrayref(<<"", $attr, $$beg, $end);
226 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
227 ORDER BY num ASC LIMIT 1000
228
229         $$beg = $mids->[-1]->[0] + 1 if @$mids;
230         $mids
231 }
232
233 # only used for mapping external serial numbers (e.g. articles from gmane)
234 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
235 sub mid_set {
236         my ($self, $num, $mid) = @_;
237         my $sth = $self->{mid_set} ||= do {
238                 $self->{dbh}->prepare(
239                         'INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)');
240         };
241         my $result = $sth->execute($num, $mid);
242         $self->num_highwater($num) if (defined($result) && $result == 1);
243         $result;
244 }
245
246 sub DESTROY {
247         my ($self) = @_;
248         delete $self->{dbh};
249         my $f = delete $self->{tmp_name};
250         if (defined $f && $self->{pid} == $$) {
251                 unlink $f or warn "failed to unlink $f: $!\n";
252         }
253 }
254
255 sub atfork_parent {
256         my ($self) = @_;
257         my $f = $self->{tmp_name} or die "not a temporary clone\n";
258         delete $self->{dbh} and die "tmp_clone dbh not prepared for parent";
259         my $dbh = $self->{dbh} = dbh_new($f, 1);
260         $dbh->do('PRAGMA synchronous = OFF');
261 }
262
263 sub atfork_prepare {
264         my ($self) = @_;
265         my $f = $self->{tmp_name} or die "not a temporary clone\n";
266         $self->{pid} == $$ or
267                 die "BUG: atfork_prepare not called from $self->{pid}\n";
268         $self->{dbh} or die "temporary clone not open\n";
269         # must clobber prepared statements
270         %$self = (tmp_name => $f, pid => $$);
271 }
272
273 sub skip_artnum {
274         my ($self, $skip_artnum) = @_;
275         return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
276
277         my $cur = num_highwater($self) // 0;
278         if ($skip_artnum < $cur) {
279                 die "E: current article number $cur ",
280                         "exceeds --skip-artnum=$skip_artnum\n";
281         } else {
282                 my $ok;
283                 for (1..10) {
284                         my $mid = 'skip'.rand.'@'.rand.'.example.com';
285                         $ok = mid_set($self, $skip_artnum, $mid);
286                         if ($ok) {
287                                 mid_delete($self, $mid);
288                                 last;
289                         }
290                 }
291                 $ok or die '--skip-artnum failed';
292
293                 # in the future, the indexer may use this value for
294                 # new messages in old epochs
295                 meta_accessor($self, 'skip_artnum', $skip_artnum);
296         }
297 }
298
299 1;