]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
0fa2d3c08ba901e12f0900786f6bd9a3fab18e9d
[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 use IO::Handle (); # ->autoflush
32
33 sub new {
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};
38         $self;
39 }
40
41 sub git { $_[0]->{priv_eidx}->git } # read-only
42
43 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
44
45 sub rotate_bytes {
46         $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
47 }
48
49 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
50
51 sub git_epoch_max  {
52         my ($self) = @_;
53         if (opendir(my $dh, $self->git_pfx)) {
54                 max(map {
55                         substr($_, 0, -4) + 0; # drop ".git" suffix
56                 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
57         } else {
58                 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
59         }
60 }
61
62 sub git_ident ($) {
63         my ($git) = @_;
64         my $rdr = {};
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\-\.\+]+)/);
70         $user //= 'lei-user';
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")
77 }
78
79 sub importer {
80         my ($self) = @_;
81         my $max;
82         my $im = $self->{im};
83         if ($im) {
84                 return $im if $im->{bytes_added} < $self->rotate_bytes;
85
86                 delete $self->{im};
87                 $im->done;
88                 undef $im;
89                 $self->checkpoint;
90                 $max = $self->git_epoch_max + 1;
91         }
92         my (undef, $tl) = eidx_init($self); # acquire lock
93         my $pfx = $self->git_pfx;
94         $max //= $self->git_epoch_max;
95         while (1) {
96                 my $latest = "$pfx/$max.git";
97                 my $old = -e $latest;
98                 PublicInbox::Import::init_bare($latest);
99                 my $git = PublicInbox::Git->new($latest);
100                 if (!$old) {
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);
105                 }
106                 my $packed_bytes = $git->packed_bytes;
107                 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
108                 if ($unpacked_bytes >= $self->rotate_bytes) {
109                         $max++;
110                         next;
111                 }
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';
117                 return $im;
118         }
119 }
120
121 sub search {
122         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
123 }
124
125 # follows the stderr file
126 sub _tail_err {
127         my ($self) = @_;
128         print { $self->{-err_wr} } readline($self->{-tmp_err});
129 }
130
131 sub eidx_init {
132         my ($self) = @_;
133         my $eidx = $self->{priv_eidx};
134         my $tl = wantarray && $self->{-err_wr} ?
135                         PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
136                         undef;
137         $eidx->idx_init({-private => 1}); # acquires lock
138         wantarray ? ($eidx, $tl) : $eidx;
139 }
140
141 sub _docids_for ($$) {
142         my ($self, $eml) = @_;
143         my %docids;
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) {
149                 my ($id, $prev);
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";
158                                 next;
159                         };
160                         local $self->{current_info} = $oid;
161                         my $x = PublicInbox::Eml->new($bref);
162                         $docids{$docid} = $docid if content_hash($x) eq $chash;
163                 }
164         }
165         sort { $a <=> $b } values %docids;
166 }
167
168 sub set_eml_vmd {
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);
174         }
175         $docids;
176 }
177
178 sub add_eml_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);
184         }
185         \@docids;
186 }
187
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);
194         }
195         \@docids;
196 }
197
198 sub _lms_rw ($) {
199         my ($self) = @_;
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);
205                 $lms->lms_write_prepare;
206                 $lms;
207         };
208 }
209
210 sub lms_clear_src {
211         my ($self, $folder, $id) = @_;
212         _lms_rw($self)->clear_src($folder, $id);
213 }
214
215 sub lms_mv_src {
216         my ($self, $folder, $oidbin, $id, $newbn) = @_;
217         _lms_rw($self)->mv_src($folder, $oidbin, $id, $newbn);
218 }
219
220 sub lms_forget_folders {
221         my ($self, @folders) = @_;
222         my $lms = _lms_rw($self);
223         for my $f (@folders) { $lms->forget_folder($f) }
224 }
225
226 sub lms_rename_folder {
227         my ($self, $old, $new) = @_;
228         _lms_rw($self)->rename_folder($old, $new);
229 }
230
231 sub set_sync_info {
232         my ($self, $oidhex, $folder, $id) = @_;
233         _lms_rw($self)->set_src(pack('H*', $oidhex), $folder, $id);
234 }
235
236 sub _remove_if_local { # git->cat_async arg
237         my ($bref, $oidhex, $type, $size, $self) = @_;
238         $self->{im}->remove($bref) if $bref;
239 }
240
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 = ?
249 EOF
250         }
251 }
252
253 # remove the entire message from the index, does not touch mail_sync.sqlite3
254 sub remove_eml {
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);
267                 }
268         }
269         $git->cat_async_wait;
270         remove_docids($self, @docids);
271         \@docids;
272 }
273
274 sub oid2docid ($$) {
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...
279                 warn <<EOF;
280 W: $oid indexed as multiple docids: $docid @cull, culling to fixup old bugs
281 EOF
282                 remove_docids($self, @cull);
283         }
284         $docid;
285 }
286
287 sub add_eml {
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}});
297         }
298         $im_mark or return; # duplicate blob returns undef
299
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);
309                         }
310                         @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
311                 }
312         }
313         if (@$vivify_xvmd) {
314                 $xoids //= {};
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);
326                         }
327                         for my $oid (keys %$xoids) {
328                                 $oidx->add_xref3($docid, -1, $oid, '.');
329                         }
330                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
331                 }
332                 $vivify_xvmd;
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;
341                 }
342                 \@docids;
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;
351                 $smsg;
352         }
353 }
354
355 sub set_eml {
356         my ($self, $eml, $vmd, $xoids) = @_;
357         add_eml($self, $eml, $vmd, $xoids) //
358                 set_eml_vmd($self, $eml, $vmd);
359 }
360
361 sub index_eml_only {
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);
366 }
367
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
377         $smsg->{bytes} = 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, '.');
384         }
385         my $idx = $eidx->idx_shard($smsg->{num});
386         $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
387         ($smsg, $idx);
388 }
389
390 sub update_xvmd {
391         my ($self, $xoids, $eml, $vmd_mod) = @_;
392         my ($eidx, $tl) = eidx_init($self);
393         my $oidx = $eidx->{oidx};
394         my %seen;
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);
401         }
402         return unless scalar(keys(%$xoids));
403
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, '.');
410                         }
411                         my $idx = $eidx->idx_shard($docid);
412                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
413                 }
414                 return;
415         }
416         # totally unseen
417         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
418         $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
419 }
420
421 # set or update keywords for external message, called via ipc_do
422 sub set_xvmd {
423         my ($self, $xoids, $eml, $vmd) = @_;
424
425         my ($eidx, $tl) = eidx_init($self);
426         my $oidx = $eidx->{oidx};
427         my %seen;
428
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);
436         }
437         return unless scalar(keys(%$xoids));
438
439         # n.b. we don't do _docids_for here, we expect the caller
440         # already checked $lse->kw_changed before calling this sub
441
442         return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
443         # totally unseen:
444         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
445         $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
446 }
447
448 sub checkpoint {
449         my ($self, $wait) = @_;
450         if (my $im = $self->{im}) {
451                 $wait ? $im->barrier : $im->checkpoint;
452         }
453         delete $self->{lms};
454         $self->{priv_eidx}->checkpoint($wait);
455 }
456
457 sub xchg_stderr {
458         my ($self) = @_;
459         _tail_err($self) if $self->{-err_wr};
460         my $dir = $self->{priv_eidx}->{topdir};
461         return unless -e $dir;
462         my $old = delete $self->{-tmp_err};
463         my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
464         my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
465                                 SUFFIX => '.err', DIR => $dir);
466         open STDERR, '>>', $err->filename or die "dup2: $!";
467         STDERR->autoflush(1); # shared with shard subprocesses
468         $self->{-tmp_err} = $err; # separate file description for RO access
469         undef;
470 }
471
472 sub done {
473         my ($self, $sock_ref) = @_;
474         my $err = '';
475         if (my $im = delete($self->{im})) {
476                 eval { $im->done };
477                 if ($@) {
478                         $err .= "import done: $@\n";
479                         warn $err;
480                 }
481         }
482         delete $self->{lms};
483         $self->{priv_eidx}->done; # V2Writable::done
484         xchg_stderr($self);
485         die $err if $err;
486
487         # notify clients ->done has been issued
488         defined($sock_ref) and
489                 $self->{s2d_op_p}->pkt_do('sto_done_complete', $sock_ref);
490 }
491
492 sub ipc_atfork_child {
493         my ($self) = @_;
494         my $lei = $self->{lei};
495         $lei->_lei_atfork_child(1) if $lei;
496         xchg_stderr($self);
497         if (my $to_close = delete($self->{to_close})) {
498                 close($_) for @$to_close;
499         }
500         $self->SUPER::ipc_atfork_child;
501 }
502
503 sub write_prepare {
504         my ($self, $lei) = @_;
505         $lei // die 'BUG: $lei not passed';
506         unless ($self->{-ipc_req}) {
507                 # s2d => store-to-daemon messages
508                 require PublicInbox::PktOp;
509                 my ($s2d_op_c, $s2d_op_p) = PublicInbox::PktOp->pair;
510                 my $dir = $lei->store_path;
511                 $self->ipc_lock_init("$dir/ipc.lock");
512                 substr($dir, -length('/lei/store'), 10, '');
513                 pipe(my ($r, $w)) or die "pipe: $!";
514                 $w->autoflush(1);
515                 # Mail we import into lei are private, so headers filtered out
516                 # by -mda for public mail are not appropriate
517                 local @PublicInbox::MDA::BAD_HEADERS = ();
518                 $self->ipc_worker_spawn("lei/store $dir", $lei->oldset, {
519                                         lei => $lei,
520                                         -err_wr => $w,
521                                         to_close => [ $r, $s2d_op_c->{sock} ],
522                                         s2d_op_p => $s2d_op_p,
523                                 });
524                 require PublicInbox::LeiStoreErr;
525                 PublicInbox::LeiStoreErr->new($r, $lei);
526                 $s2d_op_c->{ops} = {
527                         sto_done_complete => [ $lei->can('sto_done_complete') ]
528                 };
529         }
530         $lei->{sto} = $self;
531 }
532
533 # TODO: support SHA-256
534 sub git_blob_id { # called via LEI->git_blob_id
535         my ($self, $eml) = @_;
536         $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
537         git_sha(1, $eml)->hexdigest;
538 }
539
540 # called by lei-daemon before lei->refresh_watches
541 sub add_sync_folders {
542         my ($self, @folders) = @_;
543         my $lms = _lms_rw($self);
544         for my $f (@folders) { $lms->fid_for($f, 1) }
545 }
546
547 1;