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);
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, $arg) = @_;
136 $type // return; # called by git->async_abort
137 my ($write_cb, $smsg) = @$arg;
138 if ($type eq 'missing' && $smsg->{-lms_rw}) {
139 if ($bref = $smsg->{-lms_rw}->local_blob($oid, 1)) {
141 $size = length($$bref);
144 return warn("W: $oid is $type (!= blob)\n") if $type ne 'blob';
145 return warn("E: $oid is empty\n") unless $size;
146 die "BUG: expected=$smsg->{blob} got=$oid" if $smsg->{blob} ne $oid;
147 $write_cb->($bref, $smsg);
150 sub reap_compress { # dwaitpid callback
151 my ($lei, $pid) = @_;
152 my $cmd = delete $lei->{"pid.$pid"};
154 $lei->fail("@$cmd failed", $? >> 8);
157 sub _post_augment_mbox { # open a compressor process from top-level process
158 my ($self, $lei) = @_;
159 my $zsfx = $self->{zsfx} or return;
160 my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
161 my ($r, $w) = @{delete $lei->{zpipe}};
162 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2}, pgid => 0 };
163 my $pid = spawn($cmd, undef, $rdr);
165 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
166 $dup->{$_} = $lei->{$_} for qw(2 sock);
167 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
171 # --augment existing output destination, with deduplication
172 sub _augment { # MboxReader eml_cb
173 my ($eml, $lei) = @_;
174 # ignore return value, just populate the skv
175 $lei->{dedupe}->is_dup($eml);
178 sub _mbox_augment_kw_maybe {
179 my ($eml, $lei, $lse, $augment) = @_;
180 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
181 update_kw_maybe($lei, $lse, $eml, $kw);
182 _augment($eml, $lei) if $augment;
185 sub _mbox_write_cb ($$) {
186 my ($self, $lei) = @_;
187 my $ovv = $lei->{ovv};
188 my $m = 'eml2'.$ovv->{fmt};
189 my $eml2mbox = $self->can($m) or die "$self->$m missing";
190 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
191 $lei->{1}->autoflush(1);
192 my $atomic_append = !defined($ovv->{lock_path});
193 my $dedupe = $lei->{dedupe};
194 $dedupe->prepare_dedupe;
195 my $lse = $lei->{lse}; # may be undef
196 my $set_recent = $dedupe->has_entries;
197 sub { # for git_to_mail
198 my ($buf, $smsg, $eml) = @_;
199 $eml //= PublicInbox::Eml->new($buf);
200 return if $dedupe->is_dup($eml, $smsg);
201 $lse->xsmsg_vmd($smsg) if $lse;
202 $smsg->{-recent} = 1 if $set_recent;
203 $buf = $eml2mbox->($eml, $smsg);
204 if ($atomic_append) {
205 atomic_append($lei, $buf);
207 my $lk = $ovv->lock_for_scope;
214 sub update_kw_maybe ($$$$) {
215 my ($lei, $lse, $eml, $kw) = @_;
217 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
218 my $vmd = { kw => $kw };
219 if (scalar @$docids) { # already in lei/store
220 $lei->{sto}->wq_do('set_eml_vmd', undef, $vmd, $docids) if $c;
221 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
222 # it's in an external, only set kw, here
223 $lei->{sto}->wq_do('set_xvmd', $xoids, $eml, $vmd);
224 } else { # never-before-seen, import the whole thing
225 # XXX this is critical in protecting against accidental
226 # data loss without --augment
227 $lei->{sto}->wq_do('set_eml', $eml, $vmd);
231 sub _md_update { # maildir_each_eml cb
232 my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
233 update_kw_maybe($lei, $lse, $eml, $kw);
234 $unlink ? unlink($f) : _augment($eml, $lei);
237 # maildir_each_file callback, \&CORE::unlink doesn't work with it
238 sub _unlink { unlink($_[0]) }
242 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
245 sub kw2suffix ($;@) {
247 join('', sort(map { $kw2char{$_} // () } @$kw, @_));
250 sub _buf2maildir ($$$$) {
251 my ($dst, $buf, $smsg, $dir) = @_;
252 my $kw = $smsg->{kw} // [];
253 my $rand = ''; # chosen by die roll :P
254 my ($tmp, $fh, $base, $ok);
255 my $common = $smsg->{blob} // _rand;
256 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
258 $tmp = $dst.'tmp/'.$rand.$common;
259 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
260 $!{EEXIST} && ($rand = _rand.','));
261 if ($ok && print $fh $$buf and close($fh)) {
262 $dst .= $dir; # 'new/' or 'cur/'
265 $base = $rand.$common.':2,'.kw2suffix($kw);
266 } while (!($ok = rename_noreplace($tmp, $dst.$base)) &&
267 $!{EEXIST} && ($rand = _rand.','));
270 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
271 $_[0] = undef; # clobber dst
277 sub _maildir_write_cb ($$) {
278 my ($self, $lei) = @_;
279 my $dedupe = $lei->{dedupe};
280 $dedupe->prepare_dedupe if $dedupe;
281 my $dst = $lei->{ovv}->{dst};
282 my $lse = $lei->{lse}; # may be undef
283 my $lms = $self->{-lms_rw};
284 my $out = $lms ? 'maildir:'.$lei->abs_path($dst) : undef;
285 $lms->lms_write_prepare if $lms;
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 $lms->set_src($smsg->oidbin, $out, $n) if $lms;
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 $lms = $self->{-lms_rw};
316 $lms->lms_write_prepare if $lms;
317 sub { # for git_to_mail
318 my ($bref, $smsg, $eml) = @_;
319 $mic // return $lei->fail; # mic may be undef-ed in last run
320 return if $dedupe && $dedupe->is_dup($eml //
321 PublicInbox::Eml->new($$bref),
323 $lse->xsmsg_vmd($smsg) if $lse;
324 my $uid = eval { $append->($mic, $folder, $bref, $smsg, $eml) };
329 # imap_append returns UID if IMAP server has UIDPLUS extension
330 ($lms && $uid =~ /\A[0-9]+\z/) and
331 $lms->set_src($smsg->oidbin, $$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 $self->{-wq_nr_workers} = 1; # for pager
419 @conflict = qw(mua save);
420 } elsif ($fmt eq 'v2') {
421 die "--dedupe=oid and v2 are incompatible\n" if
422 ($lei->{opt}->{dedupe}//'') eq 'oid';
423 $self->{base_type} = 'v2';
424 $self->{-wq_nr_workers} = 1; # v2 has shards
425 $lei->{opt}->{save} = \1;
426 $dst = $lei->{ovv}->{dst} = $lei->abs_path($dst);
427 @conflict = qw(mua sort);
429 die "bad mail --format=$fmt\n";
431 if ($self->{base_type} =~ /\A(?:text|mbox)\z/) {
432 (-d $dst || (-e _ && !-w _)) and die
433 "$dst exists and is not a writable file\n";
435 my @err = map { defined($lei->{opt}->{$_}) ? "--$_" : () } @conflict;
436 die "@err incompatible with $fmt\n" if @err;
438 $lei->{dedupe} = $lei->{lss} // do {
439 my $dd_cls = 'PublicInbox::'.
440 ($lei->{opt}->{save} ? 'LeiSavedSearch' : 'LeiDedupe');
441 eval "require $dd_cls";
442 die "$dd_cls: $@" if $@;
443 my $dd = $dd_cls->new($lei);
444 $lei->{lss} //= $dd if $dd && $dd->can('cfg_set');
450 sub _pre_augment_maildir {
451 my ($self, $lei) = @_;
452 my $dst = $lei->{ovv}->{dst};
453 for my $x (qw(tmp new cur)) {
457 File::Path::mkpath($d);
458 -d $d or die "$d is not a directory";
460 # for utime, so no opendir
461 open $self->{poke_dh}, '<', "${dst}cur" or die "open ${dst}cur: $!";
464 sub clobber_dst_prepare ($;$) {
466 if (my $lms = defined($f) ? $lei->lms : undef) {
467 $lms->lms_write_prepare;
468 $lms->forget_folders($f);
470 my $dedupe = $lei->{dedupe} or return;
471 $dedupe->reset_dedupe if $dedupe->can('reset_dedupe');
474 sub _do_augment_maildir {
475 my ($self, $lei) = @_;
476 return if $lei->{cmd} eq 'up';
477 my $dst = $lei->{ovv}->{dst};
478 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
479 my $mdr = PublicInbox::MdirReader->new;
480 if ($lei->{opt}->{augment}) {
481 my $dedupe = $lei->{dedupe};
482 if ($dedupe && $dedupe->prepare_dedupe) {
483 $mdr->{shard_info} = $self->{shard_info};
484 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
485 $dedupe->pause_dedupe;
488 clobber_dst_prepare($lei, "maildir:$dst");
489 $mdr->{shard_info} = $self->{shard_info};
490 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
491 } else {# clobber existing Maildir
492 clobber_dst_prepare($lei, "maildir:$dst");
493 $mdr->maildir_each_file($dst, \&_unlink);
497 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
498 my ($uri, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
499 update_kw_maybe($lei, $lse, $eml, $kw);
501 $lei->{net}->imap_delete_1($uri, $uid, $delete_mic);
503 _augment($eml, $lei);
507 sub _do_augment_imap {
508 my ($self, $lei) = @_;
509 return if $lei->{cmd} eq 'up';
510 my $net = $lei->{net};
511 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
512 if ($lei->{opt}->{augment}) {
513 my $dedupe = $lei->{dedupe};
514 if ($dedupe && $dedupe->prepare_dedupe) {
515 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
517 $dedupe->pause_dedupe;
521 clobber_dst_prepare($lei, "$self->{uri}");
522 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
523 $lei, $lse, \$delete_mic);
524 $delete_mic->expunge if $delete_mic;
525 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
526 # clobber existing IMAP folder
527 clobber_dst_prepare($lei, "$self->{uri}");
528 $net->imap_delete_all($self->{uri});
532 sub _pre_augment_text {
533 my ($self, $lei) = @_;
534 my $dst = $lei->{ovv}->{dst};
536 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
538 $out = $lei->{$devfd};
539 } else { # normal-looking path
541 open $out, '>', $dst or die "open($dst): $!";
542 } elsif (-f _ || !-e _) {
543 # text allows augment, HTML/Atom won't
544 my $mode = $lei->{opt}->{augment} ? '>>' : '>';
545 open $out, $mode, $dst or die "open($mode, $dst): $!";
547 die "$dst is not a file or FIFO\n";
550 $lei->{ovv}->ovv_out_lk_init if !$lei->{ovv}->{lock_path};
555 sub _pre_augment_mbox {
556 my ($self, $lei) = @_;
557 my $dst = $lei->{ovv}->{dst};
559 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
561 $out = $lei->{$devfd};
562 } else { # normal-looking path
564 open $out, '>', $dst or die "open($dst): $!";
565 } elsif (-f _ || !-e _) {
566 require PublicInbox::MboxLock;
567 my $m = $lei->{opt}->{'lock'} //
568 PublicInbox::MboxLock->defaults;
569 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
570 $out = $self->{mbl}->{fh};
572 die "$dst is not a file or FIFO\n";
574 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
576 # Perl does SEEK_END even with O_APPEND :<
577 $self->{seekable} = seek($out, 0, SEEK_SET);
578 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
579 die "seek($dst): $!\n";
581 if (!$self->{seekable}) {
582 my $imp_before = $lei->{opt}->{'import-before'};
583 die "--import-before specified but $dst is not seekable\n"
584 if $imp_before && !ref($imp_before);
585 die "--augment specified but $dst is not seekable\n" if
586 $lei->{opt}->{augment};
587 die "cannot --save with unseekable $dst\n" if
588 $lei->{dedupe} && $lei->{dedupe}->can('reset_dedupe');
590 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
591 pipe(my ($r, $w)) or die "pipe: $!";
592 $lei->{zpipe} = [ $r, $w ];
593 $lei->{ovv}->{lock_path} and
594 die 'BUG: unexpected {ovv}->{lock_path}';
595 $lei->{ovv}->ovv_out_lk_init;
596 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
597 $lei->{ovv}->ovv_out_lk_init;
603 sub _do_augment_mbox {
604 my ($self, $lei) = @_;
605 return unless $self->{seekable};
606 my $opt = $lei->{opt};
607 return if $lei->{cmd} eq 'up';
609 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
610 return clobber_dst_prepare($lei) unless -s $out;
611 unless ($opt->{augment} || $opt->{'import-before'}) {
612 truncate($out, 0) or die "truncate($dst): $!";
616 if (my $zsfx = $self->{zsfx}) {
617 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
619 open($rd, '+>>&', $out) or die "dup: $!";
622 if ($opt->{augment}) {
623 $dedupe = $lei->{dedupe};
624 $dedupe->prepare_dedupe if $dedupe;
626 clobber_dst_prepare($lei);
628 if ($opt->{'import-before'}) { # the default
629 my $lse = $lei->{lse};
630 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
631 $lei, $lse, $opt->{augment});
632 if (!$opt->{augment} and !truncate($out, 0)) {
633 die "truncate($dst): $!";
635 } else { # --augment --no-import-before
636 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
638 # maybe some systems don't honor O_APPEND, Perl does this:
639 seek($out, 0, SEEK_END) or die "seek $dst: $!";
640 $dedupe->pause_dedupe if $dedupe;
643 sub v2w_done_wait { # dwaitpid callback
644 my ($arg, $pid) = @_;
645 my ($v2w, $lei) = @$arg;
646 $lei->child_error($?, "error for $v2w->{ibx}->{inboxdir}") if $?;
649 sub _pre_augment_v2 {
650 my ($self, $lei) = @_;
651 my $dir = $self->{dst};
652 require PublicInbox::InboxWritable;
655 my $opt = { -min_inbox_version => 2 };
656 require PublicInbox::Admin;
657 my @ibx = PublicInbox::Admin::resolve_inboxes([ $dir ], $opt);
658 $ibx = $ibx[0] or die "$dir is not a v2 inbox\n";
661 $ibx = PublicInbox::Inbox->new({
662 name => 'lei-result', # XXX configurable
665 address => [ 'lei@example.com' ],
668 PublicInbox::InboxWritable->new($ibx, @creat);
669 $ibx->init_inbox if @creat;
670 my $v2w = $ibx->importer;
671 $v2w->wq_workers_start("lei/v2w $dir", 1, $lei->oldset, {lei => $lei});
672 $v2w->wq_wait_async(\&v2w_done_wait, $lei);
674 return if !$lei->{opt}->{shared};
675 my $d = "$lei->{ale}->{git}->{git_dir}/objects";
676 my $al = "$dir/git/0.git/objects/info/alternates";
677 open my $fh, '+>>', $al or die "open($al): $!";
678 seek($fh, 0, SEEK_SET) or die "seek($al): $!";
679 grep(/\A\Q$d\E\n/, <$fh>) and return;
680 print $fh "$d\n" or die "print($al): $!";
681 close $fh or die "close($al): $!";
684 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
685 my ($self, $lei) = @_;
686 # _pre_augment_maildir, _pre_augment_mbox, _pre_augment_v2
687 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
691 sub do_augment { # slow, runs in wq worker
692 my ($self, $lei) = @_;
693 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
694 my $m = $self->can("_do_augment_$self->{base_type}") or return;
698 # fast (spawn compressor or mkdir), runs in same process as pre_augment
700 my ($self, $lei, @args) = @_;
701 $self->{-au_noted}++ and $lei->qerr("# writing to $self->{dst} ...");
703 my $wait = $lei->{opt}->{'import-before'} ?
704 $lei->{sto}->wq_do('checkpoint', 1) : 0;
706 my $m = $self->can("_post_augment_$self->{base_type}") or return;
707 $m->($self, $lei, @args);
710 # called by every single l2m worker process
713 my $lei = $self->{lei};
714 # lei_xsearch can start as soon as all l2m workers get here
715 $lei->{pkt_op_p}->pkt_do('incr_start_query') or
716 die "incr_start_query: $!";
718 if (lock_free($self)) { # all workers do_augment
719 my $mod = $self->{-wq_nr_workers};
720 my $shard = $self->{-wq_worker_nr};
721 if (my $net = $lei->{net}) {
722 $net->{shard_info} = [ $mod, $shard ];
724 $self->{shard_info} = [ $mod, $shard ];
726 $aug = 'incr_post_augment';
727 } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
728 $aug = 'do_post_augment';
731 local $0 = 'do_augment';
732 eval { do_augment($self, $lei) };
733 $lei->fail($@) if $@;
734 $lei->{pkt_op_p}->pkt_do($aug) or die "pkt_do($aug): $!";
736 # done augmenting, connect the compressor pipe for each worker
737 if (my $zpipe = delete $lei->{zpipe}) {
738 $lei->{1} = $zpipe->[1];
741 my $au_peers = delete $self->{au_peers};
742 if ($au_peers) { # wait for peer l2m to finish augmenting:
743 $au_peers->[1] = undef;
744 sysread($au_peers->[0], my $barrier1, 1);
746 $self->{wcb} = $self->write_cb($lei);
747 if ($au_peers) { # wait for peer l2m to set write_cb
748 $au_peers->[3] = undef;
749 sysread($au_peers->[2], my $barrier2, 1);
753 sub ipc_atfork_child {
755 my $lei = $self->{lei};
756 $lei->_lei_atfork_child;
757 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
758 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
759 $self->{git} = $self->{lei}->{ale}->git;
760 $SIG{TERM} = sub { # avoid ->DESTROY ordering problems
761 my $git = delete $self->{git};
762 $git->async_wait_all if $git;
765 $self->SUPER::ipc_atfork_child;
769 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
772 # wakes up the MUA when complete so it can refresh messages list
775 if ($self->{base_type} eq 'maildir') {
777 utime($t, $t, $self->{poke_dh}) or warn "futimes: $!";
781 sub write_mail { # via ->wq_io_do
782 my ($self, $smsg, $eml) = @_;
783 return $self->{wcb}->(undef, $smsg, $eml) if $eml;
784 $smsg->{-lms_rw} = $self->{-lms_rw};
785 $self->{git}->cat_async($smsg->{blob}, \&git_to_mail,
786 [$self->{wcb}, $smsg]);
789 sub wq_atexit_child {
791 local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
792 my $lei = $self->{lei};
794 $lei->{ale}->git->async_wait_all;
795 my $nr = delete($lei->{-nr_write}) or return;
796 return if $lei->{early_mua} || !$lei->{-progress} || !$lei->{pkt_op_p};
797 $lei->{pkt_op_p}->pkt_do('l2m_progress', $nr);
800 # runs on a 1s timer in lei-daemon
801 sub augment_inprogress {
802 my ($err, $opt, $dst, $au_noted) = @_;
804 return if $$au_noted++ || !$err || !defined(fileno($err));
805 print $err '# '.($opt->{'import-before'} ?
806 "importing non-external contents of $dst" : (
807 ($opt->{dedupe} // 'content') ne 'none') ?
808 "scanning old contents of $dst for dedupe" :
809 "removing old contents of $dst")." ...\n";
811 warn "E: $@ ($dst)" if $@;
814 # called in top-level lei-daemon when LeiAuth is done
815 sub net_merge_all_done {
816 my ($self, $lei) = @_;
817 if ($PublicInbox::DS::in_loop &&
818 $self->can("_do_augment_$self->{base_type}") &&
819 !$lei->{opt}->{quiet}) {
820 $self->{-au_noted} = 0;
821 PublicInbox::DS::add_timer(1, \&augment_inprogress,
822 $lei->{2}, $lei->{opt},
823 $self->{dst}, \$self->{-au_noted});
825 $self->wq_broadcast('do_post_auth');