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 $pfx = $self->git_pfx;
92 $max //= $self->git_epoch_max;
94 my $latest = "$pfx/$max.git";
96 PublicInbox::Import::init_bare($latest);
97 my $git = PublicInbox::Git->new($latest);
99 $git->qx(qw(config core.sharedRepository 0600));
100 $self->done; # force eidx_init on next round
102 my $packed_bytes = $git->packed_bytes;
103 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
104 if ($unpacked_bytes >= $self->rotate_bytes) {
108 my ($n, $e) = git_ident($git);
109 $self->{im} = $im = PublicInbox::Import->new($git, $n, $e);
110 $im->{bytes_added} = int($packed_bytes / $self->packing_factor);
111 $im->{lock_path} = undef;
112 $im->{path_type} = 'v2';
118 PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
121 # follows the stderr file
124 print { $self->{-err_wr} } readline($self->{-tmp_err});
129 my $eidx = $self->{priv_eidx};
130 my $tl = wantarray && $self->{-err_wr} ?
131 PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
133 $eidx->idx_init({-private => 1});
134 wantarray ? ($eidx, $tl) : $eidx;
137 sub _docids_for ($$) {
138 my ($self, $eml) = @_;
140 my $eidx = $self->{priv_eidx};
141 my ($chash, $mids) = PublicInbox::LeiSearch::content_key($eml);
142 my $oidx = $eidx->{oidx};
143 my $im = $self->{im};
144 for my $mid (@$mids) {
146 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
147 next if $cur->{bytes} == 0; # external-only message
148 my $oid = $cur->{blob};
149 my $docid = $cur->{num};
150 my $bref = $im ? $im->cat_blob($oid) : undef;
151 $bref //= $eidx->git->cat_file($oid) // do {
152 warn "W: $oid (#$docid) <$mid> not found\n";
155 local $self->{current_info} = $oid;
156 my $x = PublicInbox::Eml->new($bref);
157 $docids{$docid} = $docid if content_hash($x) eq $chash;
160 sort { $a <=> $b } values %docids;
164 my ($self, $eml, $vmd, $docids) = @_;
165 my ($eidx, $tl) = eidx_init($self);
166 $docids //= [ _docids_for($self, $eml) ];
167 for my $docid (@$docids) {
168 $eidx->idx_shard($docid)->ipc_do('set_vmd', $docid, $vmd);
174 my ($self, $eml, $vmd) = @_;
175 my ($eidx, $tl) = eidx_init($self);
176 my @docids = _docids_for($self, $eml);
177 for my $docid (@docids) {
178 $eidx->idx_shard($docid)->ipc_do('add_vmd', $docid, $vmd);
184 my ($self, $eml, $vmd) = @_;
185 my ($eidx, $tl) = eidx_init($self);
186 my @docids = _docids_for($self, $eml);
187 for my $docid (@docids) {
188 $eidx->idx_shard($docid)->ipc_do('remove_vmd', $docid, $vmd);
194 my ($self, $eml, $vmd, $xoids) = @_;
195 my $im = $self->importer; # may create new epoch
196 my ($eidx, $tl) = eidx_init($self); # updates/writes alternates file
197 my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
198 my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
199 $im->add($eml, undef, $smsg) or return; # duplicate returns undef
201 local $self->{current_info} = $smsg->{blob};
202 my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
203 if ($xoids) { # fuzzy matches from externals in ale->xoids_for
204 delete $xoids->{$smsg->{blob}}; # added later
205 if (scalar keys %$xoids) {
206 my %docids = map { $_ => 1 } @$vivify_xvmd;
207 for my $oid (keys %$xoids) {
208 my @id = $oidx->blob_exists($oid);
211 @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
216 $xoids->{$smsg->{blob}} = 1;
217 for my $docid (@$vivify_xvmd) {
218 my $cur = $oidx->get_art($docid);
219 my $idx = $eidx->idx_shard($docid);
220 if (!$cur || $cur->{bytes} == 0) { # really vivifying
221 $smsg->{num} = $docid;
222 $oidx->add_overview($eml, $smsg);
223 $smsg->{-merge_vmd} = 1;
224 $idx->index_eml($eml, $smsg);
225 } else { # lse fuzzy hit off ale
226 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
228 for my $oid (keys %$xoids) {
229 $oidx->add_xref3($docid, -1, $oid, '.');
231 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
234 } elsif (my @docids = _docids_for($self, $eml)) {
235 # fuzzy match from within lei/store
236 for my $docid (@docids) {
237 my $idx = $eidx->idx_shard($docid);
238 $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
239 # add_eidx_info for List-Id
240 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
241 $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
244 } else { # totally new message
245 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
246 $oidx->add_overview($eml, $smsg);
247 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
248 my $idx = $eidx->idx_shard($smsg->{num});
249 $idx->index_eml($eml, $smsg);
250 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
256 my ($self, $eml, $vmd, $xoids) = @_;
257 add_eml($self, $eml, $vmd, $xoids) //
258 set_eml_vmd($self, $eml, $vmd);
261 sub _external_only ($$$) {
262 my ($self, $xoids, $eml) = @_;
263 my $eidx = $self->{priv_eidx};
264 my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
265 my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
266 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
267 # save space for an externals-only message
268 my $hdr = $eml->header_obj;
269 $smsg->populate($hdr); # sets lines == 0
271 delete @$smsg{qw(From Subject)};
272 $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
273 $oidx->add_overview($hdr, $smsg); # subject+references for threading
274 $smsg->{subject} = '';
275 for my $oid (keys %$xoids) {
276 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
278 my $idx = $eidx->idx_shard($smsg->{num});
279 $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
284 my ($self, $xoids, $eml, $vmd_mod) = @_;
285 my ($eidx, $tl) = eidx_init($self);
286 my $oidx = $eidx->{oidx};
288 for my $oid (keys %$xoids) {
289 my @docids = $oidx->blob_exists($oid) or next;
290 scalar(@docids) > 1 and
291 warn "W: $oid indexed as multiple docids: @docids\n";
292 for my $docid (@docids) {
293 next if $seen{$docid}++;
294 my $idx = $eidx->idx_shard($docid);
295 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
297 delete $xoids->{$oid};
299 return unless scalar(keys(%$xoids));
301 # see if it was indexed, but with different OID(s)
302 if (my @docids = _docids_for($self, $eml)) {
303 for my $docid (@docids) {
304 next if $seen{$docid};
305 for my $oid (keys %$xoids) {
306 $oidx->add_xref3($docid, -1, $oid, '.');
308 my $idx = $eidx->idx_shard($docid);
309 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
314 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
315 $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
318 # set or update keywords for external message, called via ipc_do
320 my ($self, $xoids, $eml, $vmd) = @_;
322 my ($eidx, $tl) = eidx_init($self);
323 my $oidx = $eidx->{oidx};
326 # see if we can just update existing docs
327 for my $oid (keys %$xoids) {
328 my @docids = $oidx->blob_exists($oid) or next;
329 scalar(@docids) > 1 and
330 warn "W: $oid indexed as multiple docids: @docids\n";
331 for my $docid (@docids) {
332 next if $seen{$docid}++;
333 my $idx = $eidx->idx_shard($docid);
334 $idx->ipc_do('set_vmd', $docid, $vmd);
336 delete $xoids->{$oid}; # all done with this oid
338 return unless scalar(keys(%$xoids));
340 # n.b. we don't do _docids_for here, we expect the caller
341 # already checked $lse->kw_changed before calling this sub
343 return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
345 my ($smsg, $idx) = _external_only($self, $xoids, $eml);
346 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
350 my ($self, $wait) = @_;
351 if (my $im = $self->{im}) {
352 $wait ? $im->barrier : $im->checkpoint;
354 $self->{priv_eidx}->checkpoint($wait);
359 _tail_err($self) if $self->{-err_wr};
360 my $dir = $self->{priv_eidx}->{topdir};
361 return unless -e $dir;
362 my $old = delete $self->{-tmp_err};
363 my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
364 my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
365 SUFFIX => '.err', DIR => $dir);
366 open STDERR, '>>', $err->filename or die "dup2: $!";
367 STDERR->autoflush(1); # shared with shard subprocesses
368 $self->{-tmp_err} = $err; # separate file description for RO access
375 if (my $im = delete($self->{im})) {
378 $err .= "import done: $@\n";
382 $self->{priv_eidx}->done; # V2Writable::done
387 sub ipc_atfork_child {
389 my $lei = $self->{lei};
390 $lei->_lei_atfork_child(1) if $lei;
392 if (my $err = delete($self->{err_pipe})) {
394 $self->{-err_wr} = $err->[1];
396 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
397 $self->SUPER::ipc_atfork_child;
401 my ($self, $lei) = @_;
402 unless ($self->{-ipc_req}) {
403 my $d = $lei->store_path;
404 $self->ipc_lock_init("$d/ipc.lock");
405 substr($d, -length('/lei/store'), 10, '');
407 unless ($lei->{oneshot}) {
408 pipe(my ($r, $w)) or die "pipe: $!";
409 $err_pipe = [ $r, $w ];
411 # Mail we import into lei are private, so headers filtered out
412 # by -mda for public mail are not appropriate
413 local @PublicInbox::MDA::BAD_HEADERS = ();
414 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
415 { lei => $lei, err_pipe => $err_pipe });
417 require PublicInbox::LeiStoreErr;
418 PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);