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, $eidx_key) = @_;
84 id_for($self, 'inboxes', 'ibx_id', eidx_key => $eidx_key);
88 my ($self, $path) = @_;
89 return unless defined $path && $path ne '';
90 id_for($self, 'subject', 'sid', 'path' => $path);
94 my ($self, $mid) = @_;
95 id_for($self, 'msgid', 'id', 'mid' => $mid);
99 my ($self, $num, $tid_ref) = @_;
100 my $dbh = $self->{dbh};
102 my $sth = $dbh->prepare_cached(<<'', undef, 1);
103 SELECT tid FROM over WHERE num = ? LIMIT 1
106 $$tid_ref = $sth->fetchrow_array; # may be undef
108 foreach (qw(over id2num)) {
109 $dbh->prepare_cached(<<"")->execute($num);
110 DELETE FROM $_ WHERE num = ?
115 # this includes ghosts
117 my ($self, $mid, $cols, $cb, @arg) = @_;
118 my $dbh = $self->{dbh};
121 I originally wanted to stuff everything into a single query:
123 SELECT over.* FROM over
124 LEFT JOIN id2num ON over.num = id2num.num
125 LEFT JOIN msgid ON msgid.id = id2num.id
126 WHERE msgid.mid = ? AND over.num >= ?
127 ORDER BY over.num ASC
130 But it's faster broken out (and we're always in a
131 transaction for subroutines in this file)
134 my $sth = $dbh->prepare_cached(<<'', undef, 1);
135 SELECT id FROM msgid WHERE mid = ? LIMIT 1
138 my $id = $sth->fetchrow_array;
139 defined $id or return;
142 $cols = join(',', map { $_ } @$cols);
144 my $prev = get_counter($dbh, 'ghost');
146 $sth = $dbh->prepare_cached(<<"", undef, 1);
147 SELECT num FROM id2num WHERE id = ? AND num >= ?
151 $sth->execute($id, $prev);
152 my $nums = $sth->fetchall_arrayref;
153 my $nr = scalar(@$nums) or return;
154 $prev = $nums->[-1]->[0];
156 $sth = $dbh->prepare_cached(<<"", undef, 1);
157 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
160 $sth->execute($_->[0]);
161 my $smsg = $sth->fetchrow_hashref;
162 $smsg = PublicInbox::Over::load_from_row($smsg);
163 $cb->($self, $smsg, @arg) or return;
165 return if $nr != $lim;
169 sub _resolve_mid_to_tid {
170 my ($self, $smsg, $tid) = @_;
171 my $cur_tid = $smsg->{tid};
173 merge_threads($self, $$tid, $cur_tid);
174 } elsif ($cur_tid > $self->{min_tid}) {
176 } else { # rethreading, queue up dead ghosts
177 $$tid = next_tid($self);
178 my $n = $smsg->{num};
180 $self->{dbh}->prepare_cached(<<'')->execute($$tid, $n);
181 UPDATE over SET tid = ? WHERE num = ?
184 push(@{$self->{-ghosts_to_delete}}, $n);
190 # this will create a ghost as necessary
191 sub resolve_mid_to_tid {
192 my ($self, $mid) = @_;
194 each_by_mid($self, $mid, ['tid'], \&_resolve_mid_to_tid, \$tid);
195 if (my $del = delete $self->{-ghosts_to_delete}) {
196 delete_by_num($self, $_) for @$del;
198 $tid // do { # create a new ghost
199 my $id = mid2id($self, $mid);
200 my $num = next_ghost_num($self);
201 $num < 0 or die "ghost num is non-negative: $num\n";
202 $tid = next_tid($self);
203 my $dbh = $self->{dbh};
204 $dbh->prepare_cached(<<'')->execute($num, $tid);
205 INSERT INTO over (num, tid) VALUES (?,?)
207 $dbh->prepare_cached(<<'')->execute($id, $num);
208 INSERT INTO id2num (id, num) VALUES (?,?)
215 my ($self, $winner_tid, $loser_tid) = @_;
216 return if $winner_tid == $loser_tid;
217 my $dbh = $self->{dbh};
218 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
219 UPDATE over SET tid = ? WHERE tid = ?
224 my ($self, $refs, $old_tid) = @_;
228 # first ref *should* be the thread root,
229 # but we can never trust clients to do the right thing
230 my $ref = $refs->[0];
231 $tid = resolve_mid_to_tid($self, $ref);
232 merge_threads($self, $tid, $old_tid) if defined $old_tid;
234 # the rest of the refs should point to this tid:
235 foreach my $i (1..$#$refs) {
237 my $ptid = resolve_mid_to_tid($self, $ref);
238 merge_threads($self, $tid, $ptid);
241 $tid = $old_tid // next_tid($self);
246 sub parse_references ($$$) {
247 my ($smsg, $hdr, $mids) = @_;
248 my $refs = references($hdr);
249 push(@$refs, @$mids) if scalar(@$mids) > 1;
250 return $refs if scalar(@$refs) == 0;
252 # prevent circular references here:
253 my %seen = ( $smsg->{mid} => 1 );
255 foreach my $ref (@$refs) {
256 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
257 warn "References: <$ref> too long, ignoring\n";
260 push(@keep, $ref) unless $seen{$ref}++;
262 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
266 # normalize subjects so they are suitable as pathnames for URLs
267 # XXX: consider for removal
268 sub subject_path ($) {
270 $subj = subject_normalized($subj);
271 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
277 my $dd = $smsg->to_doc_data;
283 my ($self, $eml, $smsg) = @_;
284 $smsg->{lines} = $eml->body_raw =~ tr!\n!\n!;
285 my $mids = mids_for_index($eml);
286 my $refs = parse_references($smsg, $eml, $mids);
287 my $subj = $smsg->{subject};
290 $xpath = subject_path($subj);
291 $xpath = id_compress($xpath);
293 add_over($self, $smsg, $mids, $refs, $xpath, ddd_for($smsg));
297 my ($self, $smsg, $mid, $refs, $old_tid, $v) = @_;
298 my $cur_tid = $smsg->{tid};
299 my $n = $smsg->{num};
300 die "num must not be zero for $mid" if !$n;
301 my $cur_valid = $cur_tid > $self->{min_tid};
303 if ($n > 0) { # regular mail
305 $$old_tid //= $cur_tid;
306 merge_threads($self, $$old_tid, $cur_tid);
308 $$old_tid //= next_tid($self);
310 } elsif ($n < 0) { # ghost
311 $$old_tid //= $cur_valid ? $cur_tid : next_tid($self);
312 $$old_tid = link_refs($self, $refs, $$old_tid);
313 delete_by_num($self, $n);
320 my ($self, $smsg, $mids, $refs, $xpath, $ddd) = @_;
323 my $num = $smsg->{num};
326 delete_by_num($self, $num, \$old_tid);
327 $old_tid = undef if ($old_tid // 0) <= $self->{min_tid};
328 foreach my $mid (@$mids) {
330 each_by_mid($self, $mid, ['tid'], \&_add_over,
331 $mid, $refs, \$old_tid, \$v);
332 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
335 $smsg->{tid} = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
336 $smsg->{sid} = sid($self, $xpath);
337 my $dbh = $self->{dbh};
338 my $sth = $dbh->prepare_cached(<<'');
339 INSERT INTO over (num, tid, sid, ts, ds, ddd)
343 $sth->bind_param($nc, $num);
344 $sth->bind_param(++$nc, $smsg->{$_}) for (qw(tid sid ts ds));
345 $sth->bind_param(++$nc, $ddd, SQL_BLOB);
347 $sth = $dbh->prepare_cached(<<'');
348 INSERT INTO id2num (id, num) VALUES (?,?)
350 foreach my $mid (@$mids) {
351 my $id = mid2id($self, $mid);
352 $sth->execute($id, $num);
357 my ($self, $smsg, $oid, $removed) = @_;
358 if (!defined($oid) || $smsg->{blob} eq $oid) {
359 delete_by_num($self, $smsg->{num});
360 push @$removed, $smsg->{num};
365 # returns number of removed messages in scalar context,
366 # array of removed article numbers in array context.
367 # $oid may be undef to match only on $mid
369 my ($self, $oid, $mid) = @_;
372 each_by_mid($self, $mid, ['ddd'], \&_remove_oid, $oid, $removed);
376 sub _num_mid0_for_oid {
377 my ($self, $smsg, $oid, $res) = @_;
378 my $blob = $smsg->{blob};
379 return 1 if (!defined($blob) || $blob ne $oid); # continue;
380 @$res = ($smsg->{num}, $smsg->{mid});
384 sub num_mid0_for_oid {
385 my ($self, $oid, $mid) = @_;
388 each_by_mid($self, $mid, ['ddd'], \&_num_mid0_for_oid, $oid, $res);
389 @$res, # ($num, $mid0);
396 CREATE TABLE IF NOT EXISTS over (
397 num INTEGER PRIMARY KEY NOT NULL, /* NNTP article number == IMAP UID */
398 tid INTEGER NOT NULL, /* THREADID (IMAP REFERENCES threading, JMAP) */
399 sid INTEGER, /* Subject ID (IMAP ORDEREDSUBJECT "threading") */
400 ts INTEGER, /* IMAP INTERNALDATE (Received: header, git commit time) */
401 ds INTEGER, /* RFC-2822 sent Date: header, git author time */
402 ddd VARBINARY /* doc-data-deflated (->to_doc_data, ->load_from_data) */
405 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
406 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
407 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
408 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
411 CREATE TABLE IF NOT EXISTS counter (
412 key VARCHAR(8) PRIMARY KEY NOT NULL,
413 val INTEGER DEFAULT 0,
417 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
418 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
421 CREATE TABLE IF NOT EXISTS subject (
422 sid INTEGER PRIMARY KEY AUTOINCREMENT,
423 path VARCHAR(40) NOT NULL, /* SHA-1 of normalized subject */
428 CREATE TABLE IF NOT EXISTS id2num (
429 id INTEGER NOT NULL, /* <=> msgid.id */
430 num INTEGER NOT NULL,
434 # performance critical:
435 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
436 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
439 CREATE TABLE IF NOT EXISTS msgid (
440 id INTEGER PRIMARY KEY AUTOINCREMENT, /* <=> id2num.id */
441 mid VARCHAR(244) NOT NULL,
449 delete $self->{txn} or return;
450 $self->{dbh}->commit;
455 return if $self->{txn};
456 my $dbh = $self->dbh or return;
458 # $dbh->{Profile} = 2;
464 delete $self->{txn} or return;
465 $self->{dbh}->rollback;
470 die "in transaction" if $self->{txn};
471 $self->SUPER::dbh_close;
476 my $fn = $self->{filename} // do {
477 Carp::confess('BUG: no {filename}') unless $self->{dbh};
482 require File::Basename;
483 File::Path::mkpath(File::Basename::dirname($fn));
486 PublicInbox::Over::dbh($self);
490 sub rethread_prepare {
491 my ($self, $opt) = @_;
492 return unless $opt->{rethread};
494 my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
495 my $pr = $opt->{-progress};
496 $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
500 my ($self, $opt) = @_;
501 return unless $opt->{rethread} && $self->{txn};
502 defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
503 my $dbh = $self->{dbh} or croak('BUG: no dbh');
504 my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
505 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
507 my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
508 my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
509 my $pr = $opt->{-progress};
513 $show_id->execute($r->{num});
514 while (defined(my $id = $show_id->fetchrow_array)) {
516 $show_mid->execute($id);
517 my $mid = $show_mid->fetchrow_array;
518 if (!defined($mid)) {
520 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
525 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
528 delete_by_num($self, $r->{num});
530 $pr->("I: rethread culled $total ghosts\n") if $pr && $total;
533 # used for cross-inbox search
536 $self->{-eidx_prep} //= do {
537 my $dbh = $self->dbh;
539 INSERT OR IGNORE INTO counter (key) VALUES ('eidx_docid')
542 CREATE TABLE IF NOT EXISTS inboxes (
543 ibx_id INTEGER PRIMARY KEY AUTOINCREMENT,
544 eidx_key VARCHAR(255) NOT NULL, /* {newsgroup} // {inboxdir} */
549 CREATE TABLE IF NOT EXISTS xref3 (
550 docid INTEGER NOT NULL, /* <=> over.num */
551 ibx_id INTEGER NOT NULL, /* <=> inboxes.ibx_id */
552 xnum INTEGER NOT NULL, /* NNTP article number in ibx */
553 oidbin VARBINARY NOT NULL, /* 20-byte SHA-1 or 32-byte SHA-256 */
554 UNIQUE (docid, ibx_id, xnum, oidbin)
557 $dbh->do('CREATE INDEX IF NOT EXISTS idx_docid ON xref3 (docid)');
559 # performance critical, this is not UNIQUE since we may need to
560 # tolerate some old bugs from indexing mirrors
561 $dbh->do('CREATE INDEX IF NOT EXISTS idx_nntp ON '.
562 'xref3 (oidbin,xnum,ibx_id)');
565 CREATE TABLE IF NOT EXISTS eidx_meta (
566 key VARCHAR(255) PRIMARY KEY,
567 val VARCHAR(255) NOT NULL
570 # A queue of current docids which need reindexing.
571 # eidxq persists across aborted -extindex invocations
572 # Currently used for "-extindex --reindex" for Xapian
573 # data, but may be used in more places down the line.
575 CREATE TABLE IF NOT EXISTS eidxq (
576 docid INTEGER PRIMARY KEY NOT NULL
583 sub eidx_meta { # requires transaction
584 my ($self, $key, $val) = @_;
586 my $sql = 'SELECT val FROM eidx_meta WHERE key = ? LIMIT 1';
587 my $dbh = $self->{dbh};
588 defined($val) or return $dbh->selectrow_array($sql, undef, $key);
590 my $prev = $dbh->selectrow_array($sql, undef, $key);
592 $sql = 'UPDATE eidx_meta SET val = ? WHERE key = ?';
593 $dbh->do($sql, undef, $val, $key);
595 $sql = 'INSERT INTO eidx_meta (key,val) VALUES (?,?)';
596 $dbh->do($sql, undef, $key, $val);
603 get_counter($self->{dbh}, 'eidx_docid');
607 my ($self, $docid, $xnum, $oidhex, $eidx_key) = @_;
609 my $ibx_id = ibx_id($self, $eidx_key);
610 my $oidbin = pack('H*', $oidhex);
611 my $sth = $self->{dbh}->prepare_cached(<<'');
612 INSERT OR IGNORE INTO xref3 (docid, ibx_id, xnum, oidbin) VALUES (?, ?, ?, ?)
614 $sth->bind_param(1, $docid);
615 $sth->bind_param(2, $ibx_id);
616 $sth->bind_param(3, $xnum);
617 $sth->bind_param(4, $oidbin, SQL_BLOB);
621 # returns remaining reference count to $docid
623 my ($self, $docid, $oidhex, $eidx_key, $rm_eidx_info) = @_;
625 my $oidbin = pack('H*', $oidhex);
627 if (defined $eidx_key) {
628 $ibx_id = ibx_id($self, $eidx_key);
629 $sth = $self->{dbh}->prepare_cached(<<'');
630 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ? AND oidbin = ?
632 $sth->bind_param(1, $docid);
633 $sth->bind_param(2, $ibx_id);
634 $sth->bind_param(3, $oidbin, SQL_BLOB);
636 $sth = $self->{dbh}->prepare_cached(<<'');
637 DELETE FROM xref3 WHERE docid = ? AND oidbin = ?
639 $sth->bind_param(1, $docid);
640 $sth->bind_param(2, $oidbin, SQL_BLOB);
643 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
644 SELECT COUNT(*) FROM xref3 WHERE docid = ?
646 $sth->execute($docid);
647 my $nr = $sth->fetchrow_array;
649 delete_by_num($self, $docid);
650 } elsif (defined($ibx_id) && $rm_eidx_info) {
651 # if deduplication rules in ContentHash change, it's
652 # possible a docid can have multiple rows with the
653 # same ibx_id. This governs whether or not we call
654 # ->shard_remove_eidx_info in ExtSearchIdx.
655 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
656 SELECT COUNT(*) FROM xref3 WHERE docid = ? AND ibx_id = ?
658 $sth->execute($docid, $ibx_id);
659 my $count = $sth->fetchrow_array;
660 $$rm_eidx_info = ($count == 0);
665 # for when an xref3 goes missing, this does NOT update {ts}
667 my ($self, $smsg, $oidhex) = @_;
668 my $sth = $self->{dbh}->prepare(<<'');
669 UPDATE over SET ddd = ? WHERE num = ?
671 $smsg->{blob} = $oidhex;
672 $sth->bind_param(1, ddd_for($smsg), SQL_BLOB);
673 $sth->bind_param(2, $smsg->{num});
678 my ($self, $docid) = @_;
679 $self->dbh->prepare_cached(<<'')->execute($docid);
680 INSERT OR IGNORE INTO eidxq (docid) VALUES (?)
685 my ($self, $docid) = @_;
686 $self->dbh->prepare_cached(<<'')->execute($docid);
687 DELETE FROM eidxq WHERE docid = ?