]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: remove "resent" message for duplicate Message-IDs
[public-inbox.git] / lib / PublicInbox / V2Writable.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 # This interface wraps and mimics PublicInbox::Import
5 package PublicInbox::V2Writable;
6 use strict;
7 use warnings;
8 use base qw(PublicInbox::Lock);
9 use PublicInbox::SearchIdxPart;
10 use PublicInbox::SearchIdxSkeleton;
11 use PublicInbox::MIME;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids);
15 use PublicInbox::ContentId qw(content_id content_digest);
16 use PublicInbox::Inbox;
17
18 # an estimate of the post-packed size to the raw uncompressed size
19 my $PACKING_FACTOR = 0.4;
20
21 # assume 2 cores if GNU nproc(1) is not available
22 sub nproc () {
23         int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
24 }
25
26 sub new {
27         my ($class, $v2ibx, $creat) = @_;
28         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
29         unless (-d $dir) {
30                 if ($creat) {
31                         require File::Path;
32                         File::Path::mkpath($dir);
33                 } else {
34                         die "$dir does not exist\n";
35                 }
36         }
37
38         my $nparts = 0;
39         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
40
41         # always load existing partitions in case core count changes:
42         if (-d $xpfx) {
43                 foreach my $part (<$xpfx/*>) {
44                         -d $part && $part =~ m!/\d+\z! or next;
45                         eval {
46                                 Search::Xapian::Database->new($part)->close;
47                                 $nparts++;
48                         };
49                 }
50         }
51         $nparts = nproc() if ($nparts == 0);
52
53         my $self = {
54                 -inbox => $v2ibx,
55                 im => undef, #  PublicInbox::Import
56                 xap_rw => undef, # PublicInbox::V2SearchIdx
57                 xap_ro => undef,
58                 partitions => $nparts,
59                 parallel => 1,
60                 transact_bytes => 0,
61                 lock_path => "$dir/inbox.lock",
62                 # limit each repo to 1GB or so
63                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
64         };
65         bless $self, $class;
66 }
67
68 # returns undef on duplicate or spam
69 # mimics Import::add and wraps it for v2
70 sub add {
71         my ($self, $mime, $check_cb) = @_;
72
73         # spam check:
74         if ($check_cb) {
75                 $mime = $check_cb->($mime) or return;
76         }
77
78         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
79         # as does SQLite 3.4.1+ (released in 2007-07-20), and
80         # Xapian 1.3.2+ (released 2015-03-15).
81         # For the most part, we can spawn git-fast-import without
82         # leaking FDs to it...
83         $self->idx_init;
84
85         my $mid0;
86         my $num = num_for($self, $mime, \$mid0);
87         defined $num or return; # duplicate
88         defined $mid0 or die "BUG: $mid0 undefined\n";
89         my $im = $self->importer;
90         my $cmt = $im->add($mime);
91         $cmt = $im->get_mark($cmt);
92         my ($oid, $len, $msgref) = @{$im->{last_object}};
93
94         my $nparts = $self->{partitions};
95         my $part = $num % $nparts;
96         my $idx = $self->idx_part($part);
97         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
98         my $n = $self->{transact_bytes} += $len;
99         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
100                 $self->checkpoint;
101         }
102
103         $mime;
104 }
105
106 sub num_for {
107         my ($self, $mime, $mid0) = @_;
108         my $mids = mids($mime->header_obj);
109         if (@$mids) {
110                 my $mid = $mids->[0];
111                 my $num = $self->{skel}->{mm}->mid_insert($mid);
112                 if (defined $num) { # common case
113                         $$mid0 = $mid;
114                         return $num;
115                 };
116
117                 # crap, Message-ID is already known, hope somebody just resent:
118                 $self->barrier;
119                 foreach my $m (@$mids) {
120                         # read-only lookup now safe to do after above barrier
121                         my $existing = $self->lookup_content($mime, $m);
122                         # easy, don't store duplicates
123                         # note: do not add more diagnostic info here since
124                         # it gets noisy on public-inbox-watch restarts
125                         return if $existing;
126                 }
127
128                 # very unlikely:
129                 warn "<$mid> reused for mismatched content\n";
130
131                 # try the rest of the mids
132                 foreach my $i (1..$#$mids) {
133                         my $m = $mids->[$i];
134                         $num = $self->{skel}->{mm}->mid_insert($m);
135                         if (defined $num) {
136                                 warn "alternative <$m> for <$mid> found\n";
137                                 $$mid0 = $m;
138                                 return $num;
139                         }
140                 }
141         }
142         # none of the existing Message-IDs are good, generate a new one:
143         num_for_harder($self, $mime, $mid0);
144 }
145
146 sub num_for_harder {
147         my ($self, $mime, $mid0) = @_;
148
149         my $hdr = $mime->header_obj;
150         my $dig = content_digest($mime);
151         $$mid0 = PublicInbox::Import::digest2mid($dig);
152         my $num = $self->{skel}->{mm}->mid_insert($$mid0);
153         unless (defined $num) {
154                 # it's hard to spoof the last Received: header
155                 my @recvd = $hdr->header_raw('Received');
156                 $dig->add("Received: $_") foreach (@recvd);
157                 $$mid0 = PublicInbox::Import::digest2mid($dig);
158                 $num = $self->{skel}->{mm}->mid_insert($$mid0);
159
160                 # fall back to a random Message-ID and give up determinism:
161                 until (defined($num)) {
162                         $dig->add(rand);
163                         $$mid0 = PublicInbox::Import::digest2mid($dig);
164                         warn "using random Message-ID <$$mid0> as fallback\n";
165                         $num = $self->{skel}->{mm}->mid_insert($$mid0);
166                 }
167         }
168         my @cur = $hdr->header_raw('Message-Id');
169         $hdr->header_set('Message-Id', "<$$mid0>", @cur);
170         $num;
171 }
172
173 sub idx_part {
174         my ($self, $part) = @_;
175         $self->{idx_parts}->[$part];
176 }
177
178 # idempotent
179 sub idx_init {
180         my ($self) = @_;
181         return if $self->{idx_parts};
182         my $ibx = $self->{-inbox};
183
184         # do not leak read-only FDs to child processes, we only have these
185         # FDs for duplicate detection so they should not be
186         # frequently activated.
187         delete $ibx->{$_} foreach (qw(git mm search));
188
189         $self->lock_acquire;
190
191         # first time initialization, first we create the skeleton pipe:
192         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
193
194         # need to create all parts before initializing msgmap FD
195         my $max = $self->{partitions} - 1;
196         my $idx = $self->{idx_parts} = [];
197         for my $i (0..$max) {
198                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
199         }
200
201         # Now that all subprocesses are up, we can open the FD for SQLite:
202         $skel->_msgmap_init->{dbh}->begin_work;
203 }
204
205 sub remove {
206         my ($self, $mime, $cmt_msg) = @_;
207         $self->barrier;
208         $self->idx_init;
209         my $im = $self->importer;
210         my $ibx = $self->{-inbox};
211         my $srch = $ibx->search;
212         my $cid = content_id($mime);
213         my $skel = $self->{skel};
214         my $parts = $self->{idx_parts};
215         my $mm = $skel->{mm};
216         my $removed;
217         my $mids = mids($mime->header_obj);
218         foreach my $mid (@$mids) {
219                 $srch->reopen->each_smsg_by_mid($mid, sub {
220                         my ($smsg) = @_;
221                         $smsg->load_expand;
222                         my $msg = $ibx->msg_by_smsg($smsg);
223                         if (!defined($msg)) {
224                                 warn "broken smsg for $mid\n";
225                                 return 1; # continue
226                         }
227                         my $orig = $$msg;
228                         my $cur = PublicInbox::MIME->new($msg);
229                         if (content_id($cur) eq $cid) {
230                                 $mm->num_delete($smsg->num);
231                                 # $removed should only be set once assuming
232                                 # no bugs in our deduplication code:
233                                 $removed = $smsg;
234                                 $removed->{mime} = $cur;
235                                 $im->remove(\$orig, $cmt_msg);
236                                 $orig = undef;
237                                 $removed->num; # memoize this for callers
238
239                                 my $oid = $smsg->{blob};
240                                 foreach my $idx (@$parts, $skel) {
241                                         $idx->remote_remove($oid, $mid);
242                                 }
243                         }
244                         1; # continue
245                 });
246                 $self->barrier;
247         }
248         $removed;
249 }
250
251 sub done {
252         my ($self) = @_;
253         my $locked = defined $self->{idx_parts};
254         my $im = delete $self->{im};
255         $im->done if $im; # PublicInbox::Import::done
256         $self->searchidx_checkpoint(0);
257         $self->lock_release if $locked;
258 }
259
260 sub checkpoint {
261         my ($self) = @_;
262         my $im = $self->{im};
263         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
264         $self->searchidx_checkpoint(1);
265 }
266
267 # issue a write barrier to ensure all data is visible to other processes
268 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
269 sub barrier {
270         my ($self) = @_;
271
272         if (my $im = $self->{im}) {
273                 $im->barrier;
274         }
275         my $skel = $self->{skel};
276         my $parts = $self->{idx_parts};
277         if ($parts && $skel) {
278                 my $dbh = $skel->{mm}->{dbh};
279                 $dbh->commit; # SQLite data is second in importance
280
281                 # Now deal with Xapian
282                 $skel->barrier_init(scalar(@$parts));
283                 # each partition needs to issue a barrier command to skel:
284                 $_->remote_barrier foreach @$parts;
285
286                 $skel->barrier_wait; # wait for each Xapian partition
287
288                 $dbh->begin_work;
289         }
290         $self->{transact_bytes} = 0;
291 }
292
293 sub searchidx_checkpoint {
294         my ($self, $more) = @_;
295
296         # order matters, we can only close {skel} after all partitions
297         # are done because the partitions also write to {skel}
298         if (my $parts = $self->{idx_parts}) {
299                 foreach my $idx (@$parts) {
300                         $idx->remote_commit; # propagates commit to skel
301                         $idx->remote_close unless $more;
302                 }
303                 delete $self->{idx_parts} unless $more;
304         }
305
306         if (my $skel = $self->{skel}) {
307                 my $dbh = $skel->{mm}->{dbh};
308                 $dbh->commit;
309                 if ($more) {
310                         $dbh->begin_work;
311                 } else {
312                         $skel->remote_close;
313                         delete $self->{skel};
314                 }
315         }
316         $self->{transact_bytes} = 0;
317 }
318
319 sub git_init {
320         my ($self, $new) = @_;
321         my $pfx = "$self->{-inbox}->{mainrepo}/git";
322         my $git_dir = "$pfx/$new.git";
323         die "$git_dir exists\n" if -e $git_dir;
324         my @cmd = (qw(git init --bare -q), $git_dir);
325         PublicInbox::Import::run_die(\@cmd);
326
327         my $all = "$self->{-inbox}->{mainrepo}/all.git";
328         unless (-d $all) {
329                 @cmd = (qw(git init --bare -q), $all);
330                 PublicInbox::Import::run_die(\@cmd);
331                 @cmd = (qw/git config/, "--file=$all/config",
332                                 'repack.writeBitmaps', 'true');
333                 PublicInbox::Import::run_die(\@cmd);
334         }
335
336         @cmd = (qw/git config/, "--file=$git_dir/config",
337                         'include.path', '../../all.git/config');
338         PublicInbox::Import::run_die(\@cmd);
339
340         my $alt = "$all/objects/info/alternates";
341         my $new_obj_dir = "../../git/$new.git/objects";
342         my %alts;
343         if (-e $alt) {
344                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
345                 %alts = map { chomp; $_ => 1 } (<$fh>);
346         }
347         return $git_dir if $alts{$new_obj_dir};
348         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
349         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
350         close $fh or die "close $alt: $!\n";
351         $git_dir
352 }
353
354 sub importer {
355         my ($self) = @_;
356         my $im = $self->{im};
357         if ($im) {
358                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
359                         return $im;
360                 } else {
361                         $self->{im} = undef;
362                         $im->done;
363                         $self->searchidx_checkpoint(1);
364                         $im = undef;
365                         my $git_dir = $self->git_init(++$self->{max_git});
366                         my $git = PublicInbox::Git->new($git_dir);
367                         return $self->import_init($git, 0);
368                 }
369         }
370         my $latest;
371         my $max = -1;
372         my $new = 0;
373         my $pfx = "$self->{-inbox}->{mainrepo}/git";
374         if (-d $pfx) {
375                 foreach my $git_dir (glob("$pfx/*.git")) {
376                         $git_dir =~ m!/(\d+)\.git\z! or next;
377                         my $n = $1;
378                         if ($n > $max) {
379                                 $max = $n;
380                                 $latest = $git_dir;
381                         }
382                 }
383         }
384         if (defined $latest) {
385                 my $git = PublicInbox::Git->new($latest);
386                 my $packed_bytes = $git->packed_bytes;
387                 if ($packed_bytes >= $self->{rotate_bytes}) {
388                         $new = $max + 1;
389                 } else {
390                         $self->{max_git} = $max;
391                         return $self->import_init($git, $packed_bytes);
392                 }
393         }
394         $self->{max_git} = $new;
395         $latest = $self->git_init($new);
396         $self->import_init(PublicInbox::Git->new($latest), 0);
397 }
398
399 sub import_init {
400         my ($self, $git, $packed_bytes) = @_;
401         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
402         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
403         $im->{want_object_info} = 1;
404         $im->{lock_path} = undef;
405         $im->{path_type} = 'v2';
406         $self->{im} = $im;
407 }
408
409 # XXX experimental
410 sub diff ($$$) {
411         my ($mid, $cur, $new) = @_;
412         use File::Temp qw(tempfile);
413         use PublicInbox::Spawn qw(spawn);
414
415         my ($ah, $an) = tempfile('email-cur-XXXXXXXX');
416         print $ah $cur->as_string or die "print: $!";
417         close $ah or die "close: $!";
418         my ($bh, $bn) = tempfile('email-new-XXXXXXXX');
419         print $bh $new->as_string or die "print: $!";
420         close $bh or die "close: $!";
421         my $cmd = [ qw(diff -u), $an, $bn ];
422         print STDERR "# MID conflict <$mid>\n";
423         my $pid = spawn($cmd, undef, { 1 => 2 });
424         defined $pid or die "diff failed to spawn $!";
425         waitpid($pid, 0) == $pid or die "diff did not finish";
426         unlink($an, $bn);
427 }
428
429 sub lookup_content {
430         my ($self, $mime, $mid) = @_;
431         my $ibx = $self->{-inbox};
432
433         my $srch = $ibx->search->reopen;
434         my $cid = content_id($mime);
435         my $found;
436         $srch->each_smsg_by_mid($mid, sub {
437                 my ($smsg) = @_;
438                 $smsg->load_expand;
439                 my $msg = $ibx->msg_by_smsg($smsg);
440                 if (!defined($msg)) {
441                         warn "broken smsg for $mid\n";
442                         return 1; # continue
443                 }
444                 my $cur = PublicInbox::MIME->new($msg);
445                 if (content_id($cur) eq $cid) {
446                         $smsg->{mime} = $cur;
447                         $found = $smsg;
448                         return 0; # break out of loop
449                 }
450
451                 # XXX DEBUG_DIFF is experimental and may be removed
452                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
453
454                 1; # continue
455         });
456         $found;
457 }
458
459 sub atfork_child {
460         my ($self) = @_;
461         if (my $parts = $self->{idx_parts}) {
462                 $_->atfork_child foreach @$parts;
463         }
464         if (my $im = $self->{im}) {
465                 $im->atfork_child;
466         }
467 }
468
469 1;