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