]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/OverIdx.pm
9640f9d13bf57b1e9ae23d48bf9c7c41930b3b4b
[public-inbox.git] / lib / PublicInbox / OverIdx.pm
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>
3
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.
7 #
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;
11 use strict;
12 use warnings;
13 use base qw(PublicInbox::Over);
14 use IO::Handle;
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;
21
22 sub dbh_new {
23         my ($self) = @_;
24         my $dbh = $self->SUPER::dbh_new(1);
25         $dbh->do('PRAGMA journal_mode = TRUNCATE');
26         $dbh->do('PRAGMA cache_size = 80000');
27         create_tables($dbh);
28         $dbh;
29 }
30
31 sub get_counter ($$) {
32         my ($dbh, $key) = @_;
33         my $sth = $dbh->prepare_cached(<<'', undef, 1);
34 SELECT val FROM counter WHERE key = ? LIMIT 1
35
36         $sth->execute($key);
37         $sth->fetchrow_array;
38 }
39
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 = ?
45
46         $sth->execute($key);
47
48         get_counter($dbh, $key);
49 }
50
51 sub next_tid { adj_counter($_[0], 'thread', '+') }
52 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
53
54 sub id_for ($$$$$) {
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 (?)
59
60         if ($in == 0) {
61                 my $sth = $dbh->prepare_cached(<<"", undef, 1);
62 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
63
64                 $sth->execute($val);
65                 $sth->fetchrow_array;
66         } else {
67                 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
68         }
69 }
70
71 sub sid {
72         my ($self, $path) = @_;
73         return unless defined $path && $path ne '';
74         id_for($self, 'subject', 'sid', 'path' => $path);
75 }
76
77 sub mid2id {
78         my ($self, $mid) = @_;
79         id_for($self, 'msgid', 'id', 'mid' => $mid);
80 }
81
82 sub delete_by_num {
83         my ($self, $num, $tid_ref) = @_;
84         my $dbh = $self->{dbh};
85         if ($tid_ref) {
86                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
87 SELECT tid FROM over WHERE num = ? LIMIT 1
88
89                 $sth->execute($num);
90                 $$tid_ref = $sth->fetchrow_array; # may be undef
91         }
92         foreach (qw(over id2num)) {
93                 $dbh->prepare_cached(<<"")->execute($num);
94 DELETE FROM $_ WHERE num = ?
95
96         }
97 }
98
99 # this includes ghosts
100 sub each_by_mid {
101         my ($self, $mid, $cols, $cb) = @_;
102         my $dbh = $self->{dbh};
103
104 =over
105         I originally wanted to stuff everything into a single query:
106
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
112         LIMIT 1000
113
114         But it's faster broken out (and we're always in a
115         transaction for subroutines in this file)
116 =cut
117
118         my $sth = $dbh->prepare_cached(<<'', undef, 1);
119 SELECT id FROM msgid WHERE mid = ? LIMIT 1
120
121         $sth->execute($mid);
122         my $id = $sth->fetchrow_array;
123         defined $id or return;
124
125         push(@$cols, 'num');
126         $cols = join(',', map { $_ } @$cols);
127         my $lim = 10;
128         my $prev = get_counter($dbh, 'ghost');
129         while (1) {
130                 $sth = $dbh->prepare_cached(<<"", undef, 1);
131 SELECT num FROM id2num WHERE id = ? AND num >= ?
132 ORDER BY num ASC
133 LIMIT $lim
134
135                 $sth->execute($id, $prev);
136                 my $nums = $sth->fetchall_arrayref;
137                 my $nr = scalar(@$nums) or return;
138                 $prev = $nums->[-1]->[0];
139
140                 $sth = $dbh->prepare_cached(<<"", undef, 1);
141 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
142
143                 foreach (@$nums) {
144                         $sth->execute($_->[0]);
145                         my $smsg = $sth->fetchrow_hashref;
146                         $cb->(PublicInbox::Over::load_from_row($smsg)) or
147                                 return;
148                 }
149                 return if $nr != $lim;
150         }
151 }
152
153 # this will create a ghost as necessary
154 sub resolve_mid_to_tid {
155         my ($self, $mid) = @_;
156         my $tid;
157         each_by_mid($self, $mid, ['tid'], sub {
158                 my ($smsg) = @_;
159                 my $cur_tid = $smsg->{tid};
160                 if (defined $tid) {
161                         merge_threads($self, $tid, $cur_tid);
162                 } else {
163                         $tid = $cur_tid;
164                 }
165                 1;
166         });
167         defined $tid ? $tid : create_ghost($self, $mid);
168 }
169
170 sub create_ghost {
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 (?,?)
179
180         $dbh->prepare_cached(<<'')->execute($id, $num);
181 INSERT INTO id2num (id, num) VALUES (?,?)
182
183         $tid;
184 }
185
186 sub merge_threads {
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 = ?
192
193 }
194
195 sub link_refs {
196         my ($self, $refs, $old_tid) = @_;
197         my $tid;
198
199         if (@$refs) {
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;
205
206                 # the rest of the refs should point to this tid:
207                 foreach my $i (1..$#$refs) {
208                         $ref = $refs->[$i];
209                         my $ptid = resolve_mid_to_tid($self, $ref);
210                         merge_threads($self, $tid, $ptid);
211                 }
212         } else {
213                 $tid = defined $old_tid ? $old_tid : $self->next_tid;
214         }
215         $tid;
216 }
217
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;
225
226         # prevent circular references here:
227         my %seen = ( $mid0 => 1 );
228         my @keep;
229         foreach my $ref (@$refs) {
230                 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
231                         warn "References: <$ref> too long, ignoring\n";
232                         next;
233                 }
234                 push(@keep, $ref) unless $seen{$ref}++;
235         }
236         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
237         \@keep;
238 }
239
240 # normalize subjects so they are suitable as pathnames for URLs
241 # XXX: consider for removal
242 sub subject_path ($) {
243         my ($subj) = @_;
244         $subj = subject_normalized($subj);
245         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
246         lc($subj);
247 }
248
249 sub add_overview {
250         my ($self, $mime, $bytes, $num, $oid, $mid0, $times) = @_;
251         my $lines = $mime->body_raw =~ tr!\n!\n!;
252         my $smsg = bless {
253                 mime => $mime,
254                 mid => $mid0,
255                 bytes => $bytes,
256                 lines => $lines,
257                 blob => $oid,
258         }, 'PublicInbox::Smsg';
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;
263         my $xpath;
264         if ($subj ne '') {
265                 $xpath = subject_path($subj);
266                 $xpath = id_compress($xpath);
267         }
268         my $dd = $smsg->to_doc_data;
269         utf8::encode($dd);
270         $dd = compress($dd);
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);
275 }
276
277 sub add_over {
278         my ($self, $values) = @_;
279         my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
280         my $old_tid;
281         my $vivified = 0;
282
283         $self->begin_lazy;
284         $self->delete_by_num($num, \$old_tid);
285         foreach my $mid (@$mids) {
286                 my $v = 0;
287                 each_by_mid($self, $mid, ['tid'], sub {
288                         my ($cur) = @_;
289                         my $cur_tid = $cur->{tid};
290                         my $n = $cur->{num};
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);
298                                 $v++;
299                         }
300                         1;
301                 });
302                 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
303                 $vivified += $v;
304         }
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)
310 VALUES (?,?,?,?,?,?)
311
312         my $n = 0;
313         my @v = ($num, $tid, $sid, $ts, $ds);
314         foreach (@v) { $sth->bind_param(++$n, $_) }
315         $sth->bind_param(++$n, $ddd, SQL_BLOB);
316         $sth->execute;
317         $sth = $dbh->prepare_cached(<<'');
318 INSERT INTO id2num (id, num) VALUES (?,?)
319
320         foreach my $mid (@$mids) {
321                 my $id = $self->mid2id($mid);
322                 $sth->execute($id, $num);
323         }
324 }
325
326 # returns number of removed messages
327 # $oid may be undef to match only on $mid
328 sub remove_oid {
329         my ($self, $oid, $mid) = @_;
330         my $nr = 0;
331         $self->begin_lazy;
332         each_by_mid($self, $mid, ['ddd'], sub {
333                 my ($smsg) = @_;
334                 if (!defined($oid) || $smsg->{blob} eq $oid) {
335                         $self->delete_by_num($smsg->{num});
336                         $nr++;
337                 }
338                 1;
339         });
340         $nr;
341 }
342
343 sub num_mid0_for_oid {
344         my ($self, $oid, $mid) = @_;
345         my ($num, $mid0);
346         $self->begin_lazy;
347         each_by_mid($self, $mid, ['ddd'], sub {
348                 my ($smsg) = @_;
349                 my $blob = $smsg->{blob};
350                 return 1 if (!defined($blob) || $blob ne $oid); # continue;
351                 ($num, $mid0) = ($smsg->{num}, $smsg->{mid});
352                 0; # done
353         });
354         ($num, $mid0);
355 }
356
357 sub create_tables {
358         my ($dbh) = @_;
359
360         $dbh->do(<<'');
361 CREATE TABLE IF NOT EXISTS over (
362         num INTEGER NOT NULL,
363         tid INTEGER NOT NULL,
364         sid INTEGER,
365         ts INTEGER,
366         ds INTEGER,
367         ddd VARBINARY, /* doc-data-deflated */
368         UNIQUE (num)
369 )
370
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)');
375
376         $dbh->do(<<'');
377 CREATE TABLE IF NOT EXISTS counter (
378         key VARCHAR(8) PRIMARY KEY NOT NULL,
379         val INTEGER DEFAULT 0,
380         UNIQUE (key)
381 )
382
383         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
384         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
385
386         $dbh->do(<<'');
387 CREATE TABLE IF NOT EXISTS subject (
388         sid INTEGER PRIMARY KEY AUTOINCREMENT,
389         path VARCHAR(40) NOT NULL,
390         UNIQUE (path)
391 )
392
393         $dbh->do(<<'');
394 CREATE TABLE IF NOT EXISTS id2num (
395         id INTEGER NOT NULL,
396         num INTEGER NOT NULL,
397         UNIQUE (id, num)
398 )
399
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)');
403
404         $dbh->do(<<'');
405 CREATE TABLE IF NOT EXISTS msgid (
406         id INTEGER PRIMARY KEY AUTOINCREMENT,
407         mid VARCHAR(244) NOT NULL,
408         UNIQUE (mid)
409 )
410
411 }
412
413 sub commit_lazy {
414         my ($self) = @_;
415         delete $self->{txn} or return;
416         $self->{dbh}->commit;
417 }
418
419 sub begin_lazy {
420         my ($self) = @_;
421         return if $self->{txn};
422         my $dbh = $self->connect or return;
423         $dbh->begin_work;
424         # $dbh->{Profile} = 2;
425         $self->{txn} = 1;
426 }
427
428 sub rollback_lazy {
429         my ($self) = @_;
430         delete $self->{txn} or return;
431         $self->{dbh}->rollback;
432 }
433
434 sub disconnect {
435         my ($self) = @_;
436         die "in transaction" if $self->{txn};
437         $self->{dbh} = undef;
438 }
439
440 sub create {
441         my ($self) = @_;
442         unless (-r $self->{filename}) {
443                 require File::Path;
444                 require File::Basename;
445                 File::Path::mkpath(File::Basename::dirname($self->{filename}));
446         }
447         # create the DB:
448         PublicInbox::Over::connect($self);
449         $self->disconnect;
450 }
451
452 1;