]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei q: parallelize Maildir and mbox writing
[public-inbox.git] / lib / PublicInbox / LeiToMail.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::Eml;
10 use PublicInbox::Lock;
11 use PublicInbox::ProcessPipe;
12 use PublicInbox::Spawn qw(which spawn popen_rd);
13 use PublicInbox::LeiDedupe;
14 use Symbol qw(gensym);
15 use IO::Handle; # ->autoflush
16 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
17 use Errno qw(EEXIST ESPIPE ENOENT);
18 use PublicInbox::Git;
19
20 my %kw2char = ( # Maildir characters
21         draft => 'D',
22         flagged => 'F',
23         answered => 'R',
24         seen => 'S'
25 );
26
27 my %kw2status = (
28         flagged => [ 'X-Status' => 'F' ],
29         answered => [ 'X-Status' => 'A' ],
30         seen => [ 'Status' => 'R' ],
31         draft => [ 'X-Status' => 'T' ],
32 );
33
34 sub _mbox_hdr_buf ($$$) {
35         my ($eml, $type, $kw) = @_;
36         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
37         my %hdr; # set Status, X-Status
38         for my $k (@$kw) {
39                 if (my $ent = $kw2status{$k}) {
40                         push @{$hdr{$ent->[0]}}, $ent->[1];
41                 } else { # X-Label?
42                         warn "TODO: keyword `$k' not supported for mbox\n";
43                 }
44         }
45         while (my ($name, $chars) = each %hdr) {
46                 $eml->header_set($name, join('', sort @$chars));
47         }
48         my $buf = delete $eml->{hdr};
49
50         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
51         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
52
53         substr($$buf, 0, 0, # prepend From line
54                 "From lei\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
55         $buf;
56 }
57
58 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
59         my ($fh, $buf) = @_;
60         defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
61         $w == length($$buf) or die "short write: $w != ".length($$buf);
62 }
63
64 sub _print_full {
65         my ($fh, $buf) = @_;
66         print $fh $$buf or die "print: $!";
67 }
68
69 sub eml2mboxrd ($;$) {
70         my ($eml, $kw) = @_;
71         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
72         if (my $bdy = delete $eml->{bdy}) {
73                 $$bdy =~ s/^(>*From )/>$1/gm;
74                 $$buf .= $eml->{crlf};
75                 substr($$bdy, 0, 0, $$buf); # prepend header
76                 $buf = $bdy;
77         }
78         $$buf .= $eml->{crlf};
79         $buf;
80 }
81
82 sub eml2mboxo {
83         my ($eml, $kw) = @_;
84         my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
85         if (my $bdy = delete $eml->{bdy}) {
86                 $$bdy =~ s/^From />From /gm;
87                 $$buf .= $eml->{crlf};
88                 substr($$bdy, 0, 0, $$buf); # prepend header
89                 $buf = $bdy;
90         }
91         $$buf .= $eml->{crlf};
92         $buf;
93 }
94
95 # mboxcl still escapes "From " lines
96 sub eml2mboxcl {
97         my ($eml, $kw) = @_;
98         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
99         my $crlf = $eml->{crlf};
100         if (my $bdy = delete $eml->{bdy}) {
101                 $$bdy =~ s/^From />From /gm;
102                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
103                 substr($$bdy, 0, 0, $$buf); # prepend header
104                 $buf = $bdy;
105         }
106         $$buf .= $crlf;
107         $buf;
108 }
109
110 # mboxcl2 has no "From " escaping
111 sub eml2mboxcl2 {
112         my ($eml, $kw) = @_;
113         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
114         my $crlf = $eml->{crlf};
115         if (my $bdy = delete $eml->{bdy}) {
116                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
117                 substr($$bdy, 0, 0, $$buf); # prepend header
118                 $buf = $bdy;
119         }
120         $$buf .= $crlf;
121         $buf;
122 }
123
124 sub git_to_mail { # git->cat_async callback
125         my ($bref, $oid, $type, $size, $arg) = @_;
126         if ($type ne 'blob') {
127                 if ($type eq 'missing') {
128                         warn "missing $oid\n";
129                 } else {
130                         warn "unexpected type=$type for $oid\n";
131                 }
132         }
133         if ($size > 0) {
134                 my ($write_cb, $kw) = @$arg;
135                 $write_cb->($bref, $oid, $kw);
136         }
137 }
138
139 sub reap_compress { # dwaitpid callback
140         my ($lei, $pid) = @_;
141         my $cmd = delete $lei->{"pid.$pid"};
142         return if $? == 0;
143         $lei->fail("@$cmd failed", $? >> 8);
144 }
145
146 # all of these support -c for stdout and -d for decompression,
147 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
148 # { foo => '' } means "--foo" is passed to the command-line,
149 # otherwise { foo => '--bar' } passes "--bar"
150 our %zsfx2cmd = (
151         gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
152         bz2 => [ 'bzip2', {} ],
153         xz => [ 'xz', { threads => '-T' } ],
154         # XXX does anybody care for these?  I prefer zstd on entire FSes,
155         # so it's probably not necessary on a per-file basis
156         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
157         #       rsyncable => '', threads => '-T' } ],
158         # zz => [ 'pigz', { -default => [ '--zlib' ],
159         #       rsyncable => '', threads => '-p' }],
160         # lzo => [ 'lzop', {} ],
161         # lzma => [ 'lzma', {} ],
162 );
163
164 sub zsfx2cmd ($$$) {
165         my ($zsfx, $decompress, $lei) = @_;
166         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
167         my @info = @$x;
168         my $cmd_opt = pop @info;
169         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
170         for my $exe (@info) {
171                 # I think respecting client's ENV{GZIP} is OK, not sure
172                 # about ENV overrides for other, less-common compressors
173                 if ($exe eq uc($exe)) {
174                         $exe = $lei->{env}->{$exe} or next;
175                 }
176                 $cmd[0] = which($exe) and last;
177         }
178         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
179         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
180         for my $bool (qw(rsyncable)) {
181                 my $switch = $cmd_opt->{rsyncable} // next;
182                 push @cmd, '--'.($switch || $bool);
183         }
184         for my $key (qw(threads)) { # support compression level?
185                 my $switch = $cmd_opt->{$key} // next;
186                 my $val = $lei->{opt}->{$key} // next;
187                 push @cmd, $switch, $val;
188         }
189         \@cmd;
190 }
191
192 sub _post_augment_mbox { # open a compressor process
193         my ($self, $lei) = @_;
194         my $zsfx = $self->{zsfx} or return;
195         my $cmd = zsfx2cmd($zsfx, undef, $lei);
196         pipe(my ($r, $w)) or die "pipe: $!";
197         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
198         my $pid = spawn($cmd, $lei->{env}, $rdr);
199         $lei->{"pid.$pid"} = $cmd;
200         my $pp = gensym;
201         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
202         $lei->{1} = $pp;
203         die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
204         $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
205 }
206
207 sub decompress_src ($$$) {
208         my ($in, $zsfx, $lei) = @_;
209         my $cmd = zsfx2cmd($zsfx, 1, $lei);
210         popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
211 }
212
213 sub dup_src ($) {
214         my ($in) = @_;
215         # fileno needed because wq_set_recv_modes only used ">&=" for {1}
216         # and Perl blindly trusts that to reject the '+' (readability flag)
217         open my $dup, '+>>&=', fileno($in) or die "dup: $!";
218         $dup;
219 }
220
221 # --augment existing output destination, with deduplication
222 sub _augment { # MboxReader eml_cb
223         my ($eml, $lei) = @_;
224         # ignore return value, just populate the skv
225         $lei->{dedupe}->is_dup($eml);
226 }
227
228 sub _mbox_write_cb ($$) {
229         my ($self, $lei) = @_;
230         my $ovv = $lei->{ovv};
231         my $m = 'eml2'.$ovv->{fmt};
232         my $eml2mbox = $self->can($m) or die "$self->$m missing";
233         my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
234         $out->autoflush(1);
235         my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
236         my $dedupe = $lei->{dedupe};
237         $dedupe->prepare_dedupe;
238         sub { # for git_to_mail
239                 my ($buf, $oid, $kw) = @_;
240                 my $eml = PublicInbox::Eml->new($buf);
241                 if (!$dedupe->is_dup($eml, $oid)) {
242                         $buf = $eml2mbox->($eml, $kw);
243                         my $lk = $ovv->lock_for_scope;
244                         $write->($out, $buf);
245                 }
246         }
247 }
248
249 sub _maildir_each_file ($$;@) {
250         my ($dir, $cb, @arg) = @_;
251         for my $d (qw(new/ cur/)) {
252                 my $pfx = $dir.$d;
253                 opendir my $dh, $pfx or next;
254                 while (defined(my $fn = readdir($dh))) {
255                         $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
256                 }
257         }
258 }
259
260 sub _augment_file { # _maildir_each_file cb
261         my ($f, $lei) = @_;
262         my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
263         _augment($eml, $lei);
264 }
265
266 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
267 sub _unlink { unlink($_[0]) }
268
269 sub _buf2maildir {
270         my ($dst, $buf, $oid, $kw) = @_;
271         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
272         my $rand = ''; # chosen by die roll :P
273         my ($tmp, $fh, $final);
274         do {
275                 $tmp = $dst.'tmp/'.$rand."oid=$oid";
276         } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
277                 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
278         if (print $fh $$buf and close($fh)) {
279                 $dst .= $sfx eq '' ? 'new/' : 'cur/';
280                 $rand = '';
281                 do {
282                         $final = $dst.$rand."oid=$oid:2,$sfx";
283                 } while (!link($tmp, $final) && $! == EEXIST &&
284                         ($rand = int(rand 0x7fffffff).','));
285                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
286         } else {
287                 my $err = $!;
288                 unlink($tmp);
289                 die "Error writing $oid to $dst: $err";
290         }
291 }
292
293 sub _maildir_write_cb ($$) {
294         my ($self, $lei) = @_;
295         my $dedupe = $lei->{dedupe};
296         $dedupe->prepare_dedupe;
297         my $dst = $lei->{ovv}->{dst};
298         sub { # for git_to_mail
299                 my ($buf, $oid, $kw) = @_;
300                 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
301                 my $eml = PublicInbox::Eml->new($$buf); # copy buf
302                 return if $dedupe->is_dup($eml, $oid);
303                 undef $eml;
304                 _buf2maildir($dst, $buf, $oid, $kw);
305         }
306 }
307
308 sub write_cb { # returns a callback for git_to_mail
309         my ($self, $lei) = @_;
310         # _mbox_write_cb or _maildir_write_cb
311         my $m = "_$self->{base_type}_write_cb";
312         $self->$m($lei);
313 }
314
315 sub new {
316         my ($cls, $lei) = @_;
317         my $fmt = $lei->{ovv}->{fmt};
318         my $dst = $lei->{ovv}->{dst};
319         my $self = bless {}, $cls;
320         if ($fmt eq 'maildir') {
321                 $self->{base_type} = 'maildir';
322                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
323         } elsif (substr($fmt, 0, 4) eq 'mbox') {
324                 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
325                 $self->{base_type} = 'mbox';
326         } else {
327                 die "bad mail --format=$fmt\n";
328         }
329         $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
330         $self;
331 }
332
333 sub _pre_augment_maildir {} # noop
334
335 sub _do_augment_maildir {
336         my ($self, $lei) = @_;
337         my $dst = $lei->{ovv}->{dst};
338         if ($lei->{opt}->{augment}) {
339                 my $dedupe = $lei->{dedupe};
340                 if ($dedupe && $dedupe->prepare_dedupe) {
341                         require PublicInbox::InboxWritable; # eml_from_path
342                         _maildir_each_file($dst, \&_augment_file, $lei);
343                         $dedupe->pause_dedupe;
344                 }
345         } else { # clobber existing Maildir
346                 _maildir_each_file($dst, \&_unlink);
347         }
348 }
349
350 sub _post_augment_maildir {
351         my ($self, $lei) = @_;
352         my $dst = $lei->{ovv}->{dst};
353         for my $x (qw(tmp new cur)) {
354                 my $d = $dst.$x;
355                 next if -d $d;
356                 require File::Path;
357                 File::Path::mkpath($d) or die "mkpath($d): $!";
358                 -d $d or die "$d is not a directory";
359         }
360 }
361
362 sub _pre_augment_mbox {
363         my ($self, $lei) = @_;
364         my $dst = $lei->{ovv}->{dst};
365         if ($dst ne '/dev/stdout') {
366                 my $mode = -p $dst ? '>' : '+>>';
367                 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
368                         $! == ENOENT or die "unlink($dst): $!";
369                 }
370                 open my $out, $mode, $dst or die "open($dst): $!";
371                 $lei->{1} = $out;
372         }
373         # Perl does SEEK_END even with O_APPEND :<
374         $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
375         if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
376                 die "seek($dst): $!\n";
377         }
378         state $zsfx_allow = join('|', keys %zsfx2cmd);
379         ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/);
380 }
381
382 sub _do_augment_mbox {
383         my ($self, $lei) = @_;
384         return if !$lei->{opt}->{augment};
385         my $dedupe = $lei->{dedupe};
386         my $dst = $lei->{ovv}->{dst};
387         die "cannot augment $dst, not seekable\n" if !$self->{seekable};
388         my $out = $lei->{1};
389         if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
390                 my $zsfx = $self->{zsfx};
391                 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
392                                 dup_src($out);
393                 my $fmt = $lei->{ovv}->{fmt};
394                 require PublicInbox::MboxReader;
395                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
396         }
397         # maybe some systems don't honor O_APPEND, Perl does this:
398         seek($out, 0, SEEK_END) or die "seek $dst: $!";
399         $dedupe->pause_dedupe if $dedupe;
400 }
401
402 sub pre_augment { # fast (1 disk seek), runs in main daemon
403         my ($self, $lei) = @_;
404         # _pre_augment_maildir, _pre_augment_mbox
405         my $m = "_pre_augment_$self->{base_type}";
406         $self->$m($lei);
407 }
408
409 sub do_augment { # slow, runs in wq worker
410         my ($self, $lei) = @_;
411         # _do_augment_maildir, _do_augment_mbox
412         my $m = "_do_augment_$self->{base_type}";
413         $self->$m($lei);
414 }
415
416 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
417         my ($self, $lei) = @_;
418         # _post_augment_maildir, _post_augment_mbox
419         my $m = "_post_augment_$self->{base_type}";
420         $self->$m($lei);
421 }
422
423 sub lock_free {
424         $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
425 }
426
427 sub write_mail { # via ->wq_do
428         my ($self, $git_dir, $oid, $lei, $kw) = @_;
429         my $wcb = $self->{wcb} //= do { # first message
430                 my %sig = $lei->atfork_child_wq($self);
431                 @SIG{keys %sig} = values %sig; # not local
432                 $lei->{dedupe}->prepare_dedupe;
433                 $self->write_cb($lei);
434         };
435         my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
436         $git->cat_async($oid, \&git_to_mail, [ $wcb, $kw ]);
437 }
438
439 sub ipc_atfork_prepare {
440         my ($self) = @_;
441         # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
442         $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
443         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
444 }
445
446 sub DESTROY {
447         my ($self) = @_;
448         for my $pid_git (grep(/\A$$\0/, keys %$self)) {
449                 $self->{$pid_git}->async_wait_all;
450         }
451 }
452
453 1;