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