]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
lei: quiet down Eml-related warnings consistently
[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 $pfx = $self->git_pfx;
92         $max //= $self->git_epoch_max;
93         while (1) {
94                 my $latest = "$pfx/$max.git";
95                 my $old = -e $latest;
96                 PublicInbox::Import::init_bare($latest);
97                 my $git = PublicInbox::Git->new($latest);
98                 if (!$old) {
99                         $git->qx(qw(config core.sharedRepository 0600));
100                         $self->done; # force eidx_init on next round
101                 }
102                 my $packed_bytes = $git->packed_bytes;
103                 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
104                 if ($unpacked_bytes >= $self->rotate_bytes) {
105                         $max++;
106                         next;
107                 }
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';
113                 return $im;
114         }
115 }
116
117 sub search {
118         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
119 }
120
121 # follows the stderr file
122 sub _tail_err {
123         my ($self) = @_;
124         print { $self->{-err_wr} } readline($self->{-tmp_err});
125 }
126
127 sub eidx_init {
128         my ($self) = @_;
129         my $eidx = $self->{priv_eidx};
130         my $tl = wantarray && $self->{-err_wr} ?
131                         PublicInbox::OnDestroy->new($$, \&_tail_err, $self) :
132                         undef;
133         $eidx->idx_init({-private => 1});
134         wantarray ? ($eidx, $tl) : $eidx;
135 }
136
137 sub _docids_for ($$) {
138         my ($self, $eml) = @_;
139         my %docids;
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) {
145                 my ($id, $prev);
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";
153                                 next;
154                         };
155                         local $self->{current_info} = $oid;
156                         my $x = PublicInbox::Eml->new($bref);
157                         $docids{$docid} = $docid if content_hash($x) eq $chash;
158                 }
159         }
160         sort { $a <=> $b } values %docids;
161 }
162
163 sub set_eml_vmd {
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);
169         }
170         $docids;
171 }
172
173 sub add_eml_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);
179         }
180         \@docids;
181 }
182
183 sub remove_eml_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);
189         }
190         \@docids;
191 }
192
193 sub set_sync_info ($$$) {
194         my ($self, $oidhex, $sync_info) = @_;
195         ($self->{lms} //= do {
196                 require PublicInbox::LeiMailSync;
197                 my $f = "$self->{priv_eidx}->{topdir}/mail_sync.sqlite3";
198                 my $lms = PublicInbox::LeiMailSync->new($f);
199                 $lms->lms_begin;
200                 $lms;
201         })->set_src($oidhex, @$sync_info);
202 }
203
204 sub add_eml {
205         my ($self, $eml, $vmd, $xoids) = @_;
206         my $im = $self->importer; # may create new epoch
207         my ($eidx, $tl) = eidx_init($self); # updates/writes alternates file
208         my $oidx = $eidx->{oidx}; # PublicInbox::Import::add checks this
209         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
210         my $im_mark = $im->add($eml, undef, $smsg);
211         if ($vmd && $vmd->{sync_info}) {
212                 set_sync_info($self, $smsg->{blob}, $vmd->{sync_info});
213         }
214         $im_mark or return; # duplicate blob returns undef
215
216         local $self->{current_info} = $smsg->{blob};
217         my $vivify_xvmd = delete($smsg->{-vivify_xvmd}) // []; # exact matches
218         if ($xoids) { # fuzzy matches from externals in ale->xoids_for
219                 delete $xoids->{$smsg->{blob}}; # added later
220                 if (scalar keys %$xoids) {
221                         my %docids = map { $_ => 1 } @$vivify_xvmd;
222                         for my $oid (keys %$xoids) {
223                                 my @id = $oidx->blob_exists($oid);
224                                 @docids{@id} = @id;
225                         }
226                         @$vivify_xvmd = sort { $a <=> $b } keys(%docids);
227                 }
228         }
229         if (@$vivify_xvmd) {
230                 $xoids //= {};
231                 $xoids->{$smsg->{blob}} = 1;
232                 for my $docid (@$vivify_xvmd) {
233                         my $cur = $oidx->get_art($docid);
234                         my $idx = $eidx->idx_shard($docid);
235                         if (!$cur || $cur->{bytes} == 0) { # really vivifying
236                                 $smsg->{num} = $docid;
237                                 $oidx->add_overview($eml, $smsg);
238                                 $smsg->{-merge_vmd} = 1;
239                                 $idx->index_eml($eml, $smsg);
240                         } else { # lse fuzzy hit off ale
241                                 $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
242                         }
243                         for my $oid (keys %$xoids) {
244                                 $oidx->add_xref3($docid, -1, $oid, '.');
245                         }
246                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
247                 }
248                 $vivify_xvmd;
249         } elsif (my @docids = _docids_for($self, $eml)) {
250                 # fuzzy match from within lei/store
251                 for my $docid (@docids) {
252                         my $idx = $eidx->idx_shard($docid);
253                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
254                         # add_eidx_info for List-Id
255                         $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
256                         $idx->ipc_do('add_vmd', $docid, $vmd) if $vmd;
257                 }
258                 \@docids;
259         } else { # totally new message
260                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
261                 $oidx->add_overview($eml, $smsg);
262                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
263                 my $idx = $eidx->idx_shard($smsg->{num});
264                 $idx->index_eml($eml, $smsg);
265                 $idx->ipc_do('add_vmd', $smsg->{num}, $vmd) if $vmd;
266                 $smsg;
267         }
268 }
269
270 sub set_eml {
271         my ($self, $eml, $vmd, $xoids) = @_;
272         add_eml($self, $eml, $vmd, $xoids) //
273                 set_eml_vmd($self, $eml, $vmd);
274 }
275
276 sub _external_only ($$$) {
277         my ($self, $xoids, $eml) = @_;
278         my $eidx = $self->{priv_eidx};
279         my $oidx = $eidx->{oidx} // die 'BUG: {oidx} missing';
280         my $smsg = bless { blob => '' }, 'PublicInbox::Smsg';
281         $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
282         # save space for an externals-only message
283         my $hdr = $eml->header_obj;
284         $smsg->populate($hdr); # sets lines == 0
285         $smsg->{bytes} = 0;
286         delete @$smsg{qw(From Subject)};
287         $smsg->{to} = $smsg->{cc} = $smsg->{from} = '';
288         $oidx->add_overview($hdr, $smsg); # subject+references for threading
289         $smsg->{subject} = '';
290         for my $oid (keys %$xoids) {
291                 $oidx->add_xref3($smsg->{num}, -1, $oid, '.');
292         }
293         my $idx = $eidx->idx_shard($smsg->{num});
294         $idx->index_eml(PublicInbox::Eml->new("\n\n"), $smsg);
295         ($smsg, $idx);
296 }
297
298 sub update_xvmd {
299         my ($self, $xoids, $eml, $vmd_mod) = @_;
300         my ($eidx, $tl) = eidx_init($self);
301         my $oidx = $eidx->{oidx};
302         my %seen;
303         for my $oid (keys %$xoids) {
304                 my @docids = $oidx->blob_exists($oid) or next;
305                 scalar(@docids) > 1 and
306                         warn "W: $oid indexed as multiple docids: @docids\n";
307                 for my $docid (@docids) {
308                         next if $seen{$docid}++;
309                         my $idx = $eidx->idx_shard($docid);
310                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
311                 }
312                 delete $xoids->{$oid};
313         }
314         return unless scalar(keys(%$xoids));
315
316         # see if it was indexed, but with different OID(s)
317         if (my @docids = _docids_for($self, $eml)) {
318                 for my $docid (@docids) {
319                         next if $seen{$docid};
320                         for my $oid (keys %$xoids) {
321                                 $oidx->add_xref3($docid, -1, $oid, '.');
322                         }
323                         my $idx = $eidx->idx_shard($docid);
324                         $idx->ipc_do('update_vmd', $docid, $vmd_mod);
325                 }
326                 return;
327         }
328         # totally unseen
329         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
330         $idx->ipc_do('update_vmd', $smsg->{num}, $vmd_mod);
331 }
332
333 # set or update keywords for external message, called via ipc_do
334 sub set_xvmd {
335         my ($self, $xoids, $eml, $vmd) = @_;
336
337         my ($eidx, $tl) = eidx_init($self);
338         my $oidx = $eidx->{oidx};
339         my %seen;
340
341         # see if we can just update existing docs
342         for my $oid (keys %$xoids) {
343                 my @docids = $oidx->blob_exists($oid) or next;
344                 scalar(@docids) > 1 and
345                         warn "W: $oid indexed as multiple docids: @docids\n";
346                 for my $docid (@docids) {
347                         next if $seen{$docid}++;
348                         my $idx = $eidx->idx_shard($docid);
349                         $idx->ipc_do('set_vmd', $docid, $vmd);
350                 }
351                 delete $xoids->{$oid}; # all done with this oid
352         }
353         return unless scalar(keys(%$xoids));
354
355         # n.b. we don't do _docids_for here, we expect the caller
356         # already checked $lse->kw_changed before calling this sub
357
358         return unless (@{$vmd->{kw} // []}) || (@{$vmd->{L} // []});
359         # totally unseen:
360         my ($smsg, $idx) = _external_only($self, $xoids, $eml);
361         $idx->ipc_do('add_vmd', $smsg->{num}, $vmd);
362 }
363
364 sub checkpoint {
365         my ($self, $wait) = @_;
366         if (my $im = $self->{im}) {
367                 $wait ? $im->barrier : $im->checkpoint;
368         }
369         $self->{priv_eidx}->checkpoint($wait);
370 }
371
372 sub xchg_stderr {
373         my ($self) = @_;
374         _tail_err($self) if $self->{-err_wr};
375         my $dir = $self->{priv_eidx}->{topdir};
376         return unless -e $dir;
377         my $old = delete $self->{-tmp_err};
378         my $pfx = POSIX::strftime('%Y%m%d%H%M%S', gmtime(time));
379         my $err = File::Temp->new(TEMPLATE => "$pfx.$$.lei_storeXXXX",
380                                 SUFFIX => '.err', DIR => $dir);
381         open STDERR, '>>', $err->filename or die "dup2: $!";
382         STDERR->autoflush(1); # shared with shard subprocesses
383         $self->{-tmp_err} = $err; # separate file description for RO access
384         undef;
385 }
386
387 sub done {
388         my ($self) = @_;
389         my $err = '';
390         if (my $im = delete($self->{im})) {
391                 eval { $im->done };
392                 if ($@) {
393                         $err .= "import done: $@\n";
394                         warn $err;
395                 }
396         }
397         if (my $lms = delete $self->{lms}) {
398                 $lms->lms_commit;
399         }
400         $self->{priv_eidx}->done; # V2Writable::done
401         xchg_stderr($self);
402         die $err if $err;
403 }
404
405 sub ipc_atfork_child {
406         my ($self) = @_;
407         my $lei = $self->{lei};
408         $lei->_lei_atfork_child(1) if $lei;
409         xchg_stderr($self);
410         if (my $err = delete($self->{err_pipe})) {
411                 close $err->[0];
412                 $self->{-err_wr} = $err->[1];
413         }
414         $self->SUPER::ipc_atfork_child;
415 }
416
417 sub write_prepare {
418         my ($self, $lei) = @_;
419         unless ($self->{-ipc_req}) {
420                 my $d = $lei->store_path;
421                 $self->ipc_lock_init("$d/ipc.lock");
422                 substr($d, -length('/lei/store'), 10, '');
423                 my $err_pipe;
424                 unless ($lei->{oneshot}) {
425                         pipe(my ($r, $w)) or die "pipe: $!";
426                         $err_pipe = [ $r, $w ];
427                 }
428                 # Mail we import into lei are private, so headers filtered out
429                 # by -mda for public mail are not appropriate
430                 local @PublicInbox::MDA::BAD_HEADERS = ();
431                 $self->ipc_worker_spawn("lei/store $d", $lei->oldset,
432                                         { lei => $lei, err_pipe => $err_pipe });
433                 if ($err_pipe) {
434                         require PublicInbox::LeiStoreErr;
435                         PublicInbox::LeiStoreErr->new($err_pipe->[0], $lei);
436                 }
437         }
438         $lei->{sto} = $self;
439 }
440
441 1;