]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/OverIdx.pm
overidx: document the SQLite PRAGMA we use
[public-inbox.git] / lib / PublicInbox / OverIdx.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # for XOVER, OVER in NNTP, and feeds/homepage/threads in PSGI
5 # Unlike Msgmap, this is an _UNSTABLE_ cache which can be
6 # tweaked/updated over time and rebuilt.
7 #
8 # Ghost messages (messages which are only referenced in References/In-Reply-To)
9 # are denoted by a negative NNTP article number.
10 package PublicInbox::OverIdx;
11 use strict;
12 use warnings;
13 use base qw(PublicInbox::Over);
14 use IO::Handle;
15 use DBI qw(:sql_types); # SQL_BLOB
16 use PublicInbox::MID qw/id_compress mids_for_index references/;
17 use PublicInbox::Smsg qw(subject_normalized);
18 use Compress::Zlib qw(compress);
19 use PublicInbox::Search;
20
21 sub dbh_new {
22         my ($self) = @_;
23         my $dbh = $self->SUPER::dbh_new(1);
24
25         # TRUNCATE reduces I/O compared to the default (DELETE)
26         $dbh->do('PRAGMA journal_mode = TRUNCATE');
27
28         # 80000 pages (80MiB on SQLite <3.12.0, 320MiB on 3.12.0+)
29         # was found to be good in 2018 during the large LKML import
30         # at the time.  This ought to be configurable based on HW
31         # and inbox size; I suspect it's overkill for many inboxes.
32         $dbh->do('PRAGMA cache_size = 80000');
33
34         create_tables($dbh);
35         $dbh;
36 }
37
38 sub get_counter ($$) {
39         my ($dbh, $key) = @_;
40         my $sth = $dbh->prepare_cached(<<'', undef, 1);
41 SELECT val FROM counter WHERE key = ? LIMIT 1
42
43         $sth->execute($key);
44         $sth->fetchrow_array;
45 }
46
47 sub adj_counter ($$$) {
48         my ($self, $key, $op) = @_;
49         my $dbh = $self->{dbh};
50         my $sth = $dbh->prepare_cached(<<"");
51 UPDATE counter SET val = val $op 1 WHERE key = ?
52
53         $sth->execute($key);
54
55         get_counter($dbh, $key);
56 }
57
58 sub next_tid { adj_counter($_[0], 'thread', '+') }
59 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
60
61 sub id_for ($$$$$) {
62         my ($self, $tbl, $id_col, $val_col, $val) = @_;
63         my $dbh = $self->{dbh};
64         my $in = $dbh->prepare_cached(<<"")->execute($val);
65 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
66
67         if ($in == 0) {
68                 my $sth = $dbh->prepare_cached(<<"", undef, 1);
69 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
70
71                 $sth->execute($val);
72                 $sth->fetchrow_array;
73         } else {
74                 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
75         }
76 }
77
78 sub sid {
79         my ($self, $path) = @_;
80         return unless defined $path && $path ne '';
81         id_for($self, 'subject', 'sid', 'path' => $path);
82 }
83
84 sub mid2id {
85         my ($self, $mid) = @_;
86         id_for($self, 'msgid', 'id', 'mid' => $mid);
87 }
88
89 sub delete_by_num {
90         my ($self, $num, $tid_ref) = @_;
91         my $dbh = $self->{dbh};
92         if ($tid_ref) {
93                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
94 SELECT tid FROM over WHERE num = ? LIMIT 1
95
96                 $sth->execute($num);
97                 $$tid_ref = $sth->fetchrow_array; # may be undef
98         }
99         foreach (qw(over id2num)) {
100                 $dbh->prepare_cached(<<"")->execute($num);
101 DELETE FROM $_ WHERE num = ?
102
103         }
104 }
105
106 # this includes ghosts
107 sub each_by_mid {
108         my ($self, $mid, $cols, $cb) = @_;
109         my $dbh = $self->{dbh};
110
111 =over
112         I originally wanted to stuff everything into a single query:
113
114         SELECT over.* FROM over
115         LEFT JOIN id2num ON over.num = id2num.num
116         LEFT JOIN msgid ON msgid.id = id2num.id
117         WHERE msgid.mid = ? AND over.num >= ?
118         ORDER BY over.num ASC
119         LIMIT 1000
120
121         But it's faster broken out (and we're always in a
122         transaction for subroutines in this file)
123 =cut
124
125         my $sth = $dbh->prepare_cached(<<'', undef, 1);
126 SELECT id FROM msgid WHERE mid = ? LIMIT 1
127
128         $sth->execute($mid);
129         my $id = $sth->fetchrow_array;
130         defined $id or return;
131
132         push(@$cols, 'num');
133         $cols = join(',', map { $_ } @$cols);
134         my $lim = 10;
135         my $prev = get_counter($dbh, 'ghost');
136         while (1) {
137                 $sth = $dbh->prepare_cached(<<"", undef, 1);
138 SELECT num FROM id2num WHERE id = ? AND num >= ?
139 ORDER BY num ASC
140 LIMIT $lim
141
142                 $sth->execute($id, $prev);
143                 my $nums = $sth->fetchall_arrayref;
144                 my $nr = scalar(@$nums) or return;
145                 $prev = $nums->[-1]->[0];
146
147                 $sth = $dbh->prepare_cached(<<"", undef, 1);
148 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
149
150                 foreach (@$nums) {
151                         $sth->execute($_->[0]);
152                         my $smsg = $sth->fetchrow_hashref;
153                         $cb->(PublicInbox::Over::load_from_row($smsg)) or
154                                 return;
155                 }
156                 return if $nr != $lim;
157         }
158 }
159
160 # this will create a ghost as necessary
161 sub resolve_mid_to_tid {
162         my ($self, $mid) = @_;
163         my $tid;
164         each_by_mid($self, $mid, ['tid'], sub {
165                 my ($smsg) = @_;
166                 my $cur_tid = $smsg->{tid};
167                 if (defined $tid) {
168                         merge_threads($self, $tid, $cur_tid);
169                 } else {
170                         $tid = $cur_tid;
171                 }
172                 1;
173         });
174         defined $tid ? $tid : create_ghost($self, $mid);
175 }
176
177 sub create_ghost {
178         my ($self, $mid) = @_;
179         my $id = $self->mid2id($mid);
180         my $num = $self->next_ghost_num;
181         $num < 0 or die "ghost num is non-negative: $num\n";
182         my $tid = $self->next_tid;
183         my $dbh = $self->{dbh};
184         $dbh->prepare_cached(<<'')->execute($num, $tid);
185 INSERT INTO over (num, tid) VALUES (?,?)
186
187         $dbh->prepare_cached(<<'')->execute($id, $num);
188 INSERT INTO id2num (id, num) VALUES (?,?)
189
190         $tid;
191 }
192
193 sub merge_threads {
194         my ($self, $winner_tid, $loser_tid) = @_;
195         return if $winner_tid == $loser_tid;
196         my $dbh = $self->{dbh};
197         $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
198 UPDATE over SET tid = ? WHERE tid = ?
199
200 }
201
202 sub link_refs {
203         my ($self, $refs, $old_tid) = @_;
204         my $tid;
205
206         if (@$refs) {
207                 # first ref *should* be the thread root,
208                 # but we can never trust clients to do the right thing
209                 my $ref = $refs->[0];
210                 $tid = resolve_mid_to_tid($self, $ref);
211                 merge_threads($self, $tid, $old_tid) if defined $old_tid;
212
213                 # the rest of the refs should point to this tid:
214                 foreach my $i (1..$#$refs) {
215                         $ref = $refs->[$i];
216                         my $ptid = resolve_mid_to_tid($self, $ref);
217                         merge_threads($self, $tid, $ptid);
218                 }
219         } else {
220                 $tid = defined $old_tid ? $old_tid : $self->next_tid;
221         }
222         $tid;
223 }
224
225 sub parse_references ($$$) {
226         my ($smsg, $hdr, $mids) = @_;
227         my $refs = references($hdr);
228         push(@$refs, @$mids) if scalar(@$mids) > 1;
229         return $refs if scalar(@$refs) == 0;
230
231         # prevent circular references here:
232         my %seen = ( $smsg->{mid} => 1 );
233         my @keep;
234         foreach my $ref (@$refs) {
235                 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
236                         warn "References: <$ref> too long, ignoring\n";
237                         next;
238                 }
239                 push(@keep, $ref) unless $seen{$ref}++;
240         }
241         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
242         \@keep;
243 }
244
245 # normalize subjects so they are suitable as pathnames for URLs
246 # XXX: consider for removal
247 sub subject_path ($) {
248         my ($subj) = @_;
249         $subj = subject_normalized($subj);
250         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
251         lc($subj);
252 }
253
254 sub add_overview {
255         my ($self, $mime, $smsg) = @_;
256         $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
257         $smsg->{mime} = $mime; # XXX temporary?
258         my $hdr = $mime->header_obj;
259         my $mids = mids_for_index($hdr);
260         my $refs = parse_references($smsg, $hdr, $mids);
261         my $subj = $smsg->subject;
262         my $xpath;
263         if ($subj ne '') {
264                 $xpath = subject_path($subj);
265                 $xpath = id_compress($xpath);
266         }
267         my $dd = $smsg->to_doc_data;
268         utf8::encode($dd);
269         $dd = compress($dd);
270         add_over($self, [ @$smsg{qw(ts ds num)}, $mids, $refs, $xpath, $dd ]);
271 }
272
273 sub add_over {
274         my ($self, $values) = @_;
275         my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
276         my $old_tid;
277         my $vivified = 0;
278
279         $self->begin_lazy;
280         $self->delete_by_num($num, \$old_tid);
281         foreach my $mid (@$mids) {
282                 my $v = 0;
283                 each_by_mid($self, $mid, ['tid'], sub {
284                         my ($cur) = @_;
285                         my $cur_tid = $cur->{tid};
286                         my $n = $cur->{num};
287                         die "num must not be zero for $mid" if !$n;
288                         $old_tid = $cur_tid unless defined $old_tid;
289                         if ($n > 0) { # regular mail
290                                 merge_threads($self, $old_tid, $cur_tid);
291                         } elsif ($n < 0) { # ghost
292                                 link_refs($self, $refs, $old_tid);
293                                 $self->delete_by_num($n);
294                                 $v++;
295                         }
296                         1;
297                 });
298                 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
299                 $vivified += $v;
300         }
301         my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
302         my $sid = $self->sid($xpath);
303         my $dbh = $self->{dbh};
304         my $sth = $dbh->prepare_cached(<<'');
305 INSERT INTO over (num, tid, sid, ts, ds, ddd)
306 VALUES (?,?,?,?,?,?)
307
308         my $n = 0;
309         my @v = ($num, $tid, $sid, $ts, $ds);
310         foreach (@v) { $sth->bind_param(++$n, $_) }
311         $sth->bind_param(++$n, $ddd, SQL_BLOB);
312         $sth->execute;
313         $sth = $dbh->prepare_cached(<<'');
314 INSERT INTO id2num (id, num) VALUES (?,?)
315
316         foreach my $mid (@$mids) {
317                 my $id = $self->mid2id($mid);
318                 $sth->execute($id, $num);
319         }
320 }
321
322 # returns number of removed messages
323 # $oid may be undef to match only on $mid
324 sub remove_oid {
325         my ($self, $oid, $mid) = @_;
326         my $nr = 0;
327         $self->begin_lazy;
328         each_by_mid($self, $mid, ['ddd'], sub {
329                 my ($smsg) = @_;
330                 if (!defined($oid) || $smsg->{blob} eq $oid) {
331                         $self->delete_by_num($smsg->{num});
332                         $nr++;
333                 }
334                 1;
335         });
336         $nr;
337 }
338
339 sub num_mid0_for_oid {
340         my ($self, $oid, $mid) = @_;
341         my ($num, $mid0);
342         $self->begin_lazy;
343         each_by_mid($self, $mid, ['ddd'], sub {
344                 my ($smsg) = @_;
345                 my $blob = $smsg->{blob};
346                 return 1 if (!defined($blob) || $blob ne $oid); # continue;
347                 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
348                 0; # done
349         });
350         ($num, $mid0);
351 }
352
353 sub create_tables {
354         my ($dbh) = @_;
355
356         $dbh->do(<<'');
357 CREATE TABLE IF NOT EXISTS over (
358         num INTEGER NOT NULL,
359         tid INTEGER NOT NULL,
360         sid INTEGER,
361         ts INTEGER,
362         ds INTEGER,
363         ddd VARBINARY, /* doc-data-deflated */
364         UNIQUE (num)
365 )
366
367         $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
368         $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
369         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
370         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
371
372         $dbh->do(<<'');
373 CREATE TABLE IF NOT EXISTS counter (
374         key VARCHAR(8) PRIMARY KEY NOT NULL,
375         val INTEGER DEFAULT 0,
376         UNIQUE (key)
377 )
378
379         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
380         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
381
382         $dbh->do(<<'');
383 CREATE TABLE IF NOT EXISTS subject (
384         sid INTEGER PRIMARY KEY AUTOINCREMENT,
385         path VARCHAR(40) NOT NULL,
386         UNIQUE (path)
387 )
388
389         $dbh->do(<<'');
390 CREATE TABLE IF NOT EXISTS id2num (
391         id INTEGER NOT NULL,
392         num INTEGER NOT NULL,
393         UNIQUE (id, num)
394 )
395
396         # performance critical:
397         $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
398         $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
399
400         $dbh->do(<<'');
401 CREATE TABLE IF NOT EXISTS msgid (
402         id INTEGER PRIMARY KEY AUTOINCREMENT,
403         mid VARCHAR(244) NOT NULL,
404         UNIQUE (mid)
405 )
406
407 }
408
409 sub commit_lazy {
410         my ($self) = @_;
411         delete $self->{txn} or return;
412         $self->{dbh}->commit;
413 }
414
415 sub begin_lazy {
416         my ($self) = @_;
417         return if $self->{txn};
418         my $dbh = $self->connect or return;
419         $dbh->begin_work;
420         # $dbh->{Profile} = 2;
421         $self->{txn} = 1;
422 }
423
424 sub rollback_lazy {
425         my ($self) = @_;
426         delete $self->{txn} or return;
427         $self->{dbh}->rollback;
428 }
429
430 sub disconnect {
431         my ($self) = @_;
432         die "in transaction" if $self->{txn};
433         $self->{dbh} = undef;
434 }
435
436 sub create {
437         my ($self) = @_;
438         unless (-r $self->{filename}) {
439                 require File::Path;
440                 require File::Basename;
441                 File::Path::mkpath(File::Basename::dirname($self->{filename}));
442         }
443         # create the DB:
444         PublicInbox::Over::connect($self);
445         $self->disconnect;
446 }
447
448 1;