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::SearchMsg 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, $mid0, $mids) = @_;
220 my $mime = $smsg->{mime};
221 my $hdr = $mime->header_obj;
222 my $refs = references($hdr);
223 push(@$refs, @$mids) if scalar(@$mids) > 1;
224 return $refs if scalar(@$refs) == 0;
226 # prevent circular references here:
227 my %seen = ( $mid0 => 1 );
229 foreach my $ref (@$refs) {
230 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
231 warn "References: <$ref> too long, ignoring\n";
234 push(@keep, $ref) unless $seen{$ref}++;
236 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
240 # normalize subjects so they are suitable as pathnames for URLs
241 # XXX: consider for removal
242 sub subject_path ($) {
244 $subj = subject_normalized($subj);
245 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
250 my ($self, $mime, $bytes, $num, $oid, $mid0, $times) = @_;
251 my $lines = $mime->body_raw =~ tr!\n!\n!;
258 }, 'PublicInbox::SearchMsg';
259 my $hdr = $mime->header_obj;
260 my $mids = mids_for_index($hdr);
261 my $refs = parse_references($smsg, $mid0, $mids);
262 my $subj = $smsg->subject;
265 $xpath = subject_path($subj);
266 $xpath = id_compress($xpath);
268 my $dd = $smsg->to_doc_data($oid, $mid0);
271 my $ds = msg_timestamp($hdr, $times->{autime});
272 my $ts = msg_datestamp($hdr, $times->{cotime});
273 my $values = [ $ts, $ds, $num, $mids, $refs, $xpath, $dd ];
274 add_over($self, $values);
278 my ($self, $values) = @_;
279 my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
284 $self->delete_by_num($num, \$old_tid);
285 foreach my $mid (@$mids) {
287 each_by_mid($self, $mid, ['tid'], sub {
289 my $cur_tid = $cur->{tid};
291 die "num must not be zero for $mid" if !$n;
292 $old_tid = $cur_tid unless defined $old_tid;
293 if ($n > 0) { # regular mail
294 merge_threads($self, $old_tid, $cur_tid);
295 } elsif ($n < 0) { # ghost
296 link_refs($self, $refs, $old_tid);
297 $self->delete_by_num($n);
302 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
305 my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
306 my $sid = $self->sid($xpath);
307 my $dbh = $self->{dbh};
308 my $sth = $dbh->prepare_cached(<<'');
309 INSERT INTO over (num, tid, sid, ts, ds, ddd)
313 my @v = ($num, $tid, $sid, $ts, $ds);
314 foreach (@v) { $sth->bind_param(++$n, $_) }
315 $sth->bind_param(++$n, $ddd, SQL_BLOB);
317 $sth = $dbh->prepare_cached(<<'');
318 INSERT INTO id2num (id, num) VALUES (?,?)
320 foreach my $mid (@$mids) {
321 my $id = $self->mid2id($mid);
322 $sth->execute($id, $num);
326 # returns number of removed messages
327 # $oid may be undef to match only on $mid
329 my ($self, $oid, $mid) = @_;
332 each_by_mid($self, $mid, ['ddd'], sub {
334 if (!defined($oid) || $smsg->{blob} eq $oid) {
335 $self->delete_by_num($smsg->{num});
343 sub num_mid0_for_oid {
344 my ($self, $oid, $mid) = @_;
347 each_by_mid($self, $mid, ['ddd'], sub {
349 my $blob = $smsg->{blob};
350 return 1 if (!defined($blob) || $blob ne $oid); # continue;
351 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
361 CREATE TABLE IF NOT EXISTS over (
362 num INTEGER NOT NULL,
363 tid INTEGER NOT NULL,
367 ddd VARBINARY, /* doc-data-deflated */
371 $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
372 $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
373 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
374 $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
377 CREATE TABLE IF NOT EXISTS counter (
378 key VARCHAR(8) PRIMARY KEY NOT NULL,
379 val INTEGER DEFAULT 0,
383 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
384 $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
387 CREATE TABLE IF NOT EXISTS subject (
388 sid INTEGER PRIMARY KEY AUTOINCREMENT,
389 path VARCHAR(40) NOT NULL,
394 CREATE TABLE IF NOT EXISTS id2num (
396 num INTEGER NOT NULL,
400 # performance critical:
401 $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
402 $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
405 CREATE TABLE IF NOT EXISTS msgid (
406 id INTEGER PRIMARY KEY AUTOINCREMENT,
407 mid VARCHAR(244) NOT NULL,
415 delete $self->{txn} or return;
416 $self->{dbh}->commit;
421 return if $self->{txn};
422 my $dbh = $self->connect or return;
424 # $dbh->{Profile} = 2;
430 delete $self->{txn} or return;
431 $self->{dbh}->rollback;
436 die "in transaction" if $self->{txn};
437 $self->{dbh} = undef;
442 unless (-r $self->{filename}) {
444 require File::Basename;
445 File::Path::mkpath(File::Basename::dirname($self->{filename}));
448 PublicInbox::Over::connect($self);