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): $!");
222 for (@try) { return if -e "$mdir/$_/$orig" };
223 lms_clear_src($self, "maildir:$mdir", \$orig);
226 sub sto_export_kw ($$$) {
227 my ($self, $docid, $vmdish) = @_; # vmdish (vmd or vmd_mod)
228 my ($eidx, $tl) = eidx_init($self);
229 my $lms = _lms_rw($self) // return;
230 my $xr3 = $eidx->{oidx}->get_xref3($docid, 1);
231 for my $row (@$xr3) {
232 my (undef, undef, $oidbin) = @$row;
233 my $locs = $lms->locations_for($oidbin) // next;
234 while (my ($loc, $ids) = each %$locs) {
235 if ($loc =~ s!\Amaildir:!!i) {
237 export1_kw_md($self, $loc, $id,
246 # vmd = { kw => [ qw(seen ...) ], L => [ qw(inbox ...) ] }
248 my ($self, $eml, $vmd, $docids) = @_;
249 my ($eidx, $tl) = eidx_init($self);
250 $docids //= [ _docids_for($self, $eml) ];
251 for my $docid (@$docids) {
252 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
253 sto_export_kw($self, $docid, $vmd);
259 my ($self, $eml, $vmd) = @_;
260 my ($eidx, $tl) = eidx_init($self);
261 my @docids = _docids_for($self, $eml);
262 for my $docid (@docids) {
263 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
268 sub remove_eml_vmd { # remove just the VMD
269 my ($self, $eml, $vmd) = @_;
270 my ($eidx, $tl) = eidx_init($self);
271 my @docids = _docids_for($self, $eml);
272 for my $docid (@docids) {
273 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
280 my ($eidx, $tl) = eidx_init($self);
281 $self->{lms} //= do {
282 require PublicInbox::LeiMailSync;
283 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
284 my $lms = PublicInbox::LeiMailSync->new($f);
285 $lms->lms_write_prepare;
291 my ($self, $folder, $id) = @_;
292 _lms_rw($self)->clear_src($folder, $id);
296 my ($self, $folder, $oidbin, $id, $newbn) = @_;
297 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
300 sub lms_forget_folders {
301 my ($self, @folders) = @_;
302 my $lms = _lms_rw($self);
303 for my $f (@folders) { $lms->forget_folder($f) }
306 sub lms_rename_folder {
307 my ($self, $old, $new) = @_;
308 _lms_rw($self)->rename_folder($old, $new);
312 my ($self, $oidhex, $folder, $id) = @_;
313 _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
316 sub _remove_if_local { # git->cat_async arg
317 my ($bref, $oidhex, $type, $size, $self) = @_;
318 $self->{im}->remove($bref) if $bref;
321 sub remove_docids ($;@) {
322 my ($self, @docids) = @_;
323 my $eidx = eidx_init($self);
324 for my $docid (@docids) {
325 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
326 $eidx->{oidx}->delete_by_num($docid);
327 $eidx->{oidx}->{dbh}->do(<<EOF, undef, $docid);
328 DELETE FROM xref3 WHERE docid = ?
333 # remove the entire message from the index, does not touch mail_sync.sqlite3
335 my ($self, $eml) = @_;
336 my $im = $self->importer; # may create new epoch
337 my ($eidx, $tl) = eidx_init($self);
338 my $oidx = $eidx->{oidx};
339 my @docids = _docids_for($self, $eml);
340 my $git = $eidx->git;
341 for my $docid (@docids) {
342 my $xr3 = $oidx->get_xref3($docid, 1);
343 for my $row (@$xr3) {
344 my (undef, undef, $oidbin) = @$row;
345 my $oidhex = unpack('H*', $oidbin);
346 $git->cat_async($oidhex, \&_remove_if_local, $self);
349 $git->cat_async_wait;
350 remove_docids($self, @docids);
355 my ($self, $oid) = @_;
356 my $eidx = eidx_init($self);
357 my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
358 if (@cull) { # fixup old bugs...
360 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
362 remove_docids($self, @cull);
367 sub _add_vmd ($$$$) {
368 my ($self, $idx, $docid, $vmd) = @_;
369 $idx->ipc_do('add_vmd', $docid, $vmd);
370 sto_export_kw($self, $docid, $vmd);
374 my ($self, $eml, $vmd, $xoids) = @_;
375 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
376 my ($eidx, $tl) = eidx_init($self);
377 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
378 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
379 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
380 my $im_mark = $im->add($eml, undef, $smsg);
381 if ($vmd && $vmd->{sync_info}) {
382 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
384 $im_mark or return; # duplicate blob returns undef
386 local $self->{current_info} = $smsg->{blob};
387 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
388 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
389 delete $xoids->{$smsg->{blob}}; # added later
390 if (scalar keys %$xoids) {
391 my %docids = map { $_ => 1 } @$vivify_xvmd;
392 for my $oid (keys %$xoids) {
393 my $docid = oid2docid($self, $oid);
394 $docids{$docid} = $docid if defined($docid);
396 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
399 if (@$vivify_xvmd) { # docids list
401 $xoids->{$smsg->{blob}} = 1;
402 for my $docid (@$vivify_xvmd) {
403 my $cur = $oidx->get_art($docid);
404 my $idx = $eidx->idx_shard($docid);
405 if (!$cur || $cur->{bytes} == 0) { # really vivifying
406 $smsg->{num} = $docid;
407 $oidx->add_overview($eml, $smsg);
408 $smsg->{-merge_vmd} = 1;
409 $idx->index_eml($eml, $smsg);
410 } else { # lse fuzzy hit off ale
411 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
413 for my $oid (keys %$xoids) {
414 $oidx->add_xref3($docid, -1, $oid, '.');
416 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
419 } elsif (my @docids = _docids_for($self, $eml)) {
420 # fuzzy match from within lei/store
421 for my $docid (@docids) {
422 my $idx = $eidx->idx_shard($docid);
423 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
424 # add_eidx_info for List-Id
425 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
426 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
429 } else { # totally new message
430 delete $smsg->{-oidx}; # for IPC-friendliness
431 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
432 $oidx->add_overview($eml, $smsg);
433 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
434 my $idx = $eidx->idx_shard($smsg->{num});
435 $idx->index_eml($eml, $smsg);
436 _add_vmd($self, $idx, $smsg->{num}, $vmd) if $vmd;
442 my ($self, $eml, $vmd, $xoids) = @_;
443 add_eml($self, $eml, $vmd, $xoids) //
444 set_eml_vmd($self, $eml, $vmd);
448 my ($self, $eml, $vmd, $xoids) = @_;
449 require PublicInbox::FakeImport;
450 local $self->{-fake_im} = PublicInbox::FakeImport->new;
451 set_eml($self, $eml, $vmd, $xoids);
454 # store {kw} / {L} info for a message which is only in an external
455 sub _external_only ($$$) {
456 my ($self, $xoids, $eml) = @_;
457 my $eidx = $self->{priv_eidx};
458 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
459 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
460 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
461 # save space for an externals-only message
462 my $hdr = $eml->header_obj;
463 $smsg->populate($hdr); # sets lines == 0
465 delete @$smsg{qw(From Subject)};
466 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
467 $oidx->add_overview($hdr, $smsg); # subject+references for threading
468 $smsg->{subject} = '';
469 for my $oid (keys %$xoids) {
470 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
472 my $idx = $eidx->idx_shard($smsg->{num});
473 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
478 my ($self, $xoids, $eml, $vmd_mod) = @_;
479 my ($eidx, $tl) = eidx_init($self);
480 my $oidx = $eidx->{oidx};
482 for my $oid (keys %$xoids) {
483 my $docid = oid2docid($self, $oid) // next;
484 delete $xoids->{$oid};
485 next if $seen{$docid}++;
486 my $idx = $eidx->idx_shard($docid);
487 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
488 sto_export_kw($self, $docid, $vmd_mod);
490 return unless scalar(keys(%$xoids));
492 # see if it was indexed, but with different OID(s)
493 if (my @docids = _docids_for($self, $eml)) {
494 for my $docid (@docids) {
495 next if $seen{$docid};
496 for my $oid (keys %$xoids) {
497 $oidx->add_xref3($docid, -1, $oid, '.');
499 my $idx = $eidx->idx_shard($docid);
500 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
501 sto_export_kw($self, $docid, $vmd_mod);
506 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
507 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
508 sto_export_kw($self, $smsg->{num}, $vmd_mod);
511 # set or update keywords for external message, called via ipc_do
513 my ($self, $xoids, $eml, $vmd) = @_;
515 my ($eidx, $tl) = eidx_init($self);
516 my $oidx = $eidx->{oidx};
519 # see if we can just update existing docs
520 for my $oid (keys %$xoids) {
521 my $docid = oid2docid($self, $oid) // next;
522 delete $xoids->{$oid}; # all done with this oid
523 next if $seen{$docid}++;
524 my $idx = $eidx->idx_shard($docid);
525 $idx->ipc_do('set_vmd', $docid, $vmd);
526 sto_export_kw($self, $docid, $vmd);
528 return unless scalar(keys(%$xoids));
530 # n.b. we don't do _docids_for here, we expect the caller
531 # already checked $lse->kw_changed before calling this sub
533 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
535 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
536 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
537 sto_export_kw($self, $smsg->{num}, $vmd);
541 my ($self, $wait) = @_;
542 if (my $im = $self->{im}) {
543 $wait ? $im->barrier : $im->checkpoint;
546 $self->{priv_eidx}->checkpoint($wait);
551 _tail_err($self) if $self->{-err_wr};
552 my $dir = $self->{priv_eidx}->{topdir};
553 return unless -e $dir;
554 my $old = delete $self->{-tmp_err};
555 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
556 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
557 SUFFIX => '.err', DIR => $dir);
558 open STDERR, '>>', $err->filename or die "dup2: $!";
559 STDERR->autoflush(1); # shared with shard subprocesses
560 $self->{-tmp_err} = $err; # separate file description for RO access
565 my ($self, $sock_ref) = @_;
567 if (my $im = delete($self->{im})) {
570 $err .= "import done: $@\n";
575 $self->{priv_eidx}->done; # V2Writable::done
579 # notify clients ->done has been issued
580 defined($sock_ref) and
581 $self->{s2d_op_p}->pkt_do('sto_done_complete', $sock_ref);
584 sub ipc_atfork_child {
586 my $lei = $self->{lei};
587 $lei->_lei_atfork_child(1) if $lei;
589 if (my $to_close = delete($self->{to_close})) {
590 close($_) for @$to_close;
592 openlog('lei/store', 'pid,nowait,nofatal,ndelay', 'user');
593 $self->SUPER::ipc_atfork_child;
597 my ($self, $lei) = @_;
598 $lei // die 'BUG: $lei not passed';
599 unless ($self->{-ipc_req}) {
600 # s2d => store-to-daemon messages
601 require PublicInbox::PktOp;
602 my ($s2d_op_c, $s2d_op_p) = PublicInbox::PktOp->pair;
603 my $dir = $lei->store_path;
604 $self->ipc_lock_init("$dir/ipc.lock");
605 substr($dir, -length('/lei/store'), 10, '');
606 pipe(my ($r, $w)) or die "pipe: $!";
608 # Mail we import into lei are private, so headers filtered out
609 # by -mda for public mail are not appropriate
610 local @PublicInbox::MDA::BAD_HEADERS = ();
611 $self->ipc_worker_spawn("lei/store $dir", $lei->oldset, {
614 to_close => [ $r, $s2d_op_c->{sock} ],
615 s2d_op_p => $s2d_op_p,
617 require PublicInbox::LeiStoreErr;
618 PublicInbox::LeiStoreErr->new($r, $lei);
620 sto_done_complete => [ $lei->can('sto_done_complete') ]
626 # TODO: support SHA-256
627 sub git_blob_id { # called via LEI->git_blob_id
628 my ($self, $eml) = @_;
629 $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
630 git_sha(1, $eml)->hexdigest;
633 # called by lei-daemon before lei->refresh_watches
634 sub add_sync_folders {
635 my ($self, @folders) = @_;
636 my $lms = _lms_rw($self);
637 for my $f (@folders) { $lms->fid_for($f, 1) }