]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: inject new Message-IDs on true duplicates
[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 Fcntl qw(:flock :DEFAULT);
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 my $NPROC = int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
23
24 sub new {
25         my ($class, $v2ibx, $creat) = @_;
26         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
27         unless (-d $dir) {
28                 if ($creat) {
29                         require File::Path;
30                         File::Path::mkpath($dir);
31                 } else {
32                         die "$dir does not exist\n";
33                 }
34         }
35         my $self = {
36                 -inbox => $v2ibx,
37                 im => undef, #  PublicInbox::Import
38                 xap_rw => undef, # PublicInbox::V2SearchIdx
39                 xap_ro => undef,
40                 partitions => $NPROC,
41                 transact_bytes => 0,
42                 # limit each repo to 1GB or so
43                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
44         };
45         bless $self, $class
46 }
47
48 # returns undef on duplicate or spam
49 # mimics Import::add and wraps it for v2
50 sub add {
51         my ($self, $mime, $check_cb) = @_;
52
53         # spam check:
54         if ($check_cb) {
55                 $mime = $check_cb->($mime) or return;
56         }
57
58         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
59         # as does SQLite 3.4.1+ (released in 2007-07-20), and
60         # Xapian 1.3.2+ (released 2015-03-15).
61         # For the most part, we can spawn git-fast-import without
62         # leaking FDs to it...
63         $self->idx_init;
64
65         my $num = num_for($self, $mime);
66         defined $num or return; # duplicate
67         my $im = $self->importer;
68         my $cmt = $im->add($mime);
69         $cmt = $im->get_mark($cmt);
70         my $oid = $im->{last_object_id};
71         my ($len, $msgref) = @{$im->{last_object}};
72
73         my $nparts = $self->{partitions};
74         my $part = $num % $nparts;
75         my $idx = $self->idx_part($part);
76         $idx->index_raw($len, $msgref, $num, $oid);
77         my $n = $self->{transact_bytes} += $len;
78         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
79                 $self->checkpoint;
80         }
81
82         $mime;
83 }
84
85 sub num_for {
86         my ($self, $mime) = @_;
87         my $mids = mids($mime->header_obj);
88         if (@$mids) {
89                 my $mid = $mids->[0];
90                 my $num = $self->{skel}->{mm}->mid_insert($mid);
91                 return $num if defined($num); # common case
92
93                 # crap, Message-ID is already known, hope somebody just resent:
94                 $self->done; # write barrier, clears $self->{skel}
95                 foreach my $m (@$mids) {
96                         # read-only lookup now safe to do after above barrier
97                         my $existing = $self->lookup_content($mime, $m);
98                         if ($existing) {
99                                 warn "<$m> resent\n";
100                                 return; # easy, don't store duplicates
101                         }
102                 }
103
104                 # very unlikely:
105                 warn "<$mid> reused for mismatched content\n";
106                 $self->idx_init;
107
108                 # try the rest of the mids
109                 foreach my $i (1..$#$mids) {
110                         my $m = $mids->[$i];
111                         $num = $self->{skel}->{mm}->mid_insert($m);
112                         if (defined $num) {
113                                 warn "alternative <$m> for <$mid> found\n";
114                                 return $num;
115                         }
116                 }
117         }
118         # none of the existing Message-IDs are good, generate a new one:
119         num_for_harder($self, $mime);
120 }
121
122 sub num_for_harder {
123         my ($self, $mime) = @_;
124
125         my $hdr = $mime->header_obj;
126         my $dig = content_digest($mime);
127         my $mid = $dig->clone->hexdigest . '@localhost';
128         my $num = $self->{skel}->{mm}->mid_insert($mid);
129         unless (defined $num) {
130                 # it's hard to spoof the last Received: header
131                 my @recvd = $hdr->header_raw('Received');
132                 $dig->add("Received: $_") foreach (@recvd);
133                 $mid = $dig->clone->hexdigest . '@localhost';
134                 $num = $self->{skel}->{mm}->mid_insert($mid);
135
136                 # fall back to a random Message-ID and give up determinism:
137                 until (defined($num)) {
138                         $dig->add(rand);
139                         $mid = $dig->clone->hexdigest . '@localhost';
140                         warn "using random Message-ID <$mid> as fallback\n";
141                         $num = $self->{skel}->{mm}->mid_insert($mid);
142                 }
143         }
144         my @cur = $hdr->header_raw('Message-Id');
145         $hdr->header_set('Message-Id', @cur, "<$mid>");
146         $num;
147 }
148
149 sub idx_part {
150         my ($self, $part) = @_;
151         $self->{idx_parts}->[$part];
152 }
153
154 # idempotent
155 sub idx_init {
156         my ($self) = @_;
157         return if $self->{idx_parts};
158         my $ibx = $self->{-inbox};
159
160         # do not leak read-only FDs to child processes, we only have these
161         # FDs for duplicate detection so they should not be
162         # frequently activated.
163         delete $ibx->{$_} foreach (qw(git mm search));
164
165         # first time initialization, first we create the skeleton pipe:
166         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
167
168         # need to create all parts before initializing msgmap FD
169         my $max = $self->{partitions} - 1;
170         my $idx = $self->{idx_parts} = [];
171         for my $i (0..$max) {
172                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
173         }
174
175         # Now that all subprocesses are up, we can open the FD for SQLite:
176         $skel->_msgmap_init->{dbh}->begin_work;
177 }
178
179 sub remove {
180         my ($self, $mime, $msg) = @_;
181         my $existing = $self->lookup_content($mime) or return;
182
183         # don't touch ghosts or already junked messages
184         return unless $existing->type eq 'mail';
185
186         # always write removals to the current (latest) git repo since
187         # we process chronologically
188         my $im = $self->importer;
189         my ($cmt, undef) = $im->remove($mime, $msg);
190         $cmt = $im->get_mark($cmt);
191         $self->unindex_msg($existing, $cmt);
192 }
193
194 sub done {
195         my ($self) = @_;
196         my $im = delete $self->{im};
197         $im->done if $im; # PublicInbox::Import::done
198         $self->searchidx_checkpoint(0);
199 }
200
201 sub checkpoint {
202         my ($self) = @_;
203         my $im = $self->{im};
204         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
205         $self->searchidx_checkpoint(1);
206 }
207
208 sub searchidx_checkpoint {
209         my ($self, $more) = @_;
210
211         # order matters, we can only close {skel} after all partitions
212         # are done because the partitions also write to {skel}
213         if (my $parts = $self->{idx_parts}) {
214                 foreach my $idx (@$parts) {
215                         $idx->remote_commit; # propagates commit to skel
216                         $idx->remote_close unless $more;
217                 }
218                 delete $self->{idx_parts} unless $more;
219         }
220
221         if (my $skel = $self->{skel}) {
222                 my $dbh = $skel->{mm}->{dbh};
223                 $dbh->commit;
224                 if ($more) {
225                         $dbh->begin_work;
226                 } else {
227                         $skel->remote_commit; # XXX should be unnecessary...
228                         $skel->remote_close;
229                         delete $self->{skel};
230                 }
231         }
232         $self->{transact_bytes} = 0;
233 }
234
235 sub git_init {
236         my ($self, $new) = @_;
237         my $pfx = "$self->{-inbox}->{mainrepo}/git";
238         my $git_dir = "$pfx/$new.git";
239         die "$git_dir exists\n" if -e $git_dir;
240         my @cmd = (qw(git init --bare -q), $git_dir);
241         PublicInbox::Import::run_die(\@cmd);
242         @cmd = (qw/git config/, "--file=$git_dir/config",
243                         'repack.writeBitmaps', 'true');
244         PublicInbox::Import::run_die(\@cmd);
245
246         my $all = "$self->{-inbox}->{mainrepo}/all.git";
247         unless (-d $all) {
248                 @cmd = (qw(git init --bare -q), $all);
249                 PublicInbox::Import::run_die(\@cmd);
250         }
251
252         my $alt = "$all/objects/info/alternates";
253         my $new_obj_dir = "../../git/$new.git/objects";
254         my %alts;
255         if (-e $alt) {
256                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
257                 %alts = map { chomp; $_ => 1 } (<$fh>);
258         }
259         return $git_dir if $alts{$new_obj_dir};
260         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
261         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
262         close $fh or die "close $alt: $!\n";
263         $git_dir
264 }
265
266 sub importer {
267         my ($self) = @_;
268         my $im = $self->{im};
269         if ($im) {
270                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
271                         return $im;
272                 } else {
273                         $self->{im} = undef;
274                         $im->done;
275                         $self->searchidx_checkpoint(1);
276                         $im = undef;
277                         my $git_dir = $self->git_init(++$self->{max_git});
278                         my $git = PublicInbox::Git->new($git_dir);
279                         return $self->import_init($git, 0);
280                 }
281         }
282         my $latest;
283         my $max = -1;
284         my $new = 0;
285         my $pfx = "$self->{-inbox}->{mainrepo}/git";
286         if (-d $pfx) {
287                 foreach my $git_dir (glob("$pfx/*.git")) {
288                         $git_dir =~ m!/(\d+)\.git\z! or next;
289                         my $n = $1;
290                         if ($n > $max) {
291                                 $max = $n;
292                                 $latest = $git_dir;
293                         }
294                 }
295         }
296         if (defined $latest) {
297                 my $git = PublicInbox::Git->new($latest);
298                 my $packed_bytes = $git->packed_bytes;
299                 if ($packed_bytes >= $self->{rotate_bytes}) {
300                         $new = $max + 1;
301                 } else {
302                         $self->{max_git} = $max;
303                         return $self->import_init($git, $packed_bytes);
304                 }
305         }
306         $self->{max_git} = $new;
307         $latest = $self->git_init($new);
308         $self->import_init(PublicInbox::Git->new($latest), 0);
309 }
310
311 sub import_init {
312         my ($self, $git, $packed_bytes) = @_;
313         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
314         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
315         $im->{want_object_id} = 1;
316         $im->{ssoma_lock} = 0;
317         $im->{path_type} = 'v2';
318         $self->{im} = $im;
319 }
320
321 sub lookup_content {
322         my ($self, $mime, $mid) = @_;
323         my $ibx = $self->{-inbox};
324
325         my $srch = $ibx->search;
326         my $cid = content_id($mime);
327         my $found;
328         $srch->each_smsg_by_mid($mid, sub {
329                 my ($smsg) = @_;
330                 $smsg->load_expand;
331                 my $msg = $ibx->msg_by_smsg($smsg);
332                 if (!defined($msg)) {
333                         warn "broken smsg for $mid\n";
334                         return 1; # continue
335                 }
336                 my $cur = PublicInbox::MIME->new($msg);
337                 if (content_id($cur) eq $cid) {
338                         $smsg->{mime} = $cur;
339                         $found = $smsg;
340                         return 0; # break out of loop
341                 }
342                 1; # continue
343         });
344         $found;
345 }
346
347 sub atfork_child {
348         my ($self) = @_;
349         if (my $parts = $self->{idx_parts}) {
350                 $_->atfork_child foreach @$parts;
351         }
352         if (my $im = $self->{im}) {
353                 $im->atfork_child;
354         }
355 }
356
357 1;