]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
lei forget-mail-sync: rely on lei/store process
[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 git_sha);
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) //
155                                 _lms_rw($self)->local_blob($oid, 1) // do {
156                                 warn "W: $oid (#$docid) <$mid> not found\n";
157                                 next;
158                         };
159                         local $self->{current_info} = $oid;
160                         my $x = PublicInbox::Eml->new($bref);
161                         $docids{$docid} = $docid if content_hash($x) eq $chash;
162                 }
163         }
164         sort { $a <=> $b } values %docids;
165 }
166
167 sub set_eml_vmd {
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);
173         }
174         $docids;
175 }
176
177 sub add_eml_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);
183         }
184         \@docids;
185 }
186
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);
193         }
194         \@docids;
195 }
196
197 sub _lms_rw ($) {
198         my ($self) = @_;
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);
204                 $lms->lms_begin;
205                 $lms;
206         };
207 }
208
209 sub lms_clear_src {
210         my ($self, $folder, $id) = @_;
211         _lms_rw($self)->clear_src($folder, $id);
212 }
213
214 sub lms_mv_src {
215         my ($self, $folder, $oidbin, $id, $newbn) = @_;
216         _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
217 }
218
219 sub lms_forget_folders {
220         my ($self, @folders) = @_;
221         my $lms = _lms_rw($self);
222         for my $f (@folders) { $lms->forget_folder($f) }
223 }
224
225 sub set_sync_info {
226         my ($self, $oidhex, $folder, $id) = @_;
227         _lms_rw($self)->set_src($oidhex, $folder, $id);
228 }
229
230 sub _remove_if_local { # git->cat_async arg
231         my ($bref, $oidhex, $type, $size, $self) = @_;
232         $self->{im}->remove($bref) if $bref;
233 }
234
235 sub remove_docids ($;@) {
236         my ($self, @docids) = @_;
237         my $eidx = eidx_init($self);
238         for my $docid (@docids) {
239                 $eidx->idx_shard($docid)->ipc_do('xdb_remove', $docid);
240                 $self->{oidx}->delete_by_num($docid);
241                 $self->{oidx}->{dbh}->do(<<EOF, undef, $docid);
242 DELETE FROM xref3 WHERE docid = ?
243 EOF
244         }
245 }
246
247 # remove the entire message from the index, does not touch mail_sync.sqlite3
248 sub remove_eml {
249         my ($self, $eml) = @_;
250         my $im = $self->importer; # may create new epoch
251         my ($eidx, $tl) = eidx_init($self);
252         my $oidx = $eidx->{oidx};
253         my @docids = _docids_for($self, $eml);
254         my $git = $eidx->git;
255         for my $docid (@docids) {
256                 my $xr3 = $oidx->get_xref3($docid, 1);
257                 for my $row (@$xr3) {
258                         my (undef, undef, $oidbin) = @$row;
259                         my $oidhex = unpack('H*', $oidbin);
260                         $git->cat_async($oidhex, \&_remove_if_local, $self);
261                 }
262         }
263         $git->cat_async_wait;
264         remove_docids($self, @docids);
265         \@docids;
266 }
267
268 sub oid2docid ($$) {
269         my ($self, $oid) = @_;
270         my $eidx = eidx_init($self);
271         my ($docid, @cull) = $eidx->{oidx}->blob_exists($oid);
272         if (@cull) { # fixup old bugs...
273                 warn <<EOF;
274 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
275 EOF
276                 remove_docids($self, @cull);
277         }
278         $docid;
279 }
280
281 sub add_eml {
282         my ($self, $eml, $vmd, $xoids) = @_;
283         my $im = $self->{-fake_im} // $self->importer; # may create new epoch
284         my ($eidx, $tl) = eidx_init($self);
285         my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
286         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
287         $smsg->{-eidx_git} = $eidx->git if !$self->{-fake_im};
288         my $im_mark = $im->add($eml, undef, $smsg);
289         if ($vmd && $vmd->{sync_info}) {
290                 set_sync_info($self, $smsg->{blob}, @{$vmd->{sync_info}});
291         }
292         $im_mark or return; # duplicate blob returns undef
293
294         local $self->{current_info} = $smsg->{blob};
295         my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
296         if ($xoids) { # fuzzy matches from externals in ale->xoids_for
297                 delete $xoids->{$smsg->{blob}}; # added later
298                 if (scalar keys %$xoids) {
299                         my %docids = map { $_ => 1 } @$vivify_xvmd;
300                         for my $oid (keys %$xoids) {
301                                 my $docid = oid2docid($self, $oid);
302                                 $docids{$docid} = $docid if defined($docid);
303                         }
304                         @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
305                 }
306         }
307         if (@$vivify_xvmd) {
308                 $xoids //= {};
309                 $xoids->{$smsg->{blob}} = 1;
310                 for my $docid (@$vivify_xvmd) {
311                         my $cur = $oidx->get_art($docid);
312                         my $idx = $eidx->idx_shard($docid);
313                         if (!$cur || $cur->{bytes} == 0) { # really vivifying
314                                 $smsg->{num} = $docid;
315                                 $oidx->add_overview($eml, $smsg);
316                                 $smsg->{-merge_vmd} = 1;
317                                 $idx->index_eml($eml, $smsg);
318                         } else { # lse fuzzy hit off ale
319                                 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
320                         }
321                         for my $oid (keys %$xoids) {
322                                 $oidx->add_xref3($docid, -1, $oid, '.');
323                         }
324                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
325                 }
326                 $vivify_xvmd;
327         } elsif (my @docids = _docids_for($self, $eml)) {
328                 # fuzzy match from within lei/store
329                 for my $docid (@docids) {
330                         my $idx = $eidx->idx_shard($docid);
331                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
332                         # add_eidx_info for List-Id
333                         $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
334                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
335                 }
336                 \@docids;
337         } else { # totally new message
338                 delete $smsg->{-oidx}; # for IPC-friendliness
339                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
340                 $oidx->add_overview($eml, $smsg);
341                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
342                 my $idx = $eidx->idx_shard($smsg->{num});
343                 $idx->index_eml($eml, $smsg);
344                 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
345                 $smsg;
346         }
347 }
348
349 sub set_eml {
350         my ($self, $eml, $vmd, $xoids) = @_;
351         add_eml($self, $eml, $vmd, $xoids) //
352                 set_eml_vmd($self, $eml, $vmd);
353 }
354
355 sub index_eml_only {
356         my ($self, $eml, $vmd, $xoids) = @_;
357         require PublicInbox::FakeImport;
358         local $self->{-fake_im} = PublicInbox::FakeImport->new;
359         set_eml($self, $eml, $vmd, $xoids);
360 }
361
362 sub _external_only ($$$) {
363         my ($self, $xoids, $eml) = @_;
364         my $eidx = $self->{priv_eidx};
365         my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
366         my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
367         $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
368         # save space for an externals-only message
369         my $hdr = $eml->header_obj;
370         $smsg->populate($hdr); # sets lines == 0
371         $smsg->{bytes} = 0;
372         delete @$smsg{qw(From Subject)};
373         $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
374         $oidx->add_overview($hdr, $smsg); # subject+references for threading
375         $smsg->{subject} = '';
376         for my $oid (keys %$xoids) {
377                 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
378         }
379         my $idx = $eidx->idx_shard($smsg->{num});
380         $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
381         ($smsg, $idx);
382 }
383
384 sub update_xvmd {
385         my ($self, $xoids, $eml, $vmd_mod) = @_;
386         my ($eidx, $tl) = eidx_init($self);
387         my $oidx = $eidx->{oidx};
388         my %seen;
389         for my $oid (keys %$xoids) {
390                 my $docid = oid2docid($self, $oid) // next;
391                 delete $xoids->{$oid};
392                 next if $seen{$docid}++;
393                 my $idx = $eidx->idx_shard($docid);
394                 $idx->ipc_do('update_vmd', $docid, $vmd_mod);
395         }
396         return unless scalar(keys(%$xoids));
397
398         # see if it was indexed, but with different OID(s)
399         if (my @docids = _docids_for($self, $eml)) {
400                 for my $docid (@docids) {
401                         next if $seen{$docid};
402                         for my $oid (keys %$xoids) {
403                                 $oidx->add_xref3($docid, -1, $oid, '.');
404                         }
405                         my $idx = $eidx->idx_shard($docid);
406                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
407                 }
408                 return;
409         }
410         # totally unseen
411         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
412         $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
413 }
414
415 # set or update keywords for external message, called via ipc_do
416 sub set_xvmd {
417         my ($self, $xoids, $eml, $vmd) = @_;
418
419         my ($eidx, $tl) = eidx_init($self);
420         my $oidx = $eidx->{oidx};
421         my %seen;
422
423         # see if we can just update existing docs
424         for my $oid (keys %$xoids) {
425                 my $docid = oid2docid($self, $oid) // next;
426                 delete $xoids->{$oid}; # all done with this oid
427                 next if $seen{$docid}++;
428                 my $idx = $eidx->idx_shard($docid);
429                 $idx->ipc_do('set_vmd', $docid, $vmd);
430         }
431         return unless scalar(keys(%$xoids));
432
433         # n.b. we don't do _docids_for here, we expect the caller
434         # already checked $lse->kw_changed before calling this sub
435
436         return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
437         # totally unseen:
438         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
439         $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
440 }
441
442 sub checkpoint {
443         my ($self, $wait) = @_;
444         if (my $im = $self->{im}) {
445                 $wait ? $im->barrier : $im->checkpoint;
446         }
447         if (my $lms = delete $self->{lms}) {
448                 $lms->lms_commit;
449         }
450         $self->{priv_eidx}->checkpoint($wait);
451 }
452
453 sub xchg_stderr {
454         my ($self) = @_;
455         _tail_err($self) if $self->{-err_wr};
456         my $dir = $self->{priv_eidx}->{topdir};
457         return unless -e $dir;
458         my $old = delete $self->{-tmp_err};
459         my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
460         my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
461                                 SUFFIX => '.err', DIR => $dir);
462         open STDERR, '>>', $err->filename or die "dup2: $!";
463         STDERR->autoflush(1); # shared with shard subprocesses
464         $self->{-tmp_err} = $err; # separate file description for RO access
465         undef;
466 }
467
468 sub done {
469         my ($self) = @_;
470         my $err = '';
471         if (my $im = delete($self->{im})) {
472                 eval { $im->done };
473                 if ($@) {
474                         $err .= "import done: $@\n";
475                         warn $err;
476                 }
477         }
478         if (my $lms = delete $self->{lms}) {
479                 $lms->lms_commit;
480         }
481         $self->{priv_eidx}->done; # V2Writable::done
482         xchg_stderr($self);
483         die $err if $err;
484 }
485
486 sub ipc_atfork_child {
487         my ($self) = @_;
488         my $lei = $self->{lei};
489         $lei->_lei_atfork_child(1) if $lei;
490         xchg_stderr($self);
491         if (my $err = delete($self->{err_pipe})) {
492                 close $err->[0];
493                 $self->{-err_wr} = $err->[1];
494         }
495         $self->SUPER::ipc_atfork_child;
496 }
497
498 sub write_prepare {
499         my ($self, $lei) = @_;
500         unless ($self->{-ipc_req}) {
501                 my $d = $lei->store_path;
502                 $self->ipc_lock_init("$d/ipc.lock");
503                 substr($d, -length('/lei/store'), 10, '');
504                 pipe(my ($r, $w)) or die "pipe: $!";
505                 my $err_pipe = [ $r, $w ];
506                 # Mail we import into lei are private, so headers filtered out
507                 # by -mda for public mail are not appropriate
508                 local @PublicInbox::MDA::BAD_HEADERS = ();
509                 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
510                                         { lei => $lei, err_pipe => $err_pipe });
511                 require PublicInbox::LeiStoreErr;
512                 PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);
513         }
514         $lei->{sto} = $self;
515 }
516
517 # TODO: support SHA-256
518 sub git_blob_id { # called via LEI->git_blob_id
519         my ($self, $eml) = @_;
520         $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
521         git_sha(1, $eml)->hexdigest;
522 }
523
524 1;