]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
msgmap: note how we use ->created_at
[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 (v1) and ::V2Writable (v2)
10 package PublicInbox::Msgmap;
11 use strict;
12 use v5.10.1;
13 use DBI;
14 use DBD::SQLite;
15 use PublicInbox::Over;
16 use PublicInbox::Spawn;
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                 $dbh->begin_work;
36                 create_tables($dbh);
37                 $self->created_at(time) unless $self->created_at;
38
39                 my $max = $self->max // 0;
40                 $self->num_highwater($max);
41                 $dbh->commit;
42         }
43         $self;
44 }
45
46 # used to keep track of used numeric mappings for v2 reindex
47 sub tmp_clone {
48         my ($self, $dir) = @_;
49         require File::Temp;
50         my $tmp = "mm_tmp-$$-XXXXXX";
51         my ($fh, $fn) = File::Temp::tempfile($tmp, EXLOCK => 0, DIR => $dir);
52         PublicInbox::Spawn::nodatacow_fd(fileno($fh));
53         $self->{dbh}->sqlite_backup_to_file($fn);
54         $tmp = ref($self)->new_file($fn, 2);
55         $tmp->{dbh}->do('PRAGMA journal_mode = MEMORY');
56         $tmp->{pid} = $$;
57         $tmp;
58 }
59
60 # n.b. invoked directly by scripts/xhdr-num2mid
61 sub meta_accessor {
62         my ($self, $key, $value) = @_;
63
64         my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
65         my $dbh = $self->{dbh};
66         my $prev;
67         defined $value or return $dbh->selectrow_array($sql, undef, $key);
68
69         $prev = $dbh->selectrow_array($sql, undef, $key);
70
71         if (defined $prev) {
72                 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
73                 $dbh->do($sql, undef, $value, $key);
74         } else {
75                 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
76                 $dbh->do($sql, undef, $key, $value);
77         }
78         $prev;
79 }
80
81 sub last_commit {
82         my ($self, $commit) = @_;
83         $self->meta_accessor('last_commit', $commit);
84 }
85
86 # v2 uses this to keep track of how up-to-date Xapian is
87 # old versions may be automatically GC'ed away in the future,
88 # but it's a trivial amount of storage.
89 sub last_commit_xap {
90         my ($self, $version, $i, $commit) = @_;
91         $self->meta_accessor("last_xap$version-$i", $commit);
92 }
93
94 # this is the UIDVALIDITY for IMAP (cf. RFC 3501 sec 2.3.1.1. item 3)
95 sub created_at {
96         my ($self, $second) = @_;
97         $self->meta_accessor('created_at', $second);
98 }
99
100 sub num_highwater {
101         my ($self, $num) = @_;
102         my $high = $self->{num_highwater} ||=
103             $self->meta_accessor('num_highwater');
104         if (defined($num) && (!defined($high) || ($num > $high))) {
105                 $self->{num_highwater} = $num;
106                 $self->meta_accessor('num_highwater', $num);
107         }
108         $self->{num_highwater};
109 }
110
111 sub mid_insert {
112         my ($self, $mid) = @_;
113         my $dbh = $self->{dbh};
114         my $sth = $dbh->prepare_cached(<<'');
115 INSERT INTO msgmap (mid) VALUES (?)
116
117         return unless eval { $sth->execute($mid) };
118         my $num = $dbh->last_insert_id(undef, undef, 'msgmap', 'num');
119         $self->num_highwater($num) if defined($num);
120         $num;
121 }
122
123 sub mid_for {
124         my ($self, $num) = @_;
125         my $dbh = $self->{dbh};
126         my $sth = $self->{mid_for} ||=
127                 $dbh->prepare('SELECT mid FROM msgmap WHERE num = ? LIMIT 1');
128         $sth->bind_param(1, $num);
129         $sth->execute;
130         $sth->fetchrow_array;
131 }
132
133 sub num_for {
134         my ($self, $mid) = @_;
135         my $dbh = $self->{dbh};
136         my $sth = $self->{num_for} ||=
137                 $dbh->prepare('SELECT num FROM msgmap WHERE mid = ? LIMIT 1');
138         $sth->bind_param(1, $mid);
139         $sth->execute;
140         $sth->fetchrow_array;
141 }
142
143 sub max {
144         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
145                                                 undef, 1);
146         $sth->execute;
147         $sth->fetchrow_array;
148 }
149
150 sub minmax {
151         # breaking MIN and MAX into separate queries speeds up from 250ms
152         # to around 700us with 2.7million messages.
153         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MIN(num) FROM msgmap',
154                                                 undef, 1);
155         $sth->execute;
156         ($sth->fetchrow_array, max($_[0]));
157 }
158
159 sub mid_delete {
160         my ($self, $mid) = @_;
161         my $dbh = $self->{dbh};
162         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
163         $sth->bind_param(1, $mid);
164         $sth->execute;
165 }
166
167 sub num_delete {
168         my ($self, $num) = @_;
169         my $dbh = $self->{dbh};
170         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
171         $sth->bind_param(1, $num);
172         $sth->execute;
173 }
174
175 sub create_tables {
176         my ($dbh) = @_;
177
178         $dbh->do(<<'');
179 CREATE TABLE IF NOT EXISTS msgmap (
180         num INTEGER PRIMARY KEY AUTOINCREMENT,
181         mid VARCHAR(1000) NOT NULL,
182         UNIQUE (mid)
183 )
184
185         $dbh->do(<<'');
186 CREATE TABLE IF NOT EXISTS meta (
187         key VARCHAR(32) PRIMARY KEY,
188         val VARCHAR(255) NOT NULL
189 )
190
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 'BUG: not a temporary clone';
242         $self->{dbh} and die 'BUG: tmp_clone dbh not prepared for parent';
243         defined($self->{filename}) or die 'BUG: {filename} not defined';
244         $self->{dbh} = PublicInbox::Over::dbh_new($self, 2);
245         $self->{dbh}->do('PRAGMA journal_mode = MEMORY');
246 }
247
248 sub atfork_prepare {
249         my ($self) = @_;
250         my $pid = $self->{pid} or die 'BUG: not a temporary clone';
251         $pid == $$ or die "BUG: atfork_prepare not called by $pid";
252         my $dbh = $self->{dbh} or die 'BUG: temporary clone not open';
253
254         # must clobber prepared statements
255         %$self = (filename => $dbh->sqlite_db_filename, pid => $pid);
256 }
257
258 sub skip_artnum {
259         my ($self, $skip_artnum) = @_;
260         return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
261
262         my $cur = num_highwater($self) // 0;
263         if ($skip_artnum < $cur) {
264                 die "E: current article number $cur ",
265                         "exceeds --skip-artnum=$skip_artnum\n";
266         } else {
267                 my $ok;
268                 for (1..10) {
269                         my $mid = 'skip'.rand.'@'.rand.'.example.com';
270                         $ok = mid_set($self, $skip_artnum, $mid);
271                         if ($ok) {
272                                 mid_delete($self, $mid);
273                                 last;
274                         }
275                 }
276                 $ok or die '--skip-artnum failed';
277
278                 # in the future, the indexer may use this value for
279                 # new messages in old epochs
280                 meta_accessor($self, 'skip_artnum', $skip_artnum);
281         }
282 }
283
284 sub check_inodes {
285         my ($self) = @_;
286         # no filename if in-:memory:
287         my $f = $self->{dbh}->sqlite_db_filename // return;
288         if (my @st = stat($f)) { # did st_dev, st_ino change?
289                 my $st = pack('dd', $st[0], $st[1]);
290                 if ($st ne ($self->{st} // $st)) {
291                         my $tmp = eval { ref($self)->new_file($f) };
292                         if ($@) {
293                                 warn "E: DBI->connect($f): $@\n";
294                         } else {
295                                 %$self = %$tmp;
296                         }
297                 }
298         } else {
299                 warn "W: stat $f: $!\n";
300         }
301 }
302
303 1;