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 PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
19 use Compress::Zlib qw(compress);
20 use PublicInbox::Search;
24 my $dbh = $self->SUPER::dbh_new(1);
25 $dbh->do('PRAGMA journal_mode = TRUNCATE');
26 $dbh->do('PRAGMA cache_size = 80000');
31 sub get_counter ($$) {
33 my $sth = $dbh->prepare_cached(<<'', undef, 1);
34 SELECT val FROM counter WHERE key = ? LIMIT 1
40 sub adj_counter ($$$) {
41 my ($self, $key, $op) = @_;
42 my $dbh = $self->{dbh};
43 my $sth = $dbh->prepare_cached(<<"");
44 UPDATE counter SET val = val $op 1 WHERE key = ?
48 get_counter($dbh, $key);
51 sub next_tid { adj_counter($_[0], 'thread', '+') }
52 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
55 my ($self, $tbl, $id_col, $val_col, $val) = @_;
56 my $dbh = $self->{dbh};
57 my $in = $dbh->prepare_cached(<<"")->execute($val);
58 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
61 my $sth = $dbh->prepare_cached(<<"", undef, 1);
62 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
67 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
72 my ($self, $path) = @_;
73 return unless defined $path && $path ne '';
74 id_for($self, 'subject', 'sid', 'path' => $path);
78 my ($self, $mid) = @_;
79 id_for($self, 'msgid', 'id', 'mid' => $mid);
83 my ($self, $num, $tid_ref) = @_;
84 my $dbh = $self->{dbh};
86 my $sth = $dbh->prepare_cached(<<'', undef, 1);
87 SELECT tid FROM over WHERE num = ? LIMIT 1
90 $$tid_ref = $sth->fetchrow_array; # may be undef
92 foreach (qw(over id2num)) {
93 $dbh->prepare_cached(<<"")->execute($num);
94 DELETE FROM $_ WHERE num = ?
99 # this includes ghosts
101 my ($self, $mid, $cols, $cb) = @_;
102 my $dbh = $self->{dbh};
105 I originally wanted to stuff everything into a single query:
107 SELECT over.* FROM over
108 LEFT JOIN id2num ON over.num = id2num.num
109 LEFT JOIN msgid ON msgid.id = id2num.id
110 WHERE msgid.mid = ? AND over.num >= ?
111 ORDER BY over.num ASC
114 But it's faster broken out (and we're always in a
115 transaction for subroutines in this file)
118 my $sth = $dbh->prepare_cached(<<'', undef, 1);
119 SELECT id FROM msgid WHERE mid = ? LIMIT 1
122 my $id = $sth->fetchrow_array;
123 defined $id or return;
126 $cols = join(',', map { $_ } @$cols);
128 my $prev = get_counter($dbh, 'ghost');
130 $sth = $dbh->prepare_cached(<<"", undef, 1);
131 SELECT num FROM id2num WHERE id = ? AND num >= ?
135 $sth->execute($id, $prev);
136 my $nums = $sth->fetchall_arrayref;
137 my $nr = scalar(@$nums) or return;
138 $prev = $nums->[-1]->[0];
140 $sth = $dbh->prepare_cached(<<"", undef, 1);
141 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
144 $sth->execute($_->[0]);
145 my $smsg = $sth->fetchrow_hashref;
146 $cb->(PublicInbox::Over::load_from_row($smsg)) or
149 return if $nr != $lim;
153 # this will create a ghost as necessary
154 sub resolve_mid_to_tid {
155 my ($self, $mid) = @_;
157 each_by_mid($self, $mid, ['tid'], sub {
159 my $cur_tid = $smsg->{tid};
161 merge_threads($self, $tid, $cur_tid);
167 defined $tid ? $tid : create_ghost($self, $mid);
171 my ($self, $mid) = @_;
172 my $id = $self->mid2id($mid);
173 my $num = $self->next_ghost_num;
174 $num < 0 or die "ghost num is non-negative: $num\n";
175 my $tid = $self->next_tid;
176 my $dbh = $self->{dbh};
177 $dbh->prepare_cached(<<'')->execute($num, $tid);
178 INSERT INTO over (num, tid) VALUES (?,?)
180 $dbh->prepare_cached(<<'')->execute($id, $num);
181 INSERT INTO id2num (id, num) VALUES (?,?)
187 my ($self, $winner_tid, $loser_tid) = @_;
188 return if $winner_tid == $loser_tid;
189 my $dbh = $self->{dbh};
190 $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
191 UPDATE over SET tid = ? WHERE tid = ?
196 my ($self, $refs, $old_tid) = @_;
200 # first ref *should* be the thread root,
201 # but we can never trust clients to do the right thing
202 my $ref = $refs->[0];
203 $tid = resolve_mid_to_tid($self, $ref);
204 merge_threads($self, $tid, $old_tid) if defined $old_tid;
206 # the rest of the refs should point to this tid:
207 foreach my $i (1..$#$refs) {
209 my $ptid = resolve_mid_to_tid($self, $ref);
210 merge_threads($self, $tid, $ptid);
213 $tid = defined $old_tid ? $old_tid : $self->next_tid;
218 sub parse_references ($$$) {
219 my ($smsg, $hdr, $mids) = @_;
220 my $refs = references($hdr);
221 push(@$refs, @$mids) if scalar(@$mids) > 1;
222 return $refs if scalar(@$refs) == 0;
224 # prevent circular references here:
225 my %seen = ( $smsg->{mid} => 1 );
227 foreach my $ref (@$refs) {
228 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
229 warn "References: <$ref> too long, ignoring\n";
232 push(@keep, $ref) unless $seen{$ref}++;
234 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
238 # normalize subjects so they are suitable as pathnames for URLs
239 # XXX: consider for removal
240 sub subject_path ($) {
242 $subj = subject_normalized($subj);
243 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
248 my ($self, $mime, $bytes, $num, $oid, $mid0, $times) = @_;
249 my $lines = $mime->body_raw =~ tr!\n!\n!;
256 }, 'PublicInbox::Smsg';
257 my $hdr = $mime->header_obj;
258 my $mids = mids_for_index($hdr);
259 my $refs = parse_references($smsg, $hdr, $mids);
260 my $subj = $smsg->subject;
263 $xpath = subject_path($subj);
264 $xpath = id_compress($xpath);
266 my $dd = $smsg->to_doc_data;
269 my $ds = msg_timestamp($hdr, $times->{autime});
270 my $ts = msg_datestamp($hdr, $times->{cotime});
271 my $values = [ $ts, $ds, $num, $mids, $refs, $xpath, $dd ];
272 add_over($self, $values);
276 my ($self, $values) = @_;
277 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
282 $self->delete_by_num($num, \$old_tid);
283 foreach my $mid (@$mids) {
285 each_by_mid($self, $mid, ['tid'], sub {
287 my $cur_tid = $cur->{tid};
289 die "num must not be zero for $mid" if !$n;
290 $old_tid = $cur_tid unless defined $old_tid;
291 if ($n > 0) { # regular mail
292 merge_threads($self, $old_tid, $cur_tid);
293 } elsif ($n < 0) { # ghost
294 link_refs($self, $refs, $old_tid);
295 $self->delete_by_num($n);
300 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
303 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
304 my $sid = $self->sid($xpath);
305 my $dbh = $self->{dbh};
306 my $sth = $dbh->prepare_cached(<<'');
307 INSERT INTO over (num, tid, sid, ts, ds, ddd)
311 my @v = ($num, $tid, $sid, $ts, $ds);
312 foreach (@v) { $sth->bind_param(++$n, $_) }
313 $sth->bind_param(++$n, $ddd, SQL_BLOB);
315 $sth = $dbh->prepare_cached(<<'');
316 INSERT INTO id2num (id, num) VALUES (?,?)
318 foreach my $mid (@$mids) {
319 my $id = $self->mid2id($mid);
320 $sth->execute($id, $num);
324 # returns number of removed messages
325 # $oid may be undef to match only on $mid
327 my ($self, $oid, $mid) = @_;
330 each_by_mid($self, $mid, ['ddd'], sub {
332 if (!defined($oid) || $smsg->{blob} eq $oid) {
333 $self->delete_by_num($smsg->{num});
341 sub num_mid0_for_oid {
342 my ($self, $oid, $mid) = @_;
345 each_by_mid($self, $mid, ['ddd'], sub {
347 my $blob = $smsg->{blob};
348 return 1 if (!defined($blob) || $blob ne $oid); # continue;
349 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
359 CREATE TABLE IF NOT EXISTS over (
360 num INTEGER NOT NULL,
361 tid INTEGER NOT NULL,
365 ddd VARBINARY, /* doc-data-deflated */
369 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
370 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
371 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
372 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
375 CREATE TABLE IF NOT EXISTS counter (
376 key VARCHAR(8) PRIMARY KEY NOT NULL,
377 val INTEGER DEFAULT 0,
381 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
382 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
385 CREATE TABLE IF NOT EXISTS subject (
386 sid INTEGER PRIMARY KEY AUTOINCREMENT,
387 path VARCHAR(40) NOT NULL,
392 CREATE TABLE IF NOT EXISTS id2num (
394 num INTEGER NOT NULL,
398 # performance critical:
399 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
400 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
403 CREATE TABLE IF NOT EXISTS msgid (
404 id INTEGER PRIMARY KEY AUTOINCREMENT,
405 mid VARCHAR(244) NOT NULL,
413 delete $self->{txn} or return;
414 $self->{dbh}->commit;
419 return if $self->{txn};
420 my $dbh = $self->connect or return;
422 # $dbh->{Profile} = 2;
428 delete $self->{txn} or return;
429 $self->{dbh}->rollback;
434 die "in transaction" if $self->{txn};
435 $self->{dbh} = undef;
440 unless (-r $self->{filename}) {
442 require File::Basename;
443 File::Path::mkpath(File::Basename::dirname($self->{filename}));
446 PublicInbox::Over::connect($self);