]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
rewrite Linux nodatacow use in pure Perl w/o system
[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 minmax {
148         # breaking MIN and MAX into separate queries speeds up from 250ms
149         # to around 700us with 2.7million messages.
150         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MIN(num) FROM msgmap',
151                                                 undef, 1);
152         $sth->execute;
153         ($sth->fetchrow_array // 0, max($_[0]));
154 }
155
156 sub mid_delete {
157         my ($self, $mid) = @_;
158         $self->{dbh}->do('DELETE FROM msgmap WHERE mid = ?', undef, $mid);
159 }
160
161 sub num_delete {
162         my ($self, $num) = @_;
163         $self->{dbh}->do('DELETE FROM msgmap WHERE num = ?', undef, $num);
164 }
165
166 sub create_tables {
167         my ($dbh) = @_;
168
169         $dbh->do(<<'');
170 CREATE TABLE IF NOT EXISTS msgmap (
171         num INTEGER PRIMARY KEY AUTOINCREMENT,
172         mid VARCHAR(1000) NOT NULL,
173         UNIQUE (mid)
174 )
175
176         $dbh->do(<<'');
177 CREATE TABLE IF NOT EXISTS meta (
178         key VARCHAR(32) PRIMARY KEY,
179         val VARCHAR(255) NOT NULL
180 )
181
182 }
183
184 sub msg_range {
185         my ($self, $beg, $end, $cols) = @_;
186         $cols //= 'num,mid';
187         my $attr = { Columns => [] };
188         my $mids = $self->{dbh}->selectall_arrayref(<<"", $attr, $$beg, $end);
189 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
190 ORDER BY num ASC LIMIT 1000
191
192         $$beg = $mids->[-1]->[0] + 1 if @$mids;
193         $mids
194 }
195
196 # only used for mapping external serial numbers (e.g. articles from gmane)
197 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
198 sub mid_set {
199         my ($self, $num, $mid) = @_;
200         my $sth = $self->{dbh}->prepare_cached(<<"");
201 INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)
202
203         my $result = $sth->execute($num, $mid);
204         $self->num_highwater($num) if (defined($result) && $result == 1);
205         $result;
206 }
207
208 sub DESTROY {
209         my ($self) = @_;
210         my $dbh = $self->{dbh} or return;
211         if (($self->{pid} // 0) == $$) {
212                 my $f = $dbh->sqlite_db_filename;
213                 unlink $f or warn "failed to unlink $f: $!\n";
214         }
215 }
216
217 sub atfork_parent {
218         my ($self) = @_;
219         $self->{pid} or die 'BUG: not a temporary clone';
220         $self->{dbh} and die 'BUG: tmp_clone dbh not prepared for parent';
221         defined($self->{filename}) or die 'BUG: {filename} not defined';
222         $self->{dbh} = PublicInbox::Over::dbh_new($self, 2);
223         $self->{dbh}->do('PRAGMA journal_mode = MEMORY');
224 }
225
226 sub atfork_prepare {
227         my ($self) = @_;
228         my $pid = $self->{pid} or die 'BUG: not a temporary clone';
229         $pid == $$ or die "BUG: atfork_prepare not called by $pid";
230         my $dbh = $self->{dbh} or die 'BUG: temporary clone not open';
231
232         # must clobber prepared statements
233         %$self = (filename => $dbh->sqlite_db_filename, pid => $pid);
234 }
235
236 sub skip_artnum {
237         my ($self, $skip_artnum) = @_;
238         return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
239
240         my $cur = num_highwater($self) // 0;
241         if ($skip_artnum < $cur) {
242                 die "E: current article number $cur ",
243                         "exceeds --skip-artnum=$skip_artnum\n";
244         } else {
245                 my $ok;
246                 for (1..10) {
247                         my $mid = 'skip'.rand.'@'.rand.'.example.com';
248                         $ok = mid_set($self, $skip_artnum, $mid);
249                         if ($ok) {
250                                 mid_delete($self, $mid);
251                                 last;
252                         }
253                 }
254                 $ok or die '--skip-artnum failed';
255
256                 # in the future, the indexer may use this value for
257                 # new messages in old epochs
258                 meta_accessor($self, 'skip_artnum', $skip_artnum);
259         }
260 }
261
262 sub check_inodes {
263         my ($self) = @_;
264         $self->{dbh} // return;
265         my $rw = !$self->{dbh}->{ReadOnly};
266         PublicInbox::Over::check_inodes($self);
267         $self->{dbh} //= PublicInbox::Over::dbh_new($self, !$rw);
268 }
269
270 1;