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