1 # Copyright (C) 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);
24 use PublicInbox::MID qw(mids);
25 use PublicInbox::LeiSearch;
27 use PublicInbox::Spawn qw(spawn);
28 use PublicInbox::MdirReader;
29 use PublicInbox::LeiToMail;
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);
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)
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\-\.\+]+)/);
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")
75 return $im if $im->{bytes_added} < $self->rotate_bytes;
81 $max = $self->{priv_eidx}->{mg}->git_epochs + 1;
83 my (undef, $tl) = eidx_init($self); # acquire lock
84 $max //= $self->{priv_eidx}->{mg}->git_epochs;
86 my $latest = $self->{priv_eidx}->{mg}->add_epoch($max);
87 my $git = PublicInbox::Git->new($latest);
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) {
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';
107 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
110 # follows the stderr file
113 print { $self->{-err_wr} } readline($self->{-tmp_err});
118 my $eidx = $self->{priv_eidx};
119 my $tl = wantarray && $self->{-err_wr} ?
120 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
122 $eidx->idx_init({-private => 1}); # acquires lock
123 wantarray ? ($eidx, $tl) : $eidx;
126 sub _docids_for ($$) {
127 my ($self, $eml) = @_;
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) {
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";
145 local $self->{current_info} = $oid;
146 my $x = PublicInbox::Eml->new($bref);
147 $docids{$docid} = $docid if content_hash($x) eq $chash;
150 sort { $a <=> $b } values %docids;
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
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}) {
162 } elsif (my $add = $vmdish->{'+kw'}) {
164 } elsif (my $del = $vmdish->{-kw}) {
166 } # else no changes...
168 } else { # no keywords, yet, could be in new/
171 if (my $set = $vmdish->{kw}) {
173 } elsif (my $add = $vmdish->{'+kw'}) {
174 @$kw{@$add} = (); # auto-vivify
175 } else { # ignore $vmdish->{-kw}
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
183 # we use link(2) + unlink(2) since rename(2) may
184 # inadvertently clobber if the "uniquefilename" part wasn't
186 my $dst = "$mdir/cur/$bn";
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);
194 } elsif ($! == EEXIST) { # lost race with "lei export-kw"?
196 } elsif ($! != ENOENT) {
197 syslog('warning', "rename_noreplace($src -> $dst): $!");
200 for (@try) { return if -e "$mdir/$_/$orig" };
201 $self->{lms}->clear_src("maildir:$mdir", \$orig);
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) {
215 export1_kw_md($self, $loc, $id,
224 # vmd = { kw => [ qw(seen ...) ], L => [ qw(inbox ...) ] }
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);
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);
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);
256 sub _lms_rw ($) { # it is important to have eidx processes open before lms
259 require PublicInbox::LeiMailSync;
260 my ($eidx, $tl) = eidx_init($self);
261 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
262 my $lms = PublicInbox::LeiMailSync->new($f);
263 $lms->lms_write_prepare;
268 sub _remove_if_local { # git->cat_async arg
269 my ($bref, $oidhex, $type, $size, $self) = @_;
270 $self->{im}->remove($bref) if $bref;
273 sub remove_docids ($;@) {
274 my ($self, @docids) = @_;
275 my $eidx = eidx_init($self);
276 for my $docid (@docids) {
277 $eidx->remove_doc($docid);
278 $eidx->{oidx}->{dbh}->do(<<EOF, undef, $docid);
279 DELETE FROM xref3 WHERE docid = ?
284 # remove the entire message from the index, does not touch mail_sync.sqlite3
286 my ($self, $eml) = @_;
287 my $im = $self->importer; # may create new epoch
288 my ($eidx, $tl) = eidx_init($self);
289 my $oidx = $eidx->{oidx};
290 my @docids = _docids_for($self, $eml);
291 my $git = $eidx->git;
292 for my $docid (@docids) {
293 my $xr3 = $oidx->get_xref3($docid, 1);
294 for my $row (@$xr3) {
295 my (undef, undef, $oidbin) = @$row;
296 my $oidhex = unpack('H*', $oidbin);
297 $git->cat_async($oidhex, \&_remove_if_local, $self);
300 $git->async_wait_all;
301 remove_docids($self, @docids);
306 my ($self, $oid) = @_;
307 my $eidx = eidx_init($self);
308 my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
309 if (@cull) { # fixup old bugs...
311 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
313 remove_docids($self, @cull);
318 sub _add_vmd ($$$$) {
319 my ($self, $idx, $docid, $vmd) = @_;
320 $idx->ipc_do('add_vmd', $docid, $vmd);
321 sto_export_kw($self, $docid, $vmd);
324 sub _docids_and_maybe_kw ($$) {
325 my ($self, $docids) = @_;
326 return $docids unless wantarray;
328 for my $num (@$docids) { # likely only 1, unless ContentHash changes
329 # can't use ->search->msg_keywords on uncommitted docs
330 my $idx = $self->{priv_eidx}->idx_shard($num);
331 my $tmp = eval { $idx->ipc_do('get_terms', 'K', $num) };
332 if ($@) { warn "#$num get_terms: $@" }
333 else { @$kw{keys %$tmp} = values(%$tmp) };
335 ($docids, [ sort keys %$kw ]);
338 sub _reindex_1 { # git->cat_async callback
339 my ($bref, $hex, $type, $size, $smsg) = @_;
340 my $self = delete $smsg->{-sto};
341 my ($eidx, $tl) = eidx_init($self);
342 $bref //= _lms_rw($self)->local_blob($hex, 1);
344 my $eml = PublicInbox::Eml->new($bref);
345 $smsg->{-merge_vmd} = 1; # preserve existing keywords
346 $eidx->idx_shard($smsg->{num})->index_eml($eml, $smsg);
347 } elsif ($type eq 'missing') {
348 # pre-release/buggy lei may've indexed external-only msgs,
349 # try to correct that, here
350 warn("E: missing $hex, culling (ancient lei artifact?)\n");
351 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
353 $eidx->{oidx}->update_blob($smsg, '');
354 my $eml = PublicInbox::Eml->new("\r\n\r\n");
355 $eidx->idx_shard($smsg->{num})->index_eml($eml, $smsg);
357 warn("E: $type $hex\n");
362 my ($self, $art) = @_;
363 my ($eidx, $tl) = eidx_init($self);
364 my $smsg = $eidx->{oidx}->get_art($art) // return;
365 return if $smsg->{bytes} == 0; # external-only message
366 $smsg->{-sto} = $self;
367 $eidx->git->cat_async($smsg->{blob} // die("no blob (#$art)"),
368 \&_reindex_1, $smsg);
373 my ($eidx, $tl) = eidx_init($self);
374 $eidx->git->async_wait_all;
375 # ->done to be called via sto_done_request
379 my ($self, $eml, $vmd, $xoids) = @_;
380 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
381 my ($eidx, $tl) = eidx_init($self);
382 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
383 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
384 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
385 my $im_mark = $im->add($eml, undef, $smsg);
386 if ($vmd && $vmd->{sync_info}) {
387 _lms_rw($self)->set_src($smsg->oidbin, @{$vmd->{sync_info}});
389 unless ($im_mark) { # duplicate blob returns undef
390 return unless wantarray;
391 my @docids = $oidx->blob_exists($smsg->{blob});
392 return _docids_and_maybe_kw $self, \@docids;
395 local $self->{current_info} = $smsg->{blob};
396 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
397 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
398 delete $xoids->{$smsg->{blob}}; # added later
399 if (scalar keys %$xoids) {
400 my %docids = map { $_ => 1 } @$vivify_xvmd;
401 for my $oid (keys %$xoids) {
402 my $docid = oid2docid($self, $oid);
403 $docids{$docid} = $docid if defined($docid);
405 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
408 if (@$vivify_xvmd) { # docids list
410 $xoids->{$smsg->{blob}} = 1;
411 for my $docid (@$vivify_xvmd) {
412 my $cur = $oidx->get_art($docid);
413 my $idx = $eidx->idx_shard($docid);
414 if (!$cur || $cur->{bytes} == 0) { # really vivifying
415 $smsg->{num} = $docid;
416 $oidx->add_overview($eml, $smsg);
417 $smsg->{-merge_vmd} = 1;
418 $idx->index_eml($eml, $smsg);
419 } else { # lse fuzzy hit off ale
420 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
422 for my $oid (keys %$xoids) {
423 $oidx->add_xref3($docid, -1, $oid, '.');
425 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
427 _docids_and_maybe_kw $self, $vivify_xvmd;
428 } elsif (my @docids = _docids_for($self, $eml)) {
429 # fuzzy match from within lei/store
430 for my $docid (@docids) {
431 my $idx = $eidx->idx_shard($docid);
432 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
433 # add_eidx_info for List-Id
434 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
435 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
437 _docids_and_maybe_kw $self, \@docids;
438 } else { # totally new message, no keywords
439 delete $smsg->{-oidx}; # for IPC-friendliness
440 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
441 $oidx->add_overview($eml, $smsg);
442 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
443 my $idx = $eidx->idx_shard($smsg->{num});
444 $idx->index_eml($eml, $smsg);
445 _add_vmd($self, $idx, $smsg->{num}, $vmd) if $vmd;
446 wantarray ? ($smsg, []) : $smsg;
451 my ($self, $eml, $vmd, $xoids) = @_;
452 add_eml($self, $eml, $vmd, $xoids) //
453 set_eml_vmd($self, $eml, $vmd);
457 my ($self, $eml, $vmd, $xoids) = @_;
458 require PublicInbox::FakeImport;
459 local $self->{-fake_im} = PublicInbox::FakeImport->new;
460 set_eml($self, $eml, $vmd, $xoids);
463 # store {kw} / {L} info for a message which is only in an external
464 sub _external_only ($$$) {
465 my ($self, $xoids, $eml) = @_;
466 my $eidx = $self->{priv_eidx};
467 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
468 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
469 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
470 # save space for an externals-only message
471 my $hdr = $eml->header_obj;
472 $smsg->populate($hdr); # sets lines == 0
474 delete @$smsg{qw(From Subject)};
475 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
476 $oidx->add_overview($hdr, $smsg); # subject+references for threading
477 $smsg->{subject} = '';
478 for my $oid (keys %$xoids) {
479 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
481 my $idx = $eidx->idx_shard($smsg->{num});
482 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
487 my ($self, $xoids, $eml, $vmd_mod) = @_;
488 my ($eidx, $tl) = eidx_init($self);
489 my $oidx = $eidx->{oidx};
491 for my $oid (keys %$xoids) {
492 my $docid = oid2docid($self, $oid) // next;
493 delete $xoids->{$oid};
494 next if $seen{$docid}++;
495 my $idx = $eidx->idx_shard($docid);
496 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
497 sto_export_kw($self, $docid, $vmd_mod);
499 return unless scalar(keys(%$xoids));
501 # see if it was indexed, but with different OID(s)
502 if (my @docids = _docids_for($self, $eml)) {
503 for my $docid (@docids) {
504 next if $seen{$docid};
505 for my $oid (keys %$xoids) {
506 $oidx->add_xref3($docid, -1, $oid, '.');
508 my $idx = $eidx->idx_shard($docid);
509 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
510 sto_export_kw($self, $docid, $vmd_mod);
515 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
516 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
517 sto_export_kw($self, $smsg->{num}, $vmd_mod);
520 # set or update keywords for external message, called via ipc_do
522 my ($self, $xoids, $eml, $vmd) = @_;
524 my ($eidx, $tl) = eidx_init($self);
525 my $oidx = $eidx->{oidx};
528 # see if we can just update existing docs
529 for my $oid (keys %$xoids) {
530 my $docid = oid2docid($self, $oid) // next;
531 delete $xoids->{$oid}; # all done with this oid
532 next if $seen{$docid}++;
533 my $idx = $eidx->idx_shard($docid);
534 $idx->ipc_do('set_vmd', $docid, $vmd);
535 sto_export_kw($self, $docid, $vmd);
537 return unless scalar(keys(%$xoids));
539 # n.b. we don't do _docids_for here, we expect the caller
540 # already checked $lse->kw_changed before calling this sub
542 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
544 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
545 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
546 sto_export_kw($self, $smsg->{num}, $vmd);
550 my ($self, $wait) = @_;
551 if (my $im = $self->{im}) {
552 $wait ? $im->barrier : $im->checkpoint;
555 $self->{priv_eidx}->checkpoint($wait);
560 _tail_err($self) if $self->{-err_wr};
561 my $dir = $self->{priv_eidx}->{topdir};
562 return unless -e $dir;
563 my $old = delete $self->{-tmp_err};
564 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
565 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.err-XXXX",
566 SUFFIX => '.err', DIR => $dir);
567 open STDERR, '>>', $err->filename or die "dup2: $!";
568 STDERR->autoflush(1); # shared with shard subprocesses
569 $self->{-tmp_err} = $err; # separate file description for RO access
574 my ($self, $sock_ref) = @_;
576 if (my $im = delete($self->{im})) {
579 $err .= "import done: $@\n";
584 $self->{priv_eidx}->done; # V2Writable::done
589 sub ipc_atfork_child {
591 my $lei = $self->{lei};
592 $lei->_lei_atfork_child(1) if $lei;
594 if (my $to_close = delete($self->{to_close})) {
595 close($_) for @$to_close;
597 openlog('lei/store', 'pid,nowait,nofatal,ndelay', 'user');
598 $self->SUPER::ipc_atfork_child;
602 my ($self, @args) = @_;
603 local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
604 $self->SUPER::recv_and_run(@args);
607 sub _sto_atexit { # dwaitpid callback
608 my ($args, $pid) = @_;
609 my $self = $args->[0];
610 warn "lei/store PID:$pid died \$?=$?\n" if $?;
614 my ($self, $lei) = @_;
615 $lei // die 'BUG: $lei not passed';
616 unless ($self->{-ipc_req}) {
617 my $dir = $lei->store_path;
618 substr($dir, -length('/lei/store'), 10, '');
619 pipe(my ($r, $w)) or die "pipe: $!";
621 # Mail we import into lei are private, so headers filtered out
622 # by -mda for public mail are not appropriate
623 local @PublicInbox::MDA::BAD_HEADERS = ();
624 $self->wq_workers_start("lei/store $dir", 1, $lei->oldset, {
629 $self->wq_wait_async(\&_sto_atexit); # outlives $lei
630 require PublicInbox::LeiStoreErr;
631 PublicInbox::LeiStoreErr->new($r, $lei);