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