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, $smsg, $times) = @_;
249 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
250 $smsg->{mime} = $mime; # XXX temporary?
251 my $hdr = $mime->header_obj;
252 my $mids = mids_for_index($hdr);
253 my $refs = parse_references($smsg, $hdr, $mids);
254 my $subj = $smsg->subject;
257 $xpath = subject_path($subj);
258 $xpath = id_compress($xpath);
260 my $dd = $smsg->to_doc_data;
263 my $ds = msg_timestamp($hdr, $times->{autime});
264 my $ts = msg_datestamp($hdr, $times->{cotime});
265 my $values = [ $ts, $ds, $smsg->{num}, $mids, $refs, $xpath, $dd ];
266 add_over($self, $values);
270 my ($self, $values) = @_;
271 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
276 $self->delete_by_num($num, \$old_tid);
277 foreach my $mid (@$mids) {
279 each_by_mid($self, $mid, ['tid'], sub {
281 my $cur_tid = $cur->{tid};
283 die "num must not be zero for $mid" if !$n;
284 $old_tid = $cur_tid unless defined $old_tid;
285 if ($n > 0) { # regular mail
286 merge_threads($self, $old_tid, $cur_tid);
287 } elsif ($n < 0) { # ghost
288 link_refs($self, $refs, $old_tid);
289 $self->delete_by_num($n);
294 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
297 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
298 my $sid = $self->sid($xpath);
299 my $dbh = $self->{dbh};
300 my $sth = $dbh->prepare_cached(<<'');
301 INSERT INTO over (num, tid, sid, ts, ds, ddd)
305 my @v = ($num, $tid, $sid, $ts, $ds);
306 foreach (@v) { $sth->bind_param(++$n, $_) }
307 $sth->bind_param(++$n, $ddd, SQL_BLOB);
309 $sth = $dbh->prepare_cached(<<'');
310 INSERT INTO id2num (id, num) VALUES (?,?)
312 foreach my $mid (@$mids) {
313 my $id = $self->mid2id($mid);
314 $sth->execute($id, $num);
318 # returns number of removed messages
319 # $oid may be undef to match only on $mid
321 my ($self, $oid, $mid) = @_;
324 each_by_mid($self, $mid, ['ddd'], sub {
326 if (!defined($oid) || $smsg->{blob} eq $oid) {
327 $self->delete_by_num($smsg->{num});
335 sub num_mid0_for_oid {
336 my ($self, $oid, $mid) = @_;
339 each_by_mid($self, $mid, ['ddd'], sub {
341 my $blob = $smsg->{blob};
342 return 1 if (!defined($blob) || $blob ne $oid); # continue;
343 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
353 CREATE TABLE IF NOT EXISTS over (
354 num INTEGER NOT NULL,
355 tid INTEGER NOT NULL,
359 ddd VARBINARY, /* doc-data-deflated */
363 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
364 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
365 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
366 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
369 CREATE TABLE IF NOT EXISTS counter (
370 key VARCHAR(8) PRIMARY KEY NOT NULL,
371 val INTEGER DEFAULT 0,
375 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
376 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
379 CREATE TABLE IF NOT EXISTS subject (
380 sid INTEGER PRIMARY KEY AUTOINCREMENT,
381 path VARCHAR(40) NOT NULL,
386 CREATE TABLE IF NOT EXISTS id2num (
388 num INTEGER NOT NULL,
392 # performance critical:
393 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
394 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
397 CREATE TABLE IF NOT EXISTS msgid (
398 id INTEGER PRIMARY KEY AUTOINCREMENT,
399 mid VARCHAR(244) NOT NULL,
407 delete $self->{txn} or return;
408 $self->{dbh}->commit;
413 return if $self->{txn};
414 my $dbh = $self->connect or return;
416 # $dbh->{Profile} = 2;
422 delete $self->{txn} or return;
423 $self->{dbh}->rollback;
428 die "in transaction" if $self->{txn};
429 $self->{dbh} = undef;
434 unless (-r $self->{filename}) {
436 require File::Basename;
437 File::Path::mkpath(File::Basename::dirname($self->{filename}));
440 PublicInbox::Over::connect($self);