]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiStore.pm
lei_store: use per-machine refname as git HEAD
[public-inbox.git] / lib / PublicInbox / LeiStore.pm
1 # Copyright (C) 2020 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);
13 use PublicInbox::SearchIdx qw(crlf_adjust);
14 use PublicInbox::ExtSearchIdx;
15 use PublicInbox::Import;
16 use PublicInbox::InboxWritable;
17 use PublicInbox::V2Writable;
18 use PublicInbox::ContentHash qw(content_hash);
19 use PublicInbox::MID qw(mids);
20 use PublicInbox::LeiSearch;
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         if ($opt->{creat}) {
28                 PublicInbox::SearchIdx::load_xapian_writable();
29                 eidx_init($self);
30         }
31         $self;
32 }
33
34 sub git { $_[0]->{priv_eidx}->git } # read-only
35
36 sub packing_factor { $PublicInbox::V2Writable::PACKING_FACTOR }
37
38 sub rotate_bytes {
39         $_[0]->{rotate_bytes} // ((1024 * 1024 * 1024) / $_[0]->packing_factor)
40 }
41
42 sub git_pfx { "$_[0]->{priv_eidx}->{topdir}/local" };
43
44 sub git_epoch_max  {
45         my ($self) = @_;
46         if (opendir(my $dh, $self->git_pfx)) {
47                 max(map {
48                         substr($_, 0, -4) + 0; # drop ".git" suffix
49                 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // 0;
50         } else {
51                 $!{ENOENT} ? 0 : die("opendir ${\$self->git_pfx}: $!\n");
52         }
53 }
54
55 sub git_ident ($) {
56         my ($git) = @_;
57         chomp(my $i = $git->qx(qw(var GIT_COMMITTER_IDENT)));
58         warn "$git->{git_dir} GIT_COMMITTER_IDENT failed\n" if $?;
59         $i =~ /\A(.+) <([^>]+)> [0-9]+ [-\+]?[0-9]+$/ ? ($1, $2) :
60                 ('lei user', 'x@example.com')
61 }
62
63 # We will support users combining storage across multiple machines
64 # somehow.  Use per-machine refnames to make it easy-to-identify
65 # where a message came from
66 sub host_head () {
67         state $h = do {
68                 my $x = PublicInbox::ExtSearchIdx::host_ident;
69                 # Similar rules found in git.git/remote.c::valid_remote_nick
70                 # and git.git/refs.c::check_refname_component
71                 $x =~ s!(?:\.lock|/)+\z!!gs; # must not end with ".lock" or "/"
72                 $x =~ tr/././s; # no dot-dot, collapse them
73                 $x =~ s/@\{/\@-/gs;
74                 $x =~ s/\A\./-/s;
75                 # no "*", ":", "?", "[", "\", "^", "~", SP, TAB; "]" is OK
76                 $x =~ tr^a-zA-Z0-9!"#$%&'()+,\-.;<=>@]_`{|}^-^c;
77                 $x
78         };
79 }
80
81 sub importer {
82         my ($self) = @_;
83         my $max;
84         my $im = $self->{im};
85         if ($im) {
86                 return $im if $im->{bytes_added} < $self->rotate_bytes;
87
88                 delete $self->{im};
89                 $im->done;
90                 undef $im;
91                 $self->checkpoint;
92                 $max = $self->git_epoch_max + 1;
93         }
94         my $pfx = $self->git_pfx;
95         $max //= $self->git_epoch_max;
96         while (1) {
97                 my $latest = "$pfx/$max.git";
98                 my $old = -e $latest;
99                 PublicInbox::Import::init_bare($latest, host_head);
100                 my $git = PublicInbox::Git->new($latest);
101                 $git->qx(qw(config core.sharedRepository 0600)) if !$old;
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                 $im->{'ref'} = host_head;
114                 return $im;
115         }
116 }
117
118 sub search {
119         PublicInbox::LeiSearch->new($_[0]->{priv_eidx}->{topdir});
120 }
121
122 sub eidx_init {
123         my ($self) = @_;
124         my $eidx = $self->{priv_eidx};
125         $eidx->idx_init({-private => 1});
126         $eidx;
127 }
128
129 sub _docids_for ($$) {
130         my ($self, $eml) = @_;
131         my %docids;
132         my $chash = content_hash($eml);
133         my $eidx = eidx_init($self);
134         my $oidx = $eidx->{oidx};
135         my $im = $self->{im};
136         for my $mid (@{mids($eml)}) {
137                 my ($id, $prev);
138                 while (my $cur = $oidx->next_by_mid($mid, \$id, \$prev)) {
139                         my $oid = $cur->{blob};
140                         my $docid = $cur->{num};
141                         my $bref = $im ? $im->cat_blob($oid) : undef;
142                         $bref //= $eidx->git->cat_file($oid) // do {
143                                 warn "W: $oid (#$docid) <$mid> not found\n";
144                                 next;
145                         };
146                         local $self->{current_info} = $oid;
147                         my $x = PublicInbox::Eml->new($bref);
148                         $docids{$docid} = $docid if content_hash($x) eq $chash;
149                 }
150         }
151         sort { $a <=> $b } values %docids;
152 }
153
154 sub set_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)->shard_set_keywords($docid, @kw);
160         }
161         \@docids;
162 }
163
164 sub add_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)->shard_add_keywords($docid, @kw);
170         }
171         \@docids;
172 }
173
174 sub remove_eml_keywords {
175         my ($self, $eml, @kw) = @_;
176         my $eidx = eidx_init($self);
177         my @docids = _docids_for($self, $eml);
178         for my $docid (@docids) {
179                 $eidx->idx_shard($docid)->shard_remove_keywords($docid, @kw);
180         }
181         \@docids;
182 }
183
184 # cf: https://doc.dovecot.org/configuration_manual/mail_location/mbox/
185 my %status2kw = (F => 'flagged', A => 'answered', R => 'seen', T => 'draft');
186 # O (old/non-recent), and D (deleted) aren't in JMAP,
187 # so probably won't be supported by us.
188 sub mbox_keywords {
189         my $eml = $_[-1];
190         my $s = "@{[$eml->header_raw('X-Status'),$eml->header_raw('Status')]}";
191         my %kw;
192         $s =~ s/([FART])/$kw{$status2kw{$1}} = 1/sge;
193         sort(keys %kw);
194 }
195
196 # cf: https://cr.yp.to/proto/maildir.html
197 my %c2kw = ('D' => 'draft', F => 'flagged', R => 'answered', S => 'seen');
198 sub maildir_keywords {
199         $_[-1] =~ /:2,([A-Z]+)\z/i ?
200                 sort(map { $c2kw{$_} // () } split(//, $1)) : ();
201 }
202
203 sub add_eml {
204         my ($self, $eml, @kw) = @_;
205         my $eidx = eidx_init($self);
206         my $oidx = $eidx->{oidx};
207         my $smsg = bless { -oidx => $oidx }, 'PublicInbox::Smsg';
208         my $im = $self->importer;
209         $im->add($eml, undef, $smsg) or return; # duplicate returns undef
210         my $msgref = delete $smsg->{-raw_email};
211         $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
212
213         local $self->{current_info} = $smsg->{blob};
214         if (my @docids = _docids_for($self, $eml)) {
215                 for my $docid (@docids) {
216                         my $idx = $eidx->idx_shard($docid);
217                         $oidx->add_xref3($docid, -1, $smsg->{blob}, '.');
218                         $idx->shard_add_eidx_info($docid, '.', $eml); # List-Id
219                         $idx->shard_add_keywords($docid, @kw) if @kw;
220                 }
221         } else {
222                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
223                 $oidx->add_overview($eml, $smsg);
224                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
225                 my $idx = $eidx->idx_shard($smsg->{num});
226                 $idx->index_raw($msgref, $eml, $smsg);
227                 $idx->shard_add_keywords($smsg->{num}, @kw) if @kw;
228         }
229         $smsg->{blob}
230 }
231
232 sub done {
233         my ($self) = @_;
234         my $err = '';
235         if (my $im = delete($self->{im})) {
236                 eval { $im->done };
237                 if ($@) {
238                         $err .= "import done: $@\n";
239                         warn $err;
240                 }
241         }
242         $self->{priv_eidx}->done;
243         die $err if $err;
244 }
245
246 1;