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