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