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