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>
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.
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;
13 use base qw(PublicInbox::Over);
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;
23 my $dbh = $self->SUPER::dbh_new(1);
25 # TRUNCATE reduces I/O compared to the default (DELETE)
26 # We do not use WAL since we're optimized for read-only ops,
27 # (and read-only requires SQLite 3.22.0 (2018-01-22)).
28 $dbh->do('PRAGMA journal_mode = TRUNCATE');
30 # 80000 pages (80MiB on SQLite <3.12.0, 320MiB on 3.12.0+)
31 # was found to be good in 2018 during the large LKML import
32 # at the time. This ought to be configurable based on HW
33 # and inbox size; I suspect it's overkill for many inboxes.
34 $dbh->do('PRAGMA cache_size = 80000');
40 sub get_counter ($$) {
42 my $sth = $dbh->prepare_cached(<<'', undef, 1);
43 SELECT val FROM counter WHERE key = ? LIMIT 1
49 sub adj_counter ($$$) {
50 my ($self, $key, $op) = @_;
51 my $dbh = $self->{dbh};
52 my $sth = $dbh->prepare_cached(<<"");
53 UPDATE counter SET val = val $op 1 WHERE key = ?
57 get_counter($dbh, $key);
60 sub next_tid { adj_counter($_[0], 'thread', '+') }
61 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
64 my ($self, $tbl, $id_col, $val_col, $val) = @_;
65 my $dbh = $self->{dbh};
66 my $in = $dbh->prepare_cached(<<"")->execute($val);
67 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
70 my $sth = $dbh->prepare_cached(<<"", undef, 1);
71 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
76 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
81 my ($self, $path) = @_;
82 return unless defined $path && $path ne '';
83 id_for($self, 'subject', 'sid', 'path' => $path);
87 my ($self, $mid) = @_;
88 id_for($self, 'msgid', 'id', 'mid' => $mid);
92 my ($self, $num, $tid_ref) = @_;
93 my $dbh = $self->{dbh};
95 my $sth = $dbh->prepare_cached(<<'', undef, 1);
96 SELECT tid FROM over WHERE num = ? LIMIT 1
99 $$tid_ref = $sth->fetchrow_array; # may be undef
101 foreach (qw(over id2num)) {
102 $dbh->prepare_cached(<<"")->execute($num);
103 DELETE FROM $_ WHERE num = ?
108 # this includes ghosts
110 my ($self, $mid, $cols, $cb) = @_;
111 my $dbh = $self->{dbh};
114 I originally wanted to stuff everything into a single query:
116 SELECT over.* FROM over
117 LEFT JOIN id2num ON over.num = id2num.num
118 LEFT JOIN msgid ON msgid.id = id2num.id
119 WHERE msgid.mid = ? AND over.num >= ?
120 ORDER BY over.num ASC
123 But it's faster broken out (and we're always in a
124 transaction for subroutines in this file)
127 my $sth = $dbh->prepare_cached(<<'', undef, 1);
128 SELECT id FROM msgid WHERE mid = ? LIMIT 1
131 my $id = $sth->fetchrow_array;
132 defined $id or return;
135 $cols = join(',', map { $_ } @$cols);
137 my $prev = get_counter($dbh, 'ghost');
139 $sth = $dbh->prepare_cached(<<"", undef, 1);
140 SELECT num FROM id2num WHERE id = ? AND num >= ?
144 $sth->execute($id, $prev);
145 my $nums = $sth->fetchall_arrayref;
146 my $nr = scalar(@$nums) or return;
147 $prev = $nums->[-1]->[0];
149 $sth = $dbh->prepare_cached(<<"", undef, 1);
150 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
153 $sth->execute($_->[0]);
154 my $smsg = $sth->fetchrow_hashref;
155 $cb->(PublicInbox::Over::load_from_row($smsg)) or
158 return if $nr != $lim;
162 # this will create a ghost as necessary
163 sub resolve_mid_to_tid {
164 my ($self, $mid) = @_;
166 each_by_mid($self, $mid, ['tid'], sub {
168 my $cur_tid = $smsg->{tid};
170 merge_threads($self, $tid, $cur_tid);
176 defined $tid ? $tid : create_ghost($self, $mid);
180 my ($self, $mid) = @_;
181 my $id = $self->mid2id($mid);
182 my $num = $self->next_ghost_num;
183 $num < 0 or die "ghost num is non-negative: $num\n";
184 my $tid = $self->next_tid;
185 my $dbh = $self->{dbh};
186 $dbh->prepare_cached(<<'')->execute($num, $tid);
187 INSERT INTO over (num, tid) VALUES (?,?)
189 $dbh->prepare_cached(<<'')->execute($id, $num);
190 INSERT INTO id2num (id, num) VALUES (?,?)
196 my ($self, $winner_tid, $loser_tid) = @_;
197 return if $winner_tid == $loser_tid;
198 my $dbh = $self->{dbh};
199 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
200 UPDATE over SET tid = ? WHERE tid = ?
205 my ($self, $refs, $old_tid) = @_;
209 # first ref *should* be the thread root,
210 # but we can never trust clients to do the right thing
211 my $ref = $refs->[0];
212 $tid = resolve_mid_to_tid($self, $ref);
213 merge_threads($self, $tid, $old_tid) if defined $old_tid;
215 # the rest of the refs should point to this tid:
216 foreach my $i (1..$#$refs) {
218 my $ptid = resolve_mid_to_tid($self, $ref);
219 merge_threads($self, $tid, $ptid);
222 $tid = defined $old_tid ? $old_tid : $self->next_tid;
227 sub parse_references ($$$) {
228 my ($smsg, $hdr, $mids) = @_;
229 my $refs = references($hdr);
230 push(@$refs, @$mids) if scalar(@$mids) > 1;
231 return $refs if scalar(@$refs) == 0;
233 # prevent circular references here:
234 my %seen = ( $smsg->{mid} => 1 );
236 foreach my $ref (@$refs) {
237 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
238 warn "References: <$ref> too long, ignoring\n";
241 push(@keep, $ref) unless $seen{$ref}++;
243 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
247 # normalize subjects so they are suitable as pathnames for URLs
248 # XXX: consider for removal
249 sub subject_path ($) {
251 $subj = subject_normalized($subj);
252 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
257 my ($self, $mime, $smsg) = @_;
258 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
259 my $hdr = $mime->header_obj;
260 my $mids = mids_for_index($hdr);
261 my $refs = parse_references($smsg, $hdr, $mids);
262 my $subj = $smsg->{subject};
265 $xpath = subject_path($subj);
266 $xpath = id_compress($xpath);
268 my $dd = $smsg->to_doc_data;
271 add_over($self, [ @$smsg{qw(ts ds num)}, $mids, $refs, $xpath, $dd ]);
275 my ($self, $values) = @_;
276 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
281 $self->delete_by_num($num, \$old_tid);
282 foreach my $mid (@$mids) {
284 each_by_mid($self, $mid, ['tid'], sub {
286 my $cur_tid = $cur->{tid};
288 die "num must not be zero for $mid" if !$n;
289 $old_tid = $cur_tid unless defined $old_tid;
290 if ($n > 0) { # regular mail
291 merge_threads($self, $old_tid, $cur_tid);
292 } elsif ($n < 0) { # ghost
293 link_refs($self, $refs, $old_tid);
294 $self->delete_by_num($n);
299 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
302 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
303 my $sid = $self->sid($xpath);
304 my $dbh = $self->{dbh};
305 my $sth = $dbh->prepare_cached(<<'');
306 INSERT INTO over (num, tid, sid, ts, ds, ddd)
310 my @v = ($num, $tid, $sid, $ts, $ds);
311 foreach (@v) { $sth->bind_param(++$n, $_) }
312 $sth->bind_param(++$n, $ddd);
314 $sth = $dbh->prepare_cached(<<'');
315 INSERT INTO id2num (id, num) VALUES (?,?)
317 foreach my $mid (@$mids) {
318 my $id = $self->mid2id($mid);
319 $sth->execute($id, $num);
323 # returns number of removed messages
324 # $oid may be undef to match only on $mid
326 my ($self, $oid, $mid) = @_;
329 each_by_mid($self, $mid, ['ddd'], sub {
331 if (!defined($oid) || $smsg->{blob} eq $oid) {
332 $self->delete_by_num($smsg->{num});
340 sub num_mid0_for_oid {
341 my ($self, $oid, $mid) = @_;
344 each_by_mid($self, $mid, ['ddd'], sub {
346 my $blob = $smsg->{blob};
347 return 1 if (!defined($blob) || $blob ne $oid); # continue;
348 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
358 CREATE TABLE IF NOT EXISTS over (
359 num INTEGER NOT NULL,
360 tid INTEGER NOT NULL,
364 ddd VARBINARY, /* doc-data-deflated */
368 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
369 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
370 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
371 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
374 CREATE TABLE IF NOT EXISTS counter (
375 key VARCHAR(8) PRIMARY KEY NOT NULL,
376 val INTEGER DEFAULT 0,
380 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
381 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
384 CREATE TABLE IF NOT EXISTS subject (
385 sid INTEGER PRIMARY KEY AUTOINCREMENT,
386 path VARCHAR(40) NOT NULL,
391 CREATE TABLE IF NOT EXISTS id2num (
393 num INTEGER NOT NULL,
397 # performance critical:
398 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
399 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
402 CREATE TABLE IF NOT EXISTS msgid (
403 id INTEGER PRIMARY KEY AUTOINCREMENT,
404 mid VARCHAR(244) NOT NULL,
412 delete $self->{txn} or return;
413 $self->{dbh}->commit;
418 return if $self->{txn};
419 my $dbh = $self->connect or return;
421 # $dbh->{Profile} = 2;
427 delete $self->{txn} or return;
428 $self->{dbh}->rollback;
433 die "in transaction" if $self->{txn};
434 $self->SUPER::disconnect;
439 unless (-r $self->{filename}) {
441 require File::Basename;
442 File::Path::mkpath(File::Basename::dirname($self->{filename}));
445 PublicInbox::Over::connect($self);