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