]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
inbox: inline and eliminate git_cleanup
[public-inbox.git] / lib / PublicInbox / Inbox.pm
1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Represents a public-inbox (which may have multiple mailing addresses)
5 package PublicInbox::Inbox;
6 use strict;
7 use PublicInbox::Git;
8 use PublicInbox::MID qw(mid2path);
9 use PublicInbox::Eml;
10 use List::Util qw(max);
11 use Carp qw(croak);
12
13 # returns true if further checking is required
14 sub cleanup_shards { $_[0]->{search} ? $_[0]->{search}->cleanup_shards : undef }
15
16 sub do_cleanup {
17         my ($ibx) = @_;
18         my $live;
19         if (defined $ibx->{git}) {
20                 $live = $ibx->isa(__PACKAGE__) ? $ibx->{git}->cleanup(1)
21                                         : $ibx->{git}->cleanup_if_unlinked;
22                 delete($ibx->{git}) unless $live;
23         }
24         $ibx->cleanup_shards and $live = 1;
25         for my $git (@{$ibx->{-repo_objs} // []}) {
26                 $live = 1 if $git->cleanup(1);
27         }
28         delete(@$ibx{qw(over mm description cloneurl -imap_url -nntp_url)});
29         PublicInbox::DS::add_uniq_timer($ibx+0, 5, \&do_cleanup, $ibx) if $live;
30 }
31
32 sub _cleanup_later ($) {
33         # no need to require DS, here, if it were enabled another
34         # module would've require'd it, already
35         eval { PublicInbox::DS::in_loop() } and
36                 PublicInbox::DS::add_uniq_timer($_[0]+0, 30, \&do_cleanup, @_)
37 }
38
39 sub _set_limiter ($$$) {
40         my ($self, $pi_cfg, $pfx) = @_;
41         my $lkey = "-${pfx}_limiter";
42         $self->{$lkey} ||= do {
43                 # full key is: publicinbox.$NAME.httpbackendmax
44                 my $mkey = $pfx.'max';
45                 my $val = $self->{$mkey} or return;
46                 my $lim;
47                 if ($val =~ /\A[0-9]+\z/) {
48                         require PublicInbox::Qspawn;
49                         $lim = PublicInbox::Qspawn::Limiter->new($val);
50                 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
51                         $lim = $pi_cfg->limiter($val);
52                         warn "$mkey limiter=$val not found\n" if !$lim;
53                 } else {
54                         warn "$mkey limiter=$val not understood\n";
55                 }
56                 $lim;
57         }
58 }
59
60 sub new {
61         my ($class, $opts) = @_;
62         my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
63         my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
64         $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
65         my $pi_cfg = delete $opts->{-pi_cfg};
66         _set_limiter($opts, $pi_cfg, 'httpbackend');
67         my $fmax = $opts->{feedmax};
68         if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
69                 $opts->{feedmax} += 0;
70         } else {
71                 delete $opts->{feedmax};
72         }
73         # allow any combination of multi-line or comma-delimited hide entries
74         my $hide = {};
75         if (defined(my $h = $opts->{hide})) {
76                 foreach my $v (@$h) {
77                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
78                 }
79                 $opts->{-hide} = $hide;
80         }
81         bless $opts, $class;
82 }
83
84 sub version {
85         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
86 }
87
88 sub git_epoch {
89         my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
90         $self->{"$epoch.git"} //= do {
91                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
92                 return unless -d $git_dir;
93                 my $g = PublicInbox::Git->new($git_dir);
94                 my $lim = $self->{-httpbackend_limiter};
95                 $g->{-httpbackend_limiter} = $lim if $lim;
96                 # caller must manually cleanup when done
97                 $g;
98         };
99 }
100
101 sub git {
102         my ($self) = @_;
103         $self->{git} //= do {
104                 my $git_dir = $self->{inboxdir};
105                 $git_dir .= '/all.git' if $self->version == 2;
106                 my $g = PublicInbox::Git->new($git_dir);
107                 my $lim = $self->{-httpbackend_limiter};
108                 $g->{-httpbackend_limiter} = $lim if $lim;
109                 _cleanup_later($self);
110                 $g;
111         };
112 }
113
114 sub max_git_epoch {
115         my ($self) = @_;
116         return if $self->version < 2;
117         my $cur = $self->{-max_git_epoch};
118         my $changed;
119         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
120                 $self->{git}->cleanup if $changed;
121                 my $gits = "$self->{inboxdir}/git";
122                 if (opendir my $dh, $gits) {
123                         my $max = max(map {
124                                 substr($_, 0, -4) + 0; # drop ".git" suffix
125                         } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
126                         $cur = $self->{-max_git_epoch} = $max;
127                 }
128         }
129         $cur;
130 }
131
132 sub mm {
133         my ($self, $req) = @_;
134         $self->{mm} //= eval {
135                 require PublicInbox::Msgmap;
136                 _cleanup_later($self);
137                 my $dir = $self->{inboxdir};
138                 if ($self->version >= 2) {
139                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
140                 } else {
141                         PublicInbox::Msgmap->new($dir);
142                 }
143         } // ($req ? croak("E: $@") : undef);
144 }
145
146 sub search {
147         my ($self) = @_;
148         $self->{search} // eval {
149                 _cleanup_later($self);
150                 require PublicInbox::Search;
151                 my $srch = PublicInbox::Search->new($self);
152                 (eval { $srch->xdb }) ? ($self->{search} = $srch) : undef;
153         };
154 }
155
156 # isrch is preferred for read-only interfaces if available since it
157 # reduces kernel cache and FD overhead
158 sub isrch { $_[0]->{isrch} // search($_[0]) }
159
160 sub over {
161         my ($self, $req) = @_;
162         $self->{over} // eval {
163                 my $srch = $self->{search} // do {
164                         require PublicInbox::Search;
165                         PublicInbox::Search->new($self);
166                 };
167                 _cleanup_later($self);
168                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
169                 $over->dbh; # may fail
170                 $self->{over} = $over;
171         } // ($req ? croak("E: $@") : undef);
172 }
173
174 sub try_cat {
175         my ($path) = @_;
176         open(my $fh, '<', $path) or return '';
177         local $/;
178         <$fh> // '';
179 }
180
181 sub cat_desc ($) {
182         my $desc = try_cat($_[0]);
183         local $/ = "\n";
184         chomp $desc;
185         utf8::decode($desc);
186         $desc =~ s/\s+/ /smg;
187         $desc eq '' ? undef : $desc;
188 }
189
190 sub description {
191         my ($self) = @_;
192         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
193                 '($INBOX_DIR/description missing)';
194 }
195
196 sub cloneurl {
197         my ($self) = @_;
198         $self->{cloneurl} // do {
199                 my $s = try_cat("$self->{inboxdir}/cloneurl");
200                 my @urls = split(/\s+/s, $s);
201                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
202         } // [];
203 }
204
205 sub base_url {
206         my ($self, $env) = @_; # env - PSGI env
207         if ($env && $env->{'psgi.url_scheme'}) {
208                 my $url = PublicInbox::Git::host_prefix_url($env, '');
209                 # for mount in Plack::Builder
210                 $url .= '/' if $url !~ m!/\z!;
211                 return $url .= $self->{name} . '/';
212         }
213         # called from a non-PSGI environment (e.g. NNTP/POP3):
214         my $url = $self->{url} // return undef;
215         $url = $url->[0] // return undef;
216         # expand protocol-relative URLs to HTTPS if we're
217         # not inside a web server
218         substr($url, 0, 0, 'https:') if substr($url, 0, 2) eq '//';
219         $url .= '/' if substr($url, -1, 1) ne '/';
220         $url;
221 }
222
223 sub _x_url ($$$) {
224         my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
225         # no checking for nntp_usable here, we can point entirely
226         # to non-local servers or users run by a different user
227         my $ns = $self->{"${x}server"} //
228                $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
229         my $group = $self->{newsgroup};
230         my @urls;
231         if ($ns && $group) {
232                 @urls = map {
233                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
234                         $u .= '/' if $u !~ m!/\z!;
235                         $u.$group;
236                 } @$ns;
237         }
238         if (my $mirrors = $self->{"${x}mirror"}) {
239                 my @m;
240                 for (@$mirrors) {
241                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
242                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
243                                 if ($group) {
244                                         $u .= '/' if $u !~ m!/\z!;
245                                         $u .= $group;
246                                 } else { # n.b. IMAP uses "newsgroup"
247                                         warn <<EOM;
248 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
249 EOM
250                                 }
251                         }
252                         # else: allow full URLs like:
253                         # nntp://news.example.com/alt.example
254                         push @m, $u;
255                 }
256
257                 # List::Util::uniq requires Perl 5.26+, maybe we
258                 # can use it by 2030 or so
259                 my %seen;
260                 @urls = grep { !$seen{$_}++ } (@urls, @m);
261         }
262         \@urls;
263 }
264
265 # my ($self, $ctx) = @_;
266 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
267 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
268
269 sub nntp_usable {
270         my ($self) = @_;
271         my $ret = mm($self) && over($self);
272         delete @$self{qw(mm over search)};
273         $ret;
274 }
275
276 # for v1 users w/o SQLite only
277 sub msg_by_path ($$) {
278         my ($self, $path) = @_;
279         git($self)->cat_file('HEAD:'.$path);
280 }
281
282 sub msg_by_smsg ($$) {
283         my ($self, $smsg) = @_;
284
285         # ghosts may have undef smsg (from SearchThread.node) or
286         # no {blob} field
287         return unless defined $smsg;
288         defined(my $blob = $smsg->{blob}) or return;
289
290         $self->git->cat_file($blob);
291 }
292
293 sub smsg_eml {
294         my ($self, $smsg) = @_;
295         my $bref = msg_by_smsg($self, $smsg) or return;
296         my $eml = PublicInbox::Eml->new($bref);
297         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
298         $eml;
299 }
300
301 sub smsg_by_mid ($$) {
302         my ($self, $mid) = @_;
303         my $over = $self->over or return;
304         my $smsg;
305         if (my $mm = $self->mm) {
306                 # favor the Message-ID we used for the NNTP article number:
307                 defined(my $num = $mm->num_for($mid)) or return;
308                 $smsg = $over->get_art($num);
309         } else {
310                 my ($id, $prev);
311                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
312         }
313         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
314 }
315
316 sub msg_by_mid ($$) {
317         my ($self, $mid) = @_;
318         my $smsg = smsg_by_mid($self, $mid);
319         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
320 }
321
322 sub recent {
323         my ($self, $opts, $after, $before) = @_;
324         $self->over->recent($opts, $after, $before);
325 }
326
327 sub modified {
328         my ($self) = @_;
329         if (my $over = $self->over) {
330                 my $msgs = $over->recent({limit => 1});
331                 if (my $smsg = $msgs->[0]) {
332                         return $smsg->{ts};
333                 }
334                 return time;
335         }
336         git($self)->modified; # v1
337 }
338
339 # returns prefix => pathname mapping
340 # (pathname is NOT public, but prefix is used for Xapian queries)
341 sub altid_map ($) {
342         my ($self) = @_;
343         eval {
344                 require PublicInbox::AltId;
345                 my $altid = $self->{altid} or return {};
346                 my %h = map {;
347                         my $x = PublicInbox::AltId->new($self, $_);
348                         "$x->{prefix}" => $x->{filename}
349                 } @$altid;
350                 \%h;
351         } // {};
352 }
353
354 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
355 sub subscribe_unlock {
356         my ($self, $ident, $obj) = @_;
357         $self->{unlock_subs}->{$ident} = $obj;
358 }
359
360 sub unsubscribe_unlock {
361         my ($self, $ident) = @_;
362         delete $self->{unlock_subs}->{$ident};
363 }
364
365 sub check_inodes ($) {
366         my ($self) = @_;
367         for (qw(over mm)) {
368                 $self->{$_}->check_inodes if $self->{$_};
369         }
370 }
371
372 # called by inotify
373 sub on_unlock {
374         my ($self) = @_;
375         check_inodes($self);
376         my $subs = $self->{unlock_subs} or return;
377         for my $obj (values %$subs) {
378                 eval { $obj->on_inbox_unlock($self) };
379                 warn "E: $@ ($self->{inboxdir})\n" if $@;
380         }
381 }
382
383 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
384
385 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
386
387 sub mailboxid { # rfc 8474, 8620, 8621
388         my ($self, $imap_slice) = @_;
389         my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
390         utf8::encode($pfx); # to octets
391         # RFC 8620, 1.2 recommends not starting with dash or digits
392         # "A good solution to these issues is to prefix every id with a single
393         #  alphabetical character."
394         'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
395                 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
396                 sprintf('-%x', uidvalidity($self) // 0)
397 }
398
399 1;