]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei q: --sort and --save|v2 are incompatible
[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->abs_path($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);
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 _v2_write_cb ($$) {
364         my ($self, $lei) = @_;
365         my $dedupe = $lei->{dedupe};
366         $dedupe->prepare_dedupe if $dedupe;
367         sub { # for git_to_mail
368                 my ($bref, $smsg, $eml) = @_;
369                 $eml //= PublicInbox::Eml->new($bref);
370                 return if $dedupe && $dedupe->is_dup($eml, $smsg);
371                 $lei->{v2w}->ipc_do('add', $eml); # V2Writable->add
372         }
373 }
374
375 sub write_cb { # returns a callback for git_to_mail
376         my ($self, $lei) = @_;
377         # _mbox_write_cb, _maildir_write_cb, _imap_write_cb, _v2_write_cb
378         my $m = "_$self->{base_type}_write_cb";
379         $self->$m($lei);
380 }
381
382 sub new {
383         my ($cls, $lei) = @_;
384         my $fmt = $lei->{ovv}->{fmt};
385         my $dst = $lei->{ovv}->{dst};
386         my $self = bless {}, $cls;
387         my @conflict;
388         if ($fmt eq 'maildir') {
389                 require PublicInbox::MdirReader;
390                 $self->{base_type} = 'maildir';
391                 -e $dst && !-d _ and die
392                                 "$dst exists and is not a directory\n";
393                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
394         } elsif (substr($fmt, 0, 4) eq 'mbox') {
395                 require PublicInbox::MboxReader;
396                 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
397                 $self->{base_type} = 'mbox';
398         } elsif ($fmt =~ /\Aimaps?\z/) {
399                 require PublicInbox::NetWriter;
400                 require PublicInbox::URIimap;
401                 my $net = PublicInbox::NetWriter->new;
402                 $net->{quiet} = $lei->{opt}->{quiet};
403                 my $uri = PublicInbox::URIimap->new($dst)->canonical;
404                 $net->add_url($uri);
405                 my $err = $net->errors($lei);
406                 return $lei->fail($err) if $err;
407                 $uri->mailbox or return $lei->fail("No mailbox: $dst");
408                 $self->{uri} = $uri;
409                 $dst = $lei->{ovv}->{dst} = $$uri; # canonicalized
410                 $lei->{net} = $net;
411                 $self->{base_type} = 'imap';
412         } elsif ($fmt eq 'text') {
413                 require PublicInbox::LeiViewText;
414                 $lei->{lvt} = PublicInbox::LeiViewText->new($lei);
415                 $self->{base_type} = 'text';
416                 @conflict = qw(mua save);
417         } elsif ($fmt eq 'v2') {
418                 die "--dedupe=oid and v2 are incompatible\n" if
419                         ($lei->{opt}->{dedupe}//'') eq 'oid';
420                 $self->{base_type} = 'v2';
421                 $lei->{opt}->{save} = \1;
422                 $dst = $lei->{ovv}->{dst} = $lei->abs_path($dst);
423                 @conflict = qw(mua sort);
424         } else {
425                 die "bad mail --format=$fmt\n";
426         }
427         if ($self->{base_type} =~ /\A(?:text|mbox)\z/) {
428                 (-d $dst || (-e _ && !-w _)) and die
429                         "$dst exists and is not a writable file\n";
430         }
431         my @err = map { defined($lei->{opt}->{$_}) ? "--$_" : () } @conflict;
432         die "@err incompatible with $fmt\n" if @err;
433         $self->{dst} = $dst;
434         $lei->{dedupe} = $lei->{lss} // do {
435                 my $dd_cls = 'PublicInbox::'.
436                         ($lei->{opt}->{save} ? 'LeiSavedSearch' : 'LeiDedupe');
437                 eval "require $dd_cls";
438                 die "$dd_cls: $@" if $@;
439                 $dd_cls->new($lei);
440         };
441         $self;
442 }
443
444 sub _pre_augment_maildir {
445         my ($self, $lei) = @_;
446         my $dst = $lei->{ovv}->{dst};
447         for my $x (qw(tmp new cur)) {
448                 my $d = $dst.$x;
449                 next if -d $d;
450                 require File::Path;
451                 File::Path::mkpath($d);
452                 -d $d or die "$d is not a directory";
453         }
454         # for utime, so no opendir
455         open $self->{poke_dh}, '<', "${dst}cur" or die "open ${dst}cur: $!";
456 }
457
458 sub _do_augment_maildir {
459         my ($self, $lei) = @_;
460         return if ($lei->{opt}->{save} // 0) < 0;
461         my $dst = $lei->{ovv}->{dst};
462         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
463         my $mdr = PublicInbox::MdirReader->new;
464         if ($lei->{opt}->{augment}) {
465                 my $dedupe = $lei->{dedupe};
466                 if ($dedupe && $dedupe->prepare_dedupe) {
467                         $mdr->{shard_info} = $self->{shard_info};
468                         $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
469                         $dedupe->pause_dedupe;
470                 }
471         } elsif ($lse) {
472                 $mdr->{shard_info} = $self->{shard_info};
473                 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
474         } else {# clobber existing Maildir
475                 $mdr->maildir_each_file($dst, \&_unlink);
476         }
477 }
478
479 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
480         my ($uri, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
481         update_kw_maybe($lei, $lse, $eml, $kw);
482         if ($delete_mic) {
483                 $lei->{net}->imap_delete_1($uri, $uid, $delete_mic);
484         } else {
485                 _augment($eml, $lei);
486         }
487 }
488
489 sub _do_augment_imap {
490         my ($self, $lei) = @_;
491         return if ($lei->{opt}->{save} // 0) < 0;
492         my $net = $lei->{net};
493         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
494         if ($lei->{opt}->{augment}) {
495                 my $dedupe = $lei->{dedupe};
496                 if ($dedupe && $dedupe->prepare_dedupe) {
497                         $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
498                                         $lei, $lse);
499                         $dedupe->pause_dedupe;
500                 }
501         } elsif ($lse) {
502                 my $delete_mic;
503                 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
504                                         $lei, $lse, \$delete_mic);
505                 $delete_mic->expunge if $delete_mic;
506         } elsif (!$self->{-wq_worker_nr}) { # undef or 0
507                 # clobber existing IMAP folder
508                 $net->imap_delete_all($self->{uri});
509         }
510 }
511
512 sub _pre_augment_text {
513         my ($self, $lei) = @_;
514         my $dst = $lei->{ovv}->{dst};
515         my $out;
516         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
517         if ($devfd >= 0) {
518                 $out = $lei->{$devfd};
519         } else { # normal-looking path
520                 if (-p $dst) {
521                         open $out, '>', $dst or die "open($dst): $!";
522                 } elsif (-f _ || !-e _) {
523                         # text allows augment, HTML/Atom won't
524                         my $mode = $lei->{opt}->{augment} ? '>>' : '>';
525                         open $out, $mode, $dst or die "open($mode, $dst): $!";
526                 } else {
527                         die "$dst is not a file or FIFO\n";
528                 }
529         }
530         $lei->{ovv}->ovv_out_lk_init if !$lei->{ovv}->{lock_path};
531         $lei->{1} = $out;
532         undef;
533 }
534
535 sub _pre_augment_mbox {
536         my ($self, $lei) = @_;
537         my $dst = $lei->{ovv}->{dst};
538         my $out;
539         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
540         if ($devfd >= 0) {
541                 $out = $lei->{$devfd};
542         } else { # normal-looking path
543                 if (-p $dst) {
544                         open $out, '>', $dst or die "open($dst): $!";
545                 } elsif (-f _ || !-e _) {
546                         require PublicInbox::MboxLock;
547                         my $m = $lei->{opt}->{'lock'} //
548                                         PublicInbox::MboxLock->defaults;
549                         $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
550                         $out = $self->{mbl}->{fh};
551                 } else {
552                         die "$dst is not a file or FIFO\n";
553                 }
554                 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
555         }
556         # Perl does SEEK_END even with O_APPEND :<
557         $self->{seekable} = seek($out, 0, SEEK_SET);
558         if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
559                 die "seek($dst): $!\n";
560         }
561         if (!$self->{seekable}) {
562                 my $imp_before = $lei->{opt}->{'import-before'};
563                 die "--import-before specified but $dst is not seekable\n"
564                         if $imp_before && !ref($imp_before);
565                 die "--augment specified but $dst is not seekable\n" if
566                         $lei->{opt}->{augment};
567         }
568         if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
569                 pipe(my ($r, $w)) or die "pipe: $!";
570                 $lei->{zpipe} = [ $r, $w ];
571                 $lei->{ovv}->{lock_path} and
572                         die 'BUG: unexpected {ovv}->{lock_path}';
573                 $lei->{ovv}->ovv_out_lk_init;
574         } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
575                 $lei->{ovv}->ovv_out_lk_init;
576         }
577         $lei->{1} = $out;
578         undef;
579 }
580
581 sub _do_augment_mbox {
582         my ($self, $lei) = @_;
583         return unless $self->{seekable};
584         my $opt = $lei->{opt};
585         return if ($opt->{save} // 0) < 0;
586         my $out = $lei->{1};
587         my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
588         return unless -s $out;
589         unless ($opt->{augment} || $opt->{'import-before'}) {
590                 truncate($out, 0) or die "truncate($dst): $!";
591                 return;
592         }
593         my $rd;
594         if (my $zsfx = $self->{zsfx}) {
595                 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
596         } else {
597                 open($rd, '+>>&', $out) or die "dup: $!";
598         }
599         my $dedupe;
600         if ($opt->{augment}) {
601                 $dedupe = $lei->{dedupe};
602                 $dedupe->prepare_dedupe if $dedupe;
603         }
604         if ($opt->{'import-before'}) { # the default
605                 my $lse = $lei->{lse};
606                 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
607                                                 $lei, $lse, $opt->{augment});
608                 if (!$opt->{augment} and !truncate($out, 0)) {
609                         die "truncate($dst): $!";
610                 }
611         } else { # --augment --no-import-before
612                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
613         }
614         # maybe some systems don't honor O_APPEND, Perl does this:
615         seek($out, 0, SEEK_END) or die "seek $dst: $!";
616         $dedupe->pause_dedupe if $dedupe;
617 }
618
619 sub _pre_augment_v2 {
620         my ($self, $lei) = @_;
621         my $dir = $self->{dst};
622         require PublicInbox::InboxWritable;
623         my ($ibx, @creat);
624         if (-d $dir) {
625                 my $opt = { -min_inbox_version => 2 };
626                 require PublicInbox::Admin;
627                 my @ibx = PublicInbox::Admin::resolve_inboxes([ $dir ], $opt);
628                 $ibx = $ibx[0] or die "$dir is not a v2 inbox\n";
629         } else {
630                 $creat[0] = {};
631                 $ibx = PublicInbox::Inbox->new({
632                         name => 'lei-result', # XXX configurable
633                         inboxdir => $dir,
634                         version => 2,
635                         address => [ 'lei@example.com' ],
636                 });
637         }
638         PublicInbox::InboxWritable->new($ibx, @creat);
639         $ibx->init_inbox if @creat;
640         my $v2w = $lei->{v2w} = $ibx->importer;
641         $v2w->ipc_lock_init("$dir/ipc.lock");
642         $v2w->ipc_worker_spawn("lei/v2w $dir", $lei->oldset, { lei => $lei });
643         return if !$lei->{opt}->{shared};
644         my $d = "$lei->{ale}->{git}->{git_dir}/objects";
645         my $al = "$dir/git/0.git/objects/info/alternates";
646         open my $fh, '+>>', $al or die "open($al): $!";
647         seek($fh, 0, SEEK_SET) or die "seek($al): $!";
648         grep(/\A\Q$d\E\n/, <$fh>) and return;
649         print $fh "$d\n" or die "print($al): $!";
650         close $fh or die "close($al): $!";
651 }
652
653 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
654         my ($self, $lei) = @_;
655         # _pre_augment_maildir, _pre_augment_mbox, _pre_augment_v2
656         my $m = $self->can("_pre_augment_$self->{base_type}") or return;
657         $m->($self, $lei);
658 }
659
660 sub do_augment { # slow, runs in wq worker
661         my ($self, $lei) = @_;
662         # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
663         my $m = $self->can("_do_augment_$self->{base_type}") or return;
664         $m->($self, $lei);
665 }
666
667 # fast (spawn compressor or mkdir), runs in same process as pre_augment
668 sub post_augment {
669         my ($self, $lei, @args) = @_;
670         my $wait = $lei->{opt}->{'import-before'} ?
671                         $lei->{sto}->ipc_do('checkpoint', 1) : 0;
672         # _post_augment_mbox
673         my $m = $self->can("_post_augment_$self->{base_type}") or return;
674         $m->($self, $lei, @args);
675 }
676
677 # called by every single l2m worker process
678 sub do_post_auth {
679         my ($self) = @_;
680         my $lei = $self->{lei};
681         # lei_xsearch can start as soon as all l2m workers get here
682         pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
683                 die "incr_start_query: $!";
684         my $aug;
685         if (lock_free($self)) { # all workers do_augment
686                 my $mod = $self->{-wq_nr_workers};
687                 my $shard = $self->{-wq_worker_nr};
688                 if (my $net = $lei->{net}) {
689                         $net->{shard_info} = [ $mod, $shard ];
690                 } else { # Maildir
691                         $self->{shard_info} = [ $mod, $shard ];
692                 }
693                 $aug = '+'; # incr_post_augment
694         } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
695                 $aug = '.'; # do_post_augment
696         }
697         if ($aug) {
698                 local $0 = 'do_augment';
699                 eval { do_augment($self, $lei) };
700                 $lei->fail($@) if $@;
701                 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
702                                 die "do_post_augment trigger: $!";
703         }
704         # done augmenting, connect the compressor pipe for each worker
705         if (my $zpipe = delete $lei->{zpipe}) {
706                 $lei->{1} = $zpipe->[1];
707                 close $zpipe->[0];
708         }
709         my $au_peers = delete $self->{au_peers};
710         if ($au_peers) { # wait for peer l2m to finish augmenting:
711                 $au_peers->[1] = undef;
712                 sysread($au_peers->[0], my $barrier1, 1);
713         }
714         $self->{wcb} = $self->write_cb($lei);
715         if ($au_peers) { # wait for peer l2m to set write_cb
716                 $au_peers->[3] = undef;
717                 sysread($au_peers->[2], my $barrier2, 1);
718         }
719 }
720
721 sub ipc_atfork_child {
722         my ($self) = @_;
723         my $lei = $self->{lei};
724         $lei->_lei_atfork_child;
725         if (my $lse = $lei->{lse}) {
726                 $self->{-lms_ro} = $lse->{-lms_ro} //= $lse->lms;
727         }
728         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
729         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
730         $self->SUPER::ipc_atfork_child;
731 }
732
733 sub lock_free {
734         $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
735 }
736
737 # wakes up the MUA when complete so it can refresh messages list
738 sub poke_dst {
739         my ($self) = @_;
740         if ($self->{base_type} eq 'maildir') {
741                 my $t = time + 1;
742                 utime($t, $t, $self->{poke_dh}) or warn "futimes: $!";
743         }
744 }
745
746 sub write_mail { # via ->wq_io_do
747         my ($self, $smsg, $eml) = @_;
748         return $self->{wcb}->(undef, $smsg, $eml) if $eml;
749         $smsg->{-lms_ro} = $self->{-lms_ro};
750         $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
751                                 [$self->{wcb}, $smsg]);
752 }
753
754 sub wq_atexit_child {
755         my ($self) = @_;
756         my $lei = $self->{lei};
757         delete $self->{wcb};
758         $lei->{ale}->git->async_wait_all;
759         my $nr = delete($lei->{-nr_write}) or return;
760         return if $lei->{early_mua} || !$lei->{-progress} || !$lei->{pkt_op_p};
761         require PublicInbox::PktOp;
762         PublicInbox::PktOp::pkt_do($lei->{pkt_op_p}, 'l2m_progress', $nr);
763 }
764
765 # called in top-level lei-daemon when LeiAuth is done
766 sub net_merge_all_done {
767         my ($self) = @_;
768         $self->wq_broadcast('do_post_auth');
769         $self->wq_close(1);
770 }
771
772 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
773 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;
774 1;