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