]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
af5edbc24732817eb3b2dcfd51b4d9da2dacc17d
[public-inbox.git] / lib / PublicInbox / LeiStore.pm
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>
3 #
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)
7 #
8 # for xref3, the following are constant: $eidx_key = '.', $xnum = -1
9 #
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
13 # lei WQ workers.
14 package PublicInbox::LeiStore;
15 use strict;
16 use v5.10.1;
17 use parent qw(PublicInbox::Lock PublicInbox::IPC);
18 use PublicInbox::ExtSearchIdx;
19 use PublicInbox::Eml;
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;
26 use PublicInbox::MDA;
27 use PublicInbox::Spawn qw(spawn);
28 use List::Util qw(max);
29 use File::Temp ();
30 use POSIX ();
31
32 sub new {
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};
37         $self;
38 }
39
40 sub git { $_[0]->{priv_eidx}->git } # read-only
41
42 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
43
44 sub rotate_bytes {
45         $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
46 }
47
48 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
49
50 sub git_epoch_max  {
51         my ($self) = @_;
52         if (opendir(my $dh, $self->git_pfx)) {
53                 max(map {
54                         substr($_, 0, -4) + 0; # drop ".git" suffix
55                 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
56         } else {
57                 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
58         }
59 }
60
61 sub git_ident ($) {
62         my ($git) = @_;
63         my $rdr = {};
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\-\.\+]+)/);
69         $user //= 'lei-user';
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")
76 }
77
78 sub importer {
79         my ($self) = @_;
80         my $max;
81         my $im = $self->{im};
82         if ($im) {
83                 return $im if $im->{bytes_added} < $self->rotate_bytes;
84
85                 delete $self->{im};
86                 $im->done;
87                 undef $im;
88                 $self->checkpoint;
89                 $max = $self->git_epoch_max + 1;
90         }
91         my (undef, $tl) = eidx_init($self); # acquire lock
92         my $pfx = $self->git_pfx;
93         $max //= $self->git_epoch_max;
94         while (1) {
95                 my $latest = "$pfx/$max.git";
96                 my $old = -e $latest;
97                 PublicInbox::Import::init_bare($latest);
98                 my $git = PublicInbox::Git->new($latest);
99                 if (!$old) {
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);
104                 }
105                 my $packed_bytes = $git->packed_bytes;
106                 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
107                 if ($unpacked_bytes >= $self->rotate_bytes) {
108                         $max++;
109                         next;
110                 }
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';
116                 return $im;
117         }
118 }
119
120 sub search {
121         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
122 }
123
124 # follows the stderr file
125 sub _tail_err {
126         my ($self) = @_;
127         print { $self->{-err_wr} } readline($self->{-tmp_err});
128 }
129
130 sub eidx_init {
131         my ($self) = @_;
132         my $eidx = $self->{priv_eidx};
133         my $tl = wantarray && $self->{-err_wr} ?
134                         PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
135                         undef;
136         $eidx->idx_init({-private => 1}); # acquires lock
137         wantarray ? ($eidx, $tl) : $eidx;
138 }
139
140 sub _docids_for ($$) {
141         my ($self, $eml) = @_;
142         my %docids;
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) {
148                 my ($id, $prev);
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";
156                                 next;
157                         };
158                         local $self->{current_info} = $oid;
159                         my $x = PublicInbox::Eml->new($bref);
160                         $docids{$docid} = $docid if content_hash($x) eq $chash;
161                 }
162         }
163         sort { $a <=> $b } values %docids;
164 }
165
166 sub set_eml_vmd {
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);
172         }
173         $docids;
174 }
175
176 sub add_eml_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);
182         }
183         \@docids;
184 }
185
186 sub remove_eml_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);
192         }
193         \@docids;
194 }
195
196 sub set_sync_info {
197         my ($self, $oidhex, $folder, $id) = @_;
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);
202                 $lms->lms_begin;
203                 $lms;
204         })->set_src($oidhex, $folder, $id);
205 }
206
207 sub add_eml {
208         my ($self, $eml, $vmd, $xoids) = @_;
209         my $im = $self->{-fake_im} // $self->importer; # may create new epoch
210         my ($eidx, $tl) = eidx_init($self);
211         my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
212         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
213         $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
214         my $im_mark = $im->add($eml, undef, $smsg);
215         if ($vmd && $vmd->{sync_info}) {
216                 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
217         }
218         $im_mark or return; # duplicate blob returns undef
219
220         local $self->{current_info} = $smsg->{blob};
221         my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
222         if ($xoids) { # fuzzy matches from externals in ale->xoids_for
223                 delete $xoids->{$smsg->{blob}}; # added later
224                 if (scalar keys %$xoids) {
225                         my %docids = map { $_ => 1 } @$vivify_xvmd;
226                         for my $oid (keys %$xoids) {
227                                 my @id = $oidx->blob_exists($oid);
228                                 @docids{@id} = @id;
229                         }
230                         @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
231                 }
232         }
233         if (@$vivify_xvmd) {
234                 $xoids //= {};
235                 $xoids->{$smsg->{blob}} = 1;
236                 for my $docid (@$vivify_xvmd) {
237                         my $cur = $oidx->get_art($docid);
238                         my $idx = $eidx->idx_shard($docid);
239                         if (!$cur || $cur->{bytes} == 0) { # really vivifying
240                                 $smsg->{num} = $docid;
241                                 $oidx->add_overview($eml, $smsg);
242                                 $smsg->{-merge_vmd} = 1;
243                                 $idx->index_eml($eml, $smsg);
244                         } else { # lse fuzzy hit off ale
245                                 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
246                         }
247                         for my $oid (keys %$xoids) {
248                                 $oidx->add_xref3($docid, -1, $oid, '.');
249                         }
250                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
251                 }
252                 $vivify_xvmd;
253         } elsif (my @docids = _docids_for($self, $eml)) {
254                 # fuzzy match from within lei/store
255                 for my $docid (@docids) {
256                         my $idx = $eidx->idx_shard($docid);
257                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
258                         # add_eidx_info for List-Id
259                         $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
260                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
261                 }
262                 \@docids;
263         } else { # totally new message
264                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
265                 $oidx->add_overview($eml, $smsg);
266                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
267                 my $idx = $eidx->idx_shard($smsg->{num});
268                 $idx->index_eml($eml, $smsg);
269                 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
270                 $smsg;
271         }
272 }
273
274 sub set_eml {
275         my ($self, $eml, $vmd, $xoids) = @_;
276         add_eml($self, $eml, $vmd, $xoids) //
277                 set_eml_vmd($self, $eml, $vmd);
278 }
279
280 sub index_eml_only {
281         my ($self, $eml, $vmd, $xoids) = @_;
282         require PublicInbox::FakeImport;
283         local $self->{-fake_im} = PublicInbox::FakeImport->new;
284         set_eml($self, $eml, $vmd, $xoids);
285 }
286
287 sub _external_only ($$$) {
288         my ($self, $xoids, $eml) = @_;
289         my $eidx = $self->{priv_eidx};
290         my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
291         my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
292         $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
293         # save space for an externals-only message
294         my $hdr = $eml->header_obj;
295         $smsg->populate($hdr); # sets lines == 0
296         $smsg->{bytes} = 0;
297         delete @$smsg{qw(From Subject)};
298         $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
299         $oidx->add_overview($hdr, $smsg); # subject+references for threading
300         $smsg->{subject} = '';
301         for my $oid (keys %$xoids) {
302                 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
303         }
304         my $idx = $eidx->idx_shard($smsg->{num});
305         $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
306         ($smsg, $idx);
307 }
308
309 sub update_xvmd {
310         my ($self, $xoids, $eml, $vmd_mod) = @_;
311         my ($eidx, $tl) = eidx_init($self);
312         my $oidx = $eidx->{oidx};
313         my %seen;
314         for my $oid (keys %$xoids) {
315                 my @docids = $oidx->blob_exists($oid) or next;
316                 scalar(@docids) > 1 and
317                         warn "W: $oid indexed as multiple docids: @docids\n";
318                 for my $docid (@docids) {
319                         next if $seen{$docid}++;
320                         my $idx = $eidx->idx_shard($docid);
321                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
322                 }
323                 delete $xoids->{$oid};
324         }
325         return unless scalar(keys(%$xoids));
326
327         # see if it was indexed, but with different OID(s)
328         if (my @docids = _docids_for($self, $eml)) {
329                 for my $docid (@docids) {
330                         next if $seen{$docid};
331                         for my $oid (keys %$xoids) {
332                                 $oidx->add_xref3($docid, -1, $oid, '.');
333                         }
334                         my $idx = $eidx->idx_shard($docid);
335                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
336                 }
337                 return;
338         }
339         # totally unseen
340         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
341         $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
342 }
343
344 # set or update keywords for external message, called via ipc_do
345 sub set_xvmd {
346         my ($self, $xoids, $eml, $vmd) = @_;
347
348         my ($eidx, $tl) = eidx_init($self);
349         my $oidx = $eidx->{oidx};
350         my %seen;
351
352         # see if we can just update existing docs
353         for my $oid (keys %$xoids) {
354                 my @docids = $oidx->blob_exists($oid) or next;
355                 scalar(@docids) > 1 and
356                         warn "W: $oid indexed as multiple docids: @docids\n";
357                 for my $docid (@docids) {
358                         next if $seen{$docid}++;
359                         my $idx = $eidx->idx_shard($docid);
360                         $idx->ipc_do('set_vmd', $docid, $vmd);
361                 }
362                 delete $xoids->{$oid}; # all done with this oid
363         }
364         return unless scalar(keys(%$xoids));
365
366         # n.b. we don't do _docids_for here, we expect the caller
367         # already checked $lse->kw_changed before calling this sub
368
369         return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
370         # totally unseen:
371         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
372         $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
373 }
374
375 sub checkpoint {
376         my ($self, $wait) = @_;
377         if (my $im = $self->{im}) {
378                 $wait ? $im->barrier : $im->checkpoint;
379         }
380         $self->{priv_eidx}->checkpoint($wait);
381 }
382
383 sub xchg_stderr {
384         my ($self) = @_;
385         _tail_err($self) if $self->{-err_wr};
386         my $dir = $self->{priv_eidx}->{topdir};
387         return unless -e $dir;
388         my $old = delete $self->{-tmp_err};
389         my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
390         my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
391                                 SUFFIX => '.err', DIR => $dir);
392         open STDERR, '>>', $err->filename or die "dup2: $!";
393         STDERR->autoflush(1); # shared with shard subprocesses
394         $self->{-tmp_err} = $err; # separate file description for RO access
395         undef;
396 }
397
398 sub done {
399         my ($self) = @_;
400         my $err = '';
401         if (my $im = delete($self->{im})) {
402                 eval { $im->done };
403                 if ($@) {
404                         $err .= "import done: $@\n";
405                         warn $err;
406                 }
407         }
408         if (my $lms = delete $self->{lms}) {
409                 $lms->lms_commit;
410         }
411         $self->{priv_eidx}->done; # V2Writable::done
412         xchg_stderr($self);
413         die $err if $err;
414 }
415
416 sub ipc_atfork_child {
417         my ($self) = @_;
418         my $lei = $self->{lei};
419         $lei->_lei_atfork_child(1) if $lei;
420         xchg_stderr($self);
421         if (my $err = delete($self->{err_pipe})) {
422                 close $err->[0];
423                 $self->{-err_wr} = $err->[1];
424         }
425         $self->SUPER::ipc_atfork_child;
426 }
427
428 sub write_prepare {
429         my ($self, $lei) = @_;
430         unless ($self->{-ipc_req}) {
431                 my $d = $lei->store_path;
432                 $self->ipc_lock_init("$d/ipc.lock");
433                 substr($d, -length('/lei/store'), 10, '');
434                 pipe(my ($r, $w)) or die "pipe: $!";
435                 my $err_pipe = [ $r, $w ];
436                 # Mail we import into lei are private, so headers filtered out
437                 # by -mda for public mail are not appropriate
438                 local @PublicInbox::MDA::BAD_HEADERS = ();
439                 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
440                                         { lei => $lei, err_pipe => $err_pipe });
441                 require PublicInbox::LeiStoreErr;
442                 PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);
443         }
444         $lei->{sto} = $self;
445 }
446
447 1;