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