]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
inbox: cloneurl: avoid undef to hash table value
[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 = {}; # string(inbox) -> inbox
20
21 sub git_cleanup ($) {
22         my ($self) = @_;
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;
31         $live;
32 }
33
34 # returns true if further checking is required
35 sub cleanup_shards { $_[0]->{search} ? $_[0]->{search}->cleanup_shards : undef }
36
37 sub cleanup_task () {
38         $cleanup_timer = undef;
39         my $next = {};
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;
45                 }
46                 check_inodes($ibx);
47                 $next->{"$ibx"} = $ibx if $again;
48         }
49         $CLEANUP = $next;
50         $cleanup_timer //= PublicInbox::DS::later(\&cleanup_task);
51 }
52
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
59         }
60 }
61
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;
69                 my $lim;
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;
76                 } else {
77                         warn "$mkey limiter=$val not understood\n";
78                 }
79                 $lim;
80         }
81 }
82
83 sub new {
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;
93         } else {
94                 delete $opts->{feedmax};
95         }
96         # allow any combination of multi-line or comma-delimited hide entries
97         my $hide = {};
98         if (defined(my $h = $opts->{hide})) {
99                 foreach my $v (@$h) {
100                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
101                 }
102                 $opts->{-hide} = $hide;
103         }
104         bless $opts, $class;
105 }
106
107 sub version {
108         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
109 }
110
111 sub git_epoch {
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
120                 $g;
121         };
122 }
123
124 sub git {
125         my ($self) = @_;
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);
133                 $g;
134         };
135 }
136
137 sub max_git_epoch {
138         my ($self) = @_;
139         return if $self->version < 2;
140         my $cur = $self->{-max_git_epoch};
141         my $changed;
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) {
146                         my $max = max(map {
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;
150                 }
151         }
152         $cur;
153 }
154
155 sub mm {
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");
162                 } else {
163                         PublicInbox::Msgmap->new($dir);
164                 }
165         } // ($req ? croak("E: $@") : undef);
166 }
167
168 sub search {
169         my ($self) = @_;
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;
175         };
176 }
177
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]) }
181
182 sub over {
183         my ($self, $req) = @_;
184         $self->{over} // eval {
185                 my $srch = $self->{search} // do {
186                         require PublicInbox::Search;
187                         PublicInbox::Search->new($self);
188                 };
189                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
190                 $over->dbh; # may fail
191                 $self->{over} = $over;
192         } // ($req ? croak("E: $@") : undef);
193 }
194
195 sub try_cat {
196         my ($path) = @_;
197         open(my $fh, '<', $path) or return '';
198         local $/;
199         <$fh> // '';
200 }
201
202 sub cat_desc ($) {
203         my $desc = try_cat($_[0]);
204         local $/ = "\n";
205         chomp $desc;
206         utf8::decode($desc);
207         $desc =~ s/\s+/ /smg;
208         $desc eq '' ? undef : $desc;
209 }
210
211 sub description {
212         my ($self) = @_;
213         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
214                 '($INBOX_DIR/description missing)';
215 }
216
217 sub cloneurl {
218         my ($self) = @_;
219         $self->{cloneurl} // do {
220                 my $s = try_cat("$self->{inboxdir}/cloneurl");
221                 my @urls = split(/\s+/s, $s);
222                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
223         } // [];
224 }
225
226 sub base_url {
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} . '/';
233         }
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!;
242                 $url;
243         };
244 }
245
246 sub _x_url ($$$) {
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};
253         my @urls;
254         if ($ns && $group) {
255                 @urls = map {
256                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
257                         $u .= '/' if $u !~ m!/\z!;
258                         $u.$group;
259                 } @$ns;
260         }
261         if (my $mirrors = $self->{"${x}mirror"}) {
262                 my @m;
263                 for (@$mirrors) {
264                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
265                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
266                                 if ($group) {
267                                         $u .= '/' if $u !~ m!/\z!;
268                                         $u .= $group;
269                                 } else { # n.b. IMAP uses "newsgroup"
270                                         warn <<EOM;
271 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
272 EOM
273                                 }
274                         }
275                         # else: allow full URLs like:
276                         # nntp://news.example.com/alt.example
277                         push @m, $u;
278                 }
279
280                 # List::Util::uniq requires Perl 5.26+, maybe we
281                 # can use it by 2030 or so
282                 my %seen;
283                 @urls = grep { !$seen{$_}++ } (@urls, @m);
284         }
285         \@urls;
286 }
287
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]) }
291
292 sub nntp_usable {
293         my ($self) = @_;
294         my $ret = mm($self) && over($self);
295         delete @$self{qw(mm over search)};
296         $ret;
297 }
298
299 # for v1 users w/o SQLite only
300 sub msg_by_path ($$) {
301         my ($self, $path) = @_;
302         git($self)->cat_file('HEAD:'.$path);
303 }
304
305 sub msg_by_smsg ($$) {
306         my ($self, $smsg) = @_;
307
308         # ghosts may have undef smsg (from SearchThread.node) or
309         # no {blob} field
310         return unless defined $smsg;
311         defined(my $blob = $smsg->{blob}) or return;
312
313         $self->git->cat_file($blob);
314 }
315
316 sub smsg_eml {
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
321         $eml;
322 }
323
324 sub smsg_by_mid ($$) {
325         my ($self, $mid) = @_;
326         my $over = $self->over or return;
327         my $smsg;
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);
332         } else {
333                 my ($id, $prev);
334                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
335         }
336         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
337 }
338
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));
343 }
344
345 sub recent {
346         my ($self, $opts, $after, $before) = @_;
347         $self->over->recent($opts, $after, $before);
348 }
349
350 sub modified {
351         my ($self) = @_;
352         if (my $over = $self->over) {
353                 my $msgs = $over->recent({limit => 1});
354                 if (my $smsg = $msgs->[0]) {
355                         return $smsg->{ts};
356                 }
357                 return time;
358         }
359         git($self)->modified; # v1
360 }
361
362 # returns prefix => pathname mapping
363 # (pathname is NOT public, but prefix is used for Xapian queries)
364 sub altid_map ($) {
365         my ($self) = @_;
366         $self->{-altid_map} //= eval {
367                 require PublicInbox::AltId;
368                 my $altid = $self->{altid} or return {};
369                 my %h = map {;
370                         my $x = PublicInbox::AltId->new($self, $_);
371                         "$x->{prefix}" => $x->{filename}
372                 } @$altid;
373                 \%h;
374         } // {};
375 }
376
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;
381 }
382
383 sub unsubscribe_unlock {
384         my ($self, $ident) = @_;
385         delete $self->{unlock_subs}->{$ident};
386 }
387
388 sub check_inodes ($) {
389         my ($self) = @_;
390         for (qw(over mm)) { # TODO: search
391                 $self->{$_}->check_inodes if $self->{$_};
392         }
393 }
394
395 # called by inotify
396 sub on_unlock {
397         my ($self) = @_;
398         check_inodes($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 $@;
403         }
404 }
405
406 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
407
408 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
409
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)
420 }
421
422 1;