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