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