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