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