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