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 List::Util qw(max);
31 use IO::Handle (); # ->autoflush
34 my (undef, $dir, $opt) = @_;
35 my $eidx = PublicInbox::ExtSearchIdx->new($dir, $opt);
36 my $self = bless { priv_eidx => $eidx }, __PACKAGE__;
37 eidx_init($self)->done if $opt->{creat};
41 sub git { $_[0]->{priv_eidx}->git } # read-only
43 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
46 $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
49 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
53 if (opendir(my $dh, $self->git_pfx)) {
55 substr($_, 0, -4) + 0; # drop ".git" suffix
56 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
58 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
65 open $rdr->{2}, '>', '/dev/null' or die "open /dev/null: $!";
66 chomp(my $i = $git->qx([qw(var GIT_COMMITTER_IDENT)], undef, $rdr));
67 $i =~ /\A(.+) <([^>]+)> [0-9]+ [-\+]?[0-9]+$/ and return ($1, $2);
68 my ($user, undef, undef, undef, undef, undef, $gecos) = getpwuid($<);
69 ($user) = (($user // $ENV{USER} // '') =~ /([\w\-\.\+]+)/);
71 ($gecos) = (($gecos // '') =~ /([\w\-\.\+ \t]+)/);
72 $gecos //= 'lei user';
73 require Sys::Hostname;
74 my ($host) = (Sys::Hostname::hostname() =~ /([\w\-\.]+)/);
75 $host //= 'localhost';
76 ($gecos, "$user\@$host")
84 return $im if $im->{bytes_added} < $self->rotate_bytes;
90 $max = $self->git_epoch_max + 1;
92 my (undef, $tl) = eidx_init($self); # acquire lock
93 my $pfx = $self->git_pfx;
94 $max //= $self->git_epoch_max;
96 my $latest = "$pfx/$max.git";
98 PublicInbox::Import::init_bare($latest);
99 my $git = PublicInbox::Git->new($latest);
101 $git->qx(qw(config core.sharedRepository 0600));
102 $self->done; # unlock
103 # re-acquire lock, update alternates for new epoch
104 (undef, $tl) = eidx_init($self);
106 my $packed_bytes = $git->packed_bytes;
107 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
108 if ($unpacked_bytes >= $self->rotate_bytes) {
112 my ($n, $e) = git_ident($git);
113 $self->{im} = $im = PublicInbox::Import->new($git, $n, $e);
114 $im->{bytes_added} = int($packed_bytes / $self->packing_factor);
115 $im->{lock_path} = undef;
116 $im->{path_type} = 'v2';
122 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
125 # follows the stderr file
128 print { $self->{-err_wr} } readline($self->{-tmp_err});
133 my $eidx = $self->{priv_eidx};
134 my $tl = wantarray && $self->{-err_wr} ?
135 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
137 $eidx->idx_init({-private => 1}); # acquires lock
138 wantarray ? ($eidx, $tl) : $eidx;
141 sub _docids_for ($$) {
142 my ($self, $eml) = @_;
144 my $eidx = $self->{priv_eidx};
145 my ($chash, $mids) = PublicInbox::LeiSearch::content_key($eml);
146 my $oidx = $eidx->{oidx};
147 my $im = $self->{im};
148 for my $mid (@$mids) {
150 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
151 next if $cur->{bytes} == 0; # external-only message
152 my $oid = $cur->{blob};
153 my $docid = $cur->{num};
154 my $bref = $im ? $im->cat_blob($oid) : undef;
155 $bref //= $eidx->git->cat_file($oid) //
156 _lms_rw($self)->local_blob($oid, 1) // do {
157 warn "W: $oid (#$docid) <$mid> not found\n";
160 local $self->{current_info} = $oid;
161 my $x = PublicInbox::Eml->new($bref);
162 $docids{$docid} = $docid if content_hash($x) eq $chash;
165 sort { $a <=> $b } values %docids;
169 my ($self, $eml, $vmd, $docids) = @_;
170 my ($eidx, $tl) = eidx_init($self);
171 $docids //= [ _docids_for($self, $eml) ];
172 for my $docid (@$docids) {
173 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
179 my ($self, $eml, $vmd) = @_;
180 my ($eidx, $tl) = eidx_init($self);
181 my @docids = _docids_for($self, $eml);
182 for my $docid (@docids) {
183 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
188 sub remove_eml_vmd { # remove just the VMD
189 my ($self, $eml, $vmd) = @_;
190 my ($eidx, $tl) = eidx_init($self);
191 my @docids = _docids_for($self, $eml);
192 for my $docid (@docids) {
193 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
200 my ($eidx, $tl) = eidx_init($self);
201 $self->{lms} //= do {
202 require PublicInbox::LeiMailSync;
203 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
204 my $lms = PublicInbox::LeiMailSync->new($f);
211 my ($self, $folder, $id) = @_;
212 _lms_rw($self)->clear_src($folder, $id);
216 my ($self, $folder, $oidbin, $id, $newbn) = @_;
217 _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
220 sub lms_forget_folders {
221 my ($self, @folders) = @_;
222 my $lms = _lms_rw($self);
223 for my $f (@folders) { $lms->forget_folder($f) }
226 sub lms_rename_folder {
227 my ($self, $old, $new) = @_;
228 _lms_rw($self)->rename_folder($old, $new);
232 my ($self, $oidhex, $folder, $id) = @_;
233 _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
236 sub _remove_if_local { # git->cat_async arg
237 my ($bref, $oidhex, $type, $size, $self) = @_;
238 $self->{im}->remove($bref) if $bref;
241 sub remove_docids ($;@) {
242 my ($self, @docids) = @_;
243 my $eidx = eidx_init($self);
244 for my $docid (@docids) {
245 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
246 $eidx->{oidx}->delete_by_num($docid);
247 $eidx->{oidx}->{dbh}->do(<<EOF, undef, $docid);
248 DELETE FROM xref3 WHERE docid = ?
253 # remove the entire message from the index, does not touch mail_sync.sqlite3
255 my ($self, $eml) = @_;
256 my $im = $self->importer; # may create new epoch
257 my ($eidx, $tl) = eidx_init($self);
258 my $oidx = $eidx->{oidx};
259 my @docids = _docids_for($self, $eml);
260 my $git = $eidx->git;
261 for my $docid (@docids) {
262 my $xr3 = $oidx->get_xref3($docid, 1);
263 for my $row (@$xr3) {
264 my (undef, undef, $oidbin) = @$row;
265 my $oidhex = unpack('H*', $oidbin);
266 $git->cat_async($oidhex, \&_remove_if_local, $self);
269 $git->cat_async_wait;
270 remove_docids($self, @docids);
275 my ($self, $oid) = @_;
276 my $eidx = eidx_init($self);
277 my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
278 if (@cull) { # fixup old bugs...
280 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
282 remove_docids($self, @cull);
288 my ($self, $eml, $vmd, $xoids) = @_;
289 my $im = $self->{-fake_im} // $self->importer; # may create new epoch
290 my ($eidx, $tl) = eidx_init($self);
291 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
292 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
293 $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
294 my $im_mark = $im->add($eml, undef, $smsg);
295 if ($vmd && $vmd->{sync_info}) {
296 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
298 $im_mark or return; # duplicate blob returns undef
300 local $self->{current_info} = $smsg->{blob};
301 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
302 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
303 delete $xoids->{$smsg->{blob}}; # added later
304 if (scalar keys %$xoids) {
305 my %docids = map { $_ => 1 } @$vivify_xvmd;
306 for my $oid (keys %$xoids) {
307 my $docid = oid2docid($self, $oid);
308 $docids{$docid} = $docid if defined($docid);
310 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
315 $xoids->{$smsg->{blob}} = 1;
316 for my $docid (@$vivify_xvmd) {
317 my $cur = $oidx->get_art($docid);
318 my $idx = $eidx->idx_shard($docid);
319 if (!$cur || $cur->{bytes} == 0) { # really vivifying
320 $smsg->{num} = $docid;
321 $oidx->add_overview($eml, $smsg);
322 $smsg->{-merge_vmd} = 1;
323 $idx->index_eml($eml, $smsg);
324 } else { # lse fuzzy hit off ale
325 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
327 for my $oid (keys %$xoids) {
328 $oidx->add_xref3($docid, -1, $oid, '.');
330 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
333 } elsif (my @docids = _docids_for($self, $eml)) {
334 # fuzzy match from within lei/store
335 for my $docid (@docids) {
336 my $idx = $eidx->idx_shard($docid);
337 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
338 # add_eidx_info for List-Id
339 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
340 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
343 } else { # totally new message
344 delete $smsg->{-oidx}; # for IPC-friendliness
345 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
346 $oidx->add_overview($eml, $smsg);
347 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
348 my $idx = $eidx->idx_shard($smsg->{num});
349 $idx->index_eml($eml, $smsg);
350 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
356 my ($self, $eml, $vmd, $xoids) = @_;
357 add_eml($self, $eml, $vmd, $xoids) //
358 set_eml_vmd($self, $eml, $vmd);
362 my ($self, $eml, $vmd, $xoids) = @_;
363 require PublicInbox::FakeImport;
364 local $self->{-fake_im} = PublicInbox::FakeImport->new;
365 set_eml($self, $eml, $vmd, $xoids);
368 sub _external_only ($$$) {
369 my ($self, $xoids, $eml) = @_;
370 my $eidx = $self->{priv_eidx};
371 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
372 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
373 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
374 # save space for an externals-only message
375 my $hdr = $eml->header_obj;
376 $smsg->populate($hdr); # sets lines == 0
378 delete @$smsg{qw(From Subject)};
379 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
380 $oidx->add_overview($hdr, $smsg); # subject+references for threading
381 $smsg->{subject} = '';
382 for my $oid (keys %$xoids) {
383 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
385 my $idx = $eidx->idx_shard($smsg->{num});
386 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
391 my ($self, $xoids, $eml, $vmd_mod) = @_;
392 my ($eidx, $tl) = eidx_init($self);
393 my $oidx = $eidx->{oidx};
395 for my $oid (keys %$xoids) {
396 my $docid = oid2docid($self, $oid) // next;
397 delete $xoids->{$oid};
398 next if $seen{$docid}++;
399 my $idx = $eidx->idx_shard($docid);
400 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
402 return unless scalar(keys(%$xoids));
404 # see if it was indexed, but with different OID(s)
405 if (my @docids = _docids_for($self, $eml)) {
406 for my $docid (@docids) {
407 next if $seen{$docid};
408 for my $oid (keys %$xoids) {
409 $oidx->add_xref3($docid, -1, $oid, '.');
411 my $idx = $eidx->idx_shard($docid);
412 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
417 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
418 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
421 # set or update keywords for external message, called via ipc_do
423 my ($self, $xoids, $eml, $vmd) = @_;
425 my ($eidx, $tl) = eidx_init($self);
426 my $oidx = $eidx->{oidx};
429 # see if we can just update existing docs
430 for my $oid (keys %$xoids) {
431 my $docid = oid2docid($self, $oid) // next;
432 delete $xoids->{$oid}; # all done with this oid
433 next if $seen{$docid}++;
434 my $idx = $eidx->idx_shard($docid);
435 $idx->ipc_do('set_vmd', $docid, $vmd);
437 return unless scalar(keys(%$xoids));
439 # n.b. we don't do _docids_for here, we expect the caller
440 # already checked $lse->kw_changed before calling this sub
442 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
444 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
445 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
449 my ($self, $wait) = @_;
450 if (my $im = $self->{im}) {
451 $wait ? $im->barrier : $im->checkpoint;
453 if (my $lms = delete $self->{lms}) {
456 $self->{priv_eidx}->checkpoint($wait);
461 _tail_err($self) if $self->{-err_wr};
462 my $dir = $self->{priv_eidx}->{topdir};
463 return unless -e $dir;
464 my $old = delete $self->{-tmp_err};
465 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
466 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
467 SUFFIX => '.err', DIR => $dir);
468 open STDERR, '>>', $err->filename or die "dup2: $!";
469 STDERR->autoflush(1); # shared with shard subprocesses
470 $self->{-tmp_err} = $err; # separate file description for RO access
475 my ($self, $sock_ref) = @_;
477 if (my $im = delete($self->{im})) {
480 $err .= "import done: $@\n";
484 if (my $lms = delete $self->{lms}) {
487 $self->{priv_eidx}->done; # V2Writable::done
491 # notify clients ->done has been issued
492 defined($sock_ref) and
493 $self->{s2d_op_p}->pkt_do('sto_done_complete', $sock_ref);
496 sub ipc_atfork_child {
498 my $lei = $self->{lei};
499 $lei->_lei_atfork_child(1) if $lei;
501 if (my $to_close = delete($self->{to_close})) {
502 close($_) for @$to_close;
504 $self->SUPER::ipc_atfork_child;
508 my ($self, $lei) = @_;
509 $lei // die 'BUG: $lei not passed';
510 unless ($self->{-ipc_req}) {
511 # s2d => store-to-daemon messages
512 require PublicInbox::PktOp;
513 my ($s2d_op_c, $s2d_op_p) = PublicInbox::PktOp->pair;
514 my $dir = $lei->store_path;
515 $self->ipc_lock_init("$dir/ipc.lock");
516 substr($dir, -length('/lei/store'), 10, '');
517 pipe(my ($r, $w)) or die "pipe: $!";
519 # Mail we import into lei are private, so headers filtered out
520 # by -mda for public mail are not appropriate
521 local @PublicInbox::MDA::BAD_HEADERS = ();
522 $self->ipc_worker_spawn("lei/store $dir", $lei->oldset, {
525 to_close => [ $r, $s2d_op_c->{sock} ],
526 s2d_op_p => $s2d_op_p,
528 require PublicInbox::LeiStoreErr;
529 PublicInbox::LeiStoreErr->new($r, $lei);
531 sto_done_complete => [ $lei->can('sto_done_complete') ]
537 # TODO: support SHA-256
538 sub git_blob_id { # called via LEI->git_blob_id
539 my ($self, $eml) = @_;
540 $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
541 git_sha(1, $eml)->hexdigest;