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>
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);
16 my %kw2char = ( # Maildir characters
19 forwarded => 'P', # passed
25 flagged => [ 'X-Status' => 'F' ],
26 answered => [ 'X-Status' => 'A' ],
27 seen => [ 'Status' => 'R' ],
28 draft => [ 'X-Status' => 'T' ],
31 sub _mbox_hdr_buf ($$$) {
32 my ($eml, $type, $smsg) = @_;
33 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
35 my %hdr = (Status => []); # set Status, X-Status
36 for my $k (@{$smsg->{kw} // []}) {
37 if (my $ent = $kw2status{$k}) {
38 push @{$hdr{$ent->[0]}}, $ent->[1];
40 warn "# keyword `$k' not supported for mbox\n";
43 # When writing to empty mboxes, messages are always 'O'
44 # (not-\Recent in IMAP), it saves MUAs the trouble of
45 # rewriting the mbox if no other changes are made.
46 # We put 'O' at the end (e.g. "Status: RO") to match mutt(1) output.
47 # We only set smsg->{-recent} if augmenting existing stores.
48 my $status = join('', sort(@{$hdr{Status}}));
49 $status .= 'O' unless $smsg->{-recent};
50 $eml->header_set('Status', $status) if $status;
51 if (my $chars = delete $hdr{'X-Status'}) {
52 $eml->header_set('X-Status', join('', sort(@$chars)));
54 my $buf = delete $eml->{hdr};
56 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
57 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
58 my $ident = $smsg->{blob} // 'lei';
59 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
61 substr($$buf, 0, 0, # prepend From line
62 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
66 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
68 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
69 return if $w == length($$buf);
70 $buf = "short atomic write: $w != ".length($$buf);
72 return $lei->note_sigpipe(1);
74 $buf = "atomic write: $!";
79 sub eml2mboxrd ($;$) {
80 my ($eml, $smsg) = @_;
81 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
82 if (my $bdy = delete $eml->{bdy}) {
83 $$bdy =~ s/^(>*From )/>$1/gm;
84 $$buf .= $eml->{crlf};
85 substr($$bdy, 0, 0, $$buf); # prepend header
88 $$buf .= $eml->{crlf};
93 my ($eml, $smsg) = @_;
94 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
95 if (my $bdy = delete $eml->{bdy}) {
96 $$bdy =~ s/^From />From /gm;
97 $$buf .= $eml->{crlf};
98 substr($$bdy, 0, 0, $$buf); # prepend header
101 $$buf .= $eml->{crlf};
105 sub _mboxcl_common ($$$) {
106 my ($buf, $bdy, $crlf) = @_;
107 # add Lines: so mutt won't have to add it on MUA close
108 my $lines = $$bdy =~ tr!\n!\n!;
109 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
110 'Lines: '.$lines.$crlf.$crlf;
111 substr($$bdy, 0, 0, $$buf); # prepend header
116 # mboxcl still escapes "From " lines
118 my ($eml, $smsg) = @_;
119 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
120 my $bdy = delete($eml->{bdy}) // \(my $empty = '');
121 $$bdy =~ s/^From />From /gm;
122 _mboxcl_common($buf, $bdy, $eml->{crlf});
125 # mboxcl2 has no "From " escaping
127 my ($eml, $smsg) = @_;
128 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
129 my $bdy = delete($eml->{bdy}) // \(my $empty = '');
130 _mboxcl_common($buf, $bdy, $eml->{crlf});
133 sub git_to_mail { # git->cat_async callback
134 my ($bref, $oid, $type, $size, $arg) = @_;
135 $type // return; # called by git->async_abort
136 my ($write_cb, $smsg) = @$arg;
137 if ($type eq 'missing' && $smsg->{-lms_ro}) {
138 if ($bref = $smsg->{-lms_ro}->local_blob($oid, 1)) {
140 $size = length($$bref);
143 return warn("W: $oid is $type (!= blob)\n") if $type ne 'blob';
144 return warn("E: $oid is empty\n") unless $size;
145 die "BUG: expected=$smsg->{blob} got=$oid" if $smsg->{blob} ne $oid;
146 $write_cb->($bref, $smsg);
149 sub reap_compress { # dwaitpid callback
150 my ($lei, $pid) = @_;
151 my $cmd = delete $lei->{"pid.$pid"};
153 $lei->fail("@$cmd failed", $? >> 8);
156 sub _post_augment_mbox { # open a compressor process from top-level process
157 my ($self, $lei) = @_;
158 my $zsfx = $self->{zsfx} or return;
159 my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
160 my ($r, $w) = @{delete $lei->{zpipe}};
161 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2}, pgid => 0 };
162 my $pid = spawn($cmd, undef, $rdr);
164 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
165 $dup->{$_} = $lei->{$_} for qw(2 sock);
166 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
170 # --augment existing output destination, with deduplication
171 sub _augment { # MboxReader eml_cb
172 my ($eml, $lei) = @_;
173 # ignore return value, just populate the skv
174 $lei->{dedupe}->is_dup($eml);
177 sub _mbox_augment_kw_maybe {
178 my ($eml, $lei, $lse, $augment) = @_;
179 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
180 update_kw_maybe($lei, $lse, $eml, $kw);
181 _augment($eml, $lei) if $augment;
184 sub _mbox_write_cb ($$) {
185 my ($self, $lei) = @_;
186 my $ovv = $lei->{ovv};
187 my $m = 'eml2'.$ovv->{fmt};
188 my $eml2mbox = $self->can($m) or die "$self->$m missing";
189 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
190 $lei->{1}->autoflush(1);
191 my $atomic_append = !defined($ovv->{lock_path});
192 my $dedupe = $lei->{dedupe};
193 $dedupe->prepare_dedupe;
194 my $lse = $lei->{lse}; # may be undef
195 my $set_recent = $dedupe->has_entries;
196 sub { # for git_to_mail
197 my ($buf, $smsg, $eml) = @_;
198 $eml //= PublicInbox::Eml->new($buf);
199 return if $dedupe->is_dup($eml, $smsg);
200 $lse->xsmsg_vmd($smsg) if $lse;
201 $smsg->{-recent} = 1 if $set_recent;
202 $buf = $eml2mbox->($eml, $smsg);
203 if ($atomic_append) {
204 atomic_append($lei, $buf);
206 my $lk = $ovv->lock_for_scope;
213 sub update_kw_maybe ($$$$) {
214 my ($lei, $lse, $eml, $kw) = @_;
216 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
217 my $vmd = { kw => $kw };
218 if (scalar @$docids) { # already in lei/store
219 $lei->{sto}->wq_do('set_eml_vmd', undef, $vmd, $docids) if $c;
220 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
221 # it's in an external, only set kw, here
222 $lei->{sto}->wq_do('set_xvmd', $xoids, $eml, $vmd);
223 } else { # never-before-seen, import the whole thing
224 # XXX this is critical in protecting against accidental
225 # data loss without --augment
226 $lei->{sto}->wq_do('set_eml', $eml, $vmd);
230 sub _md_update { # maildir_each_eml cb
231 my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
232 update_kw_maybe($lei, $lse, $eml, $kw);
233 $unlink ? unlink($f) : _augment($eml, $lei);
236 # maildir_each_file callback, \&CORE::unlink doesn't work with it
237 sub _unlink { unlink($_[0]) }
241 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
244 sub kw2suffix ($;@) {
246 join('', sort(map { $kw2char{$_} // () } @$kw, @_));
249 sub _buf2maildir ($$$$) {
250 my ($dst, $buf, $smsg, $dir) = @_;
251 my $kw = $smsg->{kw} // [];
252 my $rand = ''; # chosen by die roll :P
253 my ($tmp, $fh, $base, $ok);
254 my $common = $smsg->{blob} // _rand;
255 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
257 $tmp = $dst.'tmp/'.$rand.$common;
258 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
259 $!{EEXIST} && ($rand = _rand.','));
260 if ($ok && print $fh $$buf and close($fh)) {
261 $dst .= $dir; # 'new/' or 'cur/'
264 $base = $rand.$common.':2,'.kw2suffix($kw);
265 } while (!($ok = link($tmp, $dst.$base)) && $!{EEXIST} &&
266 ($rand = _rand.','));
267 die "link($tmp, $dst$base): $!" unless $ok;
268 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
271 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
272 $_[0] = undef; # clobber dst
278 sub _maildir_write_cb ($$) {
279 my ($self, $lei) = @_;
280 my $dedupe = $lei->{dedupe};
281 $dedupe->prepare_dedupe if $dedupe;
282 my $dst = $lei->{ovv}->{dst};
283 my $lse = $lei->{lse}; # may be undef
284 my $sto = $lei->{opt}->{'mail-sync'} ? $lei->{sto} : undef;
285 my $out = $sto ? 'maildir:'.$lei->abs_path($dst) : undef;
287 # Favor cur/ and only write to new/ when augmenting. This
288 # saves MUAs from having to do a mass rename when the initial
289 # search result set is huge.
290 my $dir = $dedupe && $dedupe->has_entries ? 'new/' : 'cur/';
291 sub { # for git_to_mail
292 my ($bref, $smsg, $eml) = @_;
293 $dst // return $lei->fail; # dst may be undef-ed in last run
294 return if $dedupe && $dedupe->is_dup($eml //
295 PublicInbox::Eml->new($$bref),
297 $lse->xsmsg_vmd($smsg) if $lse;
298 my $n = _buf2maildir($dst, $bref // \($eml->as_string),
300 $sto->wq_do('set_sync_info', $smsg->{blob}, $out, $n) if $sto;
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),
322 $lse->xsmsg_vmd($smsg) if $lse;
323 my $uid = eval { $append->($mic, $folder, $bref, $smsg, $eml) };
328 # imap_append returns UID if IMAP server has UIDPLUS extension
329 ($sto && $uid =~ /\A[0-9]+\z/) and
330 $sto->wq_do('set_sync_info',
331 $smsg->{blob}, $$uri, $uid + 0);
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);
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");
356 sub _v2_write_cb ($$) {
357 my ($self, $lei) = @_;
358 my $dedupe = $lei->{dedupe};
359 $dedupe->prepare_dedupe if $dedupe;
360 sub { # for git_to_mail
361 my ($bref, $smsg, $eml) = @_;
362 $eml //= PublicInbox::Eml->new($bref);
363 return if $dedupe && $dedupe->is_dup($eml, $smsg);
364 $lei->{v2w}->wq_do('add', $eml); # V2Writable->add
369 sub write_cb { # returns a callback for git_to_mail
370 my ($self, $lei) = @_;
371 # _mbox_write_cb, _maildir_write_cb, _imap_write_cb, _v2_write_cb
372 my $m = "_$self->{base_type}_write_cb";
377 my ($cls, $lei) = @_;
378 my $fmt = $lei->{ovv}->{fmt};
379 my $dst = $lei->{ovv}->{dst};
380 my $self = bless {}, $cls;
382 if ($fmt eq 'maildir') {
383 require PublicInbox::MdirReader;
384 $self->{base_type} = 'maildir';
385 -e $dst && !-d _ and die
386 "$dst exists and is not a directory\n";
387 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
388 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
389 } elsif (substr($fmt, 0, 4) eq 'mbox') {
390 require PublicInbox::MboxReader;
391 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
392 $self->{base_type} = 'mbox';
393 if ($lei->{cmd} eq 'q' &&
394 (($lei->path_to_fd($dst) // -1) < 0) &&
395 (-f $dst || !-e _)) {
396 $lei->{opt}->{save} //= \1;
398 } elsif ($fmt =~ /\Aimaps?\z/) {
399 require PublicInbox::NetWriter;
400 require PublicInbox::URIimap;
401 # {net} may exist from "lei up" for auth
402 my $net = $lei->{net} // PublicInbox::NetWriter->new;
403 $net->{quiet} = $lei->{opt}->{quiet};
404 my $uri = PublicInbox::URIimap->new($dst)->canonical;
405 $net->add_url($$uri);
406 my $err = $net->errors($lei);
407 return $lei->fail($err) if $err;
408 $uri->mailbox or return $lei->fail("No mailbox: $dst");
410 $dst = $lei->{ovv}->{dst} = $$uri; # canonicalized
412 $self->{base_type} = 'imap';
413 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
414 } elsif ($fmt eq 'text' || $fmt eq 'reply') {
415 require PublicInbox::LeiViewText;
416 $lei->{lvt} = PublicInbox::LeiViewText->new($lei, $fmt);
417 $self->{base_type} = 'text';
418 @conflict = qw(mua save);
419 } elsif ($fmt eq 'v2') {
420 die "--dedupe=oid and v2 are incompatible\n" if
421 ($lei->{opt}->{dedupe}//'') eq 'oid';
422 $self->{base_type} = 'v2';
423 $lei->{opt}->{save} = \1;
424 $dst = $lei->{ovv}->{dst} = $lei->abs_path($dst);
425 @conflict = qw(mua sort);
427 die "bad mail --format=$fmt\n";
429 if ($self->{base_type} =~ /\A(?:text|mbox)\z/) {
430 (-d $dst || (-e _ && !-w _)) and die
431 "$dst exists and is not a writable file\n";
433 my @err = map { defined($lei->{opt}->{$_}) ? "--$_" : () } @conflict;
434 die "@err incompatible with $fmt\n" if @err;
436 $lei->{dedupe} = $lei->{lss} // do {
437 my $dd_cls = 'PublicInbox::'.
438 ($lei->{opt}->{save} ? 'LeiSavedSearch' : 'LeiDedupe');
439 eval "require $dd_cls";
440 die "$dd_cls: $@" if $@;
441 my $dd = $dd_cls->new($lei);
442 $lei->{lss} //= $dd if $dd && $dd->can('cfg_set');
448 sub _pre_augment_maildir {
449 my ($self, $lei) = @_;
450 my $dst = $lei->{ovv}->{dst};
451 for my $x (qw(tmp new cur)) {
455 File::Path::mkpath($d);
456 -d $d or die "$d is not a directory";
458 # for utime, so no opendir
459 open $self->{poke_dh}, '<', "${dst}cur" or die "open ${dst}cur: $!";
462 sub clobber_dst_prepare ($;$) {
464 if (my $lms = defined($f) ? $lei->lms : undef) {
465 $lms->lms_write_prepare;
466 $lms->forget_folders($f);
468 my $dedupe = $lei->{dedupe} or return;
469 $dedupe->reset_dedupe if $dedupe->can('reset_dedupe');
472 sub _do_augment_maildir {
473 my ($self, $lei) = @_;
474 return if $lei->{cmd} eq 'up';
475 my $dst = $lei->{ovv}->{dst};
476 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
477 my $mdr = PublicInbox::MdirReader->new;
478 if ($lei->{opt}->{augment}) {
479 my $dedupe = $lei->{dedupe};
480 if ($dedupe && $dedupe->prepare_dedupe) {
481 $mdr->{shard_info} = $self->{shard_info};
482 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
483 $dedupe->pause_dedupe;
486 clobber_dst_prepare($lei, "maildir:$dst");
487 $mdr->{shard_info} = $self->{shard_info};
488 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
489 } else {# clobber existing Maildir
490 clobber_dst_prepare($lei, "maildir:$dst");
491 $mdr->maildir_each_file($dst, \&_unlink);
495 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
496 my ($uri, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
497 update_kw_maybe($lei, $lse, $eml, $kw);
499 $lei->{net}->imap_delete_1($uri, $uid, $delete_mic);
501 _augment($eml, $lei);
505 sub _do_augment_imap {
506 my ($self, $lei) = @_;
507 return if $lei->{cmd} eq 'up';
508 my $net = $lei->{net};
509 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
510 if ($lei->{opt}->{augment}) {
511 my $dedupe = $lei->{dedupe};
512 if ($dedupe && $dedupe->prepare_dedupe) {
513 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
515 $dedupe->pause_dedupe;
519 clobber_dst_prepare($lei, "$self->{uri}");
520 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
521 $lei, $lse, \$delete_mic);
522 $delete_mic->expunge if $delete_mic;
523 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
524 # clobber existing IMAP folder
525 clobber_dst_prepare($lei, "$self->{uri}");
526 $net->imap_delete_all($self->{uri});
530 sub _pre_augment_text {
531 my ($self, $lei) = @_;
532 my $dst = $lei->{ovv}->{dst};
534 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
536 $out = $lei->{$devfd};
537 } else { # normal-looking path
539 open $out, '>', $dst or die "open($dst): $!";
540 } elsif (-f _ || !-e _) {
541 # text allows augment, HTML/Atom won't
542 my $mode = $lei->{opt}->{augment} ? '>>' : '>';
543 open $out, $mode, $dst or die "open($mode, $dst): $!";
545 die "$dst is not a file or FIFO\n";
548 $lei->{ovv}->ovv_out_lk_init if !$lei->{ovv}->{lock_path};
553 sub _pre_augment_mbox {
554 my ($self, $lei) = @_;
555 my $dst = $lei->{ovv}->{dst};
557 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
559 $out = $lei->{$devfd};
560 } else { # normal-looking path
562 open $out, '>', $dst or die "open($dst): $!";
563 } elsif (-f _ || !-e _) {
564 require PublicInbox::MboxLock;
565 my $m = $lei->{opt}->{'lock'} //
566 PublicInbox::MboxLock->defaults;
567 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
568 $out = $self->{mbl}->{fh};
570 die "$dst is not a file or FIFO\n";
572 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
574 # Perl does SEEK_END even with O_APPEND :<
575 $self->{seekable} = seek($out, 0, SEEK_SET);
576 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
577 die "seek($dst): $!\n";
579 if (!$self->{seekable}) {
580 my $imp_before = $lei->{opt}->{'import-before'};
581 die "--import-before specified but $dst is not seekable\n"
582 if $imp_before && !ref($imp_before);
583 die "--augment specified but $dst is not seekable\n" if
584 $lei->{opt}->{augment};
585 die "cannot --save with unseekable $dst\n" if
586 $lei->{dedupe} && $lei->{dedupe}->can('reset_dedupe');
588 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
589 pipe(my ($r, $w)) or die "pipe: $!";
590 $lei->{zpipe} = [ $r, $w ];
591 $lei->{ovv}->{lock_path} and
592 die 'BUG: unexpected {ovv}->{lock_path}';
593 $lei->{ovv}->ovv_out_lk_init;
594 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
595 $lei->{ovv}->ovv_out_lk_init;
601 sub _do_augment_mbox {
602 my ($self, $lei) = @_;
603 return unless $self->{seekable};
604 my $opt = $lei->{opt};
605 return if $lei->{cmd} eq 'up';
607 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
608 return clobber_dst_prepare($lei) unless -s $out;
609 unless ($opt->{augment} || $opt->{'import-before'}) {
610 truncate($out, 0) or die "truncate($dst): $!";
614 if (my $zsfx = $self->{zsfx}) {
615 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
617 open($rd, '+>>&', $out) or die "dup: $!";
620 if ($opt->{augment}) {
621 $dedupe = $lei->{dedupe};
622 $dedupe->prepare_dedupe if $dedupe;
624 clobber_dst_prepare($lei);
626 if ($opt->{'import-before'}) { # the default
627 my $lse = $lei->{lse};
628 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
629 $lei, $lse, $opt->{augment});
630 if (!$opt->{augment} and !truncate($out, 0)) {
631 die "truncate($dst): $!";
633 } else { # --augment --no-import-before
634 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
636 # maybe some systems don't honor O_APPEND, Perl does this:
637 seek($out, 0, SEEK_END) or die "seek $dst: $!";
638 $dedupe->pause_dedupe if $dedupe;
641 sub v2w_done_wait { # dwaitpid callback
642 my ($arg, $pid) = @_;
643 my ($v2w, $lei) = @$arg;
644 $lei->child_error($?, "error for $v2w->{ibx}->{inboxdir}") if $?;
647 sub _pre_augment_v2 {
648 my ($self, $lei) = @_;
649 my $dir = $self->{dst};
650 require PublicInbox::InboxWritable;
653 my $opt = { -min_inbox_version => 2 };
654 require PublicInbox::Admin;
655 my @ibx = PublicInbox::Admin::resolve_inboxes([ $dir ], $opt);
656 $ibx = $ibx[0] or die "$dir is not a v2 inbox\n";
659 $ibx = PublicInbox::Inbox->new({
660 name => 'lei-result', # XXX configurable
663 address => [ 'lei@example.com' ],
666 PublicInbox::InboxWritable->new($ibx, @creat);
667 $ibx->init_inbox if @creat;
668 my $v2w = $ibx->importer;
669 $v2w->wq_workers_start("lei/v2w $dir", 1, $lei->oldset, {lei => $lei});
670 $v2w->wq_wait_async(\&v2w_done_wait, $lei);
672 return if !$lei->{opt}->{shared};
673 my $d = "$lei->{ale}->{git}->{git_dir}/objects";
674 my $al = "$dir/git/0.git/objects/info/alternates";
675 open my $fh, '+>>', $al or die "open($al): $!";
676 seek($fh, 0, SEEK_SET) or die "seek($al): $!";
677 grep(/\A\Q$d\E\n/, <$fh>) and return;
678 print $fh "$d\n" or die "print($al): $!";
679 close $fh or die "close($al): $!";
682 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
683 my ($self, $lei) = @_;
684 # _pre_augment_maildir, _pre_augment_mbox, _pre_augment_v2
685 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
689 sub do_augment { # slow, runs in wq worker
690 my ($self, $lei) = @_;
691 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
692 my $m = $self->can("_do_augment_$self->{base_type}") or return;
696 # fast (spawn compressor or mkdir), runs in same process as pre_augment
698 my ($self, $lei, @args) = @_;
699 $self->{-au_noted}++ and $lei->qerr("# writing to $self->{dst} ...");
701 my $wait = $lei->{opt}->{'import-before'} ?
702 $lei->{sto}->wq_do('checkpoint', 1) : 0;
704 my $m = $self->can("_post_augment_$self->{base_type}") or return;
705 $m->($self, $lei, @args);
708 # called by every single l2m worker process
711 my $lei = $self->{lei};
712 # lei_xsearch can start as soon as all l2m workers get here
713 $lei->{pkt_op_p}->pkt_do('incr_start_query') or
714 die "incr_start_query: $!";
716 if (lock_free($self)) { # all workers do_augment
717 my $mod = $self->{-wq_nr_workers};
718 my $shard = $self->{-wq_worker_nr};
719 if (my $net = $lei->{net}) {
720 $net->{shard_info} = [ $mod, $shard ];
722 $self->{shard_info} = [ $mod, $shard ];
724 $aug = 'incr_post_augment';
725 } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
726 $aug = 'do_post_augment';
729 local $0 = 'do_augment';
730 eval { do_augment($self, $lei) };
731 $lei->fail($@) if $@;
732 $lei->{pkt_op_p}->pkt_do($aug) or die "pkt_do($aug): $!";
734 # done augmenting, connect the compressor pipe for each worker
735 if (my $zpipe = delete $lei->{zpipe}) {
736 $lei->{1} = $zpipe->[1];
739 my $au_peers = delete $self->{au_peers};
740 if ($au_peers) { # wait for peer l2m to finish augmenting:
741 $au_peers->[1] = undef;
742 sysread($au_peers->[0], my $barrier1, 1);
744 $self->{wcb} = $self->write_cb($lei);
745 if ($au_peers) { # wait for peer l2m to set write_cb
746 $au_peers->[3] = undef;
747 sysread($au_peers->[2], my $barrier2, 1);
751 sub ipc_atfork_child {
753 my $lei = $self->{lei};
754 $lei->_lei_atfork_child;
755 if (my $lse = $lei->{lse}) {
756 $self->{-lms_ro} = $lse->{-lms_ro} //= $lse->lms;
758 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
759 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
760 $self->SUPER::ipc_atfork_child;
764 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
767 # wakes up the MUA when complete so it can refresh messages list
770 if ($self->{base_type} eq 'maildir') {
772 utime($t, $t, $self->{poke_dh}) or warn "futimes: $!";
776 sub write_mail { # via ->wq_io_do
777 my ($self, $smsg, $eml) = @_;
778 return $self->{wcb}->(undef, $smsg, $eml) if $eml;
779 $smsg->{-lms_ro} = $self->{-lms_ro};
780 $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
781 [$self->{wcb}, $smsg]);
784 sub wq_atexit_child {
786 local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
787 my $lei = $self->{lei};
789 $lei->{ale}->git->async_wait_all;
790 my $nr = delete($lei->{-nr_write}) or return;
791 return if $lei->{early_mua} || !$lei->{-progress} || !$lei->{pkt_op_p};
792 $lei->{pkt_op_p}->pkt_do('l2m_progress', $nr);
795 # runs on a 1s timer in lei-daemon
796 sub augment_inprogress {
797 my ($err, $opt, $dst, $au_noted) = @_;
799 return if $$au_noted++ || !$err || !defined(fileno($err));
800 print $err '# '.($opt->{'import-before'} ?
801 "importing non-external contents of $dst" : (
802 ($opt->{dedupe} // 'content') ne 'none') ?
803 "scanning old contents of $dst for dedupe" :
804 "removing old contents of $dst")." ...\n";
806 warn "E: $@ ($dst)" if $@;
809 # called in top-level lei-daemon when LeiAuth is done
810 sub net_merge_all_done {
811 my ($self, $lei) = @_;
812 if ($PublicInbox::DS::in_loop &&
813 $self->can("_do_augment_$self->{base_type}") &&
814 !$lei->{opt}->{quiet}) {
815 $self->{-au_noted} = 0;
816 PublicInbox::DS::add_timer(1, \&augment_inprogress,
817 $lei->{2}, $lei->{opt},
818 $self->{dst}, \$self->{-au_noted});
820 $self->wq_broadcast('do_post_auth');