]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei: support /dev/fd/[0-2] inputs and outputs in daemon
[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 PublicInbox::Git;
15 use PublicInbox::GitAsyncCat;
16 use PublicInbox::PktOp qw(pkt_do);
17 use Symbol qw(gensym);
18 use IO::Handle; # ->autoflush
19 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
20 use Errno qw(EEXIST ESPIPE ENOENT EPIPE);
21 use Digest::SHA qw(sha256_hex);
22
23 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
24 # but we may use in-process libgit2 in the future.
25 $PublicInbox::GitAsyncCat::GCF2C = 0;
26
27 my %kw2char = ( # Maildir characters
28         draft => 'D',
29         flagged => 'F',
30         answered => 'R',
31         seen => 'S'
32 );
33
34 my %kw2status = (
35         flagged => [ 'X-Status' => 'F' ],
36         answered => [ 'X-Status' => 'A' ],
37         seen => [ 'Status' => 'R' ],
38         draft => [ 'X-Status' => 'T' ],
39 );
40
41 sub _mbox_hdr_buf ($$$) {
42         my ($eml, $type, $smsg) = @_;
43         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
44
45         my %hdr = (Status => []); # set Status, X-Status
46         for my $k (@{$smsg->{kw} // []}) {
47                 if (my $ent = $kw2status{$k}) {
48                         push @{$hdr{$ent->[0]}}, $ent->[1];
49                 } else { # X-Label?
50                         warn "TODO: keyword `$k' not supported for mbox\n";
51                 }
52         }
53         # Messages are always 'O' (non-\Recent in IMAP), it saves
54         # MUAs the trouble of rewriting the mbox if no other
55         # changes are made.  We put 'O' at the end (e.g. "Status: RO")
56         # to match mutt(1) output.
57         $eml->header_set('Status', join('', sort(@{$hdr{Status}})). 'O');
58         if (my $chars = delete $hdr{'X-Status'}) {
59                 $eml->header_set('X-Status', join('', sort(@$chars)));
60         }
61         my $buf = delete $eml->{hdr};
62
63         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
64         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
65         my $ident = $smsg->{blob} // 'lei';
66         if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
67
68         substr($$buf, 0, 0, # prepend From line
69                 "From $ident\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
70         $buf;
71 }
72
73 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
74         my ($lei, $buf) = @_;
75         if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
76                 return if $w == length($$buf);
77                 $buf = "short atomic write: $w != ".length($$buf);
78         } elsif ($! == EPIPE) {
79                 return $lei->note_sigpipe(1);
80         } else {
81                 $buf = "atomic write: $!";
82         }
83         $lei->fail($buf);
84 }
85
86 sub eml2mboxrd ($;$) {
87         my ($eml, $smsg) = @_;
88         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
89         if (my $bdy = delete $eml->{bdy}) {
90                 $$bdy =~ s/^(>*From )/>$1/gm;
91                 $$buf .= $eml->{crlf};
92                 substr($$bdy, 0, 0, $$buf); # prepend header
93                 $buf = $bdy;
94         }
95         $$buf .= $eml->{crlf};
96         $buf;
97 }
98
99 sub eml2mboxo {
100         my ($eml, $smsg) = @_;
101         my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
102         if (my $bdy = delete $eml->{bdy}) {
103                 $$bdy =~ s/^From />From /gm;
104                 $$buf .= $eml->{crlf};
105                 substr($$bdy, 0, 0, $$buf); # prepend header
106                 $buf = $bdy;
107         }
108         $$buf .= $eml->{crlf};
109         $buf;
110 }
111
112 sub _mboxcl_common ($$$) {
113         my ($buf, $bdy, $crlf) = @_;
114         # add Lines: so mutt won't have to add it on MUA close
115         my $lines = $$bdy =~ tr!\n!\n!;
116         $$buf .= 'Content-Length: '.length($$bdy).$crlf.
117                 'Lines: '.$lines.$crlf.$crlf;
118         substr($$bdy, 0, 0, $$buf); # prepend header
119         $_[0] = $bdy;
120 }
121
122 # mboxcl still escapes "From " lines
123 sub eml2mboxcl {
124         my ($eml, $smsg) = @_;
125         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
126         my $crlf = $eml->{crlf};
127         if (my $bdy = delete $eml->{bdy}) {
128                 $$bdy =~ s/^From />From /gm;
129                 _mboxcl_common($buf, $bdy, $crlf);
130         }
131         $$buf .= $crlf;
132         $buf;
133 }
134
135 # mboxcl2 has no "From " escaping
136 sub eml2mboxcl2 {
137         my ($eml, $smsg) = @_;
138         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
139         my $crlf = $eml->{crlf};
140         if (my $bdy = delete $eml->{bdy}) {
141                 _mboxcl_common($buf, $bdy, $crlf);
142         }
143         $$buf .= $crlf;
144         $buf;
145 }
146
147 sub git_to_mail { # git->cat_async callback
148         my ($bref, $oid, $type, $size, $arg) = @_;
149         if ($type ne 'blob') {
150                 if ($type eq 'missing') {
151                         warn "missing $oid\n";
152                 } else {
153                         warn "unexpected type=$type for $oid\n";
154                 }
155         }
156         my ($write_cb, $smsg) = @$arg;
157         if ($smsg->{blob} ne $oid) {
158                 die "BUG: expected=$smsg->{blob} got=$oid";
159         }
160         $write_cb->($bref, $smsg) if $size > 0;
161 }
162
163 sub reap_compress { # dwaitpid callback
164         my ($lei, $pid) = @_;
165         my $cmd = delete $lei->{"pid.$pid"};
166         return if $? == 0;
167         $lei->fail("@$cmd failed", $? >> 8);
168 }
169
170 # all of these support -c for stdout and -d for decompression,
171 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
172 # { foo => '' } means "--foo" is passed to the command-line,
173 # otherwise { foo => '--bar' } passes "--bar"
174 our %zsfx2cmd = (
175         gz => [ qw(GZIP pigz gzip), { rsyncable => '' } ],
176         bz2 => [ 'bzip2', {} ],
177         xz => [ 'xz', {} ],
178         # XXX does anybody care for these?  I prefer zstd on entire FSes,
179         # so it's probably not necessary on a per-file basis
180         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
181         #       rsyncable => '', threads => '-T' } ],
182         # zz => [ 'pigz', { -default => [ '--zlib' ],
183         #       rsyncable => '', threads => '-p' }],
184         # lzo => [ 'lzop', {} ],
185         # lzma => [ 'lzma', {} ],
186 );
187
188 sub zsfx2cmd ($$$) {
189         my ($zsfx, $decompress, $lei) = @_;
190         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
191         my @info = @$x;
192         my $cmd_opt = pop @info;
193         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
194         for my $exe (@info) {
195                 # I think respecting client's ENV{GZIP} is OK, not sure
196                 # about ENV overrides for other, less-common compressors
197                 if ($exe eq uc($exe)) {
198                         $exe = $lei->{env}->{$exe} or next;
199                 }
200                 $cmd[0] = which($exe) and last;
201         }
202         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
203         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
204         for my $bool (qw(rsyncable)) {
205                 my $switch = $cmd_opt->{rsyncable} // next;
206                 push @cmd, '--'.($switch || $bool);
207         }
208         for my $key (qw(rsyncable)) { # support compression level?
209                 my $switch = $cmd_opt->{$key} // next;
210                 my $val = $lei->{opt}->{$key} // next;
211                 push @cmd, $switch, $val;
212         }
213         \@cmd;
214 }
215
216 sub _post_augment_mbox { # open a compressor process
217         my ($self, $lei) = @_;
218         my $zsfx = $self->{zsfx} or return;
219         my $cmd = zsfx2cmd($zsfx, undef, $lei);
220         my ($r, $w) = @{delete $lei->{zpipe}};
221         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
222         my $pid = spawn($cmd, undef, $rdr);
223         my $pp = gensym;
224         my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
225         $dup->{$_} = $lei->{$_} for qw(2 sock);
226         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
227         $lei->{1} = $pp;
228 }
229
230 sub decompress_src ($$$) {
231         my ($in, $zsfx, $lei) = @_;
232         my $cmd = zsfx2cmd($zsfx, 1, $lei);
233         popen_rd($cmd, undef, { 0 => $in, 2 => $lei->{2} });
234 }
235
236 sub dup_src ($) {
237         my ($in) = @_;
238         open my $dup, '+>>&', $in or die "dup: $!";
239         $dup;
240 }
241
242 # --augment existing output destination, with deduplication
243 sub _augment { # MboxReader eml_cb
244         my ($eml, $lei) = @_;
245         # ignore return value, just populate the skv
246         $lei->{dedupe}->is_dup($eml);
247 }
248
249 sub _mbox_augment_kw_maybe {
250         my ($eml, $lei, $lse, $augment) = @_;
251         my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
252         update_kw_maybe($lei, $lse, $eml, $kw);
253         _augment($eml, $lei) if $augment;
254 }
255
256 sub _mbox_write_cb ($$) {
257         my ($self, $lei) = @_;
258         my $ovv = $lei->{ovv};
259         my $m = 'eml2'.$ovv->{fmt};
260         my $eml2mbox = $self->can($m) or die "$self->$m missing";
261         $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
262         $lei->{1}->autoflush(1);
263         my $atomic_append = !defined($ovv->{lock_path});
264         my $dedupe = $lei->{dedupe};
265         $dedupe->prepare_dedupe;
266         my $lse = $lei->{lse}; # may be undef
267         sub { # for git_to_mail
268                 my ($buf, $smsg, $eml) = @_;
269                 $eml //= PublicInbox::Eml->new($buf);
270                 return if $dedupe->is_dup($eml, $smsg->{blob});
271                 $lse->xsmsg_vmd($smsg) if $lse;
272                 $buf = $eml2mbox->($eml, $smsg);
273                 return atomic_append($lei, $buf) if $atomic_append;
274                 my $lk = $ovv->lock_for_scope;
275                 $lei->out($$buf);
276         }
277 }
278
279 sub update_kw_maybe ($$$$) {
280         my ($lei, $lse, $eml, $kw) = @_;
281         return unless $lse;
282         my $x = $lse->kw_changed($eml, $kw);
283         my $vmd = { kw => $kw };
284         if ($x) {
285                 $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
286         } elsif (!defined($x)) {
287                 if (my $xoids = $lei->{ale}->xoids_for($eml)) {
288                         $lei->{sto}->ipc_do('set_xvmd', $xoids, $eml, $vmd);
289                 } else {
290                         $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
291                 }
292         }
293 }
294
295 sub _augment_or_unlink { # maildir_each_eml cb
296         my ($f, $kw, $eml, $lei, $lse, $mod, $shard, $unlink) = @_;
297         if ($mod) {
298                 # can't get dirent.d_ino w/ pure Perl, so we extract the OID
299                 # if it looks like one:
300                 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
301                                 $1 : sha256_hex($f);
302                 my $recno = hex(substr($hex, 0, 8));
303                 return if ($recno % $mod) != $shard;
304                 update_kw_maybe($lei, $lse, $eml, $kw);
305         }
306         $unlink ? unlink($f) : _augment($eml, $lei);
307 }
308
309 # maildir_each_file callback, \&CORE::unlink doesn't work with it
310 sub _unlink { unlink($_[0]) }
311
312 sub _rand () {
313         state $seq = 0;
314         sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
315 }
316
317 sub _buf2maildir {
318         my ($dst, $buf, $smsg) = @_;
319         my $kw = $smsg->{kw} // [];
320         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
321         my $rand = ''; # chosen by die roll :P
322         my ($tmp, $fh, $final, $ok);
323         my $common = $smsg->{blob} // _rand;
324         if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
325         do {
326                 $tmp = $dst.'tmp/'.$rand.$common;
327         } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
328                 $! == EEXIST && ($rand = _rand.','));
329         if ($ok && print $fh $$buf and close($fh)) {
330                 # ignore new/ and write only to cur/, otherwise MUAs
331                 # with R/W access to the Maildir will end up doing
332                 # a mass rename which can take a while with thousands
333                 # of messages.
334                 $dst .= 'cur/';
335                 $rand = '';
336                 do {
337                         $final = $dst.$rand.$common.':2,'.$sfx;
338                 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
339                         ($rand = _rand.','));
340                 die "link($tmp, $final): $!" unless $ok;
341                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
342         } else {
343                 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
344                 $_[0] = undef; # clobber dst
345                 unlink($tmp);
346                 die $err;
347         }
348 }
349
350 sub _maildir_write_cb ($$) {
351         my ($self, $lei) = @_;
352         my $dedupe = $lei->{dedupe};
353         $dedupe->prepare_dedupe if $dedupe;
354         my $dst = $lei->{ovv}->{dst};
355         my $lse = $lei->{lse}; # may be undef
356         sub { # for git_to_mail
357                 my ($buf, $smsg, $eml) = @_;
358                 $dst // return $lei->fail; # dst may be undef-ed in last run
359                 $buf //= \($eml->as_string);
360                 $lse->xsmsg_vmd($smsg) if $lse;
361                 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
362                 $eml //= PublicInbox::Eml->new($$buf); # copy buf
363                 return if $dedupe->is_dup($eml, $smsg->{blob});
364                 undef $eml;
365                 _buf2maildir($dst, $buf, $smsg);
366         }
367 }
368
369 sub _imap_write_cb ($$) {
370         my ($self, $lei) = @_;
371         my $dedupe = $lei->{dedupe};
372         $dedupe->prepare_dedupe if $dedupe;
373         my $imap_append = $lei->{net}->can('imap_append');
374         my $mic = $lei->{net}->mic_get($self->{uri});
375         my $folder = $self->{uri}->mailbox;
376         my $lse = $lei->{lse}; # may be undef
377         sub { # for git_to_mail
378                 my ($bref, $smsg, $eml) = @_;
379                 $mic // return $lei->fail; # dst may be undef-ed in last run
380                 if ($dedupe) {
381                         $eml //= PublicInbox::Eml->new($$bref); # copy bref
382                         return if $dedupe->is_dup($eml, $smsg->{blob});
383                 }
384                 $lse->xsmsg_vmd($smsg) if $lse;
385                 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
386                 if (my $err = $@) {
387                         undef $mic;
388                         die $err;
389                 }
390         }
391 }
392
393 sub write_cb { # returns a callback for git_to_mail
394         my ($self, $lei) = @_;
395         # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
396         my $m = "_$self->{base_type}_write_cb";
397         $self->$m($lei);
398 }
399
400 sub new {
401         my ($cls, $lei) = @_;
402         my $fmt = $lei->{ovv}->{fmt};
403         my $dst = $lei->{ovv}->{dst};
404         my $self = bless {}, $cls;
405         if ($fmt eq 'maildir') {
406                 require PublicInbox::MdirReader;
407                 $self->{base_type} = 'maildir';
408                 -e $dst && !-d _ and die
409                                 "$dst exists and is not a directory\n";
410                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
411         } elsif (substr($fmt, 0, 4) eq 'mbox') {
412                 require PublicInbox::MboxReader;
413                 (-d $dst || (-e _ && !-w _)) and die
414                         "$dst exists and is not a writable file\n";
415                 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
416                 $self->{base_type} = 'mbox';
417         } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
418                 require PublicInbox::NetWriter;
419                 my $net = PublicInbox::NetWriter->new;
420                 $net->add_url($dst);
421                 $net->{quiet} = $lei->{opt}->{quiet};
422                 my $err = $net->errors($dst);
423                 return $lei->fail($err) if $err;
424                 require PublicInbox::URIimap; # TODO: URI cast early
425                 $self->{uri} = PublicInbox::URIimap->new($dst);
426                 $self->{uri}->mailbox or die "No mailbox: $dst";
427                 $lei->{net} = $net;
428                 $self->{base_type} = 'imap';
429         } else {
430                 die "bad mail --format=$fmt\n";
431         }
432         $self->{dst} = $dst;
433         $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
434         $self;
435 }
436
437 sub _pre_augment_maildir {
438         my ($self, $lei) = @_;
439         my $dst = $lei->{ovv}->{dst};
440         for my $x (qw(tmp new cur)) {
441                 my $d = $dst.$x;
442                 next if -d $d;
443                 require File::Path;
444                 File::Path::mkpath($d);
445                 -d $d or die "$d is not a directory";
446         }
447 }
448
449 sub _do_augment_maildir {
450         my ($self, $lei) = @_;
451         my $dst = $lei->{ovv}->{dst};
452         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
453         my ($mod, $shard) = @{$self->{shard_info} // []};
454         if ($lei->{opt}->{augment}) {
455                 my $dedupe = $lei->{dedupe};
456                 if ($dedupe && $dedupe->prepare_dedupe) {
457                         PublicInbox::MdirReader::maildir_each_eml($dst,
458                                                 \&_augment_or_unlink,
459                                                 $lei, $lse, $mod, $shard);
460                         $dedupe->pause_dedupe;
461                 }
462         } elsif ($lse) {
463                 PublicInbox::MdirReader::maildir_each_eml($dst,
464                                         \&_augment_or_unlink,
465                                         $lei, $lse, $mod, $shard, 1);
466         } else {# clobber existing Maildir
467                 PublicInbox::MdirReader::maildir_each_file($dst, \&_unlink);
468         }
469 }
470
471 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
472         my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
473         update_kw_maybe($lei, $lse, $eml, $kw);
474         if ($delete_mic) {
475                 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
476         } else {
477                 _augment($eml, $lei);
478         }
479 }
480
481 sub _do_augment_imap {
482         my ($self, $lei) = @_;
483         my $net = $lei->{net};
484         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
485         if ($lei->{opt}->{augment}) {
486                 my $dedupe = $lei->{dedupe};
487                 if ($dedupe && $dedupe->prepare_dedupe) {
488                         $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
489                                         $lei, $lse);
490                         $dedupe->pause_dedupe;
491                 }
492         } elsif ($lse) {
493                 my $delete_mic;
494                 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
495                                         $lei, $lse, \$delete_mic);
496                 $delete_mic->expunge if $delete_mic;
497         } elsif (!$self->{-wq_worker_nr}) { # undef or 0
498                 # clobber existing IMAP folder
499                 $net->imap_delete_all($self->{uri});
500         }
501 }
502
503 sub _pre_augment_mbox {
504         my ($self, $lei) = @_;
505         my $dst = $lei->{ovv}->{dst};
506         my $out;
507         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
508         if ($devfd >= 0) {
509                 $out = $lei->{$devfd};
510         } else { # normal-looking path
511                 if (-p $dst) {
512                         open $out, '>', $dst or die "open($dst): $!";
513                 } elsif (-f _ || !-e _) {
514                         require PublicInbox::MboxLock;
515                         my $m = $lei->{opt}->{'lock'} //
516                                         PublicInbox::MboxLock->defaults;
517                         $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
518                         $out = $self->{mbl}->{fh};
519                 } else {
520                         die "$dst is not a file or FIFO\n";
521                 }
522                 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
523         }
524         # Perl does SEEK_END even with O_APPEND :<
525         $self->{seekable} = seek($out, 0, SEEK_SET);
526         if (!$self->{seekable} && $! != ESPIPE && !defined($devfd)) {
527                 die "seek($dst): $!\n";
528         }
529         if (!$self->{seekable}) {
530                 my $imp_before = $lei->{opt}->{'import-before'};
531                 die "--import-before specified but $dst is not seekable\n"
532                         if $imp_before && !ref($imp_before);
533                 die "--augment specified but $dst is not seekable\n" if
534                         $lei->{opt}->{augment};
535         }
536         state $zsfx_allow = join('|', keys %zsfx2cmd);
537         if (($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/)) {
538                 pipe(my ($r, $w)) or die "pipe: $!";
539                 $lei->{zpipe} = [ $r, $w ];
540                 $lei->{ovv}->{lock_path} and
541                         die 'BUG: unexpected {ovv}->{lock_path}';
542                 $lei->{ovv}->ovv_out_lk_init;
543         } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
544                 $lei->{ovv}->ovv_out_lk_init;
545         }
546         $lei->{1} = $out;
547         undef;
548 }
549
550 sub _do_augment_mbox {
551         my ($self, $lei) = @_;
552         return unless $self->{seekable};
553         my $opt = $lei->{opt};
554         my $out = $lei->{1};
555         my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
556         return unless -s $out;
557         unless ($opt->{augment} || $opt->{'import-before'}) {
558                 truncate($out, 0) or die "truncate($dst): $!";
559                 return;
560         }
561         my $zsfx = $self->{zsfx};
562         my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) : dup_src($out);
563         my $dedupe;
564         if ($opt->{augment}) {
565                 $dedupe = $lei->{dedupe};
566                 $dedupe->prepare_dedupe if $dedupe;
567         }
568         if ($opt->{'import-before'}) { # the default
569                 my $lse = $lei->{lse};
570                 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
571                                                 $lei, $lse, $opt->{augment});
572                 if (!$opt->{augment} and !truncate($out, 0)) {
573                         die "truncate($dst): $!";
574                 }
575         } else { # --augment --no-import-before
576                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
577         }
578         # maybe some systems don't honor O_APPEND, Perl does this:
579         seek($out, 0, SEEK_END) or die "seek $dst: $!";
580         $dedupe->pause_dedupe if $dedupe;
581 }
582
583 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
584         my ($self, $lei) = @_;
585         # _pre_augment_maildir, _pre_augment_mbox
586         my $m = $self->can("_pre_augment_$self->{base_type}") or return;
587         $m->($self, $lei);
588 }
589
590 sub do_augment { # slow, runs in wq worker
591         my ($self, $lei) = @_;
592         # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
593         my $m = "_do_augment_$self->{base_type}";
594         $self->$m($lei);
595 }
596
597 # fast (spawn compressor or mkdir), runs in same process as pre_augment
598 sub post_augment {
599         my ($self, $lei, @args) = @_;
600         my $wait = $lei->{opt}->{'import-before'} ?
601                         $lei->{sto}->ipc_do('checkpoint', 1) : 0;
602         # _post_augment_mbox
603         my $m = $self->can("_post_augment_$self->{base_type}") or return;
604         $m->($self, $lei, @args);
605 }
606
607 sub do_post_auth {
608         my ($self) = @_;
609         my $lei = $self->{lei};
610         # lei_xsearch can start as soon as all l2m workers get here
611         pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
612                 die "incr_start_query: $!";
613         my $aug;
614         if (lock_free($self)) {
615                 my $mod = $self->{-wq_nr_workers};
616                 my $shard = $self->{-wq_worker_nr};
617                 if (my $net = $lei->{net}) {
618                         $net->{shard_info} = [ $mod, $shard ];
619                 } else { # Maildir (MH?)
620                         $self->{shard_info} = [ $mod, $shard ];
621                 }
622                 $aug = '+'; # incr_post_augment
623         } elsif ($self->{-wq_worker_nr} == 0) {
624                 $aug = '.'; # do_post_augment
625         }
626         if ($aug) {
627                 local $0 = 'do_augment';
628                 eval { do_augment($self, $lei) };
629                 $lei->fail($@) if $@;
630                 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
631                                 die "do_post_augment trigger: $!";
632         }
633         if (my $zpipe = delete $lei->{zpipe}) {
634                 $lei->{1} = $zpipe->[1];
635                 close $zpipe->[0];
636         }
637         $self->{wcb} = $self->write_cb($lei);
638 }
639
640 sub ipc_atfork_child {
641         my ($self) = @_;
642         my $lei = $self->{lei};
643         $lei->_lei_atfork_child;
644         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
645         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
646         $self->SUPER::ipc_atfork_child;
647 }
648
649 sub lock_free {
650         $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
651 }
652
653 sub poke_dst {
654         my ($self) = @_;
655         if ($self->{base_type} eq 'maildir') {
656                 my $t = time + 1;
657                 utime($t, $t, $self->{dst} . 'cur');
658         }
659 }
660
661 sub write_mail { # via ->wq_io_do
662         my ($self, $smsg) = @_;
663         git_async_cat($self->{lei}->{ale}->git, $smsg->{blob}, \&git_to_mail,
664                                 [$self->{wcb}, $smsg]);
665 }
666
667 sub wq_atexit_child {
668         my ($self) = @_;
669         delete $self->{wcb};
670         $self->{lei}->{ale}->git->async_wait_all;
671         $SIG{__WARN__} = 'DEFAULT';
672 }
673
674 # called in top-level lei-daemon when LeiAuth is done
675 sub net_merge_complete {
676         my ($self) = @_;
677         $self->wq_broadcast('do_post_auth');
678         $self->wq_close(1);
679 }
680
681 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
682 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;
683 1;