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