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>
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.
9 # This is maintained by ::SearchIdx
10 package PublicInbox::Msgmap;
15 use File::Temp qw(tempfile);
18 my ($class, $git_dir, $writable) = @_;
19 my $d = "$git_dir/public-inbox";
20 if ($writable && !-d $d && !mkdir $d) {
22 -d $d or die "$d not created: $err";
24 new_file($class, "$d/msgmap.sqlite3", $writable);
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: $!";
32 my $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
36 ReadOnly => !$writable,
37 sqlite_use_immediate_transaction => 1,
43 my ($class, $f, $writable) = @_;
44 return if !$writable && !-r $f;
46 my $dbh = dbh_new($f, $writable);
47 my $self = bless { dbh => $dbh }, $class;
52 # TRUNCATE reduces I/O compared to the default (DELETE)
53 $dbh->do('PRAGMA journal_mode = TRUNCATE');
56 $self->created_at(time) unless $self->created_at;
58 my $max = $self->max // 0;
59 $self->num_highwater($max);
65 # used to keep track of used numeric mappings for v2 reindex
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
75 close $fh or die "failed to close $fn: $!";
79 # n.b. invoked directly by scripts/xhdr-num2mid
81 my ($self, $key, $value) = @_;
83 my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
84 my $dbh = $self->{dbh};
86 defined $value or return $dbh->selectrow_array($sql, undef, $key);
88 $prev = $dbh->selectrow_array($sql, undef, $key);
91 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
92 $dbh->do($sql, undef, $value, $key);
94 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
95 $dbh->do($sql, undef, $key, $value);
101 my ($self, $commit) = @_;
102 $self->meta_accessor('last_commit', $commit);
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);
114 my ($self, $second) = @_;
115 $self->meta_accessor('created_at', $second);
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);
126 $self->{num_highwater};
130 my ($self, $mid) = @_;
131 my $dbh = $self->{dbh};
132 my $sth = $dbh->prepare_cached(<<'');
133 INSERT INTO msgmap (mid) VALUES (?)
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);
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);
148 $sth->fetchrow_array;
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);
158 $sth->fetchrow_array;
162 my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
165 $sth->fetchrow_array;
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',
174 ($sth->fetchrow_array, max($_[0]));
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);
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);
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, ' .
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)');
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
216 $$num = $ids->[-1] if @$ids;
221 my ($self, $beg, $end, $cols) = @_;
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
229 $$beg = $mids->[-1]->[0] + 1 if @$mids;
233 # only used for mapping external serial numbers (e.g. articles from gmane)
234 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
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 (?,?)');
241 my $result = $sth->execute($num, $mid);
242 $self->num_highwater($num) if (defined($result) && $result == 1);
249 my $f = delete $self->{tmp_name};
250 if (defined $f && $self->{pid} == $$) {
251 unlink $f or warn "failed to unlink $f: $!\n";
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');
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 => $$);