1 # Copyright (C) 2018-2021 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 # $cb may delete rows and invalidate nums
162 my $smsg = $sth->fetchrow_hashref // next;
163 $smsg = PublicInbox::Over::load_from_row($smsg);
164 $cb->($self, $smsg, @arg) or return;
166 return if $nr != $lim;
170 sub _resolve_mid_to_tid {
171 my ($self, $smsg, $tid) = @_;
172 my $cur_tid = $smsg->{tid};
174 merge_threads($self, $$tid, $cur_tid);
175 } elsif ($cur_tid > $self->{min_tid}) {
177 } else { # rethreading, queue up dead ghosts
178 $$tid = next_tid($self);
179 my $n = $smsg->{num};
181 $self->{dbh}->prepare_cached(<<'')->execute($$tid, $n);
182 UPDATE over SET tid = ? WHERE num = ?
185 push(@{$self->{-ghosts_to_delete}}, $n);
191 # this will create a ghost as necessary
192 sub resolve_mid_to_tid {
193 my ($self, $mid) = @_;
195 each_by_mid($self, $mid, ['tid'], \&_resolve_mid_to_tid, \$tid);
196 if (my $del = delete $self->{-ghosts_to_delete}) {
197 delete_by_num($self, $_) for @$del;
199 $tid // do { # create a new ghost
200 my $id = mid2id($self, $mid);
201 my $num = next_ghost_num($self);
202 $num < 0 or die "ghost num is non-negative: $num\n";
203 $tid = next_tid($self);
204 my $dbh = $self->{dbh};
205 $dbh->prepare_cached(<<'')->execute($num, $tid);
206 INSERT INTO over (num, tid) VALUES (?,?)
208 $dbh->prepare_cached(<<'')->execute($id, $num);
209 INSERT INTO id2num (id, num) VALUES (?,?)
216 my ($self, $winner_tid, $loser_tid) = @_;
217 return if $winner_tid == $loser_tid;
218 my $dbh = $self->{dbh};
219 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
220 UPDATE over SET tid = ? WHERE tid = ?
225 my ($self, $refs, $old_tid) = @_;
229 # first ref *should* be the thread root,
230 # but we can never trust clients to do the right thing
231 my $ref = $refs->[0];
232 $tid = resolve_mid_to_tid($self, $ref);
233 merge_threads($self, $tid, $old_tid) if defined $old_tid;
235 # the rest of the refs should point to this tid:
236 foreach my $i (1..$#$refs) {
238 my $ptid = resolve_mid_to_tid($self, $ref);
239 merge_threads($self, $tid, $ptid);
242 $tid = $old_tid // next_tid($self);
247 # normalize subjects somewhat, they used to be ASCII-only but now
248 # we use \w for UTF-8 support. We may still drop it entirely and
249 # rely on Xapian for subject matches...
250 sub subject_path ($) {
252 $subj = subject_normalized($subj);
253 $subj =~ s![^\w\.~/\-]+!_!g;
259 my $dd = $smsg->to_doc_data;
265 my ($self, $eml, $smsg) = @_;
266 $smsg->{lines} = $eml->body_raw =~ tr!\n!\n!;
267 my $mids = mids_for_index($eml);
268 my $refs = $smsg->parse_references($eml, $mids);
271 $eml->{-lei_fake_mid};
273 my $subj = $smsg->{subject};
276 $xpath = subject_path($subj);
277 $xpath = id_compress($xpath);
279 add_over($self, $smsg, $mids, $refs, $xpath, ddd_for($smsg));
283 my ($self, $smsg, $mid, $refs, $old_tid, $v) = @_;
284 my $cur_tid = $smsg->{tid};
285 my $n = $smsg->{num};
286 die "num must not be zero for $mid" if !$n;
287 my $cur_valid = $cur_tid > $self->{min_tid};
289 if ($n > 0) { # regular mail
291 $$old_tid //= $cur_tid;
292 merge_threads($self, $$old_tid, $cur_tid);
294 $$old_tid //= next_tid($self);
296 } elsif ($n < 0) { # ghost
297 $$old_tid //= $cur_valid ? $cur_tid : next_tid($self);
298 $$old_tid = link_refs($self, $refs, $$old_tid);
299 delete_by_num($self, $n);
306 my ($self, $smsg, $mids, $refs, $xpath, $ddd) = @_;
309 my $num = $smsg->{num};
312 delete_by_num($self, $num, \$old_tid);
313 $old_tid = undef if ($old_tid // 0) <= $self->{min_tid};
314 foreach my $mid (@$mids) {
316 each_by_mid($self, $mid, ['tid'], \&_add_over,
317 $mid, $refs, \$old_tid, \$v);
318 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
321 $smsg->{tid} = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
322 $smsg->{sid} = sid($self, $xpath);
323 my $dbh = $self->{dbh};
324 my $sth = $dbh->prepare_cached(<<'');
325 INSERT INTO over (num, tid, sid, ts, ds, ddd)
329 $sth->bind_param($nc, $num);
330 $sth->bind_param(++$nc, $smsg->{$_}) for (qw(tid sid ts ds));
331 $sth->bind_param(++$nc, $ddd, SQL_BLOB);
333 $sth = $dbh->prepare_cached(<<'');
334 INSERT INTO id2num (id, num) VALUES (?,?)
336 foreach my $mid (@$mids) {
337 my $id = mid2id($self, $mid);
338 $sth->execute($id, $num);
343 my ($self, $smsg, $oid, $removed) = @_;
344 if (!defined($oid) || $smsg->{blob} eq $oid) {
345 delete_by_num($self, $smsg->{num});
346 push @$removed, $smsg->{num};
351 # returns number of removed messages in scalar context,
352 # array of removed article numbers in array context.
353 # $oid may be undef to match only on $mid
355 my ($self, $oid, $mid) = @_;
358 each_by_mid($self, $mid, ['ddd'], \&_remove_oid, $oid, $removed);
362 sub _num_mid0_for_oid {
363 my ($self, $smsg, $oid, $res) = @_;
364 my $blob = $smsg->{blob};
365 return 1 if (!defined($blob) || $blob ne $oid); # continue;
366 @$res = ($smsg->{num}, $smsg->{mid});
370 sub num_mid0_for_oid {
371 my ($self, $oid, $mid) = @_;
374 each_by_mid($self, $mid, ['ddd'], \&_num_mid0_for_oid, $oid, $res);
375 @$res, # ($num, $mid0);
382 CREATE TABLE IF NOT EXISTS over (
383 num INTEGER PRIMARY KEY NOT NULL, /* NNTP article number == IMAP UID */
384 tid INTEGER NOT NULL, /* THREADID (IMAP REFERENCES threading, JMAP) */
385 sid INTEGER, /* Subject ID (IMAP ORDEREDSUBJECT "threading") */
386 ts INTEGER, /* IMAP INTERNALDATE (Received: header, git commit time) */
387 ds INTEGER, /* RFC-2822 sent Date: header, git author time */
388 ddd VARBINARY /* doc-data-deflated (->to_doc_data, ->load_from_data) */
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, /* SHA-1 of normalized subject */
414 CREATE TABLE IF NOT EXISTS id2num (
415 id INTEGER NOT NULL, /* <=> msgid.id */
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, /* <=> id2num.id */
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 my $fn = $self->{filename} // do {
463 croak('BUG: no {filename}') unless $self->{dbh};
468 my ($dir) = ($fn =~ m!(.*?/)[^/]+\z!);
469 File::Path::mkpath($dir);
472 PublicInbox::Over::dbh($self);
476 sub rethread_prepare {
477 my ($self, $opt) = @_;
478 return unless $opt->{rethread};
480 my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
481 my $pr = $opt->{-progress};
482 $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
486 my ($self, $opt) = @_;
487 return unless $opt->{rethread} && $self->{txn};
488 defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
489 my $dbh = $self->{dbh} or croak('BUG: no dbh');
490 my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
491 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
493 my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
494 my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
495 my $pr = $opt->{-progress};
499 $show_id->execute($r->{num});
500 while (defined(my $id = $show_id->fetchrow_array)) {
502 $show_mid->execute($id);
503 my $mid = $show_mid->fetchrow_array;
504 if (!defined($mid)) {
506 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
511 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
514 delete_by_num($self, $r->{num});
516 $pr->("I: rethread culled $total ghosts\n") if $pr && $total;
519 # used for cross-inbox search
522 $self->{-eidx_prep} //= do {
523 my $dbh = $self->dbh;
525 INSERT OR IGNORE INTO counter (key) VALUES ('eidx_docid')
528 CREATE TABLE IF NOT EXISTS inboxes (
529 ibx_id INTEGER PRIMARY KEY AUTOINCREMENT,
530 eidx_key VARCHAR(255) NOT NULL, /* {newsgroup} // {inboxdir} */
535 CREATE TABLE IF NOT EXISTS xref3 (
536 docid INTEGER NOT NULL, /* <=> over.num */
537 ibx_id INTEGER NOT NULL, /* <=> inboxes.ibx_id */
538 xnum INTEGER NOT NULL, /* NNTP article number in ibx */
539 oidbin VARBINARY NOT NULL, /* 20-byte SHA-1 or 32-byte SHA-256 */
540 UNIQUE (docid, ibx_id, xnum, oidbin)
543 $dbh->do('CREATE INDEX IF NOT EXISTS idx_docid ON xref3 (docid)');
545 # performance critical, this is not UNIQUE since we may need to
546 # tolerate some old bugs from indexing mirrors. n.b. we used
547 # to index oidbin here, but leaving it out speeds up reindexing
548 # and "XHDR Xref <$MSGID>" isn't any slower w/o oidbin
549 $dbh->do('CREATE INDEX IF NOT EXISTS idx_reindex ON '.
550 'xref3 (xnum,ibx_id)');
552 $dbh->do('CREATE INDEX IF NOT EXISTS idx_oidbin ON xref3 (oidbin)');
555 CREATE TABLE IF NOT EXISTS eidx_meta (
556 key VARCHAR(255) PRIMARY KEY,
557 val VARCHAR(255) NOT NULL
560 # A queue of current docids which need reindexing.
561 # eidxq persists across aborted -extindex invocations
562 # Currently used for "-extindex --reindex" for Xapian
563 # data, but may be used in more places down the line.
565 CREATE TABLE IF NOT EXISTS eidxq (docid INTEGER PRIMARY KEY NOT NULL)
571 sub eidx_meta { # requires transaction
572 my ($self, $key, $val) = @_;
574 my $sql = 'SELECT val FROM eidx_meta WHERE key = ? LIMIT 1';
575 my $dbh = $self->{dbh};
576 defined($val) or return $dbh->selectrow_array($sql, undef, $key);
578 my $prev = $dbh->selectrow_array($sql, undef, $key);
580 $sql = 'UPDATE eidx_meta SET val = ? WHERE key = ?';
581 $dbh->do($sql, undef, $val, $key);
583 $sql = 'INSERT INTO eidx_meta (key,val) VALUES (?,?)';
584 $dbh->do($sql, undef, $key, $val);
591 get_counter($self->{dbh}, 'eidx_docid');
595 my ($self, $docid, $xnum, $oidhex, $eidx_key) = @_;
597 my $ibx_id = ibx_id($self, $eidx_key);
598 my $oidbin = pack('H*', $oidhex);
599 my $sth = $self->{dbh}->prepare_cached(<<'');
600 INSERT OR IGNORE INTO xref3 (docid, ibx_id, xnum, oidbin) VALUES (?, ?, ?, ?)
602 $sth->bind_param(1, $docid);
603 $sth->bind_param(2, $ibx_id);
604 $sth->bind_param(3, $xnum);
605 $sth->bind_param(4, $oidbin, SQL_BLOB);
609 # returns remaining reference count to $docid
611 my ($self, $docid, $oidhex, $eidx_key, $rm_eidx_info) = @_;
613 my $oidbin = pack('H*', $oidhex);
615 if (defined $eidx_key) {
616 $ibx_id = ibx_id($self, $eidx_key);
617 $sth = $self->{dbh}->prepare_cached(<<'');
618 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ? AND oidbin = ?
620 $sth->bind_param(1, $docid);
621 $sth->bind_param(2, $ibx_id);
622 $sth->bind_param(3, $oidbin, SQL_BLOB);
624 $sth = $self->{dbh}->prepare_cached(<<'');
625 DELETE FROM xref3 WHERE docid = ? AND oidbin = ?
627 $sth->bind_param(1, $docid);
628 $sth->bind_param(2, $oidbin, SQL_BLOB);
631 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
632 SELECT COUNT(*) FROM xref3 WHERE docid = ?
634 $sth->execute($docid);
635 my $nr = $sth->fetchrow_array;
637 delete_by_num($self, $docid);
638 } elsif (defined($ibx_id) && $rm_eidx_info) {
639 # if deduplication rules in ContentHash change, it's
640 # possible a docid can have multiple rows with the
641 # same ibx_id. This governs whether or not we call
642 # ->remove_eidx_info in ExtSearchIdx.
643 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
644 SELECT COUNT(*) FROM xref3 WHERE docid = ? AND ibx_id = ?
646 $sth->execute($docid, $ibx_id);
647 my $count = $sth->fetchrow_array;
648 $$rm_eidx_info = ($count == 0);
653 # for when an xref3 goes missing, this does NOT update {ts}
655 my ($self, $smsg, $oidhex) = @_;
656 my $sth = $self->{dbh}->prepare(<<'');
657 UPDATE over SET ddd = ? WHERE num = ?
659 $smsg->{blob} = $oidhex;
660 $sth->bind_param(1, ddd_for($smsg), SQL_BLOB);
661 $sth->bind_param(2, $smsg->{num});
665 sub merge_xref3 { # used for "-extindex --dedupe"
666 my ($self, $keep_docid, $drop_docid, $oidhex) = @_;
667 my $oidbin = pack('H*', $oidhex);
668 my $sth = $self->{dbh}->prepare_cached(<<'');
669 UPDATE OR IGNORE xref3 SET docid = ? WHERE docid = ? AND oidbin = ?
671 $sth->bind_param(1, $keep_docid);
672 $sth->bind_param(2, $drop_docid);
673 $sth->bind_param(3, $oidbin, SQL_BLOB);
676 # drop anything that conflicted
677 $sth = $self->{dbh}->prepare_cached(<<'');
678 DELETE FROM xref3 WHERE docid = ? AND oidbin = ?
680 $sth->bind_param(1, $drop_docid);
681 $sth->bind_param(2, $oidbin, SQL_BLOB);
686 my ($self, $docid) = @_;
687 $self->dbh->prepare_cached(<<'')->execute($docid);
688 INSERT OR IGNORE INTO eidxq (docid) VALUES (?)
693 my ($self, $docid) = @_;
694 $self->dbh->prepare_cached(<<'')->execute($docid);
695 DELETE FROM eidxq WHERE docid = ?
699 # returns true if we're vivifying a message for lei/store that was
700 # previously external-metadata only
702 my ($self, $smsg) = @_;
703 my @docids = $self->blob_exists($smsg->{blob});
705 for my $id (@docids) {
706 if (my $cur = $self->get_art($id)) {
707 # already indexed if bytes > 0
708 return if $cur->{bytes} > 0;
709 push @vivify_xvmd, $id;
711 warn "W: $smsg->{blob} #$id gone (bug?)\n";
714 $smsg->{-vivify_xvmd} = \@vivify_xvmd;