]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
af6380a758b187127b7240bb6f422e75dca283b5
[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 PublicInbox::Git;
8 use PublicInbox::MID qw(mid2path);
9 use PublicInbox::Eml;
10 use List::Util qw(max);
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
113         # allow any combination of multi-line or comma-delimited hide entries
114         my $hide = {};
115         if (defined(my $h = $opts->{hide})) {
116                 foreach my $v (@$h) {
117                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
118                 }
119                 $opts->{-hide} = $hide;
120         }
121         bless $opts, $class;
122 }
123
124 sub version {
125         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
126 }
127
128 sub git_epoch {
129         my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
130         $self->{"$epoch.git"} ||= do {
131                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
132                 return unless -d $git_dir;
133                 my $g = PublicInbox::Git->new($git_dir);
134                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
135                 # caller must manually cleanup when done
136                 $g;
137         };
138 }
139
140 sub git {
141         my ($self) = @_;
142         $self->{git} ||= do {
143                 my $git_dir = $self->{inboxdir};
144                 $git_dir .= '/all.git' if $self->version == 2;
145                 my $g = PublicInbox::Git->new($git_dir);
146                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
147                 _cleanup_later($self);
148                 $g;
149         };
150 }
151
152 sub max_git_epoch {
153         my ($self) = @_;
154         return if $self->version < 2;
155         my $cur = $self->{-max_git_epoch};
156         my $changed;
157         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
158                 git_cleanup($self) if $changed;
159                 my $gits = "$self->{inboxdir}/git";
160                 if (opendir my $dh, $gits) {
161                         my $max = max(map {
162                                 substr($_, 0, -4) + 0; # drop ".git" suffix
163                         } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
164                         $cur = $self->{-max_git_epoch} = $max;
165                 }
166         }
167         $cur;
168 }
169
170 sub mm {
171         my ($self) = @_;
172         $self->{mm} ||= eval {
173                 require PublicInbox::Msgmap;
174                 my $dir = $self->{inboxdir};
175                 if ($self->version >= 2) {
176                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
177                 } else {
178                         PublicInbox::Msgmap->new($dir);
179                 }
180         };
181 }
182
183 sub search {
184         my ($self) = @_;
185         my $srch = $self->{search} //= eval {
186                 _cleanup_later($self);
187                 require PublicInbox::Search;
188                 PublicInbox::Search->new($self);
189         };
190         (eval { $srch->xdb }) ? $srch : undef;
191 }
192
193 # isrch is preferred for read-only interfaces if available since it
194 # reduces kernel cache and FD overhead
195 sub isrch { $_[0]->{isrch} // search($_[0]) }
196
197 sub over {
198         $_[0]->{over} //= eval {
199                 my $srch = $_[0]->{search} //= eval {
200                         _cleanup_later($_[0]);
201                         require PublicInbox::Search;
202                         PublicInbox::Search->new($_[0]);
203                 };
204                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
205                 $over->dbh; # may fail
206                 $over;
207         };
208 }
209
210
211 sub try_cat {
212         my ($path) = @_;
213         open(my $fh, '<', $path) or return '';
214         local $/;
215         <$fh> // '';
216 }
217
218 sub cat_desc ($) {
219         my $desc = try_cat($_[0]);
220         local $/ = "\n";
221         chomp $desc;
222         utf8::decode($desc);
223         $desc =~ s/\s+/ /smg;
224         $desc eq '' ? undef : $desc;
225 }
226
227 sub description {
228         my ($self) = @_;
229         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
230                 '($INBOX_DIR/description missing)';
231 }
232
233 sub cloneurl {
234         my ($self) = @_;
235         ($self->{cloneurl} //= do {
236                 my $s = try_cat("$self->{inboxdir}/cloneurl");
237                 my @urls = split(/\s+/s, $s);
238                 scalar(@urls) ? \@urls : undef
239         }) // [];
240 }
241
242 sub base_url {
243         my ($self, $env) = @_; # env - PSGI env
244         if ($env) {
245                 my $url = PublicInbox::Git::host_prefix_url($env, '');
246                 # for mount in Plack::Builder
247                 $url .= '/' if $url !~ m!/\z!;
248                 return $url .= $self->{name} . '/';
249         }
250         # called from a non-PSGI environment (e.g. NNTP/POP3):
251         $self->{-base_url} ||= do {
252                 my $url = $self->{url}->[0] or return undef;
253                 # expand protocol-relative URLs to HTTPS if we're
254                 # not inside a web server
255                 $url = "https:$url" if $url =~ m!\A//!;
256                 $url .= '/' if $url !~ m!/\z!;
257                 $url;
258         };
259 }
260
261 sub nntp_url {
262         my ($self) = @_;
263         $self->{-nntp_url} ||= do {
264                 # no checking for nntp_usable here, we can point entirely
265                 # to non-local servers or users run by a different user
266                 my $ns = $self->{nntpserver};
267                 my $group = $self->{newsgroup};
268                 my @urls;
269                 if ($ns && $group) {
270                         $ns = [ $ns ] if ref($ns) ne 'ARRAY';
271                         @urls = map {
272                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
273                                 $u .= '/' if $u !~ m!/\z!;
274                                 $u.$group;
275                         } @$ns;
276                 }
277
278                 my $mirrors = $self->{nntpmirror};
279                 if ($mirrors) {
280                         my @m;
281                         foreach (@$mirrors) {
282                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
283                                 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
284                                         if ($group) {
285                                                 $u .= '/' if $u !~ m!/\z!;
286                                                 $u .= $group;
287                                         } else {
288                                                 warn
289 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
290                                         }
291                                 }
292                                 # else: allow full URLs like:
293                                 # nntp://news.example.com/alt.example
294                                 push @m, $u;
295                         }
296
297                         # List::Util::uniq requires Perl 5.26+, maybe we
298                         # can use it by 2030 or so
299                         my %seen;
300                         @urls = grep { !$seen{$_}++ } (@urls, @m);
301                 }
302                 \@urls;
303         };
304 }
305
306 sub nntp_usable {
307         my ($self) = @_;
308         my $ret = mm($self) && over($self);
309         $self->{mm} = $self->{over} = $self->{search} = undef;
310         $ret;
311 }
312
313 # for v1 users w/o SQLite only
314 sub msg_by_path ($$) {
315         my ($self, $path) = @_;
316         git($self)->cat_file('HEAD:'.$path);
317 }
318
319 sub msg_by_smsg ($$) {
320         my ($self, $smsg) = @_;
321
322         # ghosts may have undef smsg (from SearchThread.node) or
323         # no {blob} field
324         return unless defined $smsg;
325         defined(my $blob = $smsg->{blob}) or return;
326
327         $self->git->cat_file($blob);
328 }
329
330 sub smsg_eml {
331         my ($self, $smsg) = @_;
332         my $bref = msg_by_smsg($self, $smsg) or return;
333         my $eml = PublicInbox::Eml->new($bref);
334         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
335         $eml;
336 }
337
338 sub smsg_by_mid ($$) {
339         my ($self, $mid) = @_;
340         my $over = $self->over or return;
341         my $smsg;
342         if (my $mm = $self->mm) {
343                 # favor the Message-ID we used for the NNTP article number:
344                 defined(my $num = $mm->num_for($mid)) or return;
345                 $smsg = $over->get_art($num);
346         } else {
347                 my ($id, $prev);
348                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
349         }
350         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
351 }
352
353 sub msg_by_mid ($$) {
354         my ($self, $mid) = @_;
355         my $smsg = smsg_by_mid($self, $mid);
356         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
357 }
358
359 sub recent {
360         my ($self, $opts, $after, $before) = @_;
361         $self->over->recent($opts, $after, $before);
362 }
363
364 sub modified {
365         my ($self) = @_;
366         if (my $over = $self->over) {
367                 my $msgs = $over->recent({limit => 1});
368                 if (my $smsg = $msgs->[0]) {
369                         return $smsg->{ts};
370                 }
371                 return time;
372         }
373         git($self)->modified; # v1
374 }
375
376 # returns prefix => pathname mapping
377 # (pathname is NOT public, but prefix is used for Xapian queries)
378 sub altid_map ($) {
379         my ($self) = @_;
380         $self->{-altid_map} //= eval {
381                 require PublicInbox::AltId;
382                 my $altid = $self->{altid} or return {};
383                 my %h = map {;
384                         my $x = PublicInbox::AltId->new($self, $_);
385                         "$x->{prefix}" => $x->{filename}
386                 } @$altid;
387                 \%h;
388         } // {};
389 }
390
391 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
392 sub subscribe_unlock {
393         my ($self, $ident, $obj) = @_;
394         $self->{unlock_subs}->{$ident} = $obj;
395 }
396
397 sub unsubscribe_unlock {
398         my ($self, $ident) = @_;
399         delete $self->{unlock_subs}->{$ident};
400 }
401
402 sub check_inodes ($) {
403         my ($self) = @_;
404         for (qw(over mm)) { # TODO: search
405                 $self->{$_}->check_inodes if $self->{$_};
406         }
407 }
408
409 # called by inotify
410 sub on_unlock {
411         my ($self) = @_;
412         check_inodes($self);
413         my $subs = $self->{unlock_subs} or return;
414         for my $obj (values %$subs) {
415                 eval { $obj->on_inbox_unlock($self) };
416                 warn "E: $@ ($self->{inboxdir})\n" if $@;
417         }
418 }
419
420 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
421
422 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
423
424 1;