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;
32 use IO::Handle (); # ->autoflush
33 use Sys::Syslog qw(syslog openlog);
34 use Errno qw(EEXIST ENOENT);
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};
44 sub git { $_[0]->{priv_eidx}->git } # read-only
46 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
49 $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
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\-\.\+]+)/);
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")
74 return $im if $im->{bytes_added} < $self->rotate_bytes;
80 $max = $self->{priv_eidx}->{mg}->git_epochs + 1;
82 my (undef, $tl) = eidx_init($self); # acquire lock
83 $max //= $self->{priv_eidx}->{mg}->git_epochs;
85 my $latest = $self->{priv_eidx}->{mg}->add_epoch($max);
86 my $git = PublicInbox::Git->new($latest);
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) {
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';
106 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
109 # follows the stderr file
112 print { $self->{-err_wr} } readline($self->{-tmp_err});
117 my $eidx = $self->{priv_eidx};
118 my $tl = wantarray && $self->{-err_wr} ?
119 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
121 $eidx->idx_init({-private => 1}); # acquires lock
122 wantarray ? ($eidx, $tl) : $eidx;
125 sub _docids_for ($$) {
126 my ($self, $eml) = @_;
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) {
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";
144 local $self->{current_info} = $oid;
145 my $x = PublicInbox::Eml->new($bref);
146 $docids{$docid} = $docid if content_hash($x) eq $chash;
149 sort { $a <=> $b } values %docids;
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
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}) {
161 } elsif (my $add = $vmdish->{'+kw'}) {
163 } elsif (my $del = $vmdish->{-kw}) {
165 } # else no changes...
167 } else { # no keywords, yet, could be in new/
170 if (my $set = $vmdish->{kw}) {
172 } elsif (my $add = $vmdish->{'+kw'}) {
173 @$kw{@$add} = (); # auto-vivify
174 } else { # ignore $vmdish->{-kw}
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
182 # we use link(2) + unlink(2) since rename(2) may
183 # inadvertently clobber if the "uniquefilename" part wasn't
185 my $dst = "$mdir/cur/$bn";
187 my $src = "$mdir/$d/$orig";
188 if (link($src, $dst)) {
189 if (!unlink($src) and $! != ENOENT) {
190 syslog('warning', "unlink($src): $!");
192 # TODO: verify oidbin?
193 lms_mv_src($self, "maildir:$mdir",
194 $oidbin, \$orig, $bn);
196 } elsif ($! == EEXIST) { # lost race with "lei export-kw"?
198 } elsif ($! != ENOENT) {
199 syslog('warning', "link($src -> $dst): $!");
202 for (@try) { return if -e "$mdir/$_/$orig" };
203 lms_clear_src($self, "maildir:$mdir", \$orig);
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) {
217 export1_kw_md($self, $loc, $id,
226 # vmd = { kw => [ qw(seen ...) ], L => [ qw(inbox ...) ] }
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);
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);
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);
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;
271 my ($self, $folder, $id) = @_;
272 _lms_rw($self)->clear_src($folder, $id);
276 my ($self, $folder, $oidbin, $id, $newbn) = @_;
277 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
280 sub lms_forget_folders {
281 my ($self, @folders) = @_;
282 my $lms = _lms_rw($self);
283 for my $f (@folders) { $lms->forget_folder($f) }
286 sub lms_rename_folder {
287 my ($self, $old, $new) = @_;
288 _lms_rw($self)->rename_folder($old, $new);
292 my ($self, $oidhex, $folder, $id) = @_;
293 _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
296 sub _remove_if_local { # git->cat_async arg
297 my ($bref, $oidhex, $type, $size, $self) = @_;
298 $self->{im}->remove($bref) if $bref;
301 sub remove_docids ($;@) {
302 my ($self, @docids) = @_;
303 my $eidx = eidx_init($self);
304 for my $docid (@docids) {
305 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
306 $eidx->{oidx}->delete_by_num($docid);
307 $eidx->{oidx}->{dbh}->do(<<EOF, undef, $docid);
308 DELETE FROM xref3 WHERE docid = ?
313 # remove the entire message from the index, does not touch mail_sync.sqlite3
315 my ($self, $eml) = @_;
316 my $im = $self->importer; # may create new epoch
317 my ($eidx, $tl) = eidx_init($self);
318 my $oidx = $eidx->{oidx};
319 my @docids = _docids_for($self, $eml);
320 my $git = $eidx->git;
321 for my $docid (@docids) {
322 my $xr3 = $oidx->get_xref3($docid, 1);
323 for my $row (@$xr3) {
324 my (undef, undef, $oidbin) = @$row;
325 my $oidhex = unpack('H*', $oidbin);
326 $git->cat_async($oidhex, \&_remove_if_local, $self);
329 $git->cat_async_wait;
330 remove_docids($self, @docids);
335 my ($self, $oid) = @_;
336 my $eidx = eidx_init($self);
337 my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
338 if (@cull) { # fixup old bugs...
340 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
342 remove_docids($self, @cull);
347 sub _add_vmd ($$$$) {
348 my ($self, $idx, $docid, $vmd) = @_;
349 $idx->ipc_do('add_vmd', $docid, $vmd);
350 sto_export_kw($self, $docid, $vmd);
354 my ($self, $eml, $vmd, $xoids) = @_;
355 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
356 my ($eidx, $tl) = eidx_init($self);
357 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
358 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
359 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
360 my $im_mark = $im->add($eml, undef, $smsg);
361 if ($vmd && $vmd->{sync_info}) {
362 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
364 $im_mark or return; # duplicate blob returns undef
366 local $self->{current_info} = $smsg->{blob};
367 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
368 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
369 delete $xoids->{$smsg->{blob}}; # added later
370 if (scalar keys %$xoids) {
371 my %docids = map { $_ => 1 } @$vivify_xvmd;
372 for my $oid (keys %$xoids) {
373 my $docid = oid2docid($self, $oid);
374 $docids{$docid} = $docid if defined($docid);
376 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
379 if (@$vivify_xvmd) { # docids list
381 $xoids->{$smsg->{blob}} = 1;
382 for my $docid (@$vivify_xvmd) {
383 my $cur = $oidx->get_art($docid);
384 my $idx = $eidx->idx_shard($docid);
385 if (!$cur || $cur->{bytes} == 0) { # really vivifying
386 $smsg->{num} = $docid;
387 $oidx->add_overview($eml, $smsg);
388 $smsg->{-merge_vmd} = 1;
389 $idx->index_eml($eml, $smsg);
390 } else { # lse fuzzy hit off ale
391 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
393 for my $oid (keys %$xoids) {
394 $oidx->add_xref3($docid, -1, $oid, '.');
396 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
399 } elsif (my @docids = _docids_for($self, $eml)) {
400 # fuzzy match from within lei/store
401 for my $docid (@docids) {
402 my $idx = $eidx->idx_shard($docid);
403 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
404 # add_eidx_info for List-Id
405 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
406 _add_vmd($self, $idx, $docid, $vmd) if $vmd;
409 } else { # totally new message
410 delete $smsg->{-oidx}; # for IPC-friendliness
411 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
412 $oidx->add_overview($eml, $smsg);
413 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
414 my $idx = $eidx->idx_shard($smsg->{num});
415 $idx->index_eml($eml, $smsg);
416 _add_vmd($self, $idx, $smsg->{num}, $vmd) if $vmd;
422 my ($self, $eml, $vmd, $xoids) = @_;
423 add_eml($self, $eml, $vmd, $xoids) //
424 set_eml_vmd($self, $eml, $vmd);
428 my ($self, $eml, $vmd, $xoids) = @_;
429 require PublicInbox::FakeImport;
430 local $self->{-fake_im} = PublicInbox::FakeImport->new;
431 set_eml($self, $eml, $vmd, $xoids);
434 # store {kw} / {L} info for a message which is only in an external
435 sub _external_only ($$$) {
436 my ($self, $xoids, $eml) = @_;
437 my $eidx = $self->{priv_eidx};
438 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
439 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
440 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
441 # save space for an externals-only message
442 my $hdr = $eml->header_obj;
443 $smsg->populate($hdr); # sets lines == 0
445 delete @$smsg{qw(From Subject)};
446 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
447 $oidx->add_overview($hdr, $smsg); # subject+references for threading
448 $smsg->{subject} = '';
449 for my $oid (keys %$xoids) {
450 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
452 my $idx = $eidx->idx_shard($smsg->{num});
453 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
458 my ($self, $xoids, $eml, $vmd_mod) = @_;
459 my ($eidx, $tl) = eidx_init($self);
460 my $oidx = $eidx->{oidx};
462 for my $oid (keys %$xoids) {
463 my $docid = oid2docid($self, $oid) // next;
464 delete $xoids->{$oid};
465 next if $seen{$docid}++;
466 my $idx = $eidx->idx_shard($docid);
467 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
468 sto_export_kw($self, $docid, $vmd_mod);
470 return unless scalar(keys(%$xoids));
472 # see if it was indexed, but with different OID(s)
473 if (my @docids = _docids_for($self, $eml)) {
474 for my $docid (@docids) {
475 next if $seen{$docid};
476 for my $oid (keys %$xoids) {
477 $oidx->add_xref3($docid, -1, $oid, '.');
479 my $idx = $eidx->idx_shard($docid);
480 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
481 sto_export_kw($self, $docid, $vmd_mod);
486 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
487 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
488 sto_export_kw($self, $smsg->{num}, $vmd_mod);
491 # set or update keywords for external message, called via ipc_do
493 my ($self, $xoids, $eml, $vmd) = @_;
495 my ($eidx, $tl) = eidx_init($self);
496 my $oidx = $eidx->{oidx};
499 # see if we can just update existing docs
500 for my $oid (keys %$xoids) {
501 my $docid = oid2docid($self, $oid) // next;
502 delete $xoids->{$oid}; # all done with this oid
503 next if $seen{$docid}++;
504 my $idx = $eidx->idx_shard($docid);
505 $idx->ipc_do('set_vmd', $docid, $vmd);
506 sto_export_kw($self, $docid, $vmd);
508 return unless scalar(keys(%$xoids));
510 # n.b. we don't do _docids_for here, we expect the caller
511 # already checked $lse->kw_changed before calling this sub
513 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
515 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
516 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
517 sto_export_kw($self, $smsg->{num}, $vmd);
521 my ($self, $wait) = @_;
522 if (my $im = $self->{im}) {
523 $wait ? $im->barrier : $im->checkpoint;
526 $self->{priv_eidx}->checkpoint($wait);
531 _tail_err($self) if $self->{-err_wr};
532 my $dir = $self->{priv_eidx}->{topdir};
533 return unless -e $dir;
534 my $old = delete $self->{-tmp_err};
535 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
536 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
537 SUFFIX => '.err', DIR => $dir);
538 open STDERR, '>>', $err->filename or die "dup2: $!";
539 STDERR->autoflush(1); # shared with shard subprocesses
540 $self->{-tmp_err} = $err; # separate file description for RO access
545 my ($self, $sock_ref) = @_;
547 if (my $im = delete($self->{im})) {
550 $err .= "import done: $@\n";
555 $self->{priv_eidx}->done; # V2Writable::done
559 # notify clients ->done has been issued
560 defined($sock_ref) and
561 $self->{s2d_op_p}->pkt_do('sto_done_complete', $sock_ref);
564 sub ipc_atfork_child {
566 my $lei = $self->{lei};
567 $lei->_lei_atfork_child(1) if $lei;
569 if (my $to_close = delete($self->{to_close})) {
570 close($_) for @$to_close;
572 openlog('lei/store', 'pid,nowait,nofatal,ndelay', 'user');
573 $self->SUPER::ipc_atfork_child;
577 my ($self, $lei) = @_;
578 $lei // die 'BUG: $lei not passed';
579 unless ($self->{-ipc_req}) {
580 # s2d => store-to-daemon messages
581 require PublicInbox::PktOp;
582 my ($s2d_op_c, $s2d_op_p) = PublicInbox::PktOp->pair;
583 my $dir = $lei->store_path;
584 $self->ipc_lock_init("$dir/ipc.lock");
585 substr($dir, -length('/lei/store'), 10, '');
586 pipe(my ($r, $w)) or die "pipe: $!";
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->ipc_worker_spawn("lei/store $dir", $lei->oldset, {
594 to_close => [ $r, $s2d_op_c->{sock} ],
595 s2d_op_p => $s2d_op_p,
597 require PublicInbox::LeiStoreErr;
598 PublicInbox::LeiStoreErr->new($r, $lei);
600 sto_done_complete => [ $lei->can('sto_done_complete') ]
606 # TODO: support SHA-256
607 sub git_blob_id { # called via LEI->git_blob_id
608 my ($self, $eml) = @_;
609 $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
610 git_sha(1, $eml)->hexdigest;
613 # called by lei-daemon before lei->refresh_watches
614 sub add_sync_folders {
615 my ($self, @folders) = @_;
616 my $lms = _lms_rw($self);
617 for my $f (@folders) { $lms->fid_for($f, 1) }