]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
lei: use RENAME_NOREPLACE on Linux 3.15+
[public-inbox.git] / lib / PublicInbox / LeiStore.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 # Local storage (cache/memo) for lei(1), suitable for personal/private
5 # mail iff on encrypted device/FS.  Based on v2, but only deduplicates
6 # git storage based on git OID (index deduplication is done in ContentHash)
7 #
8 # for xref3, the following are constant: $eidx_key = '.', $xnum = -1
9 #
10 # We rely on the synchronous IPC API for this in lei-daemon and
11 # multiple lei clients to write to it at once.  This allows the
12 # lei/store IPC process to be decoupled from network latency in
13 # lei WQ workers.
14 package PublicInbox::LeiStore;
15 use strict;
16 use v5.10.1;
17 use parent qw(PublicInbox::Lock PublicInbox::IPC);
18 use PublicInbox::ExtSearchIdx;
19 use PublicInbox::Eml;
20 use PublicInbox::Import;
21 use PublicInbox::InboxWritable qw(eml_from_path);
22 use PublicInbox::V2Writable;
23 use PublicInbox::ContentHash qw(content_hash);
24 use PublicInbox::MID qw(mids);
25 use PublicInbox::LeiSearch;
26 use PublicInbox::MDA;
27 use PublicInbox::Spawn qw(spawn);
28 use PublicInbox::MdirReader;
29 use PublicInbox::LeiToMail;
30 use File::Temp ();
31 use POSIX ();
32 use IO::Handle (); # ->autoflush
33 use Sys::Syslog qw(syslog openlog);
34 use Errno qw(EEXIST ENOENT);
35 use PublicInbox::Syscall qw(rename_noreplace);
36
37 sub new {
38         my (undef, $dir, $opt) = @_;
39         my $eidx = PublicInbox::ExtSearchIdx->new($dir, $opt);
40         my $self = bless { priv_eidx => $eidx }, __PACKAGE__;
41         eidx_init($self)->done if $opt->{creat};
42         $self;
43 }
44
45 sub git { $_[0]->{priv_eidx}->git } # read-only
46
47 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
48
49 sub rotate_bytes {
50         $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
51 }
52
53 sub git_ident ($) {
54         my ($git) = @_;
55         my $rdr = {};
56         open $rdr->{2}, '>', '/dev/null' or die "open /dev/null: $!";
57         chomp(my $i = $git->qx([qw(var GIT_COMMITTER_IDENT)], undef, $rdr));
58         $i =~ /\A(.+) <([^>]+)> [0-9]+ [-\+]?[0-9]+$/ and return ($1, $2);
59         my ($user, undef, undef, undef, undef, undef, $gecos) = getpwuid($<);
60         ($user) = (($user // $ENV{USER} // '') =~ /([\w\-\.\+]+)/);
61         $user //= 'lei-user';
62         ($gecos) = (($gecos // '') =~ /([\w\-\.\+ \t]+)/);
63         $gecos //= 'lei user';
64         require Sys::Hostname;
65         my ($host) = (Sys::Hostname::hostname() =~ /([\w\-\.]+)/);
66         $host //= 'localhost';
67         ($gecos, "$user\@$host")
68 }
69
70 sub importer {
71         my ($self) = @_;
72         my $max;
73         my $im = $self->{im};
74         if ($im) {
75                 return $im if $im->{bytes_added} < $self->rotate_bytes;
76
77                 delete $self->{im};
78                 $im->done;
79                 undef $im;
80                 $self->checkpoint;
81                 $max = $self->{priv_eidx}->{mg}->git_epochs + 1;
82         }
83         my (undef, $tl) = eidx_init($self); # acquire lock
84         $max //= $self->{priv_eidx}->{mg}->git_epochs;
85         while (1) {
86                 my $latest = $self->{priv_eidx}->{mg}->add_epoch($max);
87                 my $git = PublicInbox::Git->new($latest);
88                 $self->done; # unlock
89                 # re-acquire lock, update alternates for new epoch
90                 (undef, $tl) = eidx_init($self);
91                 my $packed_bytes = $git->packed_bytes;
92                 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
93                 if ($unpacked_bytes >= $self->rotate_bytes) {
94                         $max++;
95                         next;
96                 }
97                 my ($n, $e) = git_ident($git);
98                 $self->{im} = $im = PublicInbox::Import->new($git, $n, $e);
99                 $im->{bytes_added} = int($packed_bytes / $self->packing_factor);
100                 $im->{lock_path} = undef;
101                 $im->{path_type} = 'v2';
102                 return $im;
103         }
104 }
105
106 sub search {
107         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
108 }
109
110 # follows the stderr file
111 sub _tail_err {
112         my ($self) = @_;
113         print { $self->{-err_wr} } readline($self->{-tmp_err});
114 }
115
116 sub eidx_init {
117         my ($self) = @_;
118         my $eidx = $self->{priv_eidx};
119         my $tl = wantarray && $self->{-err_wr} ?
120                         PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
121                         undef;
122         $eidx->idx_init({-private => 1}); # acquires lock
123         wantarray ? ($eidx, $tl) : $eidx;
124 }
125
126 sub _docids_for ($$) {
127         my ($self, $eml) = @_;
128         my %docids;
129         my $eidx = $self->{priv_eidx};
130         my ($chash, $mids) = PublicInbox::LeiSearch::content_key($eml);
131         my $oidx = $eidx->{oidx};
132         my $im = $self->{im};
133         for my $mid (@$mids) {
134                 my ($id, $prev);
135                 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
136                         next if $cur->{bytes} == 0; # external-only message
137                         my $oid = $cur->{blob};
138                         my $docid = $cur->{num};
139                         my $bref = $im ? $im->cat_blob($oid) : undef;
140                         $bref //= $eidx->git->cat_file($oid) //
141                                 _lms_rw($self)->local_blob($oid, 1) // do {
142                                 warn "W: $oid (#$docid) <$mid> not found\n";
143                                 next;
144                         };
145                         local $self->{current_info} = $oid;
146                         my $x = PublicInbox::Eml->new($bref);
147                         $docids{$docid} = $docid if content_hash($x) eq $chash;
148                 }
149         }
150         sort { $a <=> $b } values %docids;
151 }
152
153 # n.b. similar to LeiExportKw->export_kw_md, but this is for a single eml
154 sub export1_kw_md ($$$$$) {
155         my ($self, $mdir, $bn, $oidbin, $vmdish) = @_; # vmd/vmd_mod
156         my $orig = $bn;
157         my (@try, $unkn, $kw);
158         if ($bn =~ s/:2,([a-zA-Z]*)\z//) {
159                 ($kw, $unkn) = PublicInbox::MdirReader::flags2kw($1);
160                 if (my $set = $vmdish->{kw}) {
161                         $kw = $set;
162                 } elsif (my $add = $vmdish->{'+kw'}) {
163                         @$kw{@$add} = ();
164                 } elsif (my $del = $vmdish->{-kw}) {
165                         delete @$kw{@$del};
166                 } # else no changes...
167                 @try = qw(cur new);
168         } else { # no keywords, yet, could be in new/
169                 @try = qw(new cur);
170                 $unkn = [];
171                 if (my $set = $vmdish->{kw}) {
172                         $kw = $set;
173                 } elsif (my $add = $vmdish->{'+kw'}) {
174                         @$kw{@$add} = (); # auto-vivify
175                 } else { # ignore $vmdish->{-kw}
176                         $kw = [];
177                 }
178         }
179         $kw = [ keys %$kw ] if ref($kw) eq 'HASH';
180         $bn .= ':2,'. PublicInbox::LeiToMail::kw2suffix($kw, @$unkn);
181         return if $orig eq $bn; # no change
182
183         # we use link(2) + unlink(2) since rename(2) may
184         # inadvertently clobber if the "uniquefilename" part wasn't
185         # actually unique.
186         my $dst = "$mdir/cur/$bn";
187         for my $d (@try) {
188                 my $src = "$mdir/$d/$orig";
189                 if (rename_noreplace($src, $dst)) {
190                         # TODO: verify oidbin?
191                         $self->{lms}->mv_src("maildir:$mdir",
192                                         $oidbin, \$orig, $bn);
193                         return;
194                 } elsif ($! == EEXIST) { # lost race with "lei export-kw"?
195                         return;
196                 } elsif ($! != ENOENT) {
197                         syslog('warning', "rename_noreplace($src -> $dst): $!");
198                 }
199         }
200         for (@try) { return if -e "$mdir/$_/$orig" };
201         $self->{lms}->clear_src("maildir:$mdir", \$orig);
202 }
203
204 sub sto_export_kw ($$$) {
205         my ($self, $docid, $vmdish) = @_; # vmdish (vmd or vmd_mod)
206         my ($eidx, $tl) = eidx_init($self);
207         my $lms = _lms_rw($self) // return;
208         my $xr3 = $eidx->{oidx}->get_xref3($docid, 1);
209         for my $row (@$xr3) {
210                 my (undef, undef, $oidbin) = @$row;
211                 my $locs = $lms->locations_for($oidbin) // next;
212                 while (my ($loc, $ids) = each %$locs) {
213                         if ($loc =~ s!\Amaildir:!!i) {
214                                 for my $id (@$ids) {
215                                         export1_kw_md($self, $loc, $id,
216                                                         $oidbin, $vmdish);
217                                 }
218                         }
219                         # TODO: IMAP
220                 }
221         }
222 }
223
224 # vmd = { kw => [ qw(seen ...) ], L => [ qw(inbox ...) ] }
225 sub set_eml_vmd {
226         my ($self, $eml, $vmd, $docids) = @_;
227         my ($eidx, $tl) = eidx_init($self);
228         $docids //= [ _docids_for($self, $eml) ];
229         for my $docid (@$docids) {
230                 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
231                 sto_export_kw($self, $docid, $vmd);
232         }
233         $docids;
234 }
235
236 sub add_eml_vmd {
237         my ($self, $eml, $vmd) = @_;
238         my ($eidx, $tl) = eidx_init($self);
239         my @docids = _docids_for($self, $eml);
240         for my $docid (@docids) {
241                 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
242         }
243         \@docids;
244 }
245
246 sub remove_eml_vmd { # remove just the VMD
247         my ($self, $eml, $vmd) = @_;
248         my ($eidx, $tl) = eidx_init($self);
249         my @docids = _docids_for($self, $eml);
250         for my $docid (@docids) {
251                 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
252         }
253         \@docids;
254 }
255
256 sub _lms_rw ($) { # it is important to have eidx processes open before lms
257         my ($self) = @_;
258         my ($eidx, $tl) = eidx_init($self);
259         $self->{lms} //= do {
260                 require PublicInbox::LeiMailSync;
261                 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
262                 my $lms = PublicInbox::LeiMailSync->new($f);
263                 $lms->lms_write_prepare;
264                 $lms;
265         };
266 }
267
268 sub set_sync_info {
269         my ($self, $oidhex, $folder, $id) = @_;
270         _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
271 }
272
273 sub _remove_if_local { # git->cat_async arg
274         my ($bref, $oidhex, $type, $size, $self) = @_;
275         $self->{im}->remove($bref) if $bref;
276 }
277
278 sub remove_docids ($;@) {
279         my ($self, @docids) = @_;
280         my $eidx = eidx_init($self);
281         for my $docid (@docids) {
282                 $eidx->remove_doc($docid);
283                 $eidx->{oidx}->{dbh}->do(<<EOF, undef, $docid);
284 DELETE FROM xref3 WHERE docid = ?
285 EOF
286         }
287 }
288
289 # remove the entire message from the index, does not touch mail_sync.sqlite3
290 sub remove_eml {
291         my ($self, $eml) = @_;
292         my $im = $self->importer; # may create new epoch
293         my ($eidx, $tl) = eidx_init($self);
294         my $oidx = $eidx->{oidx};
295         my @docids = _docids_for($self, $eml);
296         my $git = $eidx->git;
297         for my $docid (@docids) {
298                 my $xr3 = $oidx->get_xref3($docid, 1);
299                 for my $row (@$xr3) {
300                         my (undef, undef, $oidbin) = @$row;
301                         my $oidhex = unpack('H*', $oidbin);
302                         $git->cat_async($oidhex, \&_remove_if_local, $self);
303                 }
304         }
305         $git->async_wait_all;
306         remove_docids($self, @docids);
307         \@docids;
308 }
309
310 sub oid2docid ($$) {
311         my ($self, $oid) = @_;
312         my $eidx = eidx_init($self);
313         my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
314         if (@cull) { # fixup old bugs...
315                 warn <<EOF;
316 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
317 EOF
318                 remove_docids($self, @cull);
319         }
320         $docid;
321 }
322
323 sub _add_vmd ($$$$) {
324         my ($self, $idx, $docid, $vmd) = @_;
325         $idx->ipc_do('add_vmd', $docid, $vmd);
326         sto_export_kw($self, $docid, $vmd);
327 }
328
329 sub _docids_and_maybe_kw ($$) {
330         my ($self, $docids) = @_;
331         return $docids unless wantarray;
332         my $kw = {};
333         for my $num (@$docids) { # likely only 1, unless ContentHash changes
334                 # can't use ->search->msg_keywords on uncommitted docs
335                 my $idx = $self->{priv_eidx}->idx_shard($num);
336                 my $tmp = eval { $idx->ipc_do('get_terms', 'K', $num) };
337                 if ($@) { warn "#$num get_terms: $@" }
338                 else { @$kw{keys %$tmp} = values(%$tmp) };
339         }
340         ($docids, [ sort keys %$kw ]);
341 }
342
343 sub add_eml {
344         my ($self, $eml, $vmd, $xoids) = @_;
345         my $im = $self->{-fake_im} // $self->importer; # may create new epoch
346         my ($eidx, $tl) = eidx_init($self);
347         my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
348         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
349         $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
350         my $im_mark = $im->add($eml, undef, $smsg);
351         if ($vmd && $vmd->{sync_info}) {
352                 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
353         }
354         unless ($im_mark) { # duplicate blob returns undef
355                 return unless wantarray;
356                 my @docids = $oidx->blob_exists($smsg->{blob});
357                 return _docids_and_maybe_kw $self, \@docids;
358         }
359
360         local $self->{current_info} = $smsg->{blob};
361         my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
362         if ($xoids) { # fuzzy matches from externals in ale->xoids_for
363                 delete $xoids->{$smsg->{blob}}; # added later
364                 if (scalar keys %$xoids) {
365                         my %docids = map { $_ => 1 } @$vivify_xvmd;
366                         for my $oid (keys %$xoids) {
367                                 my $docid = oid2docid($self, $oid);
368                                 $docids{$docid} = $docid if defined($docid);
369                         }
370                         @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
371                 }
372         }
373         if (@$vivify_xvmd) { # docids list
374                 $xoids //= {};
375                 $xoids->{$smsg->{blob}} = 1;
376                 for my $docid (@$vivify_xvmd) {
377                         my $cur = $oidx->get_art($docid);
378                         my $idx = $eidx->idx_shard($docid);
379                         if (!$cur || $cur->{bytes} == 0) { # really vivifying
380                                 $smsg->{num} = $docid;
381                                 $oidx->add_overview($eml, $smsg);
382                                 $smsg->{-merge_vmd} = 1;
383                                 $idx->index_eml($eml, $smsg);
384                         } else { # lse fuzzy hit off ale
385                                 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
386                         }
387                         for my $oid (keys %$xoids) {
388                                 $oidx->add_xref3($docid, -1, $oid, '.');
389                         }
390                         _add_vmd($self, $idx, $docid, $vmd) if $vmd;
391                 }
392                 _docids_and_maybe_kw $self, $vivify_xvmd;
393         } elsif (my @docids = _docids_for($self, $eml)) {
394                 # fuzzy match from within lei/store
395                 for my $docid (@docids) {
396                         my $idx = $eidx->idx_shard($docid);
397                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
398                         # add_eidx_info for List-Id
399                         $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
400                         _add_vmd($self, $idx, $docid, $vmd) if $vmd;
401                 }
402                 _docids_and_maybe_kw $self, \@docids;
403         } else { # totally new message, no keywords
404                 delete $smsg->{-oidx}; # for IPC-friendliness
405                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
406                 $oidx->add_overview($eml, $smsg);
407                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
408                 my $idx = $eidx->idx_shard($smsg->{num});
409                 $idx->index_eml($eml, $smsg);
410                 _add_vmd($self, $idx, $smsg->{num}, $vmd) if $vmd;
411                 wantarray ? ($smsg, []) : $smsg;
412         }
413 }
414
415 sub set_eml {
416         my ($self, $eml, $vmd, $xoids) = @_;
417         add_eml($self, $eml, $vmd, $xoids) //
418                 set_eml_vmd($self, $eml, $vmd);
419 }
420
421 sub index_eml_only {
422         my ($self, $eml, $vmd, $xoids) = @_;
423         require PublicInbox::FakeImport;
424         local $self->{-fake_im} = PublicInbox::FakeImport->new;
425         set_eml($self, $eml, $vmd, $xoids);
426 }
427
428 # store {kw} / {L} info for a message which is only in an external
429 sub _external_only ($$$) {
430         my ($self, $xoids, $eml) = @_;
431         my $eidx = $self->{priv_eidx};
432         my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
433         my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
434         $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
435         # save space for an externals-only message
436         my $hdr = $eml->header_obj;
437         $smsg->populate($hdr); # sets lines == 0
438         $smsg->{bytes} = 0;
439         delete @$smsg{qw(From Subject)};
440         $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
441         $oidx->add_overview($hdr, $smsg); # subject+references for threading
442         $smsg->{subject} = '';
443         for my $oid (keys %$xoids) {
444                 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
445         }
446         my $idx = $eidx->idx_shard($smsg->{num});
447         $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
448         ($smsg, $idx);
449 }
450
451 sub update_xvmd {
452         my ($self, $xoids, $eml, $vmd_mod) = @_;
453         my ($eidx, $tl) = eidx_init($self);
454         my $oidx = $eidx->{oidx};
455         my %seen;
456         for my $oid (keys %$xoids) {
457                 my $docid = oid2docid($self, $oid) // next;
458                 delete $xoids->{$oid};
459                 next if $seen{$docid}++;
460                 my $idx = $eidx->idx_shard($docid);
461                 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
462                 sto_export_kw($self, $docid, $vmd_mod);
463         }
464         return unless scalar(keys(%$xoids));
465
466         # see if it was indexed, but with different OID(s)
467         if (my @docids = _docids_for($self, $eml)) {
468                 for my $docid (@docids) {
469                         next if $seen{$docid};
470                         for my $oid (keys %$xoids) {
471                                 $oidx->add_xref3($docid, -1, $oid, '.');
472                         }
473                         my $idx = $eidx->idx_shard($docid);
474                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
475                         sto_export_kw($self, $docid, $vmd_mod);
476                 }
477                 return;
478         }
479         # totally unseen
480         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
481         $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
482         sto_export_kw($self, $smsg->{num}, $vmd_mod);
483 }
484
485 # set or update keywords for external message, called via ipc_do
486 sub set_xvmd {
487         my ($self, $xoids, $eml, $vmd) = @_;
488
489         my ($eidx, $tl) = eidx_init($self);
490         my $oidx = $eidx->{oidx};
491         my %seen;
492
493         # see if we can just update existing docs
494         for my $oid (keys %$xoids) {
495                 my $docid = oid2docid($self, $oid) // next;
496                 delete $xoids->{$oid}; # all done with this oid
497                 next if $seen{$docid}++;
498                 my $idx = $eidx->idx_shard($docid);
499                 $idx->ipc_do('set_vmd', $docid, $vmd);
500                 sto_export_kw($self, $docid, $vmd);
501         }
502         return unless scalar(keys(%$xoids));
503
504         # n.b. we don't do _docids_for here, we expect the caller
505         # already checked $lse->kw_changed before calling this sub
506
507         return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
508         # totally unseen:
509         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
510         $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
511         sto_export_kw($self, $smsg->{num}, $vmd);
512 }
513
514 sub checkpoint {
515         my ($self, $wait) = @_;
516         if (my $im = $self->{im}) {
517                 $wait ? $im->barrier : $im->checkpoint;
518         }
519         delete $self->{lms};
520         $self->{priv_eidx}->checkpoint($wait);
521 }
522
523 sub xchg_stderr {
524         my ($self) = @_;
525         _tail_err($self) if $self->{-err_wr};
526         my $dir = $self->{priv_eidx}->{topdir};
527         return unless -e $dir;
528         my $old = delete $self->{-tmp_err};
529         my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
530         my $err = File::Temp->new(TEMPLATE => "$pfx.$$.err-XXXX",
531                                 SUFFIX => '.err', DIR => $dir);
532         open STDERR, '>>', $err->filename or die "dup2: $!";
533         STDERR->autoflush(1); # shared with shard subprocesses
534         $self->{-tmp_err} = $err; # separate file description for RO access
535         undef;
536 }
537
538 sub done {
539         my ($self, $sock_ref) = @_;
540         my $err = '';
541         if (my $im = delete($self->{im})) {
542                 eval { $im->done };
543                 if ($@) {
544                         $err .= "import done: $@\n";
545                         warn $err;
546                 }
547         }
548         delete $self->{lms};
549         $self->{priv_eidx}->done; # V2Writable::done
550         xchg_stderr($self);
551         die $err if $err;
552 }
553
554 sub ipc_atfork_child {
555         my ($self) = @_;
556         my $lei = $self->{lei};
557         $lei->_lei_atfork_child(1) if $lei;
558         xchg_stderr($self);
559         if (my $to_close = delete($self->{to_close})) {
560                 close($_) for @$to_close;
561         }
562         openlog('lei/store', 'pid,nowait,nofatal,ndelay', 'user');
563         $self->SUPER::ipc_atfork_child;
564 }
565
566 sub recv_and_run {
567         my ($self, @args) = @_;
568         local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
569         $self->SUPER::recv_and_run(@args);
570 }
571
572 sub _sto_atexit { # dwaitpid callback
573         my ($args, $pid) = @_;
574         my $self = $args->[0];
575         warn "lei/store PID:$pid died \$?=$?\n" if $?;
576 }
577
578 sub write_prepare {
579         my ($self, $lei) = @_;
580         $lei // die 'BUG: $lei not passed';
581         unless ($self->{-ipc_req}) {
582                 my $dir = $lei->store_path;
583                 substr($dir, -length('/lei/store'), 10, '');
584                 pipe(my ($r, $w)) or die "pipe: $!";
585                 $w->autoflush(1);
586                 # Mail we import into lei are private, so headers filtered out
587                 # by -mda for public mail are not appropriate
588                 local @PublicInbox::MDA::BAD_HEADERS = ();
589                 $self->wq_workers_start("lei/store $dir", 1, $lei->oldset, {
590                                         lei => $lei,
591                                         -err_wr => $w,
592                                         to_close => [ $r ],
593                                 });
594                 $self->wq_wait_async(\&_sto_atexit); # outlives $lei
595                 require PublicInbox::LeiStoreErr;
596                 PublicInbox::LeiStoreErr->new($r, $lei);
597         }
598         $lei->{sto} = $self;
599 }
600
601 1;