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