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);
16 use PublicInbox::Over;
17 use PublicInbox::Spawn;
20 my ($class, $git_dir, $writable) = @_;
21 my $d = "$git_dir/public-inbox";
22 if ($writable && !-d $d && !mkdir $d) {
24 -d $d or die "$d not created: $err";
26 new_file($class, "$d/msgmap.sqlite3", $writable);
30 my ($class, $f, $rw) = @_;
31 return if !$rw && !-r $f;
33 my $self = bless { filename => $f }, $class;
34 my $dbh = $self->{dbh} = PublicInbox::Over::dbh_new($self, $rw);
36 # TRUNCATE reduces I/O compared to the default (DELETE)
37 $dbh->do('PRAGMA journal_mode = TRUNCATE');
41 $self->created_at(time) unless $self->created_at;
43 my $max = $self->max // 0;
44 $self->num_highwater($max);
50 # used to keep track of used numeric mappings for v2 reindex
52 my ($self, $dir) = @_;
53 my ($fh, $fn) = tempfile('msgmap-XXXXXXXX', EXLOCK => 0, DIR => $dir);
54 PublicInbox::Spawn::set_nodatacow(fileno($fh));
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');
69 # n.b. invoked directly by scripts/xhdr-num2mid
71 my ($self, $key, $value) = @_;
73 my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
74 my $dbh = $self->{dbh};
76 defined $value or return $dbh->selectrow_array($sql, undef, $key);
78 $prev = $dbh->selectrow_array($sql, undef, $key);
81 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
82 $dbh->do($sql, undef, $value, $key);
84 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
85 $dbh->do($sql, undef, $key, $value);
91 my ($self, $commit) = @_;
92 $self->meta_accessor('last_commit', $commit);
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.
99 my ($self, $version, $i, $commit) = @_;
100 $self->meta_accessor("last_xap$version-$i", $commit);
104 my ($self, $second) = @_;
105 $self->meta_accessor('created_at', $second);
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);
116 $self->{num_highwater};
120 my ($self, $mid) = @_;
121 my $dbh = $self->{dbh};
122 my $sth = $dbh->prepare_cached(<<'');
123 INSERT INTO msgmap (mid) VALUES (?)
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);
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);
138 $sth->fetchrow_array;
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);
148 $sth->fetchrow_array;
152 my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
155 $sth->fetchrow_array;
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',
164 ($sth->fetchrow_array, max($_[0]));
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);
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);
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, ' .
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)');
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
206 $$num = $ids->[-1] if @$ids;
211 my ($self, $beg, $end, $cols) = @_;
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
219 $$beg = $mids->[-1]->[0] + 1 if @$mids;
223 # only used for mapping external serial numbers (e.g. articles from gmane)
224 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
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 (?,?)');
231 my $result = $sth->execute($num, $mid);
232 $self->num_highwater($num) if (defined($result) && $result == 1);
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";
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 $self->{dbh}->do('PRAGMA journal_mode = MEMORY');
256 my $pid = $self->{pid} or die 'BUG: not a temporary clone';
257 $pid == $$ or die "BUG: atfork_prepare not called by $pid";
258 my $dbh = $self->{dbh} or die 'BUG: temporary clone not open';
260 # must clobber prepared statements
261 %$self = (filename => $dbh->sqlite_db_filename, pid => $pid);
265 my ($self, $skip_artnum) = @_;
266 return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
268 my $cur = num_highwater($self) // 0;
269 if ($skip_artnum < $cur) {
270 die "E: current article number $cur ",
271 "exceeds --skip-artnum=$skip_artnum\n";
275 my $mid = 'skip'.rand.'@'.rand.'.example.com';
276 $ok = mid_set($self, $skip_artnum, $mid);
278 mid_delete($self, $mid);
282 $ok or die '--skip-artnum failed';
284 # in the future, the indexer may use this value for
285 # new messages in old epochs
286 meta_accessor($self, 'skip_artnum', $skip_artnum);
292 # no filename if in-:memory:
293 my $f = $self->{dbh}->sqlite_db_filename // return;
294 if (my @st = stat($f)) { # did st_dev, st_ino change?
295 my $st = pack('dd', $st[0], $st[1]);
296 if ($st ne ($self->{st} // $st)) {
297 my $tmp = eval { ref($self)->new_file($f) };
299 warn "E: DBI->connect($f): $@\n";
305 warn "W: stat $f: $!\n";