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