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