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>
4 # Represents a public-inbox (which may have multiple mailing addresses)
5 package PublicInbox::Inbox;
8 use PublicInbox::MID qw(mid2path);
10 use List::Util qw(max);
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.
19 my $CLEANUP = {}; # string(inbox) -> inbox
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;
34 # returns true if further checking is required
35 sub cleanup_shards { $_[0]->{search} ? $_[0]->{search}->cleanup_shards : undef }
38 $cleanup_timer = undef;
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;
47 $next->{"$ibx"} = $ibx if $again;
50 $cleanup_timer //= PublicInbox::DS::later(\&cleanup_task);
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
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;
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;
77 warn "$mkey limiter=$val not understood\n";
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;
94 delete $opts->{feedmax};
96 # allow any combination of multi-line or comma-delimited hide entries
98 if (defined(my $h = $opts->{hide})) {
100 $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
102 $opts->{-hide} = $hide;
108 $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
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
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);
139 return if $self->version < 2;
140 my $cur = $self->{-max_git_epoch};
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) {
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;
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");
163 PublicInbox::Msgmap->new($dir);
165 } // ($req ? croak("E: $@") : undef);
170 $self->{search} // eval {
171 _cleanup_later($self);
172 require PublicInbox::Search;
173 my $srch = PublicInbox::Search->new($self);
174 (eval { $srch->xdb }) ? ($self->{search} = $srch) : undef;
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]) }
183 my ($self, $req) = @_;
184 $self->{over} // eval {
185 my $srch = $self->{search} // do {
186 require PublicInbox::Search;
187 PublicInbox::Search->new($self);
189 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
190 $over->dbh; # may fail
191 $self->{over} = $over;
192 } // ($req ? croak("E: $@") : undef);
197 open(my $fh, '<', $path) or return '';
203 my $desc = try_cat($_[0]);
207 $desc =~ s/\s+/ /smg;
208 $desc eq '' ? undef : $desc;
213 ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
214 '($INBOX_DIR/description missing)';
219 ($self->{cloneurl} //= do {
220 my $s = try_cat("$self->{inboxdir}/cloneurl");
221 my @urls = split(/\s+/s, $s);
222 scalar(@urls) ? \@urls : undef
227 my ($self, $env) = @_; # env - PSGI env
228 if ($env && $env->{'psgi.url_scheme'}) {
229 my $url = PublicInbox::Git::host_prefix_url($env, '');
230 # for mount in Plack::Builder
231 $url .= '/' if $url !~ m!/\z!;
232 return $url .= $self->{name} . '/';
234 # called from a non-PSGI environment (e.g. NNTP/POP3):
235 $self->{-base_url} ||= do {
236 my $url = $self->{url} // return undef;
237 $url = $url->[0] // return undef;
238 # expand protocol-relative URLs to HTTPS if we're
239 # not inside a web server
240 $url = "https:$url" if $url =~ m!\A//!;
241 $url .= '/' if $url !~ m!/\z!;
247 my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
248 # no checking for nntp_usable here, we can point entirely
249 # to non-local servers or users run by a different user
250 my $ns = $self->{"${x}server"} //
251 $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
252 my $group = $self->{newsgroup};
256 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
257 $u .= '/' if $u !~ m!/\z!;
261 if (my $mirrors = $self->{"${x}mirror"}) {
264 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
265 if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
267 $u .= '/' if $u !~ m!/\z!;
269 } else { # n.b. IMAP uses "newsgroup"
271 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
275 # else: allow full URLs like:
276 # nntp://news.example.com/alt.example
280 # List::Util::uniq requires Perl 5.26+, maybe we
281 # can use it by 2030 or so
283 @urls = grep { !$seen{$_}++ } (@urls, @m);
288 # my ($self, $ctx) = @_;
289 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
290 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
294 my $ret = mm($self) && over($self);
295 delete @$self{qw(mm over search)};
299 # for v1 users w/o SQLite only
300 sub msg_by_path ($$) {
301 my ($self, $path) = @_;
302 git($self)->cat_file('HEAD:'.$path);
305 sub msg_by_smsg ($$) {
306 my ($self, $smsg) = @_;
308 # ghosts may have undef smsg (from SearchThread.node) or
310 return unless defined $smsg;
311 defined(my $blob = $smsg->{blob}) or return;
313 $self->git->cat_file($blob);
317 my ($self, $smsg) = @_;
318 my $bref = msg_by_smsg($self, $smsg) or return;
319 my $eml = PublicInbox::Eml->new($bref);
320 $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
324 sub smsg_by_mid ($$) {
325 my ($self, $mid) = @_;
326 my $over = $self->over or return;
328 if (my $mm = $self->mm) {
329 # favor the Message-ID we used for the NNTP article number:
330 defined(my $num = $mm->num_for($mid)) or return;
331 $smsg = $over->get_art($num);
334 $smsg = $over->next_by_mid($mid, \$id, \$prev);
336 $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
339 sub msg_by_mid ($$) {
340 my ($self, $mid) = @_;
341 my $smsg = smsg_by_mid($self, $mid);
342 $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
346 my ($self, $opts, $after, $before) = @_;
347 $self->over->recent($opts, $after, $before);
352 if (my $over = $self->over) {
353 my $msgs = $over->recent({limit => 1});
354 if (my $smsg = $msgs->[0]) {
359 git($self)->modified; # v1
362 # returns prefix => pathname mapping
363 # (pathname is NOT public, but prefix is used for Xapian queries)
366 $self->{-altid_map} //= eval {
367 require PublicInbox::AltId;
368 my $altid = $self->{altid} or return {};
370 my $x = PublicInbox::AltId->new($self, $_);
371 "$x->{prefix}" => $x->{filename}
377 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
378 sub subscribe_unlock {
379 my ($self, $ident, $obj) = @_;
380 $self->{unlock_subs}->{$ident} = $obj;
383 sub unsubscribe_unlock {
384 my ($self, $ident) = @_;
385 delete $self->{unlock_subs}->{$ident};
388 sub check_inodes ($) {
390 for (qw(over mm)) { # TODO: search
391 $self->{$_}->check_inodes if $self->{$_};
399 my $subs = $self->{unlock_subs} or return;
400 for my $obj (values %$subs) {
401 eval { $obj->on_inbox_unlock($self) };
402 warn "E: $@ ($self->{inboxdir})\n" if $@;
406 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
408 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
410 sub mailboxid { # rfc 8474, 8620, 8621
411 my ($self, $imap_slice) = @_;
412 my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
413 utf8::encode($pfx); # to octets
414 # RFC 8620, 1.2 recommends not starting with dash or digits
415 # "A good solution to these issues is to prefix every id with a single
416 # alphabetical character."
417 'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
418 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
419 sprintf('-%x', uidvalidity($self) // 0)