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);
24 use PublicInbox::MID qw(mids);
25 use PublicInbox::LeiSearch;
27 use PublicInbox::Spawn qw(spawn);
28 use List::Util qw(max);
33 my (undef, $dir, $opt) = @_;
34 my $eidx = PublicInbox::ExtSearchIdx->new($dir, $opt);
35 my $self = bless { priv_eidx => $eidx }, __PACKAGE__;
36 eidx_init($self)->done if $opt->{creat};
40 sub git { $_[0]->{priv_eidx}->git } # read-only
42 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
45 $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
48 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
52 if (opendir(my $dh, $self->git_pfx)) {
54 substr($_, 0, -4) + 0; # drop ".git" suffix
55 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
57 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
64 open $rdr->{2}, '>', '/dev/null' or die "open /dev/null: $!";
65 chomp(my $i = $git->qx([qw(var GIT_COMMITTER_IDENT)], undef, $rdr));
66 $i =~ /\A(.+) <([^>]+)> [0-9]+ [-\+]?[0-9]+$/ and return ($1, $2);
67 my ($user, undef, undef, undef, undef, undef, $gecos) = getpwuid($<);
68 ($user) = (($user // $ENV{USER} // '') =~ /([\w\-\.\+]+)/);
70 ($gecos) = (($gecos // '') =~ /([\w\-\.\+ \t]+)/);
71 $gecos //= 'lei user';
72 require Sys::Hostname;
73 my ($host) = (Sys::Hostname::hostname() =~ /([\w\-\.]+)/);
74 $host //= 'localhost';
75 ($gecos, "$user\@$host")
83 return $im if $im->{bytes_added} < $self->rotate_bytes;
89 $max = $self->git_epoch_max + 1;
91 my (undef, $tl) = eidx_init($self); # acquire lock
92 my $pfx = $self->git_pfx;
93 $max //= $self->git_epoch_max;
95 my $latest = "$pfx/$max.git";
97 PublicInbox::Import::init_bare($latest);
98 my $git = PublicInbox::Git->new($latest);
100 $git->qx(qw(config core.sharedRepository 0600));
101 $self->done; # unlock
102 # re-acquire lock, update alternates for new epoch
103 (undef, $tl) = eidx_init($self);
105 my $packed_bytes = $git->packed_bytes;
106 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
107 if ($unpacked_bytes >= $self->rotate_bytes) {
111 my ($n, $e) = git_ident($git);
112 $self->{im} = $im = PublicInbox::Import->new($git, $n, $e);
113 $im->{bytes_added} = int($packed_bytes / $self->packing_factor);
114 $im->{lock_path} = undef;
115 $im->{path_type} = 'v2';
121 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
124 # follows the stderr file
127 print { $self->{-err_wr} } readline($self->{-tmp_err});
132 my $eidx = $self->{priv_eidx};
133 my $tl = wantarray && $self->{-err_wr} ?
134 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
136 $eidx->idx_init({-private => 1}); # acquires lock
137 wantarray ? ($eidx, $tl) : $eidx;
140 sub _docids_for ($$) {
141 my ($self, $eml) = @_;
143 my $eidx = $self->{priv_eidx};
144 my ($chash, $mids) = PublicInbox::LeiSearch::content_key($eml);
145 my $oidx = $eidx->{oidx};
146 my $im = $self->{im};
147 for my $mid (@$mids) {
149 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
150 next if $cur->{bytes} == 0; # external-only message
151 my $oid = $cur->{blob};
152 my $docid = $cur->{num};
153 my $bref = $im ? $im->cat_blob($oid) : undef;
154 $bref //= $eidx->git->cat_file($oid) //
155 _lms_rw($self)->local_blob($oid, 1) // do {
156 warn "W: $oid (#$docid) <$mid> not found\n";
159 local $self->{current_info} = $oid;
160 my $x = PublicInbox::Eml->new($bref);
161 $docids{$docid} = $docid if content_hash($x) eq $chash;
164 sort { $a <=> $b } values %docids;
168 my ($self, $eml, $vmd, $docids) = @_;
169 my ($eidx, $tl) = eidx_init($self);
170 $docids //= [ _docids_for($self, $eml) ];
171 for my $docid (@$docids) {
172 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
178 my ($self, $eml, $vmd) = @_;
179 my ($eidx, $tl) = eidx_init($self);
180 my @docids = _docids_for($self, $eml);
181 for my $docid (@docids) {
182 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
187 sub remove_eml_vmd { # remove just the VMD
188 my ($self, $eml, $vmd) = @_;
189 my ($eidx, $tl) = eidx_init($self);
190 my @docids = _docids_for($self, $eml);
191 for my $docid (@docids) {
192 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
199 my ($eidx, $tl) = eidx_init($self);
200 $self->{lms} //= do {
201 require PublicInbox::LeiMailSync;
202 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
203 my $lms = PublicInbox::LeiMailSync->new($f);
210 my ($self, $folder, $id) = @_;
211 _lms_rw($self)->clear_src($folder, $id);
215 my ($self, $folder, $oidbin, $id, $newbn) = @_;
216 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
220 my ($self, $oidhex, $folder, $id) = @_;
221 _lms_rw($self)->set_src($oidhex, $folder, $id);
224 sub _remove_if_local { # git->cat_async arg
225 my ($bref, $oidhex, $type, $size, $self) = @_;
226 $self->{im}->remove($bref) if $bref;
229 sub remove_docids ($;@) {
230 my ($self, @docids) = @_;
231 my $eidx = eidx_init($self);
232 for my $docid (@docids) {
233 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
234 $self->{oidx}->delete_by_num($docid);
235 $self->{oidx}->{dbh}->do(<<EOF, undef, $docid);
236 DELETE FROM xref3 WHERE docid = ?
241 # remove the entire message from the index, does not touch mail_sync.sqlite3
243 my ($self, $eml) = @_;
244 my $im = $self->importer; # may create new epoch
245 my ($eidx, $tl) = eidx_init($self);
246 my $oidx = $eidx->{oidx};
247 my @docids = _docids_for($self, $eml);
248 my $git = $eidx->git;
249 for my $docid (@docids) {
250 my $xr3 = $oidx->get_xref3($docid, 1);
251 for my $row (@$xr3) {
252 my (undef, undef, $oidbin) = @$row;
253 my $oidhex = unpack('H*', $oidbin);
254 $git->cat_async($oidhex, \&_remove_if_local, $self);
257 $git->cat_async_wait;
258 remove_docids($self, @docids);
263 my ($self, $oid) = @_;
264 my $eidx = eidx_init($self);
265 my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
266 if (@cull) { # fixup old bugs...
268 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
270 remove_docids($self, @cull);
272 wantarray ? ($docid) : $docid;
276 my ($self, $eml, $vmd, $xoids) = @_;
277 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
278 my ($eidx, $tl) = eidx_init($self);
279 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
280 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
281 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
282 my $im_mark = $im->add($eml, undef, $smsg);
283 if ($vmd && $vmd->{sync_info}) {
284 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
286 $im_mark or return; # duplicate blob returns undef
288 local $self->{current_info} = $smsg->{blob};
289 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
290 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
291 delete $xoids->{$smsg->{blob}}; # added later
292 if (scalar keys %$xoids) {
293 my %docids = map { $_ => 1 } @$vivify_xvmd;
294 for my $oid (keys %$xoids) {
295 my @id = oid2docid($self, $oid);
298 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
303 $xoids->{$smsg->{blob}} = 1;
304 for my $docid (@$vivify_xvmd) {
305 my $cur = $oidx->get_art($docid);
306 my $idx = $eidx->idx_shard($docid);
307 if (!$cur || $cur->{bytes} == 0) { # really vivifying
308 $smsg->{num} = $docid;
309 $oidx->add_overview($eml, $smsg);
310 $smsg->{-merge_vmd} = 1;
311 $idx->index_eml($eml, $smsg);
312 } else { # lse fuzzy hit off ale
313 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
315 for my $oid (keys %$xoids) {
316 $oidx->add_xref3($docid, -1, $oid, '.');
318 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
321 } elsif (my @docids = _docids_for($self, $eml)) {
322 # fuzzy match from within lei/store
323 for my $docid (@docids) {
324 my $idx = $eidx->idx_shard($docid);
325 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
326 # add_eidx_info for List-Id
327 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
328 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
331 } else { # totally new message
332 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
333 $oidx->add_overview($eml, $smsg);
334 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
335 my $idx = $eidx->idx_shard($smsg->{num});
336 $idx->index_eml($eml, $smsg);
337 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
343 my ($self, $eml, $vmd, $xoids) = @_;
344 add_eml($self, $eml, $vmd, $xoids) //
345 set_eml_vmd($self, $eml, $vmd);
349 my ($self, $eml, $vmd, $xoids) = @_;
350 require PublicInbox::FakeImport;
351 local $self->{-fake_im} = PublicInbox::FakeImport->new;
352 set_eml($self, $eml, $vmd, $xoids);
355 sub _external_only ($$$) {
356 my ($self, $xoids, $eml) = @_;
357 my $eidx = $self->{priv_eidx};
358 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
359 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
360 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
361 # save space for an externals-only message
362 my $hdr = $eml->header_obj;
363 $smsg->populate($hdr); # sets lines == 0
365 delete @$smsg{qw(From Subject)};
366 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
367 $oidx->add_overview($hdr, $smsg); # subject+references for threading
368 $smsg->{subject} = '';
369 for my $oid (keys %$xoids) {
370 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
372 my $idx = $eidx->idx_shard($smsg->{num});
373 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
378 my ($self, $xoids, $eml, $vmd_mod) = @_;
379 my ($eidx, $tl) = eidx_init($self);
380 my $oidx = $eidx->{oidx};
382 for my $oid (keys %$xoids) {
383 my $docid = oid2docid($self, $oid) // next;
384 delete $xoids->{$oid};
385 next if $seen{$docid}++;
386 my $idx = $eidx->idx_shard($docid);
387 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
389 return unless scalar(keys(%$xoids));
391 # see if it was indexed, but with different OID(s)
392 if (my @docids = _docids_for($self, $eml)) {
393 for my $docid (@docids) {
394 next if $seen{$docid};
395 for my $oid (keys %$xoids) {
396 $oidx->add_xref3($docid, -1, $oid, '.');
398 my $idx = $eidx->idx_shard($docid);
399 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
404 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
405 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
408 # set or update keywords for external message, called via ipc_do
410 my ($self, $xoids, $eml, $vmd) = @_;
412 my ($eidx, $tl) = eidx_init($self);
413 my $oidx = $eidx->{oidx};
416 # see if we can just update existing docs
417 for my $oid (keys %$xoids) {
418 my $docid = oid2docid($self, $oid) // next;
419 delete $xoids->{$oid}; # all done with this oid
420 next if $seen{$docid}++;
421 my $idx = $eidx->idx_shard($docid);
422 $idx->ipc_do('set_vmd', $docid, $vmd);
424 return unless scalar(keys(%$xoids));
426 # n.b. we don't do _docids_for here, we expect the caller
427 # already checked $lse->kw_changed before calling this sub
429 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
431 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
432 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
436 my ($self, $wait) = @_;
437 if (my $im = $self->{im}) {
438 $wait ? $im->barrier : $im->checkpoint;
440 if (my $lms = delete $self->{lms}) {
443 $self->{priv_eidx}->checkpoint($wait);
448 _tail_err($self) if $self->{-err_wr};
449 my $dir = $self->{priv_eidx}->{topdir};
450 return unless -e $dir;
451 my $old = delete $self->{-tmp_err};
452 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
453 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
454 SUFFIX => '.err', DIR => $dir);
455 open STDERR, '>>', $err->filename or die "dup2: $!";
456 STDERR->autoflush(1); # shared with shard subprocesses
457 $self->{-tmp_err} = $err; # separate file description for RO access
464 if (my $im = delete($self->{im})) {
467 $err .= "import done: $@\n";
471 if (my $lms = delete $self->{lms}) {
474 $self->{priv_eidx}->done; # V2Writable::done
479 sub ipc_atfork_child {
481 my $lei = $self->{lei};
482 $lei->_lei_atfork_child(1) if $lei;
484 if (my $err = delete($self->{err_pipe})) {
486 $self->{-err_wr} = $err->[1];
488 $self->SUPER::ipc_atfork_child;
492 my ($self, $lei) = @_;
493 unless ($self->{-ipc_req}) {
494 my $d = $lei->store_path;
495 $self->ipc_lock_init("$d/ipc.lock");
496 substr($d, -length('/lei/store'), 10, '');
497 pipe(my ($r, $w)) or die "pipe: $!";
498 my $err_pipe = [ $r, $w ];
499 # Mail we import into lei are private, so headers filtered out
500 # by -mda for public mail are not appropriate
501 local @PublicInbox::MDA::BAD_HEADERS = ();
502 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
503 { lei => $lei, err_pipe => $err_pipe });
504 require PublicInbox::LeiStoreErr;
505 PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);