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);
24 $dbh->do('PRAGMA journal_mode = TRUNCATE');
25 $dbh->do('PRAGMA cache_size = 80000');
30 sub get_counter ($$) {
32 my $sth = $dbh->prepare_cached(<<'', undef, 1);
33 SELECT val FROM counter WHERE key = ? LIMIT 1
39 sub adj_counter ($$$) {
40 my ($self, $key, $op) = @_;
41 my $dbh = $self->{dbh};
42 my $sth = $dbh->prepare_cached(<<"");
43 UPDATE counter SET val = val $op 1 WHERE key = ?
47 get_counter($dbh, $key);
50 sub next_tid { adj_counter($_[0], 'thread', '+') }
51 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
54 my ($self, $tbl, $id_col, $val_col, $val) = @_;
55 my $dbh = $self->{dbh};
56 my $in = $dbh->prepare_cached(<<"")->execute($val);
57 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
60 my $sth = $dbh->prepare_cached(<<"", undef, 1);
61 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
66 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
71 my ($self, $path) = @_;
72 return unless defined $path && $path ne '';
73 id_for($self, 'subject', 'sid', 'path' => $path);
77 my ($self, $mid) = @_;
78 id_for($self, 'msgid', 'id', 'mid' => $mid);
82 my ($self, $num, $tid_ref) = @_;
83 my $dbh = $self->{dbh};
85 my $sth = $dbh->prepare_cached(<<'', undef, 1);
86 SELECT tid FROM over WHERE num = ? LIMIT 1
89 $$tid_ref = $sth->fetchrow_array; # may be undef
91 foreach (qw(over id2num)) {
92 $dbh->prepare_cached(<<"")->execute($num);
93 DELETE FROM $_ WHERE num = ?
98 # this includes ghosts
100 my ($self, $mid, $cols, $cb) = @_;
101 my $dbh = $self->{dbh};
104 I originally wanted to stuff everything into a single query:
106 SELECT over.* FROM over
107 LEFT JOIN id2num ON over.num = id2num.num
108 LEFT JOIN msgid ON msgid.id = id2num.id
109 WHERE msgid.mid = ? AND over.num >= ?
110 ORDER BY over.num ASC
113 But it's faster broken out (and we're always in a
114 transaction for subroutines in this file)
117 my $sth = $dbh->prepare_cached(<<'', undef, 1);
118 SELECT id FROM msgid WHERE mid = ? LIMIT 1
121 my $id = $sth->fetchrow_array;
122 defined $id or return;
125 $cols = join(',', map { $_ } @$cols);
127 my $prev = get_counter($dbh, 'ghost');
129 $sth = $dbh->prepare_cached(<<"", undef, 1);
130 SELECT num FROM id2num WHERE id = ? AND num >= ?
134 $sth->execute($id, $prev);
135 my $nums = $sth->fetchall_arrayref;
136 my $nr = scalar(@$nums) or return;
137 $prev = $nums->[-1]->[0];
139 $sth = $dbh->prepare_cached(<<"", undef, 1);
140 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
143 $sth->execute($_->[0]);
144 my $smsg = $sth->fetchrow_hashref;
145 $cb->(PublicInbox::Over::load_from_row($smsg)) or
148 return if $nr != $lim;
152 # this will create a ghost as necessary
153 sub resolve_mid_to_tid {
154 my ($self, $mid) = @_;
156 each_by_mid($self, $mid, ['tid'], sub {
158 my $cur_tid = $smsg->{tid};
160 merge_threads($self, $tid, $cur_tid);
166 defined $tid ? $tid : create_ghost($self, $mid);
170 my ($self, $mid) = @_;
171 my $id = $self->mid2id($mid);
172 my $num = $self->next_ghost_num;
173 $num < 0 or die "ghost num is non-negative: $num\n";
174 my $tid = $self->next_tid;
175 my $dbh = $self->{dbh};
176 $dbh->prepare_cached(<<'')->execute($num, $tid);
177 INSERT INTO over (num, tid) VALUES (?,?)
179 $dbh->prepare_cached(<<'')->execute($id, $num);
180 INSERT INTO id2num (id, num) VALUES (?,?)
186 my ($self, $winner_tid, $loser_tid) = @_;
187 return if $winner_tid == $loser_tid;
188 my $dbh = $self->{dbh};
189 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
190 UPDATE over SET tid = ? WHERE tid = ?
195 my ($self, $refs, $old_tid) = @_;
199 # first ref *should* be the thread root,
200 # but we can never trust clients to do the right thing
201 my $ref = $refs->[0];
202 $tid = resolve_mid_to_tid($self, $ref);
203 merge_threads($self, $tid, $old_tid) if defined $old_tid;
205 # the rest of the refs should point to this tid:
206 foreach my $i (1..$#$refs) {
208 my $ptid = resolve_mid_to_tid($self, $ref);
209 merge_threads($self, $tid, $ptid);
212 $tid = defined $old_tid ? $old_tid : $self->next_tid;
217 sub parse_references ($$$) {
218 my ($smsg, $hdr, $mids) = @_;
219 my $refs = references($hdr);
220 push(@$refs, @$mids) if scalar(@$mids) > 1;
221 return $refs if scalar(@$refs) == 0;
223 # prevent circular references here:
224 my %seen = ( $smsg->{mid} => 1 );
226 foreach my $ref (@$refs) {
227 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
228 warn "References: <$ref> too long, ignoring\n";
231 push(@keep, $ref) unless $seen{$ref}++;
233 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
237 # normalize subjects so they are suitable as pathnames for URLs
238 # XXX: consider for removal
239 sub subject_path ($) {
241 $subj = subject_normalized($subj);
242 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
247 my ($self, $mime, $smsg) = @_;
248 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
249 $smsg->{mime} = $mime; # XXX temporary?
250 my $hdr = $mime->header_obj;
251 my $mids = mids_for_index($hdr);
252 my $refs = parse_references($smsg, $hdr, $mids);
253 my $subj = $smsg->subject;
256 $xpath = subject_path($subj);
257 $xpath = id_compress($xpath);
259 my $dd = $smsg->to_doc_data;
262 add_over($self, [ @$smsg{qw(ts ds num)}, $mids, $refs, $xpath, $dd ]);
266 my ($self, $values) = @_;
267 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
272 $self->delete_by_num($num, \$old_tid);
273 foreach my $mid (@$mids) {
275 each_by_mid($self, $mid, ['tid'], sub {
277 my $cur_tid = $cur->{tid};
279 die "num must not be zero for $mid" if !$n;
280 $old_tid = $cur_tid unless defined $old_tid;
281 if ($n > 0) { # regular mail
282 merge_threads($self, $old_tid, $cur_tid);
283 } elsif ($n < 0) { # ghost
284 link_refs($self, $refs, $old_tid);
285 $self->delete_by_num($n);
290 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
293 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
294 my $sid = $self->sid($xpath);
295 my $dbh = $self->{dbh};
296 my $sth = $dbh->prepare_cached(<<'');
297 INSERT INTO over (num, tid, sid, ts, ds, ddd)
301 my @v = ($num, $tid, $sid, $ts, $ds);
302 foreach (@v) { $sth->bind_param(++$n, $_) }
303 $sth->bind_param(++$n, $ddd, SQL_BLOB);
305 $sth = $dbh->prepare_cached(<<'');
306 INSERT INTO id2num (id, num) VALUES (?,?)
308 foreach my $mid (@$mids) {
309 my $id = $self->mid2id($mid);
310 $sth->execute($id, $num);
314 # returns number of removed messages
315 # $oid may be undef to match only on $mid
317 my ($self, $oid, $mid) = @_;
320 each_by_mid($self, $mid, ['ddd'], sub {
322 if (!defined($oid) || $smsg->{blob} eq $oid) {
323 $self->delete_by_num($smsg->{num});
331 sub num_mid0_for_oid {
332 my ($self, $oid, $mid) = @_;
335 each_by_mid($self, $mid, ['ddd'], sub {
337 my $blob = $smsg->{blob};
338 return 1 if (!defined($blob) || $blob ne $oid); # continue;
339 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
349 CREATE TABLE IF NOT EXISTS over (
350 num INTEGER NOT NULL,
351 tid INTEGER NOT NULL,
355 ddd VARBINARY, /* doc-data-deflated */
359 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
360 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
361 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
362 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
365 CREATE TABLE IF NOT EXISTS counter (
366 key VARCHAR(8) PRIMARY KEY NOT NULL,
367 val INTEGER DEFAULT 0,
371 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
372 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
375 CREATE TABLE IF NOT EXISTS subject (
376 sid INTEGER PRIMARY KEY AUTOINCREMENT,
377 path VARCHAR(40) NOT NULL,
382 CREATE TABLE IF NOT EXISTS id2num (
384 num INTEGER NOT NULL,
388 # performance critical:
389 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
390 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
393 CREATE TABLE IF NOT EXISTS msgid (
394 id INTEGER PRIMARY KEY AUTOINCREMENT,
395 mid VARCHAR(244) NOT NULL,
403 delete $self->{txn} or return;
404 $self->{dbh}->commit;
409 return if $self->{txn};
410 my $dbh = $self->connect or return;
412 # $dbh->{Profile} = 2;
418 delete $self->{txn} or return;
419 $self->{dbh}->rollback;
424 die "in transaction" if $self->{txn};
425 $self->{dbh} = undef;
430 unless (-r $self->{filename}) {
432 require File::Basename;
433 File::Path::mkpath(File::Basename::dirname($self->{filename}));
436 PublicInbox::Over::connect($self);