]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei q: reduce lei/store work for kw changes to stored mail
[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::Lock;
11 use PublicInbox::ProcessPipe;
12 use PublicInbox::Spawn qw(spawn);
13 use PublicInbox::LeiDedupe;
14 use PublicInbox::Git;
15 use PublicInbox::GitAsyncCat;
16 use PublicInbox::PktOp qw(pkt_do);
17 use Symbol qw(gensym);
18 use IO::Handle; # ->autoflush
19 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
20 use Errno qw(EEXIST ESPIPE ENOENT EPIPE);
21 use Digest::SHA qw(sha256_hex);
22
23 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
24 # but we may use in-process libgit2 in the future.
25 $PublicInbox::GitAsyncCat::GCF2C = 0;
26
27 my %kw2char = ( # Maildir characters
28         draft => 'D',
29         flagged => 'F',
30         answered => 'R',
31         seen => 'S'
32 );
33
34 my %kw2status = (
35         flagged => [ 'X-Status' => 'F' ],
36         answered => [ 'X-Status' => 'A' ],
37         seen => [ 'Status' => 'R' ],
38         draft => [ 'X-Status' => 'T' ],
39 );
40
41 sub _mbox_hdr_buf ($$$) {
42         my ($eml, $type, $smsg) = @_;
43         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
44
45         my %hdr = (Status => []); # set Status, X-Status
46         for my $k (@{$smsg->{kw} // []}) {
47                 if (my $ent = $kw2status{$k}) {
48                         push @{$hdr{$ent->[0]}}, $ent->[1];
49                 } else { # X-Label?
50                         warn "TODO: keyword `$k' not supported for mbox\n";
51                 }
52         }
53         # Messages are always 'O' (non-\Recent in IMAP), it saves
54         # MUAs the trouble of rewriting the mbox if no other
55         # changes are made.  We put 'O' at the end (e.g. "Status: RO")
56         # to match mutt(1) output.
57         $eml->header_set('Status', join('', sort(@{$hdr{Status}})). 'O');
58         if (my $chars = delete $hdr{'X-Status'}) {
59                 $eml->header_set('X-Status', join('', sort(@$chars)));
60         }
61         my $buf = delete $eml->{hdr};
62
63         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
64         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
65         my $ident = $smsg->{blob} // 'lei';
66         if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
67
68         substr($$buf, 0, 0, # prepend From line
69                 "From $ident\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
70         $buf;
71 }
72
73 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
74         my ($lei, $buf) = @_;
75         if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
76                 return if $w == length($$buf);
77                 $buf = "short atomic write: $w != ".length($$buf);
78         } elsif ($! == EPIPE) {
79                 return $lei->note_sigpipe(1);
80         } else {
81                 $buf = "atomic write: $!";
82         }
83         $lei->fail($buf);
84 }
85
86 sub eml2mboxrd ($;$) {
87         my ($eml, $smsg) = @_;
88         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
89         if (my $bdy = delete $eml->{bdy}) {
90                 $$bdy =~ s/^(>*From )/>$1/gm;
91                 $$buf .= $eml->{crlf};
92                 substr($$bdy, 0, 0, $$buf); # prepend header
93                 $buf = $bdy;
94         }
95         $$buf .= $eml->{crlf};
96         $buf;
97 }
98
99 sub eml2mboxo {
100         my ($eml, $smsg) = @_;
101         my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
102         if (my $bdy = delete $eml->{bdy}) {
103                 $$bdy =~ s/^From />From /gm;
104                 $$buf .= $eml->{crlf};
105                 substr($$bdy, 0, 0, $$buf); # prepend header
106                 $buf = $bdy;
107         }
108         $$buf .= $eml->{crlf};
109         $buf;
110 }
111
112 sub _mboxcl_common ($$$) {
113         my ($buf, $bdy, $crlf) = @_;
114         # add Lines: so mutt won't have to add it on MUA close
115         my $lines = $$bdy =~ tr!\n!\n!;
116         $$buf .= 'Content-Length: '.length($$bdy).$crlf.
117                 'Lines: '.$lines.$crlf.$crlf;
118         substr($$bdy, 0, 0, $$buf); # prepend header
119         $_[0] = $bdy;
120 }
121
122 # mboxcl still escapes "From " lines
123 sub eml2mboxcl {
124         my ($eml, $smsg) = @_;
125         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
126         my $crlf = $eml->{crlf};
127         if (my $bdy = delete $eml->{bdy}) {
128                 $$bdy =~ s/^From />From /gm;
129                 _mboxcl_common($buf, $bdy, $crlf);
130         }
131         $$buf .= $crlf;
132         $buf;
133 }
134
135 # mboxcl2 has no "From " escaping
136 sub eml2mboxcl2 {
137         my ($eml, $smsg) = @_;
138         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
139         my $crlf = $eml->{crlf};
140         if (my $bdy = delete $eml->{bdy}) {
141                 _mboxcl_common($buf, $bdy, $crlf);
142         }
143         $$buf .= $crlf;
144         $buf;
145 }
146
147 sub git_to_mail { # git->cat_async callback
148         my ($bref, $oid, $type, $size, $arg) = @_;
149         if ($type ne 'blob') {
150                 if ($type eq 'missing') {
151                         warn "missing $oid\n";
152                 } else {
153                         warn "unexpected type=$type for $oid\n";
154                 }
155         }
156         my ($write_cb, $smsg) = @$arg;
157         if ($smsg->{blob} ne $oid) {
158                 die "BUG: expected=$smsg->{blob} got=$oid";
159         }
160         $write_cb->($bref, $smsg) if $size > 0;
161 }
162
163 sub reap_compress { # dwaitpid callback
164         my ($lei, $pid) = @_;
165         my $cmd = delete $lei->{"pid.$pid"};
166         return if $? == 0;
167         $lei->fail("@$cmd failed", $? >> 8);
168 }
169
170 sub _post_augment_mbox { # open a compressor process
171         my ($self, $lei) = @_;
172         my $zsfx = $self->{zsfx} or return;
173         my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
174         my ($r, $w) = @{delete $lei->{zpipe}};
175         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
176         my $pid = spawn($cmd, undef, $rdr);
177         my $pp = gensym;
178         my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
179         $dup->{$_} = $lei->{$_} for qw(2 sock);
180         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
181         $lei->{1} = $pp;
182 }
183
184 sub dup_src ($) {
185         my ($in) = @_;
186         open my $dup, '+>>&', $in or die "dup: $!";
187         $dup;
188 }
189
190 # --augment existing output destination, with deduplication
191 sub _augment { # MboxReader eml_cb
192         my ($eml, $lei) = @_;
193         # ignore return value, just populate the skv
194         $lei->{dedupe}->is_dup($eml);
195 }
196
197 sub _mbox_augment_kw_maybe {
198         my ($eml, $lei, $lse, $augment) = @_;
199         my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
200         update_kw_maybe($lei, $lse, $eml, $kw);
201         _augment($eml, $lei) if $augment;
202 }
203
204 sub _mbox_write_cb ($$) {
205         my ($self, $lei) = @_;
206         my $ovv = $lei->{ovv};
207         my $m = 'eml2'.$ovv->{fmt};
208         my $eml2mbox = $self->can($m) or die "$self->$m missing";
209         $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
210         $lei->{1}->autoflush(1);
211         my $atomic_append = !defined($ovv->{lock_path});
212         my $dedupe = $lei->{dedupe};
213         $dedupe->prepare_dedupe;
214         my $lse = $lei->{lse}; # may be undef
215         sub { # for git_to_mail
216                 my ($buf, $smsg, $eml) = @_;
217                 $eml //= PublicInbox::Eml->new($buf);
218                 return if $dedupe->is_dup($eml, $smsg->{blob});
219                 $lse->xsmsg_vmd($smsg) if $lse;
220                 $buf = $eml2mbox->($eml, $smsg);
221                 return atomic_append($lei, $buf) if $atomic_append;
222                 my $lk = $ovv->lock_for_scope;
223                 $lei->out($$buf);
224         }
225 }
226
227 sub update_kw_maybe ($$$$) {
228         my ($lei, $lse, $eml, $kw) = @_;
229         return unless $lse;
230         my $c = $lse->kw_changed($eml, $kw, my $docids = []);
231         my $vmd = { kw => $kw };
232         if (scalar @$docids) { # already in lei/store
233                 $lei->{sto}->ipc_do('set_eml_vmd', undef, $vmd, $docids) if $c;
234         } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
235                 # it's in an external, only set kw, here
236                 $lei->{sto}->ipc_do('set_xvmd', $xoids, $eml, $vmd);
237         } else { # never-before-seen, import the whole thing
238                 # XXX this is critical in protecting against accidental
239                 # data loss without --augment
240                 $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
241         }
242 }
243
244 sub _augment_or_unlink { # maildir_each_eml cb
245         my ($f, $kw, $eml, $lei, $lse, $mod, $shard, $unlink) = @_;
246         if ($mod) {
247                 # can't get dirent.d_ino w/ pure Perl readdir, so we extract
248                 # the OID if it looks like one instead of doing stat(2)
249                 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
250                                 $1 : sha256_hex($f);
251                 my $recno = hex(substr($hex, 0, 8));
252                 return if ($recno % $mod) != $shard;
253                 update_kw_maybe($lei, $lse, $eml, $kw);
254         }
255         $unlink ? unlink($f) : _augment($eml, $lei);
256 }
257
258 # maildir_each_file callback, \&CORE::unlink doesn't work with it
259 sub _unlink { unlink($_[0]) }
260
261 sub _rand () {
262         state $seq = 0;
263         sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
264 }
265
266 sub _buf2maildir {
267         my ($dst, $buf, $smsg) = @_;
268         my $kw = $smsg->{kw} // [];
269         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
270         my $rand = ''; # chosen by die roll :P
271         my ($tmp, $fh, $final, $ok);
272         my $common = $smsg->{blob} // _rand;
273         if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
274         do {
275                 $tmp = $dst.'tmp/'.$rand.$common;
276         } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
277                 $! == EEXIST && ($rand = _rand.','));
278         if ($ok && print $fh $$buf and close($fh)) {
279                 # ignore new/ and write only to cur/, otherwise MUAs
280                 # with R/W access to the Maildir will end up doing
281                 # a mass rename which can take a while with thousands
282                 # of messages.
283                 $dst .= 'cur/';
284                 $rand = '';
285                 do {
286                         $final = $dst.$rand.$common.':2,'.$sfx;
287                 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
288                         ($rand = _rand.','));
289                 die "link($tmp, $final): $!" unless $ok;
290                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
291         } else {
292                 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
293                 $_[0] = undef; # clobber dst
294                 unlink($tmp);
295                 die $err;
296         }
297 }
298
299 sub _maildir_write_cb ($$) {
300         my ($self, $lei) = @_;
301         my $dedupe = $lei->{dedupe};
302         $dedupe->prepare_dedupe if $dedupe;
303         my $dst = $lei->{ovv}->{dst};
304         my $lse = $lei->{lse}; # may be undef
305         sub { # for git_to_mail
306                 my ($buf, $smsg, $eml) = @_;
307                 $dst // return $lei->fail; # dst may be undef-ed in last run
308                 $buf //= \($eml->as_string);
309                 $lse->xsmsg_vmd($smsg) if $lse;
310                 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
311                 $eml //= PublicInbox::Eml->new($$buf); # copy buf
312                 return if $dedupe->is_dup($eml, $smsg->{blob});
313                 undef $eml;
314                 _buf2maildir($dst, $buf, $smsg);
315         }
316 }
317
318 sub _imap_write_cb ($$) {
319         my ($self, $lei) = @_;
320         my $dedupe = $lei->{dedupe};
321         $dedupe->prepare_dedupe if $dedupe;
322         my $imap_append = $lei->{net}->can('imap_append');
323         my $mic = $lei->{net}->mic_get($self->{uri});
324         my $folder = $self->{uri}->mailbox;
325         my $lse = $lei->{lse}; # may be undef
326         sub { # for git_to_mail
327                 my ($bref, $smsg, $eml) = @_;
328                 $mic // return $lei->fail; # dst may be undef-ed in last run
329                 if ($dedupe) {
330                         $eml //= PublicInbox::Eml->new($$bref); # copy bref
331                         return if $dedupe->is_dup($eml, $smsg->{blob});
332                 }
333                 $lse->xsmsg_vmd($smsg) if $lse;
334                 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
335                 if (my $err = $@) {
336                         undef $mic;
337                         die $err;
338                 }
339         }
340 }
341
342 sub write_cb { # returns a callback for git_to_mail
343         my ($self, $lei) = @_;
344         # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
345         my $m = "_$self->{base_type}_write_cb";
346         $self->$m($lei);
347 }
348
349 sub new {
350         my ($cls, $lei) = @_;
351         my $fmt = $lei->{ovv}->{fmt};
352         my $dst = $lei->{ovv}->{dst};
353         my $self = bless {}, $cls;
354         if ($fmt eq 'maildir') {
355                 require PublicInbox::MdirReader;
356                 $self->{base_type} = 'maildir';
357                 -e $dst && !-d _ and die
358                                 "$dst exists and is not a directory\n";
359                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
360         } elsif (substr($fmt, 0, 4) eq 'mbox') {
361                 require PublicInbox::MboxReader;
362                 (-d $dst || (-e _ && !-w _)) and die
363                         "$dst exists and is not a writable file\n";
364                 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
365                 $self->{base_type} = 'mbox';
366         } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
367                 require PublicInbox::NetWriter;
368                 my $net = PublicInbox::NetWriter->new;
369                 $net->add_url($dst);
370                 $net->{quiet} = $lei->{opt}->{quiet};
371                 my $err = $net->errors($dst);
372                 return $lei->fail($err) if $err;
373                 require PublicInbox::URIimap; # TODO: URI cast early
374                 $self->{uri} = PublicInbox::URIimap->new($dst);
375                 $self->{uri}->mailbox or die "No mailbox: $dst";
376                 $lei->{net} = $net;
377                 $self->{base_type} = 'imap';
378         } else {
379                 die "bad mail --format=$fmt\n";
380         }
381         $self->{dst} = $dst;
382         $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
383         $self;
384 }
385
386 sub _pre_augment_maildir {
387         my ($self, $lei) = @_;
388         my $dst = $lei->{ovv}->{dst};
389         for my $x (qw(tmp new cur)) {
390                 my $d = $dst.$x;
391                 next if -d $d;
392                 require File::Path;
393                 File::Path::mkpath($d);
394                 -d $d or die "$d is not a directory";
395         }
396 }
397
398 sub _do_augment_maildir {
399         my ($self, $lei) = @_;
400         my $dst = $lei->{ovv}->{dst};
401         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
402         my ($mod, $shard) = @{$self->{shard_info} // []};
403         if ($lei->{opt}->{augment}) {
404                 my $dedupe = $lei->{dedupe};
405                 if ($dedupe && $dedupe->prepare_dedupe) {
406                         PublicInbox::MdirReader::maildir_each_eml($dst,
407                                                 \&_augment_or_unlink,
408                                                 $lei, $lse, $mod, $shard);
409                         $dedupe->pause_dedupe;
410                 }
411         } elsif ($lse) {
412                 PublicInbox::MdirReader::maildir_each_eml($dst,
413                                         \&_augment_or_unlink,
414                                         $lei, $lse, $mod, $shard, 1);
415         } else {# clobber existing Maildir
416                 PublicInbox::MdirReader::maildir_each_file($dst, \&_unlink);
417         }
418 }
419
420 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
421         my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
422         update_kw_maybe($lei, $lse, $eml, $kw);
423         if ($delete_mic) {
424                 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
425         } else {
426                 _augment($eml, $lei);
427         }
428 }
429
430 sub _do_augment_imap {
431         my ($self, $lei) = @_;
432         my $net = $lei->{net};
433         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
434         if ($lei->{opt}->{augment}) {
435                 my $dedupe = $lei->{dedupe};
436                 if ($dedupe && $dedupe->prepare_dedupe) {
437                         $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
438                                         $lei, $lse);
439                         $dedupe->pause_dedupe;
440                 }
441         } elsif ($lse) {
442                 my $delete_mic;
443                 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
444                                         $lei, $lse, \$delete_mic);
445                 $delete_mic->expunge if $delete_mic;
446         } elsif (!$self->{-wq_worker_nr}) { # undef or 0
447                 # clobber existing IMAP folder
448                 $net->imap_delete_all($self->{uri});
449         }
450 }
451
452 sub _pre_augment_mbox {
453         my ($self, $lei) = @_;
454         my $dst = $lei->{ovv}->{dst};
455         my $out;
456         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
457         if ($devfd >= 0) {
458                 $out = $lei->{$devfd};
459         } else { # normal-looking path
460                 if (-p $dst) {
461                         open $out, '>', $dst or die "open($dst): $!";
462                 } elsif (-f _ || !-e _) {
463                         require PublicInbox::MboxLock;
464                         my $m = $lei->{opt}->{'lock'} //
465                                         PublicInbox::MboxLock->defaults;
466                         $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
467                         $out = $self->{mbl}->{fh};
468                 } else {
469                         die "$dst is not a file or FIFO\n";
470                 }
471                 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
472         }
473         # Perl does SEEK_END even with O_APPEND :<
474         $self->{seekable} = seek($out, 0, SEEK_SET);
475         if (!$self->{seekable} && $! != ESPIPE && !defined($devfd)) {
476                 die "seek($dst): $!\n";
477         }
478         if (!$self->{seekable}) {
479                 my $imp_before = $lei->{opt}->{'import-before'};
480                 die "--import-before specified but $dst is not seekable\n"
481                         if $imp_before && !ref($imp_before);
482                 die "--augment specified but $dst is not seekable\n" if
483                         $lei->{opt}->{augment};
484         }
485         if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
486                 pipe(my ($r, $w)) or die "pipe: $!";
487                 $lei->{zpipe} = [ $r, $w ];
488                 $lei->{ovv}->{lock_path} and
489                         die 'BUG: unexpected {ovv}->{lock_path}';
490                 $lei->{ovv}->ovv_out_lk_init;
491         } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
492                 $lei->{ovv}->ovv_out_lk_init;
493         }
494         $lei->{1} = $out;
495         undef;
496 }
497
498 sub _do_augment_mbox {
499         my ($self, $lei) = @_;
500         return unless $self->{seekable};
501         my $opt = $lei->{opt};
502         my $out = $lei->{1};
503         my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
504         return unless -s $out;
505         unless ($opt->{augment} || $opt->{'import-before'}) {
506                 truncate($out, 0) or die "truncate($dst): $!";
507                 return;
508         }
509         my $zsfx = $self->{zsfx};
510         my $rd = $zsfx ? PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei)
511                         : dup_src($out);
512         my $dedupe;
513         if ($opt->{augment}) {
514                 $dedupe = $lei->{dedupe};
515                 $dedupe->prepare_dedupe if $dedupe;
516         }
517         if ($opt->{'import-before'}) { # the default
518                 my $lse = $lei->{lse};
519                 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
520                                                 $lei, $lse, $opt->{augment});
521                 if (!$opt->{augment} and !truncate($out, 0)) {
522                         die "truncate($dst): $!";
523                 }
524         } else { # --augment --no-import-before
525                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
526         }
527         # maybe some systems don't honor O_APPEND, Perl does this:
528         seek($out, 0, SEEK_END) or die "seek $dst: $!";
529         $dedupe->pause_dedupe if $dedupe;
530 }
531
532 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
533         my ($self, $lei) = @_;
534         # _pre_augment_maildir, _pre_augment_mbox
535         my $m = $self->can("_pre_augment_$self->{base_type}") or return;
536         $m->($self, $lei);
537 }
538
539 sub do_augment { # slow, runs in wq worker
540         my ($self, $lei) = @_;
541         # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
542         my $m = "_do_augment_$self->{base_type}";
543         $self->$m($lei);
544 }
545
546 # fast (spawn compressor or mkdir), runs in same process as pre_augment
547 sub post_augment {
548         my ($self, $lei, @args) = @_;
549         my $wait = $lei->{opt}->{'import-before'} ?
550                         $lei->{sto}->ipc_do('checkpoint', 1) : 0;
551         # _post_augment_mbox
552         my $m = $self->can("_post_augment_$self->{base_type}") or return;
553         $m->($self, $lei, @args);
554 }
555
556 sub do_post_auth {
557         my ($self) = @_;
558         my $lei = $self->{lei};
559         # lei_xsearch can start as soon as all l2m workers get here
560         pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
561                 die "incr_start_query: $!";
562         my $aug;
563         if (lock_free($self)) {
564                 my $mod = $self->{-wq_nr_workers};
565                 my $shard = $self->{-wq_worker_nr};
566                 if (my $net = $lei->{net}) {
567                         $net->{shard_info} = [ $mod, $shard ];
568                 } else { # Maildir
569                         $self->{shard_info} = [ $mod, $shard ];
570                 }
571                 $aug = '+'; # incr_post_augment
572         } elsif ($self->{-wq_worker_nr} == 0) {
573                 $aug = '.'; # do_post_augment
574         }
575         if ($aug) {
576                 local $0 = 'do_augment';
577                 eval { do_augment($self, $lei) };
578                 $lei->fail($@) if $@;
579                 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
580                                 die "do_post_augment trigger: $!";
581         }
582         if (my $zpipe = delete $lei->{zpipe}) {
583                 $lei->{1} = $zpipe->[1];
584                 close $zpipe->[0];
585         }
586         $self->{wcb} = $self->write_cb($lei);
587 }
588
589 sub ipc_atfork_child {
590         my ($self) = @_;
591         my $lei = $self->{lei};
592         $lei->_lei_atfork_child;
593         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
594         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
595         $self->SUPER::ipc_atfork_child;
596 }
597
598 sub lock_free {
599         $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
600 }
601
602 sub poke_dst {
603         my ($self) = @_;
604         if ($self->{base_type} eq 'maildir') {
605                 my $t = time + 1;
606                 utime($t, $t, $self->{dst} . 'cur');
607         }
608 }
609
610 sub write_mail { # via ->wq_io_do
611         my ($self, $smsg) = @_;
612         git_async_cat($self->{lei}->{ale}->git, $smsg->{blob}, \&git_to_mail,
613                                 [$self->{wcb}, $smsg]);
614 }
615
616 sub wq_atexit_child {
617         my ($self) = @_;
618         delete $self->{wcb};
619         $self->{lei}->{ale}->git->async_wait_all;
620         $SIG{__WARN__} = 'DEFAULT';
621 }
622
623 # called in top-level lei-daemon when LeiAuth is done
624 sub net_merge_complete {
625         my ($self) = @_;
626         $self->wq_broadcast('do_post_auth');
627         $self->wq_close(1);
628 }
629
630 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
631 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;
632 1;