1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
8 use parent qw(PublicInbox::IPC);
10 use PublicInbox::ProcessPipe;
11 use PublicInbox::Spawn qw(spawn);
12 use Symbol qw(gensym);
13 use IO::Handle; # ->autoflush
14 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
15 use PublicInbox::Syscall qw(rename_noreplace);
17 my %kw2char = ( # Maildir characters
20 forwarded => 'P', # passed
26 flagged => [ 'X-Status' => 'F' ],
27 answered => [ 'X-Status' => 'A' ],
28 seen => [ 'Status' => 'R' ],
29 draft => [ 'X-Status' => 'T' ],
32 sub _mbox_hdr_buf ($$$) {
33 my ($eml, $type, $smsg) = @_;
34 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
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];
41 warn "# keyword `$k' not supported for mbox\n";
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)));
55 my $buf = delete $eml->{hdr};
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" }
62 substr($$buf, 0, 0, # prepend From line
63 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
67 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
69 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
70 return if $w == length($$buf);
71 $buf = "short atomic write: $w != ".length($$buf);
73 return $lei->note_sigpipe(1);
75 $buf = "atomic write: $!";
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
89 $$buf .= $eml->{crlf};
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
102 $$buf .= $eml->{crlf};
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
117 # mboxcl still escapes "From " lines
119 my ($eml, $smsg) = @_;
120 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
121 my $bdy = delete($eml->{bdy}) // \(my $empty = '');
122 $$bdy =~ s/^From />From /gm;
123 _mboxcl_common($buf, $bdy, $eml->{crlf});
126 # mboxcl2 has no "From " escaping
128 my ($eml, $smsg) = @_;
129 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
130 my $bdy = delete($eml->{bdy}) // \(my $empty = '');
131 _mboxcl_common($buf, $bdy, $eml->{crlf});
134 sub git_to_mail { # git->cat_async callback
135 my ($bref, $oid, $type, $size, $smsg) = @_;
136 my $self = delete $smsg->{l2m} // die "BUG: no l2m";
137 $type // return; # called by git->async_abort
139 if ($type eq 'missing' &&
140 ($bref = $self->{-lms_rw}->local_blob($oid, 1))) {
142 $size = length($$bref);
144 $type eq 'blob' or return $self->{lei}->child_error(1,
145 "W: $oid is $type (!= blob)");
146 $size or return $self->{lei}->child_error(1,"E: $oid is empty");
147 $smsg->{blob} eq $oid or die "BUG: expected=$smsg->{blob}";
148 $self->{wcb}->($bref, $smsg);
150 $self->{lei}->fail("$@ (oid=$oid)") if $@;
153 sub reap_compress { # dwaitpid callback
154 my ($lei, $pid) = @_;
155 my $cmd = delete $lei->{"pid.$pid"};
157 $lei->fail("@$cmd failed", $? >> 8);
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}, pgid => 0 };
166 my $pid = spawn($cmd, undef, $rdr);
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;
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);
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;
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 my $set_recent = $dedupe->has_entries;
200 sub { # for git_to_mail
201 my ($buf, $smsg, $eml) = @_;
202 $eml //= PublicInbox::Eml->new($buf);
204 return if $dedupe->is_dup($eml, $smsg);
205 $lse->xsmsg_vmd($smsg) if $lse;
206 $smsg->{-recent} = 1 if $set_recent;
207 $buf = $eml2mbox->($eml, $smsg);
208 if ($atomic_append) {
209 atomic_append($lei, $buf);
211 my $lk = $ovv->lock_for_scope;
218 sub update_kw_maybe ($$$$) {
219 my ($lei, $lse, $eml, $kw) = @_;
221 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
222 my $vmd = { kw => $kw };
223 if (scalar @$docids) { # already in lei/store
224 $lei->{sto}->wq_do('set_eml_vmd', undef, $vmd, $docids) if $c;
225 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
226 # it's in an external, only set kw, here
227 $lei->{sto}->wq_do('set_xvmd', $xoids, $eml, $vmd);
228 } else { # never-before-seen, import the whole thing
229 # XXX this is critical in protecting against accidental
230 # data loss without --augment
231 $lei->{sto}->wq_do('set_eml', $eml, $vmd);
235 sub _md_update { # maildir_each_eml cb
236 my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
237 update_kw_maybe($lei, $lse, $eml, $kw);
238 $unlink ? unlink($f) : _augment($eml, $lei);
241 # maildir_each_file callback, \&CORE::unlink doesn't work with it
242 sub _unlink { unlink($_[0]) }
246 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
249 sub kw2suffix ($;@) {
251 join('', sort(map { $kw2char{$_} // () } @$kw, @_));
254 sub _buf2maildir ($$$$) {
255 my ($dst, $buf, $smsg, $dir) = @_;
256 my $kw = $smsg->{kw} // [];
257 my $rand = ''; # chosen by die roll :P
258 my ($tmp, $fh, $base, $ok);
259 my $common = $smsg->{blob} // _rand;
260 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
262 $tmp = $dst.'tmp/'.$rand.$common;
263 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
264 $!{EEXIST} && ($rand = _rand.','));
265 if ($ok && print $fh $$buf and close($fh)) {
266 $dst .= $dir; # 'new/' or 'cur/'
269 $base = $rand.$common.':2,'.kw2suffix($kw);
270 } while (!($ok = rename_noreplace($tmp, $dst.$base)) &&
271 $!{EEXIST} && ($rand = _rand.','));
274 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
275 $_[0] = undef; # clobber dst
281 sub _maildir_write_cb ($$) {
282 my ($self, $lei) = @_;
283 my $dedupe = $lei->{dedupe};
284 $dedupe->prepare_dedupe if $dedupe;
285 my $dst = $lei->{ovv}->{dst};
286 my $lse = $lei->{lse}; # may be undef
287 my $lms = $self->{-lms_rw};
288 my $out = $lms ? 'maildir:'.$lei->abs_path($dst) : undef;
289 $lms->lms_write_prepare if $lms;
291 # Favor cur/ and only write to new/ when augmenting. This
292 # saves MUAs from having to do a mass rename when the initial
293 # search result set is huge.
294 my $dir = $dedupe && $dedupe->has_entries ? 'new/' : 'cur/';
295 sub { # for git_to_mail
296 my ($bref, $smsg, $eml) = @_;
297 $dst // return $lei->fail; # dst may be undef-ed in last run
300 return if $dedupe && $dedupe->is_dup($eml //
301 PublicInbox::Eml->new($$bref),
303 $lse->xsmsg_vmd($smsg) if $lse;
304 my $n = _buf2maildir($dst, $bref // \($eml->as_string),
306 $lms->set_src($smsg->oidbin, $out, $n) if $lms;
311 sub _imap_write_cb ($$) {
312 my ($self, $lei) = @_;
313 my $dedupe = $lei->{dedupe};
314 $dedupe->prepare_dedupe if $dedupe;
315 my $append = $lei->{net}->can('imap_append');
316 my $uri = $self->{uri} // die 'BUG: no {uri}';
317 my $mic = $lei->{net}->mic_get($uri) // die <<EOM;
318 E: $uri connection failed.
319 E: Consider using `--jobs ,1' to limit IMAP connections
321 my $folder = $uri->mailbox;
322 $uri->uidvalidity($mic->uidvalidity($folder));
323 my $lse = $lei->{lse}; # may be undef
324 my $lms = $self->{-lms_rw};
325 $lms->lms_write_prepare if $lms;
326 sub { # for git_to_mail
327 my ($bref, $smsg, $eml) = @_;
328 $mic // return $lei->fail; # mic may be undef-ed in last run
331 return if $dedupe && $dedupe->is_dup($eml //
332 PublicInbox::Eml->new($$bref),
334 $lse->xsmsg_vmd($smsg) if $lse;
335 my $uid = eval { $append->($mic, $folder, $bref, $smsg, $eml) };
340 # imap_append returns UID if IMAP server has UIDPLUS extension
341 ($lms && $uid =~ /\A[0-9]+\z/) and
342 $lms->set_src($smsg->oidbin, $$uri, $uid + 0);
347 sub _text_write_cb ($$) {
348 my ($self, $lei) = @_;
349 my $dedupe = $lei->{dedupe};
350 $dedupe->prepare_dedupe if $dedupe;
351 my $lvt = $lei->{lvt};
352 my $ovv = $lei->{ovv};
353 $lei->{1} // die "no stdout ($ovv->{dst})"; # redirected earlier
354 $lei->{1}->autoflush(1);
355 binmode $lei->{1}, ':utf8';
356 my $lse = $lei->{lse}; # may be undef
357 sub { # for git_to_mail
358 my ($bref, $smsg, $eml) = @_;
359 $lse->xsmsg_vmd($smsg) if $lse;
360 $eml //= PublicInbox::Eml->new($bref);
361 return if $dedupe && $dedupe->is_dup($eml, $smsg);
362 my $lk = $ovv->lock_for_scope;
363 $lei->out(${$lvt->eml_to_text($smsg, $eml)}, "\n");
367 sub _v2_write_cb ($$) {
368 my ($self, $lei) = @_;
369 my $dedupe = $lei->{dedupe};
370 $dedupe->prepare_dedupe if $dedupe;
371 sub { # for git_to_mail
372 my ($bref, $smsg, $eml) = @_;
373 $eml //= PublicInbox::Eml->new($bref);
375 return if $dedupe && $dedupe->is_dup($eml, $smsg);
376 $lei->{v2w}->wq_do('add', $eml); # V2Writable->add
381 sub write_cb { # returns a callback for git_to_mail
382 my ($self, $lei) = @_;
383 # _mbox_write_cb, _maildir_write_cb, _imap_write_cb, _v2_write_cb
384 my $m = "_$self->{base_type}_write_cb";
389 my ($cls, $lei) = @_;
390 my $fmt = $lei->{ovv}->{fmt};
391 my $dst = $lei->{ovv}->{dst};
392 my $self = bless {}, $cls;
394 if ($fmt eq 'maildir') {
395 require PublicInbox::MdirReader;
396 $self->{base_type} = 'maildir';
397 -e $dst && !-d _ and die
398 "$dst exists and is not a directory\n";
399 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
400 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
401 } elsif (substr($fmt, 0, 4) eq 'mbox') {
402 require PublicInbox::MboxReader;
403 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
404 $self->{base_type} = 'mbox';
405 if ($lei->{cmd} eq 'q' &&
406 (($lei->path_to_fd($dst) // -1) < 0) &&
407 (-f $dst || !-e _)) {
408 $lei->{opt}->{save} //= \1;
410 } elsif ($fmt =~ /\Aimaps?\z/) {
411 require PublicInbox::NetWriter;
412 require PublicInbox::URIimap;
413 # {net} may exist from "lei up" for auth
414 my $net = $lei->{net} // PublicInbox::NetWriter->new;
415 $net->{quiet} = $lei->{opt}->{quiet};
416 my $uri = PublicInbox::URIimap->new($dst)->canonical;
417 $net->add_url($$uri);
418 my $err = $net->errors($lei);
419 return $lei->fail($err) if $err;
420 $uri->mailbox or return $lei->fail("No mailbox: $dst");
422 $dst = $lei->{ovv}->{dst} = $$uri; # canonicalized
424 $self->{base_type} = 'imap';
425 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
426 } elsif ($fmt eq 'text' || $fmt eq 'reply') {
427 require PublicInbox::LeiViewText;
428 $lei->{lvt} = PublicInbox::LeiViewText->new($lei, $fmt);
429 $self->{base_type} = 'text';
430 $self->{-wq_nr_workers} = 1; # for pager
431 @conflict = qw(mua save);
432 } elsif ($fmt eq 'v2') {
433 die "--dedupe=oid and v2 are incompatible\n" if
434 ($lei->{opt}->{dedupe}//'') eq 'oid';
435 $self->{base_type} = 'v2';
436 $self->{-wq_nr_workers} = 1; # v2 has shards
437 $lei->{opt}->{save} = \1;
438 $dst = $lei->{ovv}->{dst} = $lei->abs_path($dst);
439 @conflict = qw(mua sort);
441 die "bad mail --format=$fmt\n";
443 if ($self->{base_type} =~ /\A(?:text|mbox)\z/) {
444 (-d $dst || (-e _ && !-w _)) and die
445 "$dst exists and is not a writable file\n";
447 my @err = map { defined($lei->{opt}->{$_}) ? "--$_" : () } @conflict;
448 die "@err incompatible with $fmt\n" if @err;
450 $lei->{dedupe} = $lei->{lss} // do {
451 my $dd_cls = 'PublicInbox::'.
452 ($lei->{opt}->{save} ? 'LeiSavedSearch' : 'LeiDedupe');
453 eval "require $dd_cls";
454 die "$dd_cls: $@" if $@;
455 my $dd = $dd_cls->new($lei);
456 $lei->{lss} //= $dd if $dd && $dd->can('cfg_set');
462 sub _pre_augment_maildir {
463 my ($self, $lei) = @_;
464 my $dst = $lei->{ovv}->{dst};
465 for my $x (qw(tmp new cur)) {
469 File::Path::mkpath($d);
470 -d $d or die "$d is not a directory";
472 # for utime, so no opendir
473 open $self->{poke_dh}, '<', "${dst}cur" or die "open ${dst}cur: $!";
476 sub clobber_dst_prepare ($;$) {
478 if (my $lms = defined($f) ? $lei->lms : undef) {
479 $lms->lms_write_prepare;
480 $lms->forget_folders($f);
482 my $dedupe = $lei->{dedupe} or return;
483 $dedupe->reset_dedupe if $dedupe->can('reset_dedupe');
486 sub _do_augment_maildir {
487 my ($self, $lei) = @_;
488 return if $lei->{cmd} eq 'up';
489 my $dst = $lei->{ovv}->{dst};
490 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
491 my $mdr = PublicInbox::MdirReader->new;
492 if ($lei->{opt}->{augment}) {
493 my $dedupe = $lei->{dedupe};
494 if ($dedupe && $dedupe->prepare_dedupe) {
495 $mdr->{shard_info} = $self->{shard_info};
496 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
497 $dedupe->pause_dedupe;
500 clobber_dst_prepare($lei, "maildir:$dst");
501 $mdr->{shard_info} = $self->{shard_info};
502 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
503 } else {# clobber existing Maildir
504 clobber_dst_prepare($lei, "maildir:$dst");
505 $mdr->maildir_each_file($dst, \&_unlink);
509 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
510 my ($uri, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
511 update_kw_maybe($lei, $lse, $eml, $kw);
513 $lei->{net}->imap_delete_1($uri, $uid, $delete_mic);
515 _augment($eml, $lei);
519 sub _do_augment_imap {
520 my ($self, $lei) = @_;
521 return if $lei->{cmd} eq 'up';
522 my $net = $lei->{net};
523 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
524 if ($lei->{opt}->{augment}) {
525 my $dedupe = $lei->{dedupe};
526 if ($dedupe && $dedupe->prepare_dedupe) {
527 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
529 $dedupe->pause_dedupe;
533 clobber_dst_prepare($lei, "$self->{uri}");
534 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
535 $lei, $lse, \$delete_mic);
536 $delete_mic->expunge if $delete_mic;
537 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
538 # clobber existing IMAP folder
539 clobber_dst_prepare($lei, "$self->{uri}");
540 $net->imap_delete_all($self->{uri});
544 sub _pre_augment_text {
545 my ($self, $lei) = @_;
546 my $dst = $lei->{ovv}->{dst};
548 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
550 $out = $lei->{$devfd};
551 } else { # normal-looking path
553 open $out, '>', $dst or die "open($dst): $!";
554 } elsif (-f _ || !-e _) {
555 # text allows augment, HTML/Atom won't
556 my $mode = $lei->{opt}->{augment} ? '>>' : '>';
557 open $out, $mode, $dst or die "open($mode, $dst): $!";
559 die "$dst is not a file or FIFO\n";
562 $lei->{ovv}->ovv_out_lk_init if !$lei->{ovv}->{lock_path};
567 sub _pre_augment_mbox {
568 my ($self, $lei) = @_;
569 my $dst = $lei->{ovv}->{dst};
571 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
573 $out = $lei->{$devfd};
574 } else { # normal-looking path
576 open $out, '>', $dst or die "open($dst): $!";
577 } elsif (-f _ || !-e _) {
578 require PublicInbox::MboxLock;
579 my $m = $lei->{opt}->{'lock'} //
580 PublicInbox::MboxLock->defaults;
581 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
582 $out = $self->{mbl}->{fh};
584 die "$dst is not a file or FIFO\n";
586 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
588 # Perl does SEEK_END even with O_APPEND :<
589 $self->{seekable} = seek($out, 0, SEEK_SET);
590 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
591 die "seek($dst): $!\n";
593 if (!$self->{seekable}) {
594 my $imp_before = $lei->{opt}->{'import-before'};
595 die "--import-before specified but $dst is not seekable\n"
596 if $imp_before && !ref($imp_before);
597 die "--augment specified but $dst is not seekable\n" if
598 $lei->{opt}->{augment};
599 die "cannot --save with unseekable $dst\n" if
600 $lei->{dedupe} && $lei->{dedupe}->can('reset_dedupe');
602 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
603 pipe(my ($r, $w)) or die "pipe: $!";
604 $lei->{zpipe} = [ $r, $w ];
605 $lei->{ovv}->{lock_path} and
606 die 'BUG: unexpected {ovv}->{lock_path}';
607 $lei->{ovv}->ovv_out_lk_init;
608 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
609 $lei->{ovv}->ovv_out_lk_init;
615 sub _do_augment_mbox {
616 my ($self, $lei) = @_;
617 return unless $self->{seekable};
618 my $opt = $lei->{opt};
619 return if $lei->{cmd} eq 'up';
621 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
622 return clobber_dst_prepare($lei) unless -s $out;
623 unless ($opt->{augment} || $opt->{'import-before'}) {
624 truncate($out, 0) or die "truncate($dst): $!";
628 if (my $zsfx = $self->{zsfx}) {
629 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
631 open($rd, '+>>&', $out) or die "dup: $!";
634 if ($opt->{augment}) {
635 $dedupe = $lei->{dedupe};
636 $dedupe->prepare_dedupe if $dedupe;
638 clobber_dst_prepare($lei);
640 if ($opt->{'import-before'}) { # the default
641 my $lse = $lei->{lse};
642 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
643 $lei, $lse, $opt->{augment});
644 if (!$opt->{augment} and !truncate($out, 0)) {
645 die "truncate($dst): $!";
647 } else { # --augment --no-import-before
648 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
650 # maybe some systems don't honor O_APPEND, Perl does this:
651 seek($out, 0, SEEK_END) or die "seek $dst: $!";
652 $dedupe->pause_dedupe if $dedupe;
655 sub v2w_done_wait { # dwaitpid callback
656 my ($arg, $pid) = @_;
657 my ($v2w, $lei) = @$arg;
658 $lei->child_error($?, "error for $v2w->{ibx}->{inboxdir}") if $?;
661 sub _pre_augment_v2 {
662 my ($self, $lei) = @_;
663 my $dir = $self->{dst};
664 require PublicInbox::InboxWritable;
667 my $opt = { -min_inbox_version => 2 };
668 require PublicInbox::Admin;
669 my @ibx = PublicInbox::Admin::resolve_inboxes([ $dir ], $opt);
670 $ibx = $ibx[0] or die "$dir is not a v2 inbox\n";
673 $ibx = PublicInbox::Inbox->new({
674 name => 'lei-result', # XXX configurable
677 address => [ 'lei@example.com' ],
680 PublicInbox::InboxWritable->new($ibx, @creat);
681 $ibx->init_inbox if @creat;
682 my $v2w = $ibx->importer;
683 $v2w->wq_workers_start("lei/v2w $dir", 1, $lei->oldset, {lei => $lei});
684 $v2w->wq_wait_async(\&v2w_done_wait, $lei);
686 return if !$lei->{opt}->{shared};
687 my $d = "$lei->{ale}->{git}->{git_dir}/objects";
688 my $al = "$dir/git/0.git/objects/info/alternates";
689 open my $fh, '+>>', $al or die "open($al): $!";
690 seek($fh, 0, SEEK_SET) or die "seek($al): $!";
691 grep(/\A\Q$d\E\n/, <$fh>) and return;
692 print $fh "$d\n" or die "print($al): $!";
693 close $fh or die "close($al): $!";
696 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
697 my ($self, $lei) = @_;
698 # _pre_augment_maildir, _pre_augment_mbox, _pre_augment_v2
699 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
703 sub do_augment { # slow, runs in wq worker
704 my ($self, $lei) = @_;
705 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
706 my $m = $self->can("_do_augment_$self->{base_type}") or return;
710 # fast (spawn compressor or mkdir), runs in same process as pre_augment
712 my ($self, $lei, @args) = @_;
713 $self->{-au_noted}++ and $lei->qerr("# writing to $self->{dst} ...");
715 my $wait = $lei->{opt}->{'import-before'} ?
716 $lei->{sto}->wq_do('checkpoint', 1) : 0;
718 my $m = $self->can("_post_augment_$self->{base_type}") or return;
719 $m->($self, $lei, @args);
722 # called by every single l2m worker process
725 my $lei = $self->{lei};
726 # lei_xsearch can start as soon as all l2m workers get here
727 $lei->{pkt_op_p}->pkt_do('incr_start_query') or
728 die "incr_start_query: $!";
730 if (lock_free($self)) { # all workers do_augment
731 my $mod = $self->{-wq_nr_workers};
732 my $shard = $self->{-wq_worker_nr};
733 if (my $net = $lei->{net}) {
734 $net->{shard_info} = [ $mod, $shard ];
736 $self->{shard_info} = [ $mod, $shard ];
738 $aug = 'incr_post_augment';
739 } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
740 $aug = 'do_post_augment';
743 local $0 = 'do_augment';
744 eval { do_augment($self, $lei) };
745 $lei->fail($@) if $@;
746 $lei->{pkt_op_p}->pkt_do($aug) or die "pkt_do($aug): $!";
748 # done augmenting, connect the compressor pipe for each worker
749 if (my $zpipe = delete $lei->{zpipe}) {
750 $lei->{1} = $zpipe->[1];
753 my $au_peers = delete $self->{au_peers};
754 if ($au_peers) { # wait for peer l2m to finish augmenting:
755 $au_peers->[1] = undef;
756 sysread($au_peers->[0], my $barrier1, 1);
758 eval { $self->{wcb} = $self->write_cb($lei) };
759 $lei->fail($@) if $@;
760 if ($au_peers) { # wait for peer l2m to set write_cb
761 $au_peers->[3] = undef;
762 sysread($au_peers->[2], my $barrier2, 1);
766 sub ipc_atfork_child {
768 my $lei = $self->{lei};
769 $lei->_lei_atfork_child;
770 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
771 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
772 $self->{git} = $self->{lei}->{ale}->git;
773 $SIG{TERM} = sub { # avoid ->DESTROY ordering problems
774 my $git = delete $self->{git};
775 $git->async_wait_all if $git;
778 $self->SUPER::ipc_atfork_child;
782 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
785 # wakes up the MUA when complete so it can refresh messages list
788 if ($self->{base_type} eq 'maildir') {
790 utime($t, $t, $self->{poke_dh}) or warn "futimes: $!";
794 sub write_mail { # via ->wq_io_do
795 my ($self, $smsg, $eml) = @_;
797 eval { $self->{wcb}->(undef, $smsg, $eml) };
798 $self->{lei}->fail("blob=$smsg->{blob} $@") if $@;
800 $smsg->{l2m} = $self;
801 $self->{git}->cat_async($smsg->{blob}, \&git_to_mail, $smsg);
805 sub wq_atexit_child {
807 local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
808 my $lei = $self->{lei};
809 $lei->{ale}->git->async_wait_all;
810 my ($nr_w, $nr_s) = delete(@$lei{qw(-nr_write -nr_seen)});
813 return if $lei->{early_mua} || !$lei->{-progress} || !$lei->{pkt_op_p};
814 $lei->{pkt_op_p}->pkt_do('l2m_progress', $nr_w, $nr_s);
817 # runs on a 1s timer in lei-daemon
818 sub augment_inprogress {
819 my ($err, $opt, $dst, $au_noted) = @_;
821 return if $$au_noted++ || !$err || !defined(fileno($err));
822 print $err '# '.($opt->{'import-before'} ?
823 "importing non-external contents of $dst" : (
824 ($opt->{dedupe} // 'content') ne 'none') ?
825 "scanning old contents of $dst for dedupe" :
826 "removing old contents of $dst")." ...\n";
828 warn "E: $@ ($dst)" if $@;
831 # called in top-level lei-daemon when LeiAuth is done
832 sub net_merge_all_done {
833 my ($self, $lei) = @_;
834 if ($PublicInbox::DS::in_loop &&
835 $self->can("_do_augment_$self->{base_type}") &&
836 !$lei->{opt}->{quiet}) {
837 $self->{-au_noted} = 0;
838 PublicInbox::DS::add_timer(1, \&augment_inprogress,
839 $lei->{2}, $lei->{opt},
840 $self->{dst}, \$self->{-au_noted});
842 $self->wq_broadcast('do_post_auth');