]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
treewide: run update-copyrights from gnulib for 2019
[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                 $dbh->begin_work;
52                 $self->created_at(time) unless $self->created_at;
53
54                 my (undef, $max) = $self->minmax();
55                 $max ||= 0;
56                 $self->num_highwater($max);
57                 $dbh->commit;
58         }
59         $self;
60 }
61
62 # used to keep track of used numeric mappings for v2 reindex
63 sub tmp_clone {
64         my ($self) = @_;
65         my ($fh, $fn) = tempfile('msgmap-XXXXXXXX', EXLOCK => 0, TMPDIR => 1);
66         $self->{dbh}->sqlite_backup_to_file($fn);
67         my $tmp = ref($self)->new_file($fn, 1);
68         $tmp->{dbh}->do('PRAGMA synchronous = OFF');
69         $tmp->{tmp_name} = $fn; # SQLite won't work if unlinked, apparently
70         $tmp->{pid} = $$;
71         close $fh or die "failed to close $fn: $!";
72         $tmp;
73 }
74
75 # n.b. invoked directly by scripts/xhdr-num2mid
76 sub meta_accessor {
77         my ($self, $key, $value) = @_;
78
79         my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
80         my $dbh = $self->{dbh};
81         my $prev;
82         defined $value or return $dbh->selectrow_array($sql, undef, $key);
83
84         $prev = $dbh->selectrow_array($sql, undef, $key);
85
86         if (defined $prev) {
87                 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
88                 $dbh->do($sql, undef, $value, $key);
89         } else {
90                 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
91                 $dbh->do($sql, undef, $key, $value);
92         }
93         $prev;
94 }
95
96 sub last_commit {
97         my ($self, $commit) = @_;
98         $self->meta_accessor('last_commit', $commit);
99 }
100
101 # v2 uses this to keep track of how up-to-date Xapian is
102 # old versions may be automatically GC'ed away in the future,
103 # but it's a trivial amount of storage.
104 sub last_commit_xap {
105         my ($self, $version, $i, $commit) = @_;
106         $self->meta_accessor("last_xap$version-$i", $commit);
107 }
108
109 sub created_at {
110         my ($self, $second) = @_;
111         $self->meta_accessor('created_at', $second);
112 }
113
114 sub num_highwater {
115         my ($self, $num) = @_;
116         my $high = $self->{num_highwater} ||=
117             $self->meta_accessor('num_highwater');
118         if (defined($num) && (!defined($high) || ($num > $high))) {
119                 $self->{num_highwater} = $num;
120                 $self->meta_accessor('num_highwater', $num);
121         }
122         $self->{num_highwater};
123 }
124
125 sub mid_insert {
126         my ($self, $mid) = @_;
127         my $dbh = $self->{dbh};
128         my $sth = $dbh->prepare_cached(<<'');
129 INSERT INTO msgmap (mid) VALUES (?)
130
131         return unless eval { $sth->execute($mid) };
132         my $num = $dbh->last_insert_id(undef, undef, 'msgmap', 'num');
133         $self->num_highwater($num) if defined($num);
134         $num;
135 }
136
137 sub mid_for {
138         my ($self, $num) = @_;
139         my $dbh = $self->{dbh};
140         my $sth = $self->{mid_for} ||=
141                 $dbh->prepare('SELECT mid FROM msgmap WHERE num = ? LIMIT 1');
142         $sth->bind_param(1, $num);
143         $sth->execute;
144         $sth->fetchrow_array;
145 }
146
147 sub num_for {
148         my ($self, $mid) = @_;
149         my $dbh = $self->{dbh};
150         my $sth = $self->{num_for} ||=
151                 $dbh->prepare('SELECT num FROM msgmap WHERE mid = ? LIMIT 1');
152         $sth->bind_param(1, $mid);
153         $sth->execute;
154         $sth->fetchrow_array;
155 }
156
157 sub minmax {
158         my ($self) = @_;
159         my $dbh = $self->{dbh};
160         # breaking MIN and MAX into separate queries speeds up from 250ms
161         # to around 700us with 2.7million messages.
162         my $sth = $dbh->prepare_cached('SELECT MIN(num) FROM msgmap', undef, 1);
163         $sth->execute;
164         my $min = $sth->fetchrow_array;
165         $sth = $dbh->prepare_cached('SELECT MAX(num) FROM msgmap', undef, 1);
166         $sth->execute;
167         ($min, $sth->fetchrow_array);
168 }
169
170 sub mid_delete {
171         my ($self, $mid) = @_;
172         my $dbh = $self->{dbh};
173         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
174         $sth->bind_param(1, $mid);
175         $sth->execute;
176 }
177
178 sub num_delete {
179         my ($self, $num) = @_;
180         my $dbh = $self->{dbh};
181         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
182         $sth->bind_param(1, $num);
183         $sth->execute;
184 }
185
186 sub create_tables {
187         my ($dbh) = @_;
188         my $e;
189
190         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM msgmap;') };
191         defined $e or $dbh->do('CREATE TABLE msgmap (' .
192                         'num INTEGER PRIMARY KEY AUTOINCREMENT, '.
193                         'mid VARCHAR(1000) NOT NULL, ' .
194                         'UNIQUE (mid) )');
195
196         $e = eval { $dbh->selectrow_array('EXPLAIN SELECT * FROM meta') };
197         defined $e or $dbh->do('CREATE TABLE meta (' .
198                         'key VARCHAR(32) PRIMARY KEY, '.
199                         'val VARCHAR(255) NOT NULL)');
200 }
201
202 # used by NNTP.pm
203 sub ids_after {
204         my ($self, $num) = @_;
205         my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
206 SELECT num FROM msgmap WHERE num > ?
207 ORDER BY num ASC LIMIT 1000
208
209         $$num = $ids->[-1] if @$ids;
210         $ids;
211 }
212
213 sub msg_range {
214         my ($self, $beg, $end, $cols) = @_;
215         $cols //= 'num,mid';
216         my $dbh = $self->{dbh};
217         my $attr = { Columns => [] };
218         my $mids = $dbh->selectall_arrayref(<<"", $attr, $$beg, $end);
219 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
220 ORDER BY num ASC LIMIT 1000
221
222         $$beg = $mids->[-1]->[0] + 1 if @$mids;
223         $mids
224 }
225
226 # only used for mapping external serial numbers (e.g. articles from gmane)
227 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
228 sub mid_set {
229         my ($self, $num, $mid) = @_;
230         my $sth = $self->{mid_set} ||= do {
231                 $self->{dbh}->prepare(
232                         'INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)');
233         };
234         my $result = $sth->execute($num, $mid);
235         $self->num_highwater($num) if (defined($result) && $result == 1);
236         $result;
237 }
238
239 sub DESTROY {
240         my ($self) = @_;
241         delete $self->{dbh};
242         my $f = delete $self->{tmp_name};
243         if (defined $f && $self->{pid} == $$) {
244                 unlink $f or warn "failed to unlink $f: $!\n";
245         }
246 }
247
248 sub atfork_parent {
249         my ($self) = @_;
250         my $f = $self->{tmp_name} or die "not a temporary clone\n";
251         delete $self->{dbh} and die "tmp_clone dbh not prepared for parent";
252         my $dbh = $self->{dbh} = dbh_new($f, 1);
253         $dbh->do('PRAGMA synchronous = OFF');
254 }
255
256 sub atfork_prepare {
257         my ($self) = @_;
258         my $f = $self->{tmp_name} or die "not a temporary clone\n";
259         $self->{pid} == $$ or
260                 die "BUG: atfork_prepare not called from $self->{pid}\n";
261         $self->{dbh} or die "temporary clone not open\n";
262         # must clobber prepared statements
263         %$self = (tmp_name => $f, pid => $$);
264 }
265
266 1;