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 parent 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);
23 my $dbh = $self->SUPER::dbh_new($self->{-no_fsync} ? 2 : 1);
25 # 80000 pages (80MiB on SQLite <3.12.0, 320MiB on 3.12.0+)
26 # was found to be good in 2018 during the large LKML import
27 # at the time. This ought to be configurable based on HW
28 # and inbox size; I suspect it's overkill for many inboxes.
29 $dbh->do('PRAGMA cache_size = 80000');
37 my $self = $class->SUPER::new($f);
42 sub get_counter ($$) {
44 my $sth = $dbh->prepare_cached(<<'', undef, 1);
45 SELECT val FROM counter WHERE key = ? LIMIT 1
51 sub adj_counter ($$$) {
52 my ($self, $key, $op) = @_;
53 my $dbh = $self->{dbh};
54 my $sth = $dbh->prepare_cached(<<"");
55 UPDATE counter SET val = val $op 1 WHERE key = ?
59 get_counter($dbh, $key);
62 sub next_tid { adj_counter($_[0], 'thread', '+') }
63 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
66 my ($self, $tbl, $id_col, $val_col, $val) = @_;
67 my $dbh = $self->{dbh};
68 my $in = $dbh->prepare_cached(<<"")->execute($val);
69 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
72 my $sth = $dbh->prepare_cached(<<"", undef, 1);
73 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
78 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
83 my ($self, $path) = @_;
84 return unless defined $path && $path ne '';
85 id_for($self, 'subject', 'sid', 'path' => $path);
89 my ($self, $mid) = @_;
90 id_for($self, 'msgid', 'id', 'mid' => $mid);
94 my ($self, $num, $tid_ref) = @_;
95 my $dbh = $self->{dbh};
97 my $sth = $dbh->prepare_cached(<<'', undef, 1);
98 SELECT tid FROM over WHERE num = ? LIMIT 1
101 $$tid_ref = $sth->fetchrow_array; # may be undef
103 foreach (qw(over id2num)) {
104 $dbh->prepare_cached(<<"")->execute($num);
105 DELETE FROM $_ WHERE num = ?
110 # this includes ghosts
112 my ($self, $mid, $cols, $cb, @arg) = @_;
113 my $dbh = $self->{dbh};
116 I originally wanted to stuff everything into a single query:
118 SELECT over.* FROM over
119 LEFT JOIN id2num ON over.num = id2num.num
120 LEFT JOIN msgid ON msgid.id = id2num.id
121 WHERE msgid.mid = ? AND over.num >= ?
122 ORDER BY over.num ASC
125 But it's faster broken out (and we're always in a
126 transaction for subroutines in this file)
129 my $sth = $dbh->prepare_cached(<<'', undef, 1);
130 SELECT id FROM msgid WHERE mid = ? LIMIT 1
133 my $id = $sth->fetchrow_array;
134 defined $id or return;
137 $cols = join(',', map { $_ } @$cols);
139 my $prev = get_counter($dbh, 'ghost');
141 $sth = $dbh->prepare_cached(<<"", undef, 1);
142 SELECT num FROM id2num WHERE id = ? AND num >= ?
146 $sth->execute($id, $prev);
147 my $nums = $sth->fetchall_arrayref;
148 my $nr = scalar(@$nums) or return;
149 $prev = $nums->[-1]->[0];
151 $sth = $dbh->prepare_cached(<<"", undef, 1);
152 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
155 $sth->execute($_->[0]);
156 my $smsg = $sth->fetchrow_hashref;
157 $smsg = PublicInbox::Over::load_from_row($smsg);
158 $cb->($self, $smsg, @arg) or return;
160 return if $nr != $lim;
164 sub _resolve_mid_to_tid {
165 my ($self, $smsg, $tid) = @_;
166 my $cur_tid = $smsg->{tid};
168 merge_threads($self, $$tid, $cur_tid);
169 } elsif ($cur_tid > $self->{min_tid}) {
171 } else { # rethreading, queue up dead ghosts
172 $$tid = next_tid($self);
173 my $num = $smsg->{num};
174 push(@{$self->{-ghosts_to_delete}}, $num) if $num < 0;
179 # this will create a ghost as necessary
180 sub resolve_mid_to_tid {
181 my ($self, $mid) = @_;
183 each_by_mid($self, $mid, ['tid'], \&_resolve_mid_to_tid, \$tid);
184 if (my $del = delete $self->{-ghosts_to_delete}) {
185 delete_by_num($self, $_) for @$del;
187 $tid // do { # create a new ghost
188 my $id = mid2id($self, $mid);
189 my $num = next_ghost_num($self);
190 $num < 0 or die "ghost num is non-negative: $num\n";
191 $tid = next_tid($self);
192 my $dbh = $self->{dbh};
193 $dbh->prepare_cached(<<'')->execute($num, $tid);
194 INSERT INTO over (num, tid) VALUES (?,?)
196 $dbh->prepare_cached(<<'')->execute($id, $num);
197 INSERT INTO id2num (id, num) VALUES (?,?)
204 my ($self, $winner_tid, $loser_tid) = @_;
205 return if $winner_tid == $loser_tid;
206 my $dbh = $self->{dbh};
207 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
208 UPDATE over SET tid = ? WHERE tid = ?
213 my ($self, $refs, $old_tid) = @_;
217 # first ref *should* be the thread root,
218 # but we can never trust clients to do the right thing
219 my $ref = $refs->[0];
220 $tid = resolve_mid_to_tid($self, $ref);
221 merge_threads($self, $tid, $old_tid) if defined $old_tid;
223 # the rest of the refs should point to this tid:
224 foreach my $i (1..$#$refs) {
226 my $ptid = resolve_mid_to_tid($self, $ref);
227 merge_threads($self, $tid, $ptid);
230 $tid = $old_tid // next_tid($self);
235 sub parse_references ($$$) {
236 my ($smsg, $hdr, $mids) = @_;
237 my $refs = references($hdr);
238 push(@$refs, @$mids) if scalar(@$mids) > 1;
239 return $refs if scalar(@$refs) == 0;
241 # prevent circular references here:
242 my %seen = ( $smsg->{mid} => 1 );
244 foreach my $ref (@$refs) {
245 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
246 warn "References: <$ref> too long, ignoring\n";
249 push(@keep, $ref) unless $seen{$ref}++;
251 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
255 # normalize subjects so they are suitable as pathnames for URLs
256 # XXX: consider for removal
257 sub subject_path ($) {
259 $subj = subject_normalized($subj);
260 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
265 my ($self, $eml, $smsg) = @_;
266 $smsg->{lines} = $eml->body_raw =~ tr!\n!\n!;
267 my $mids = mids_for_index($eml);
268 my $refs = parse_references($smsg, $eml, $mids);
269 my $subj = $smsg->{subject};
272 $xpath = subject_path($subj);
273 $xpath = id_compress($xpath);
275 my $dd = $smsg->to_doc_data;
278 add_over($self, $smsg, $mids, $refs, $xpath, $dd);
282 my ($self, $smsg, $mid, $refs, $old_tid, $v) = @_;
283 my $cur_tid = $smsg->{tid};
284 my $n = $smsg->{num};
285 die "num must not be zero for $mid" if !$n;
286 my $cur_valid = $cur_tid > $self->{min_tid};
288 if ($n > 0) { # regular mail
290 $$old_tid //= $cur_tid;
291 merge_threads($self, $$old_tid, $cur_tid);
293 $$old_tid //= next_tid($self);
295 } elsif ($n < 0) { # ghost
296 $$old_tid //= $cur_valid ? $cur_tid : next_tid($self);
297 link_refs($self, $refs, $$old_tid);
298 delete_by_num($self, $n);
305 my ($self, $smsg, $mids, $refs, $xpath, $ddd) = @_;
308 my $num = $smsg->{num};
311 delete_by_num($self, $num, \$old_tid);
312 $old_tid = undef if ($old_tid // 0) <= $self->{min_tid};
313 foreach my $mid (@$mids) {
315 each_by_mid($self, $mid, ['tid'], \&_add_over,
316 $mid, $refs, \$old_tid, \$v);
317 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
320 $smsg->{tid} = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
321 $smsg->{sid} = sid($self, $xpath);
322 my $dbh = $self->{dbh};
323 my $sth = $dbh->prepare_cached(<<'');
324 INSERT INTO over (num, tid, sid, ts, ds, ddd)
328 $sth->bind_param($nc, $num);
329 $sth->bind_param(++$nc, $smsg->{$_}) for (qw(tid sid ts ds));
330 $sth->bind_param(++$nc, $ddd, SQL_BLOB);
332 $sth = $dbh->prepare_cached(<<'');
333 INSERT INTO id2num (id, num) VALUES (?,?)
335 foreach my $mid (@$mids) {
336 my $id = mid2id($self, $mid);
337 $sth->execute($id, $num);
342 my ($self, $smsg, $oid, $removed) = @_;
343 if (!defined($oid) || $smsg->{blob} eq $oid) {
344 delete_by_num($self, $smsg->{num});
345 push @$removed, $smsg->{num};
350 # returns number of removed messages in scalar context,
351 # array of removed article numbers in array context.
352 # $oid may be undef to match only on $mid
354 my ($self, $oid, $mid) = @_;
357 each_by_mid($self, $mid, ['ddd'], \&_remove_oid, $oid, $removed);
361 sub _num_mid0_for_oid {
362 my ($self, $smsg, $oid, $res) = @_;
363 my $blob = $smsg->{blob};
364 return 1 if (!defined($blob) || $blob ne $oid); # continue;
365 @$res = ($smsg->{num}, $smsg->{mid});
369 sub num_mid0_for_oid {
370 my ($self, $oid, $mid) = @_;
373 each_by_mid($self, $mid, ['ddd'], \&_num_mid0_for_oid, $oid, $res);
374 @$res, # ($num, $mid0);
381 CREATE TABLE IF NOT EXISTS over (
382 num INTEGER NOT NULL,
383 tid INTEGER NOT NULL,
387 ddd VARBINARY, /* doc-data-deflated */
391 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
392 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
393 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
394 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
397 CREATE TABLE IF NOT EXISTS counter (
398 key VARCHAR(8) PRIMARY KEY NOT NULL,
399 val INTEGER DEFAULT 0,
403 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
404 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
407 CREATE TABLE IF NOT EXISTS subject (
408 sid INTEGER PRIMARY KEY AUTOINCREMENT,
409 path VARCHAR(40) NOT NULL,
414 CREATE TABLE IF NOT EXISTS id2num (
416 num INTEGER NOT NULL,
420 # performance critical:
421 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
422 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
425 CREATE TABLE IF NOT EXISTS msgid (
426 id INTEGER PRIMARY KEY AUTOINCREMENT,
427 mid VARCHAR(244) NOT NULL,
435 delete $self->{txn} or return;
436 $self->{dbh}->commit;
441 return if $self->{txn};
442 my $dbh = $self->dbh or return;
444 # $dbh->{Profile} = 2;
450 delete $self->{txn} or return;
451 $self->{dbh}->rollback;
456 die "in transaction" if $self->{txn};
457 $self->SUPER::dbh_close;
462 unless (-r $self->{filename}) {
464 require File::Basename;
465 File::Path::mkpath(File::Basename::dirname($self->{filename}));
468 PublicInbox::Over::dbh($self);
472 sub rethread_prepare {
473 my ($self, $opt) = @_;
474 return unless $opt->{rethread};
476 my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
477 my $pr = $opt->{-progress};
478 $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
482 my ($self, $opt) = @_;
483 return unless $opt->{rethread} && $self->{txn};
484 defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
485 my $dbh = $self->{dbh} or croak('BUG: no dbh');
486 my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
487 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
489 my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
490 my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
491 my $pr = $opt->{-progress};
495 $show_id->execute($r->{num});
496 while (defined(my $id = $show_id->fetchrow_array)) {
498 $show_mid->execute($id);
499 my $mid = $show_mid->fetchrow_array;
500 if (!defined($mid)) {
502 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
507 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
510 delete_by_num($self, $r->{num});
512 $pr->("I: rethread culled $total ghosts\n") if $pr && $total;