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