]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/OverIdx.pm
5821c562b814de635862db755db1c7a42f9954e8
[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 Compress::Zlib qw(compress);
19 use PublicInbox::Search;
20 use Carp qw(croak);
21
22 sub dbh_new {
23         my ($self) = @_;
24         my $dbh = $self->SUPER::dbh_new($self->{-no_sync} ? 2 : 1);
25
26         # TRUNCATE reduces I/O compared to the default (DELETE)
27         # We do not use WAL since we're optimized for read-only ops,
28         # (and read-only requires SQLite 3.22.0 (2018-01-22)).
29         $dbh->do('PRAGMA journal_mode = TRUNCATE');
30
31         # 80000 pages (80MiB on SQLite <3.12.0, 320MiB on 3.12.0+)
32         # was found to be good in 2018 during the large LKML import
33         # at the time.  This ought to be configurable based on HW
34         # and inbox size; I suspect it's overkill for many inboxes.
35         $dbh->do('PRAGMA cache_size = 80000');
36
37         create_tables($dbh);
38         $dbh;
39 }
40
41 sub new {
42         my ($class, $f) = @_;
43         my $self = $class->SUPER::new($f);
44         $self->{min_tid} = 0;
45         $self;
46 }
47
48 sub get_counter ($$) {
49         my ($dbh, $key) = @_;
50         my $sth = $dbh->prepare_cached(<<'', undef, 1);
51 SELECT val FROM counter WHERE key = ? LIMIT 1
52
53         $sth->execute($key);
54         $sth->fetchrow_array;
55 }
56
57 sub adj_counter ($$$) {
58         my ($self, $key, $op) = @_;
59         my $dbh = $self->{dbh};
60         my $sth = $dbh->prepare_cached(<<"");
61 UPDATE counter SET val = val $op 1 WHERE key = ?
62
63         $sth->execute($key);
64
65         get_counter($dbh, $key);
66 }
67
68 sub next_tid { adj_counter($_[0], 'thread', '+') }
69 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
70
71 sub id_for ($$$$$) {
72         my ($self, $tbl, $id_col, $val_col, $val) = @_;
73         my $dbh = $self->{dbh};
74         my $in = $dbh->prepare_cached(<<"")->execute($val);
75 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
76
77         if ($in == 0) {
78                 my $sth = $dbh->prepare_cached(<<"", undef, 1);
79 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
80
81                 $sth->execute($val);
82                 $sth->fetchrow_array;
83         } else {
84                 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
85         }
86 }
87
88 sub sid {
89         my ($self, $path) = @_;
90         return unless defined $path && $path ne '';
91         id_for($self, 'subject', 'sid', 'path' => $path);
92 }
93
94 sub mid2id {
95         my ($self, $mid) = @_;
96         id_for($self, 'msgid', 'id', 'mid' => $mid);
97 }
98
99 sub delete_by_num {
100         my ($self, $num, $tid_ref) = @_;
101         my $dbh = $self->{dbh};
102         if ($tid_ref) {
103                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
104 SELECT tid FROM over WHERE num = ? LIMIT 1
105
106                 $sth->execute($num);
107                 $$tid_ref = $sth->fetchrow_array; # may be undef
108         }
109         foreach (qw(over id2num)) {
110                 $dbh->prepare_cached(<<"")->execute($num);
111 DELETE FROM $_ WHERE num = ?
112
113         }
114 }
115
116 # this includes ghosts
117 sub each_by_mid {
118         my ($self, $mid, $cols, $cb, @arg) = @_;
119         my $dbh = $self->{dbh};
120
121 =over
122         I originally wanted to stuff everything into a single query:
123
124         SELECT over.* FROM over
125         LEFT JOIN id2num ON over.num = id2num.num
126         LEFT JOIN msgid ON msgid.id = id2num.id
127         WHERE msgid.mid = ? AND over.num >= ?
128         ORDER BY over.num ASC
129         LIMIT 1000
130
131         But it's faster broken out (and we're always in a
132         transaction for subroutines in this file)
133 =cut
134
135         my $sth = $dbh->prepare_cached(<<'', undef, 1);
136 SELECT id FROM msgid WHERE mid = ? LIMIT 1
137
138         $sth->execute($mid);
139         my $id = $sth->fetchrow_array;
140         defined $id or return;
141
142         push(@$cols, 'num');
143         $cols = join(',', map { $_ } @$cols);
144         my $lim = 10;
145         my $prev = get_counter($dbh, 'ghost');
146         while (1) {
147                 $sth = $dbh->prepare_cached(<<"", undef, 1);
148 SELECT num FROM id2num WHERE id = ? AND num >= ?
149 ORDER BY num ASC
150 LIMIT $lim
151
152                 $sth->execute($id, $prev);
153                 my $nums = $sth->fetchall_arrayref;
154                 my $nr = scalar(@$nums) or return;
155                 $prev = $nums->[-1]->[0];
156
157                 $sth = $dbh->prepare_cached(<<"", undef, 1);
158 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
159
160                 foreach (@$nums) {
161                         $sth->execute($_->[0]);
162                         my $smsg = $sth->fetchrow_hashref;
163                         $smsg = PublicInbox::Over::load_from_row($smsg);
164                         $cb->($self, $smsg, @arg) or return;
165                 }
166                 return if $nr != $lim;
167         }
168 }
169
170 sub _resolve_mid_to_tid {
171         my ($self, $smsg, $tid) = @_;
172         my $cur_tid = $smsg->{tid};
173         if (defined $$tid) {
174                 merge_threads($self, $$tid, $cur_tid);
175         } elsif ($cur_tid > $self->{min_tid}) {
176                 $$tid = $cur_tid;
177         } else { # rethreading, queue up dead ghosts
178                 $$tid = next_tid($self);
179                 my $num = $smsg->{num};
180                 push(@{$self->{-ghosts_to_delete}}, $num) if $num < 0;
181         }
182         1;
183 }
184
185 # this will create a ghost as necessary
186 sub resolve_mid_to_tid {
187         my ($self, $mid) = @_;
188         my $tid;
189         each_by_mid($self, $mid, ['tid'], \&_resolve_mid_to_tid, \$tid);
190         if (my $del = delete $self->{-ghosts_to_delete}) {
191                 delete_by_num($self, $_) for @$del;
192         }
193         $tid // create_ghost($self, $mid);
194 }
195
196 sub create_ghost {
197         my ($self, $mid) = @_;
198         my $id = mid2id($self, $mid);
199         my $num = next_ghost_num($self);
200         $num < 0 or die "ghost num is non-negative: $num\n";
201         my $tid = next_tid($self);
202         my $dbh = $self->{dbh};
203         $dbh->prepare_cached(<<'')->execute($num, $tid);
204 INSERT INTO over (num, tid) VALUES (?,?)
205
206         $dbh->prepare_cached(<<'')->execute($id, $num);
207 INSERT INTO id2num (id, num) VALUES (?,?)
208
209         $tid;
210 }
211
212 sub merge_threads {
213         my ($self, $winner_tid, $loser_tid) = @_;
214         return if $winner_tid == $loser_tid;
215         my $dbh = $self->{dbh};
216         $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
217 UPDATE over SET tid = ? WHERE tid = ?
218
219 }
220
221 sub link_refs {
222         my ($self, $refs, $old_tid) = @_;
223         my $tid;
224
225         if (@$refs) {
226                 # first ref *should* be the thread root,
227                 # but we can never trust clients to do the right thing
228                 my $ref = $refs->[0];
229                 $tid = resolve_mid_to_tid($self, $ref);
230                 merge_threads($self, $tid, $old_tid) if defined $old_tid;
231
232                 # the rest of the refs should point to this tid:
233                 foreach my $i (1..$#$refs) {
234                         $ref = $refs->[$i];
235                         my $ptid = resolve_mid_to_tid($self, $ref);
236                         merge_threads($self, $tid, $ptid);
237                 }
238         } else {
239                 $tid = $old_tid // next_tid($self);
240         }
241         $tid;
242 }
243
244 sub parse_references ($$$) {
245         my ($smsg, $hdr, $mids) = @_;
246         my $refs = references($hdr);
247         push(@$refs, @$mids) if scalar(@$mids) > 1;
248         return $refs if scalar(@$refs) == 0;
249
250         # prevent circular references here:
251         my %seen = ( $smsg->{mid} => 1 );
252         my @keep;
253         foreach my $ref (@$refs) {
254                 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
255                         warn "References: <$ref> too long, ignoring\n";
256                         next;
257                 }
258                 push(@keep, $ref) unless $seen{$ref}++;
259         }
260         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
261         \@keep;
262 }
263
264 # normalize subjects so they are suitable as pathnames for URLs
265 # XXX: consider for removal
266 sub subject_path ($) {
267         my ($subj) = @_;
268         $subj = subject_normalized($subj);
269         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
270         lc($subj);
271 }
272
273 sub add_overview {
274         my ($self, $mime, $smsg) = @_;
275         $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
276         my $hdr = $mime->header_obj;
277         my $mids = mids_for_index($hdr);
278         my $refs = parse_references($smsg, $hdr, $mids);
279         my $subj = $smsg->{subject};
280         my $xpath;
281         if ($subj ne '') {
282                 $xpath = subject_path($subj);
283                 $xpath = id_compress($xpath);
284         }
285         my $dd = $smsg->to_doc_data;
286         utf8::encode($dd);
287         $dd = compress($dd);
288         add_over($self, [ @$smsg{qw(ts ds num)}, $mids, $refs, $xpath, $dd ]);
289 }
290
291 sub _add_over {
292         my ($self, $smsg, $mid, $refs, $old_tid, $v) = @_;
293         my $cur_tid = $smsg->{tid};
294         my $n = $smsg->{num};
295         die "num must not be zero for $mid" if !$n;
296         my $cur_valid = $cur_tid > $self->{min_tid};
297
298         if ($n > 0) { # regular mail
299                 if ($cur_valid) {
300                         $$old_tid //= $cur_tid;
301                         merge_threads($self, $$old_tid, $cur_tid);
302                 } else {
303                         $$old_tid //= next_tid($self);
304                 }
305         } elsif ($n < 0) { # ghost
306                 $$old_tid //= $cur_valid ? $cur_tid : next_tid($self);
307                 link_refs($self, $refs, $$old_tid);
308                 delete_by_num($self, $n);
309                 $$v++;
310         }
311         1;
312 }
313
314 sub add_over {
315         my ($self, $values) = @_;
316         my ($ts, $ds, $num, $mids, $refs, $xpath, $ddd) = @$values;
317         my $old_tid;
318         my $vivified = 0;
319
320         begin_lazy($self);
321         delete_by_num($self, $num, \$old_tid);
322         $old_tid = undef if ($old_tid // 0) <= $self->{min_tid};
323         foreach my $mid (@$mids) {
324                 my $v = 0;
325                 each_by_mid($self, $mid, ['tid'], \&_add_over,
326                                 $mid, $refs, \$old_tid, \$v);
327                 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
328                 $vivified += $v;
329         }
330         my $tid = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
331         my $sid = sid($self, $xpath);
332         my $dbh = $self->{dbh};
333         my $sth = $dbh->prepare_cached(<<'');
334 INSERT INTO over (num, tid, sid, ts, ds, ddd)
335 VALUES (?,?,?,?,?,?)
336
337         my $n = 0;
338         my @v = ($num, $tid, $sid, $ts, $ds);
339         foreach (@v) { $sth->bind_param(++$n, $_) }
340         $sth->bind_param(++$n, $ddd, SQL_BLOB);
341         $sth->execute;
342         $sth = $dbh->prepare_cached(<<'');
343 INSERT INTO id2num (id, num) VALUES (?,?)
344
345         foreach my $mid (@$mids) {
346                 my $id = mid2id($self, $mid);
347                 $sth->execute($id, $num);
348         }
349 }
350
351 sub _remove_oid {
352         my ($self, $smsg, $oid, $removed) = @_;
353         if (!defined($oid) || $smsg->{blob} eq $oid) {
354                 delete_by_num($self, $smsg->{num});
355                 push @$removed, $smsg->{num};
356         }
357         1;
358 }
359
360 # returns number of removed messages in scalar context,
361 # array of removed article numbers in array context.
362 # $oid may be undef to match only on $mid
363 sub remove_oid {
364         my ($self, $oid, $mid) = @_;
365         my $removed = [];
366         begin_lazy($self);
367         each_by_mid($self, $mid, ['ddd'], \&_remove_oid, $oid, $removed);
368         @$removed;
369 }
370
371 sub _num_mid0_for_oid {
372         my ($self, $smsg, $oid, $res) = @_;
373         my $blob = $smsg->{blob};
374         return 1 if (!defined($blob) || $blob ne $oid); # continue;
375         @$res = ($smsg->{num}, $smsg->{mid});
376         0; # done
377 }
378
379 sub num_mid0_for_oid {
380         my ($self, $oid, $mid) = @_;
381         my $res = [];
382         begin_lazy($self);
383         each_by_mid($self, $mid, ['ddd'], \&_num_mid0_for_oid, $oid, $res);
384         @$res, # ($num, $mid0);
385 }
386
387 sub create_tables {
388         my ($dbh) = @_;
389
390         $dbh->do(<<'');
391 CREATE TABLE IF NOT EXISTS over (
392         num INTEGER NOT NULL,
393         tid INTEGER NOT NULL,
394         sid INTEGER,
395         ts INTEGER,
396         ds INTEGER,
397         ddd VARBINARY, /* doc-data-deflated */
398         UNIQUE (num)
399 )
400
401         $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
402         $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
403         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
404         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
405
406         $dbh->do(<<'');
407 CREATE TABLE IF NOT EXISTS counter (
408         key VARCHAR(8) PRIMARY KEY NOT NULL,
409         val INTEGER DEFAULT 0,
410         UNIQUE (key)
411 )
412
413         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
414         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
415
416         $dbh->do(<<'');
417 CREATE TABLE IF NOT EXISTS subject (
418         sid INTEGER PRIMARY KEY AUTOINCREMENT,
419         path VARCHAR(40) NOT NULL,
420         UNIQUE (path)
421 )
422
423         $dbh->do(<<'');
424 CREATE TABLE IF NOT EXISTS id2num (
425         id INTEGER NOT NULL,
426         num INTEGER NOT NULL,
427         UNIQUE (id, num)
428 )
429
430         # performance critical:
431         $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
432         $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
433
434         $dbh->do(<<'');
435 CREATE TABLE IF NOT EXISTS msgid (
436         id INTEGER PRIMARY KEY AUTOINCREMENT,
437         mid VARCHAR(244) NOT NULL,
438         UNIQUE (mid)
439 )
440
441 }
442
443 sub commit_lazy {
444         my ($self) = @_;
445         delete $self->{txn} or return;
446         $self->{dbh}->commit;
447 }
448
449 sub begin_lazy {
450         my ($self) = @_;
451         return if $self->{txn};
452         my $dbh = $self->connect or return;
453         $dbh->begin_work;
454         # $dbh->{Profile} = 2;
455         $self->{txn} = 1;
456 }
457
458 sub rollback_lazy {
459         my ($self) = @_;
460         delete $self->{txn} or return;
461         $self->{dbh}->rollback;
462 }
463
464 sub disconnect {
465         my ($self) = @_;
466         die "in transaction" if $self->{txn};
467         $self->SUPER::disconnect;
468 }
469
470 sub create {
471         my ($self) = @_;
472         unless (-r $self->{filename}) {
473                 require File::Path;
474                 require File::Basename;
475                 File::Path::mkpath(File::Basename::dirname($self->{filename}));
476         }
477         # create the DB:
478         PublicInbox::Over::connect($self);
479         $self->disconnect;
480 }
481
482 sub rethread_prepare {
483         my ($self, $opt) = @_;
484         return unless $opt->{rethread};
485         begin_lazy($self);
486         my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
487         my $pr = $opt->{-progress};
488         $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
489 }
490
491 sub rethread_done {
492         my ($self, $opt) = @_;
493         return unless $opt->{rethread} && $self->{txn};
494         defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
495         my $dbh = $self->{dbh} or croak('BUG: no dbh');
496         my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
497 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
498
499         my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
500         my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
501         my $pr = $opt->{-progress};
502         my $total = 0;
503         for my $r (@$rows) {
504                 my $exp = 0;
505                 $show_id->execute($r->{num});
506                 while (defined(my $id = $show_id->fetchrow_array)) {
507                         ++$exp;
508                         $show_mid->execute($id);
509                         my $mid = $show_mid->fetchrow_array;
510                         if (!defined($mid)) {
511                                 warn <<EOF;
512 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
513 EOF
514                                 next;
515                         }
516                         $pr->(<<EOM) if $pr;
517 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
518 EOM
519                 }
520                 delete_by_num($self, $r->{num});
521         }
522         $pr->("I: rethread culled $total ghosts\n") if $pr && $total;
523 }
524
525 1;