1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # 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)
8 # for xref3, the following are constant: $eidx_key = '.', $xnum = -1
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
14 package PublicInbox::LeiStore;
17 use parent qw(PublicInbox::Lock PublicInbox::IPC);
18 use PublicInbox::ExtSearchIdx;
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;
27 use PublicInbox::Spawn qw(spawn);
28 use PublicInbox::MdirReader;
29 use PublicInbox::LeiToMail;
30 use List::Util qw(max);
33 use IO::Handle (); # ->autoflush
34 use Sys::Syslog qw(syslog openlog);
35 use Errno qw(EEXIST ENOENT);
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};
45 sub git { $_[0]->{priv_eidx}->git } # read-only
47 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
50 $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
53 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
57 if (opendir(my $dh, $self->git_pfx)) {
59 substr($_, 0, -4) + 0; # drop ".git" suffix
60 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
62 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
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\-\.\+]+)/);
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")
88 return $im if $im->{bytes_added} < $self->rotate_bytes;
94 $max = $self->git_epoch_max + 1;
96 my (undef, $tl) = eidx_init($self); # acquire lock
97 my $pfx = $self->git_pfx;
98 $max //= $self->git_epoch_max;
100 my $latest = "$pfx/$max.git";
101 my $old = -e $latest;
102 PublicInbox::Import::init_bare($latest);
103 my $git = PublicInbox::Git->new($latest);
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);
110 my $packed_bytes = $git->packed_bytes;
111 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
112 if ($unpacked_bytes >= $self->rotate_bytes) {
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';
126 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
129 # follows the stderr file
132 print { $self->{-err_wr} } readline($self->{-tmp_err});
137 my $eidx = $self->{priv_eidx};
138 my $tl = wantarray && $self->{-err_wr} ?
139 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
141 $eidx->idx_init({-private => 1}); # acquires lock
142 wantarray ? ($eidx, $tl) : $eidx;
145 sub _docids_for ($$) {
146 my ($self, $eml) = @_;
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) {
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";
164 local $self->{current_info} = $oid;
165 my $x = PublicInbox::Eml->new($bref);
166 $docids{$docid} = $docid if content_hash($x) eq $chash;
169 sort { $a <=> $b } values %docids;
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
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}) {
181 } elsif (my $add = $vmdish->{'+kw'}) {
183 } elsif (my $del = $vmdish->{-kw}) {
185 } # else no changes...
187 } else { # no keywords, yet, could be in new/
190 if (my $set = $vmdish->{kw}) {
192 } elsif (my $add = $vmdish->{'+kw'}) {
193 @$kw{@$add} = (); # auto-vivify
194 } else { # ignore $vmdish->{-kw}
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
202 # we use link(2) + unlink(2) since rename(2) may
203 # inadvertently clobber if the "uniquefilename" part wasn't
205 my $dst = "$mdir/cur/$bn";
207 my $src = "$mdir/$d/$orig";
208 if (link($src, $dst)) {
209 if (!unlink($src) and $! != ENOENT) {
210 syslog('warning', "unlink($src): $!");
212 # TODO: verify oidbin?
213 lms_mv_src($self, "maildir:$mdir",
214 $oidbin, \$orig, $bn);
216 } elsif ($! == EEXIST) { # lost race with "lei export-kw"?
218 } elsif ($! == ENOENT) {
219 syslog('warning', "link($src -> $dst): $!")
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);
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) {
241 export1_kw_md($self, $loc, $id,
250 # vmd = { kw => [ qw(seen ...) ], L => [ qw(inbox ...) ] }
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);
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);
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);
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;
295 my ($self, $folder, $id) = @_;
296 _lms_rw($self)->clear_src($folder, $id);
300 my ($self, $folder, $oidbin, $id, $newbn) = @_;
301 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
304 sub lms_forget_folders {
305 my ($self, @folders) = @_;
306 my $lms = _lms_rw($self);
307 for my $f (@folders) { $lms->forget_folder($f) }
310 sub lms_rename_folder {
311 my ($self, $old, $new) = @_;
312 _lms_rw($self)->rename_folder($old, $new);
316 my ($self, $oidhex, $folder, $id) = @_;
317 _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
320 sub _remove_if_local { # git->cat_async arg
321 my ($bref, $oidhex, $type, $size, $self) = @_;
322 $self->{im}->remove($bref) if $bref;
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 = ?
337 # remove the entire message from the index, does not touch mail_sync.sqlite3
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);
353 $git->cat_async_wait;
354 remove_docids($self, @docids);
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...
364 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
366 remove_docids($self, @cull);
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);
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}});
388 $im_mark or return; # duplicate blob returns undef
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);
400 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
403 if (@$vivify_xvmd) { # docids list
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);
417 for my $oid (keys %$xoids) {
418 $oidx->add_xref3($docid, -1, $oid, '.');
420 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
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;
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;
446 my ($self, $eml, $vmd, $xoids) = @_;
447 add_eml($self, $eml, $vmd, $xoids) //
448 set_eml_vmd($self, $eml, $vmd);
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);
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
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, '.');
476 my $idx = $eidx->idx_shard($smsg->{num});
477 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
482 my ($self, $xoids, $eml, $vmd_mod) = @_;
483 my ($eidx, $tl) = eidx_init($self);
484 my $oidx = $eidx->{oidx};
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);
494 return unless scalar(keys(%$xoids));
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, '.');
503 my $idx = $eidx->idx_shard($docid);
504 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
505 sto_export_kw($self, $docid, $vmd_mod);
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);
515 # set or update keywords for external message, called via ipc_do
517 my ($self, $xoids, $eml, $vmd) = @_;
519 my ($eidx, $tl) = eidx_init($self);
520 my $oidx = $eidx->{oidx};
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);
532 return unless scalar(keys(%$xoids));
534 # n.b. we don't do _docids_for here, we expect the caller
535 # already checked $lse->kw_changed before calling this sub
537 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
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);
545 my ($self, $wait) = @_;
546 if (my $im = $self->{im}) {
547 $wait ? $im->barrier : $im->checkpoint;
550 $self->{priv_eidx}->checkpoint($wait);
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
569 my ($self, $sock_ref) = @_;
571 if (my $im = delete($self->{im})) {
574 $err .= "import done: $@\n";
579 $self->{priv_eidx}->done; # V2Writable::done
583 # notify clients ->done has been issued
584 defined($sock_ref) and
585 $self->{s2d_op_p}->pkt_do('sto_done_complete', $sock_ref);
588 sub ipc_atfork_child {
590 my $lei = $self->{lei};
591 $lei->_lei_atfork_child(1) if $lei;
593 if (my $to_close = delete($self->{to_close})) {
594 close($_) for @$to_close;
596 openlog('lei/store', 'pid,nowait,nofatal,ndelay', 'user');
597 $self->SUPER::ipc_atfork_child;
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: $!";
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, {
618 to_close => [ $r, $s2d_op_c->{sock} ],
619 s2d_op_p => $s2d_op_p,
621 require PublicInbox::LeiStoreErr;
622 PublicInbox::LeiStoreErr->new($r, $lei);
624 sto_done_complete => [ $lei->can('sto_done_complete') ]
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;
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) }