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