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;
437 eval { $self->{dbh}->do('PRAGMA optimize') };
442 return if $self->{txn};
443 my $dbh = $self->dbh or return;
445 # $dbh->{Profile} = 2;
451 delete $self->{txn} or return;
452 $self->{dbh}->rollback;
457 die "in transaction" if $self->{txn};
458 $self->SUPER::dbh_close;
463 my $fn = $self->{filename} // do {
464 croak('BUG: no {filename}') unless $self->{dbh};
469 my ($dir) = ($fn =~ m!(.*?/)[^/]+\z!);
470 File::Path::mkpath($dir);
473 PublicInbox::Over::dbh($self);
477 sub rethread_prepare {
478 my ($self, $opt) = @_;
479 return unless $opt->{rethread};
481 my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
482 my $pr = $opt->{-progress};
483 $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
487 my ($self, $opt) = @_;
488 return unless $opt->{rethread} && $self->{txn};
489 defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
490 my $dbh = $self->{dbh} or croak('BUG: no dbh');
491 my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
492 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
494 my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
495 my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
496 my $pr = $opt->{-progress};
500 $show_id->execute($r->{num});
501 while (defined(my $id = $show_id->fetchrow_array)) {
503 $show_mid->execute($id);
504 my $mid = $show_mid->fetchrow_array;
505 if (!defined($mid)) {
507 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
512 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
515 delete_by_num($self, $r->{num});
517 $pr->("I: rethread culled $total ghosts\n") if $pr && $total;
520 # used for cross-inbox search
523 $self->{-eidx_prep} //= do {
524 my $dbh = $self->dbh;
526 INSERT OR IGNORE INTO counter (key) VALUES ('eidx_docid')
529 CREATE TABLE IF NOT EXISTS inboxes (
530 ibx_id INTEGER PRIMARY KEY AUTOINCREMENT,
531 eidx_key VARCHAR(255) NOT NULL, /* {newsgroup} // {inboxdir} */
536 CREATE TABLE IF NOT EXISTS xref3 (
537 docid INTEGER NOT NULL, /* <=> over.num */
538 ibx_id INTEGER NOT NULL, /* <=> inboxes.ibx_id */
539 xnum INTEGER NOT NULL, /* NNTP article number in ibx */
540 oidbin VARBINARY NOT NULL, /* 20-byte SHA-1 or 32-byte SHA-256 */
541 UNIQUE (docid, ibx_id, xnum, oidbin)
544 $dbh->do('CREATE INDEX IF NOT EXISTS idx_docid ON xref3 (docid)');
546 # performance critical, this is not UNIQUE since we may need to
547 # tolerate some old bugs from indexing mirrors. n.b. we used
548 # to index oidbin here, but leaving it out speeds up reindexing
549 # and "XHDR Xref <$MSGID>" isn't any slower w/o oidbin
550 $dbh->do('CREATE INDEX IF NOT EXISTS idx_reindex ON '.
551 'xref3 (xnum,ibx_id)');
553 $dbh->do('CREATE INDEX IF NOT EXISTS idx_oidbin ON xref3 (oidbin)');
556 CREATE TABLE IF NOT EXISTS eidx_meta (
557 key VARCHAR(255) PRIMARY KEY,
558 val VARCHAR(255) NOT NULL
561 # A queue of current docids which need reindexing.
562 # eidxq persists across aborted -extindex invocations
563 # Currently used for "-extindex --reindex" for Xapian
564 # data, but may be used in more places down the line.
566 CREATE TABLE IF NOT EXISTS eidxq (docid INTEGER PRIMARY KEY NOT NULL)
572 sub eidx_meta { # requires transaction
573 my ($self, $key, $val) = @_;
575 my $sql = 'SELECT val FROM eidx_meta WHERE key = ? LIMIT 1';
576 my $dbh = $self->{dbh};
577 defined($val) or return $dbh->selectrow_array($sql, undef, $key);
579 my $prev = $dbh->selectrow_array($sql, undef, $key);
581 $sql = 'UPDATE eidx_meta SET val = ? WHERE key = ?';
582 $dbh->do($sql, undef, $val, $key);
584 $sql = 'INSERT INTO eidx_meta (key,val) VALUES (?,?)';
585 $dbh->do($sql, undef, $key, $val);
592 get_counter($self->{dbh}, 'eidx_docid');
596 my ($self, $docid, $xnum, $oidhex, $eidx_key) = @_;
598 my $ibx_id = ibx_id($self, $eidx_key);
599 my $oidbin = pack('H*', $oidhex);
600 my $sth = $self->{dbh}->prepare_cached(<<'');
601 INSERT OR IGNORE INTO xref3 (docid, ibx_id, xnum, oidbin) VALUES (?, ?, ?, ?)
603 $sth->bind_param(1, $docid);
604 $sth->bind_param(2, $ibx_id);
605 $sth->bind_param(3, $xnum);
606 $sth->bind_param(4, $oidbin, SQL_BLOB);
610 # for when an xref3 goes missing, this does NOT update {ts}
612 my ($self, $smsg, $oidhex) = @_;
613 my $sth = $self->{dbh}->prepare(<<'');
614 UPDATE over SET ddd = ? WHERE num = ?
616 $smsg->{blob} = $oidhex;
617 $sth->bind_param(1, ddd_for($smsg), SQL_BLOB);
618 $sth->bind_param(2, $smsg->{num});
622 sub merge_xref3 { # used for "-extindex --dedupe"
623 my ($self, $keep_docid, $drop_docid, $oidbin) = @_;
624 my $sth = $self->{dbh}->prepare_cached(<<'');
625 UPDATE OR IGNORE xref3 SET docid = ? WHERE docid = ? AND oidbin = ?
627 $sth->bind_param(1, $keep_docid);
628 $sth->bind_param(2, $drop_docid);
629 $sth->bind_param(3, $oidbin, SQL_BLOB);
632 # drop anything that conflicted
633 $sth = $self->{dbh}->prepare_cached(<<'');
634 DELETE FROM xref3 WHERE docid = ? AND oidbin = ?
636 $sth->bind_param(1, $drop_docid);
637 $sth->bind_param(2, $oidbin, SQL_BLOB);
642 my ($self, $docid) = @_;
643 $self->dbh->prepare_cached(<<'')->execute($docid);
644 INSERT OR IGNORE INTO eidxq (docid) VALUES (?)
649 my ($self, $docid) = @_;
650 $self->dbh->prepare_cached(<<'')->execute($docid);
651 DELETE FROM eidxq WHERE docid = ?
655 # returns true if we're vivifying a message for lei/store that was
656 # previously external-metadata only
658 my ($self, $smsg) = @_;
659 my @docids = $self->blob_exists($smsg->{blob});
661 for my $id (@docids) {
662 if (my $cur = $self->get_art($id)) {
663 # already indexed if bytes > 0
664 return if $cur->{bytes} > 0;
665 push @vivify_xvmd, $id;
667 warn "W: $smsg->{blob} #$id gone (bug?)\n";
670 $smsg->{-vivify_xvmd} = \@vivify_xvmd;