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