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