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