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