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