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