]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
776018284b5562b8fb5af5ad0c1404e7186b8c73
[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 # based on git OID.
7 #
8 # for xref3, the following are constant: $eidx_key = '.', $xnum = -1
9 package PublicInbox::LeiStore;
10 use strict;
11 use v5.10.1;
12 use parent qw(PublicInbox::Lock PublicInbox::IPC);
13 use PublicInbox::ExtSearchIdx;
14 use PublicInbox::Import;
15 use PublicInbox::InboxWritable qw(eml_from_path);
16 use PublicInbox::V2Writable;
17 use PublicInbox::ContentHash qw(content_hash content_digest);
18 use PublicInbox::MID qw(mids mids_in);
19 use PublicInbox::LeiSearch;
20 use PublicInbox::MDA;
21 use List::Util qw(max);
22
23 sub new {
24         my (undef, $dir, $opt) = @_;
25         my $eidx = PublicInbox::ExtSearchIdx->new($dir, $opt);
26         my $self = bless { priv_eidx => $eidx }, __PACKAGE__;
27         eidx_init($self)->done if $opt->{creat};
28         $self;
29 }
30
31 sub git { $_[0]->{priv_eidx}->git } # read-only
32
33 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
34
35 sub rotate_bytes {
36         $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
37 }
38
39 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
40
41 sub git_epoch_max  {
42         my ($self) = @_;
43         if (opendir(my $dh, $self->git_pfx)) {
44                 max(map {
45                         substr($_, 0, -4) + 0; # drop ".git" suffix
46                 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
47         } else {
48                 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
49         }
50 }
51
52 sub git_ident ($) {
53         my ($git) = @_;
54         chomp(my $i = $git->qx(qw(var GIT_COMMITTER_IDENT)));
55         warn "$git->{git_dir} GIT_COMMITTER_IDENT failed\n" if $?;
56         $i =~ /\A(.+) <([^>]+)> [0-9]+ [-\+]?[0-9]+$/ ? ($1, $2) :
57                 ('lei user', 'x@example.com')
58 }
59
60 sub importer {
61         my ($self) = @_;
62         my $max;
63         my $im = $self->{im};
64         if ($im) {
65                 return $im if $im->{bytes_added} < $self->rotate_bytes;
66
67                 delete $self->{im};
68                 $im->done;
69                 undef $im;
70                 $self->checkpoint;
71                 $max = $self->git_epoch_max + 1;
72         }
73         my $pfx = $self->git_pfx;
74         $max //= $self->git_epoch_max;
75         while (1) {
76                 my $latest = "$pfx/$max.git";
77                 my $old = -e $latest;
78                 PublicInbox::Import::init_bare($latest);
79                 my $git = PublicInbox::Git->new($latest);
80                 $git->qx(qw(config core.sharedRepository 0600)) if !$old;
81                 my $packed_bytes = $git->packed_bytes;
82                 my $unpacked_bytes = $packed_bytes / $self->packing_factor;
83                 if ($unpacked_bytes >= $self->rotate_bytes) {
84                         $max++;
85                         next;
86                 }
87                 my ($n, $e) = git_ident($git);
88                 $self->{im} = $im = PublicInbox::Import->new($git, $n, $e);
89                 $im->{bytes_added} = int($packed_bytes / $self->packing_factor);
90                 $im->{lock_path} = undef;
91                 $im->{path_type} = 'v2';
92                 return $im;
93         }
94 }
95
96 sub search {
97         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
98 }
99
100 sub eidx_init {
101         my ($self) = @_;
102         my $eidx = $self->{priv_eidx};
103         $eidx->idx_init({-private => 1});
104         $eidx;
105 }
106
107 # when a message has no Message-IDs at all, this is needed for
108 # unsent Draft messages, at least
109 sub _fake_mid_for ($$) {
110         my ($eml, $dig) = @_;
111         my $mids = mids_in($eml, qw(X-Alt-Message-ID Resent-Message-ID));
112         $eml->{-lei_fake_mid} =
113                 $mids->[0] // PublicInbox::Import::digest2mid($dig, $eml);
114 }
115
116 sub _docids_for ($$) {
117         my ($self, $eml) = @_;
118         my %docids;
119         my $dig = content_digest($eml);
120         my $chash = $dig->clone->digest;
121         my $eidx = eidx_init($self);
122         my $oidx = $eidx->{oidx};
123         my $im = $self->{im};
124         my $mids = mids($eml);
125         $mids->[0] //= _fake_mid_for($eml, $dig);
126         for my $mid (@$mids) {
127                 my ($id, $prev);
128                 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
129                         my $oid = $cur->{blob};
130                         my $docid = $cur->{num};
131                         my $bref = $im ? $im->cat_blob($oid) : undef;
132                         $bref //= $eidx->git->cat_file($oid) // do {
133                                 warn "W: $oid (#$docid) <$mid> not found\n";
134                                 next;
135                         };
136                         local $self->{current_info} = $oid;
137                         my $x = PublicInbox::Eml->new($bref);
138                         $docids{$docid} = $docid if content_hash($x) eq $chash;
139                 }
140         }
141         sort { $a <=> $b } values %docids;
142 }
143
144 sub set_eml_keywords {
145         my ($self, $eml, @kw) = @_;
146         my $eidx = eidx_init($self);
147         my @docids = _docids_for($self, $eml);
148         for my $docid (@docids) {
149                 $eidx->idx_shard($docid)->ipc_do('set_keywords', $docid, @kw);
150         }
151         \@docids;
152 }
153
154 sub add_eml_keywords {
155         my ($self, $eml, @kw) = @_;
156         my $eidx = eidx_init($self);
157         my @docids = _docids_for($self, $eml);
158         for my $docid (@docids) {
159                 $eidx->idx_shard($docid)->ipc_do('add_keywords', $docid, @kw);
160         }
161         \@docids;
162 }
163
164 sub remove_eml_keywords {
165         my ($self, $eml, @kw) = @_;
166         my $eidx = eidx_init($self);
167         my @docids = _docids_for($self, $eml);
168         for my $docid (@docids) {
169                 $eidx->idx_shard($docid)->ipc_do('remove_keywords', $docid, @kw)
170         }
171         \@docids;
172 }
173
174 # cf: https://doc.dovecot.org/configuration_manual/mail_location/mbox/
175 my %status2kw = (F => 'flagged', A => 'answered', R => 'seen', T => 'draft');
176 # O (old/non-recent), and D (deleted) aren't in JMAP,
177 # so probably won't be supported by us.
178 sub mbox_keywords {
179         my $eml = $_[-1];
180         my $s = "@{[$eml->header_raw('X-Status'),$eml->header_raw('Status')]}";
181         my %kw;
182         $s =~ s/([FART])/$kw{$status2kw{$1}} = 1/sge;
183         sort(keys %kw);
184 }
185
186 # cf: https://cr.yp.to/proto/maildir.html
187 my %c2kw = ('D' => 'draft', F => 'flagged', R => 'answered', S => 'seen');
188 sub maildir_keywords {
189         $_[-1] =~ /:2,([A-Z]+)\z/i ?
190                 sort(map { $c2kw{$_} // () } split(//, $1)) : ();
191 }
192
193 sub add_eml {
194         my ($self, $eml, @kw) = @_;
195         my $im = $self->importer; # may create new epoch
196         my $eidx = eidx_init($self); # writes ALL.git/objects/info/alternates
197         my $oidx = $eidx->{oidx};
198         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
199         $im->add($eml, undef, $smsg) or return; # duplicate returns undef
200
201         local $self->{current_info} = $smsg->{blob};
202         if (my @docids = _docids_for($self, $eml)) {
203                 for my $docid (@docids) {
204                         my $idx = $eidx->idx_shard($docid);
205                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
206                         # add_eidx_info for List-Id
207                         $idx->ipc_do('add_eidx_info', $docid, '.', $eml);
208                         $idx->ipc_do('add_keywords', $docid, @kw) if @kw;
209                 }
210                 \@docids;
211         } else {
212                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
213                 $oidx->add_overview($eml, $smsg);
214                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
215                 my $idx = $eidx->idx_shard($smsg->{num});
216                 $idx->index_eml($eml, $smsg);
217                 $idx->ipc_do('add_keywords', $smsg->{num}, @kw) if @kw;
218                 $smsg;
219         }
220 }
221
222 sub set_eml {
223         my ($self, $eml, @kw) = @_;
224         add_eml($self, $eml, @kw) // set_eml_keywords($self, $eml, @kw);
225 }
226
227 sub set_eml_from_maildir {
228         my ($self, $f, $set_kw) = @_;
229         my $eml = eml_from_path($f) or return;
230         set_eml($self, $eml, $set_kw ? maildir_keywords($f) : ());
231 }
232
233 sub done {
234         my ($self) = @_;
235         my $err = '';
236         if (my $im = delete($self->{im})) {
237                 eval { $im->done };
238                 if ($@) {
239                         $err .= "import done: $@\n";
240                         warn $err;
241                 }
242         }
243         $self->{priv_eidx}->done;
244         die $err if $err;
245 }
246
247 sub ipc_atfork_child {
248         my ($self) = @_;
249         my $lei = delete $self->{lei};
250         $lei->lei_atfork_child(1) if $lei;
251         $self->SUPER::ipc_atfork_child;
252 }
253
254 sub write_prepare {
255         my ($self, $lei) = @_;
256         $self->ipc_lock_init;
257         # Mail we import into lei are private, so headers filtered out
258         # by -mda for public mail are not appropriate
259         local @PublicInbox::MDA::BAD_HEADERS = ();
260         $self->ipc_worker_spawn('lei_store', $lei->oldset, { lei => $lei });
261         $lei->{sto} = $self;
262 }
263
264 1;