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);
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;
23 my $dbh = $self->SUPER::dbh_new(1);
25 # TRUNCATE reduces I/O compared to the default (DELETE)
26 $dbh->do('PRAGMA journal_mode = TRUNCATE');
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');
38 sub get_counter ($$) {
40 my $sth = $dbh->prepare_cached(<<'', undef, 1);
41 SELECT val FROM counter WHERE key = ? LIMIT 1
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 = ?
55 get_counter($dbh, $key);
58 sub next_tid { adj_counter($_[0], 'thread', '+') }
59 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
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 (?)
68 my $sth = $dbh->prepare_cached(<<"", undef, 1);
69 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
74 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
79 my ($self, $path) = @_;
80 return unless defined $path && $path ne '';
81 id_for($self, 'subject', 'sid', 'path' => $path);
85 my ($self, $mid) = @_;
86 id_for($self, 'msgid', 'id', 'mid' => $mid);
90 my ($self, $num, $tid_ref) = @_;
91 my $dbh = $self->{dbh};
93 my $sth = $dbh->prepare_cached(<<'', undef, 1);
94 SELECT tid FROM over WHERE num = ? LIMIT 1
97 $$tid_ref = $sth->fetchrow_array; # may be undef
99 foreach (qw(over id2num)) {
100 $dbh->prepare_cached(<<"")->execute($num);
101 DELETE FROM $_ WHERE num = ?
106 # this includes ghosts
108 my ($self, $mid, $cols, $cb) = @_;
109 my $dbh = $self->{dbh};
112 I originally wanted to stuff everything into a single query:
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
121 But it's faster broken out (and we're always in a
122 transaction for subroutines in this file)
125 my $sth = $dbh->prepare_cached(<<'', undef, 1);
126 SELECT id FROM msgid WHERE mid = ? LIMIT 1
129 my $id = $sth->fetchrow_array;
130 defined $id or return;
133 $cols = join(',', map { $_ } @$cols);
135 my $prev = get_counter($dbh, 'ghost');
137 $sth = $dbh->prepare_cached(<<"", undef, 1);
138 SELECT num FROM id2num WHERE id = ? AND num >= ?
142 $sth->execute($id, $prev);
143 my $nums = $sth->fetchall_arrayref;
144 my $nr = scalar(@$nums) or return;
145 $prev = $nums->[-1]->[0];
147 $sth = $dbh->prepare_cached(<<"", undef, 1);
148 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
151 $sth->execute($_->[0]);
152 my $smsg = $sth->fetchrow_hashref;
153 $cb->(PublicInbox::Over::load_from_row($smsg)) or
156 return if $nr != $lim;
160 # this will create a ghost as necessary
161 sub resolve_mid_to_tid {
162 my ($self, $mid) = @_;
164 each_by_mid($self, $mid, ['tid'], sub {
166 my $cur_tid = $smsg->{tid};
168 merge_threads($self, $tid, $cur_tid);
174 defined $tid ? $tid : create_ghost($self, $mid);
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 (?,?)
187 $dbh->prepare_cached(<<'')->execute($id, $num);
188 INSERT INTO id2num (id, num) VALUES (?,?)
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 = ?
203 my ($self, $refs, $old_tid) = @_;
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;
213 # the rest of the refs should point to this tid:
214 foreach my $i (1..$#$refs) {
216 my $ptid = resolve_mid_to_tid($self, $ref);
217 merge_threads($self, $tid, $ptid);
220 $tid = defined $old_tid ? $old_tid : $self->next_tid;
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;
231 # prevent circular references here:
232 my %seen = ( $smsg->{mid} => 1 );
234 foreach my $ref (@$refs) {
235 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
236 warn "References: <$ref> too long, ignoring\n";
239 push(@keep, $ref) unless $seen{$ref}++;
241 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
245 # normalize subjects so they are suitable as pathnames for URLs
246 # XXX: consider for removal
247 sub subject_path ($) {
249 $subj = subject_normalized($subj);
250 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
255 my ($self, $mime, $smsg) = @_;
256 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
257 my $hdr = $mime->header_obj;
258 my $mids = mids_for_index($hdr);
259 my $refs = parse_references($smsg, $hdr, $mids);
260 my $subj = $smsg->{subject};
263 $xpath = subject_path($subj);
264 $xpath = id_compress($xpath);
266 my $dd = $smsg->to_doc_data;
269 add_over($self, [ @$smsg{qw(ts ds num)}, $mids, $refs, $xpath, $dd ]);
273 my ($self, $values) = @_;
274 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
279 $self->delete_by_num($num, \$old_tid);
280 foreach my $mid (@$mids) {
282 each_by_mid($self, $mid, ['tid'], sub {
284 my $cur_tid = $cur->{tid};
286 die "num must not be zero for $mid" if !$n;
287 $old_tid = $cur_tid unless defined $old_tid;
288 if ($n > 0) { # regular mail
289 merge_threads($self, $old_tid, $cur_tid);
290 } elsif ($n < 0) { # ghost
291 link_refs($self, $refs, $old_tid);
292 $self->delete_by_num($n);
297 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
300 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
301 my $sid = $self->sid($xpath);
302 my $dbh = $self->{dbh};
303 my $sth = $dbh->prepare_cached(<<'');
304 INSERT INTO over (num, tid, sid, ts, ds, ddd)
308 my @v = ($num, $tid, $sid, $ts, $ds);
309 foreach (@v) { $sth->bind_param(++$n, $_) }
310 $sth->bind_param(++$n, $ddd, SQL_BLOB);
312 $sth = $dbh->prepare_cached(<<'');
313 INSERT INTO id2num (id, num) VALUES (?,?)
315 foreach my $mid (@$mids) {
316 my $id = $self->mid2id($mid);
317 $sth->execute($id, $num);
321 # returns number of removed messages
322 # $oid may be undef to match only on $mid
324 my ($self, $oid, $mid) = @_;
327 each_by_mid($self, $mid, ['ddd'], sub {
329 if (!defined($oid) || $smsg->{blob} eq $oid) {
330 $self->delete_by_num($smsg->{num});
338 sub num_mid0_for_oid {
339 my ($self, $oid, $mid) = @_;
342 each_by_mid($self, $mid, ['ddd'], sub {
344 my $blob = $smsg->{blob};
345 return 1 if (!defined($blob) || $blob ne $oid); # continue;
346 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
356 CREATE TABLE IF NOT EXISTS over (
357 num INTEGER NOT NULL,
358 tid INTEGER NOT NULL,
362 ddd VARBINARY, /* doc-data-deflated */
366 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
367 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
368 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
369 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
372 CREATE TABLE IF NOT EXISTS counter (
373 key VARCHAR(8) PRIMARY KEY NOT NULL,
374 val INTEGER DEFAULT 0,
378 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
379 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
382 CREATE TABLE IF NOT EXISTS subject (
383 sid INTEGER PRIMARY KEY AUTOINCREMENT,
384 path VARCHAR(40) NOT NULL,
389 CREATE TABLE IF NOT EXISTS id2num (
391 num INTEGER NOT NULL,
395 # performance critical:
396 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
397 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
400 CREATE TABLE IF NOT EXISTS msgid (
401 id INTEGER PRIMARY KEY AUTOINCREMENT,
402 mid VARCHAR(244) NOT NULL,
410 delete $self->{txn} or return;
411 $self->{dbh}->commit;
416 return if $self->{txn};
417 my $dbh = $self->connect or return;
419 # $dbh->{Profile} = 2;
425 delete $self->{txn} or return;
426 $self->{dbh}->rollback;
431 die "in transaction" if $self->{txn};
432 $self->{dbh} = undef;
437 unless (-r $self->{filename}) {
439 require File::Basename;
440 File::Path::mkpath(File::Basename::dirname($self->{filename}));
443 PublicInbox::Over::connect($self);