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