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) // do {
155 warn "W: $oid (#$docid) <$mid> not found\n";
158 local $self->{current_info} = $oid;
159 my $x = PublicInbox::Eml->new($bref);
160 $docids{$docid} = $docid if content_hash($x) eq $chash;
163 sort { $a <=> $b } values %docids;
167 my ($self, $eml, $vmd, $docids) = @_;
168 my ($eidx, $tl) = eidx_init($self);
169 $docids //= [ _docids_for($self, $eml) ];
170 for my $docid (@$docids) {
171 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
177 my ($self, $eml, $vmd) = @_;
178 my ($eidx, $tl) = eidx_init($self);
179 my @docids = _docids_for($self, $eml);
180 for my $docid (@docids) {
181 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
186 sub remove_eml_vmd { # remove just the VMD
187 my ($self, $eml, $vmd) = @_;
188 my ($eidx, $tl) = eidx_init($self);
189 my @docids = _docids_for($self, $eml);
190 for my $docid (@docids) {
191 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
198 $self->{lms} //= do {
199 require PublicInbox::LeiMailSync;
200 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
201 my $lms = PublicInbox::LeiMailSync->new($f);
208 my ($self, $folder, $id) = @_;
209 _lms_rw($self)->clear_src($folder, $id);
213 my ($self, $folder, $oidbin, $id, $newbn) = @_;
214 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
218 my ($self, $oidhex, $folder, $id) = @_;
219 _lms_rw($self)->set_src($oidhex, $folder, $id);
222 sub _remove_if_local { # git->cat_async arg
223 my ($bref, $oidhex, $type, $size, $self) = @_;
224 $self->{im}->remove($bref) if $bref;
227 # remove the entire message from the index, does not touch mail_sync.sqlite3
229 my ($self, $eml) = @_;
230 my $im = $self->importer; # may create new epoch
231 my ($eidx, $tl) = eidx_init($self);
232 my $oidx = $eidx->{oidx};
233 my @docids = _docids_for($self, $eml);
234 my $git = $eidx->git;
235 for my $docid (@docids) {
236 my $xr3 = $oidx->get_xref3($docid, 1);
237 for my $row (@$xr3) {
238 my (undef, undef, $oidbin) = @$row;
239 my $oidhex = unpack('H*', $oidbin);
240 $git->cat_async($oidhex, \&_remove_if_local, $self);
242 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
243 $oidx->delete_by_num($docid);
245 $git->cat_async_wait;
250 my ($self, $eml, $vmd, $xoids) = @_;
251 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
252 my ($eidx, $tl) = eidx_init($self);
253 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
254 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
255 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
256 my $im_mark = $im->add($eml, undef, $smsg);
257 if ($vmd && $vmd->{sync_info}) {
258 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
260 $im_mark or return; # duplicate blob returns undef
262 local $self->{current_info} = $smsg->{blob};
263 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
264 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
265 delete $xoids->{$smsg->{blob}}; # added later
266 if (scalar keys %$xoids) {
267 my %docids = map { $_ => 1 } @$vivify_xvmd;
268 for my $oid (keys %$xoids) {
269 my @id = $oidx->blob_exists($oid);
272 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
277 $xoids->{$smsg->{blob}} = 1;
278 for my $docid (@$vivify_xvmd) {
279 my $cur = $oidx->get_art($docid);
280 my $idx = $eidx->idx_shard($docid);
281 if (!$cur || $cur->{bytes} == 0) { # really vivifying
282 $smsg->{num} = $docid;
283 $oidx->add_overview($eml, $smsg);
284 $smsg->{-merge_vmd} = 1;
285 $idx->index_eml($eml, $smsg);
286 } else { # lse fuzzy hit off ale
287 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
289 for my $oid (keys %$xoids) {
290 $oidx->add_xref3($docid, -1, $oid, '.');
292 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
295 } elsif (my @docids = _docids_for($self, $eml)) {
296 # fuzzy match from within lei/store
297 for my $docid (@docids) {
298 my $idx = $eidx->idx_shard($docid);
299 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
300 # add_eidx_info for List-Id
301 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
302 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
305 } else { # totally new message
306 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
307 $oidx->add_overview($eml, $smsg);
308 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
309 my $idx = $eidx->idx_shard($smsg->{num});
310 $idx->index_eml($eml, $smsg);
311 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
317 my ($self, $eml, $vmd, $xoids) = @_;
318 add_eml($self, $eml, $vmd, $xoids) //
319 set_eml_vmd($self, $eml, $vmd);
323 my ($self, $eml, $vmd, $xoids) = @_;
324 require PublicInbox::FakeImport;
325 local $self->{-fake_im} = PublicInbox::FakeImport->new;
326 set_eml($self, $eml, $vmd, $xoids);
329 sub _external_only ($$$) {
330 my ($self, $xoids, $eml) = @_;
331 my $eidx = $self->{priv_eidx};
332 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
333 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
334 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
335 # save space for an externals-only message
336 my $hdr = $eml->header_obj;
337 $smsg->populate($hdr); # sets lines == 0
339 delete @$smsg{qw(From Subject)};
340 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
341 $oidx->add_overview($hdr, $smsg); # subject+references for threading
342 $smsg->{subject} = '';
343 for my $oid (keys %$xoids) {
344 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
346 my $idx = $eidx->idx_shard($smsg->{num});
347 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
352 my ($self, $xoids, $eml, $vmd_mod) = @_;
353 my ($eidx, $tl) = eidx_init($self);
354 my $oidx = $eidx->{oidx};
356 for my $oid (keys %$xoids) {
357 my @docids = $oidx->blob_exists($oid) or next;
358 scalar(@docids) > 1 and
359 warn "W: $oid indexed as multiple docids: @docids\n";
360 for my $docid (@docids) {
361 next if $seen{$docid}++;
362 my $idx = $eidx->idx_shard($docid);
363 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
365 delete $xoids->{$oid};
367 return unless scalar(keys(%$xoids));
369 # see if it was indexed, but with different OID(s)
370 if (my @docids = _docids_for($self, $eml)) {
371 for my $docid (@docids) {
372 next if $seen{$docid};
373 for my $oid (keys %$xoids) {
374 $oidx->add_xref3($docid, -1, $oid, '.');
376 my $idx = $eidx->idx_shard($docid);
377 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
382 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
383 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
386 # set or update keywords for external message, called via ipc_do
388 my ($self, $xoids, $eml, $vmd) = @_;
390 my ($eidx, $tl) = eidx_init($self);
391 my $oidx = $eidx->{oidx};
394 # see if we can just update existing docs
395 for my $oid (keys %$xoids) {
396 my @docids = $oidx->blob_exists($oid) or next;
397 scalar(@docids) > 1 and
398 warn "W: $oid indexed as multiple docids: @docids\n";
399 for my $docid (@docids) {
400 next if $seen{$docid}++;
401 my $idx = $eidx->idx_shard($docid);
402 $idx->ipc_do('set_vmd', $docid, $vmd);
404 delete $xoids->{$oid}; # all done with this oid
406 return unless scalar(keys(%$xoids));
408 # n.b. we don't do _docids_for here, we expect the caller
409 # already checked $lse->kw_changed before calling this sub
411 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
413 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
414 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
418 my ($self, $wait) = @_;
419 if (my $im = $self->{im}) {
420 $wait ? $im->barrier : $im->checkpoint;
422 $self->{priv_eidx}->checkpoint($wait);
427 _tail_err($self) if $self->{-err_wr};
428 my $dir = $self->{priv_eidx}->{topdir};
429 return unless -e $dir;
430 my $old = delete $self->{-tmp_err};
431 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
432 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
433 SUFFIX => '.err', DIR => $dir);
434 open STDERR, '>>', $err->filename or die "dup2: $!";
435 STDERR->autoflush(1); # shared with shard subprocesses
436 $self->{-tmp_err} = $err; # separate file description for RO access
443 if (my $im = delete($self->{im})) {
446 $err .= "import done: $@\n";
450 if (my $lms = delete $self->{lms}) {
453 $self->{priv_eidx}->done; # V2Writable::done
458 sub ipc_atfork_child {
460 my $lei = $self->{lei};
461 $lei->_lei_atfork_child(1) if $lei;
463 if (my $err = delete($self->{err_pipe})) {
465 $self->{-err_wr} = $err->[1];
467 $self->SUPER::ipc_atfork_child;
471 my ($self, $lei) = @_;
472 unless ($self->{-ipc_req}) {
473 my $d = $lei->store_path;
474 $self->ipc_lock_init("$d/ipc.lock");
475 substr($d, -length('/lei/store'), 10, '');
476 pipe(my ($r, $w)) or die "pipe: $!";
477 my $err_pipe = [ $r, $w ];
478 # Mail we import into lei are private, so headers filtered out
479 # by -mda for public mail are not appropriate
480 local @PublicInbox::MDA::BAD_HEADERS = ();
481 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
482 { lei => $lei, err_pipe => $err_pipe });
483 require PublicInbox::LeiStoreErr;
484 PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);