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