]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
267be4e381bad31d3cab4791f9e7c76d053726db
[public-inbox.git] / lib / PublicInbox / Inbox.pm
1 # Copyright (C) 2016-2020 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 warnings;
8 use PublicInbox::Git;
9 use PublicInbox::MID qw(mid2path);
10 use PublicInbox::Eml;
11
12 # Long-running "git-cat-file --batch" processes won't notice
13 # unlinked packs, so we need to restart those processes occasionally.
14 # Xapian and SQLite file handles are mostly stable, but sometimes an
15 # admin will attempt to replace them atomically after compact/vacuum
16 # and we need to be prepared for that.
17 my $cleanup_timer;
18 my $cleanup_avail = -1; # 0, or 1
19 my $have_devel_peek;
20 my $CLEANUP = {}; # string(inbox) -> inbox
21
22 sub git_cleanup ($) {
23         my ($self) = @_;
24         my $git = $self->{git} or return;
25         $git->cleanup;
26 }
27
28 sub cleanup_task () {
29         $cleanup_timer = undef;
30         my $next = {};
31         for my $ibx (values %$CLEANUP) {
32                 my $again;
33                 if ($have_devel_peek) {
34                         foreach my $f (qw(search)) {
35                                 # we bump refcnt by assigning tmp, here:
36                                 my $tmp = $ibx->{$f} or next;
37                                 next if Devel::Peek::SvREFCNT($tmp) > 2;
38                                 delete $ibx->{$f};
39                                 # refcnt is zero when tmp is out-of-scope
40                         }
41                 }
42                 git_cleanup($ibx);
43                 if (my $gits = $ibx->{-repo_objs}) {
44                         foreach my $git (@$gits) {
45                                 $again = 1 if $git->cleanup;
46                         }
47                 }
48                 check_inodes($ibx);
49                 if ($have_devel_peek) {
50                         $again ||= !!$ibx->{search};
51                 }
52                 $next->{"$ibx"} = $ibx if $again;
53         }
54         $CLEANUP = $next;
55 }
56
57 sub cleanup_possible () {
58         # no need to require DS, here, if it were enabled another
59         # module would've require'd it, already
60         eval { PublicInbox::DS::in_loop() } or return 0;
61
62         eval {
63                 require Devel::Peek; # needs separate package in Fedora
64                 $have_devel_peek = 1;
65         };
66         1;
67 }
68
69 sub _cleanup_later ($) {
70         my ($self) = @_;
71         $cleanup_avail = cleanup_possible() if $cleanup_avail < 0;
72         return if $cleanup_avail != 1;
73         $cleanup_timer ||= PublicInbox::DS::later(*cleanup_task);
74         $CLEANUP->{"$self"} = $self;
75 }
76
77 sub _set_uint ($$$) {
78         my ($opts, $field, $default) = @_;
79         my $val = $opts->{$field};
80         if (defined $val) {
81                 $val = $val->[-1] if ref($val) eq 'ARRAY';
82                 $val = undef if $val !~ /\A[0-9]+\z/;
83         }
84         $opts->{$field} = $val || $default;
85 }
86
87 sub _set_limiter ($$$) {
88         my ($self, $pi_config, $pfx) = @_;
89         my $lkey = "-${pfx}_limiter";
90         $self->{$lkey} ||= do {
91                 # full key is: publicinbox.$NAME.httpbackendmax
92                 my $mkey = $pfx.'max';
93                 my $val = $self->{$mkey} or return;
94                 my $lim;
95                 if ($val =~ /\A[0-9]+\z/) {
96                         require PublicInbox::Qspawn;
97                         $lim = PublicInbox::Qspawn::Limiter->new($val);
98                 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
99                         $lim = $pi_config->limiter($val);
100                         warn "$mkey limiter=$val not found\n" if !$lim;
101                 } else {
102                         warn "$mkey limiter=$val not understood\n";
103                 }
104                 $lim;
105         }
106 }
107
108 sub new {
109         my ($class, $opts) = @_;
110         my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
111         my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
112         $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
113         my $pi_config = delete $opts->{-pi_config};
114         _set_limiter($opts, $pi_config, 'httpbackend');
115         _set_uint($opts, 'feedmax', 25);
116         $opts->{nntpserver} ||= $pi_config->{'publicinbox.nntpserver'};
117         my $dir = $opts->{inboxdir};
118         if (defined $dir && -f "$dir/inbox.lock") {
119                 $opts->{version} = 2;
120         }
121
122         # allow any combination of multi-line or comma-delimited hide entries
123         my $hide = {};
124         if (defined(my $h = $opts->{hide})) {
125                 foreach my $v (@$h) {
126                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
127                 }
128                 $opts->{-hide} = $hide;
129         }
130         bless $opts, $class;
131 }
132
133 sub version { $_[0]->{version} // 1 }
134
135 sub git_epoch {
136         my ($self, $epoch) = @_;
137         $self->version == 2 or return;
138         $self->{"$epoch.git"} ||= do {
139                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
140                 my $g = PublicInbox::Git->new($git_dir);
141                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
142                 # no cleanup needed, we never cat-file off this, only clone
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                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
154                 _cleanup_later($self);
155                 $g;
156         };
157 }
158
159 sub max_git_epoch {
160         my ($self) = @_;
161         return if $self->version < 2;
162         my $cur = $self->{-max_git_epoch};
163         my $changed = git($self)->alternates_changed;
164         if (!defined($cur) || $changed) {
165                 git_cleanup($self) if $changed;
166                 my $gits = "$self->{inboxdir}/git";
167                 if (opendir my $dh, $gits) {
168                         my $max = -1;
169                         while (defined(my $git_dir = readdir($dh))) {
170                                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
171                                 $max = $1 if $1 > $max;
172                         }
173                         $cur = $self->{-max_git_epoch} = $max if $max >= 0;
174                 } else {
175                         warn "opendir $gits failed: $!\n";
176                 }
177         }
178         $cur;
179 }
180
181 sub mm {
182         my ($self) = @_;
183         $self->{mm} ||= eval {
184                 require PublicInbox::Msgmap;
185                 my $dir = $self->{inboxdir};
186                 if ($self->version >= 2) {
187                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
188                 } else {
189                         PublicInbox::Msgmap->new($dir);
190                 }
191         };
192 }
193
194 sub search ($;$) {
195         my ($self, $over_only) = @_;
196         my $srch = $self->{search} ||= eval {
197                 _cleanup_later($self);
198                 require PublicInbox::Search;
199                 PublicInbox::Search->new($self);
200         };
201         ($over_only || eval { $srch->xdb }) ? $srch : undef;
202 }
203
204 sub over ($) {
205         my ($self) = @_;
206         my $srch = search($self, 1) or return;
207         $self->{over} //= eval {
208                 my $over = $srch->{over_ro};
209                 $over->connect; # may fail
210                 $over;
211         }
212 }
213
214 sub try_cat {
215         my ($path) = @_;
216         my $rv = '';
217         if (open(my $fh, '<', $path)) {
218                 local $/;
219                 $rv = <$fh>;
220         }
221         $rv;
222 }
223
224 sub description {
225         my ($self) = @_;
226         ($self->{description} //= do {
227                 my $desc = try_cat("$self->{inboxdir}/description");
228                 local $/ = "\n";
229                 chomp $desc;
230                 utf8::decode($desc);
231                 $desc =~ s/\s+/ /smg;
232                 $desc eq '' ? undef : $desc;
233         }) // '($INBOX_DIR/description missing)';
234 }
235
236 sub cloneurl {
237         my ($self) = @_;
238         ($self->{cloneurl} //= do {
239                 my $s = try_cat("$self->{inboxdir}/cloneurl");
240                 my @urls = split(/\s+/s, $s);
241                 scalar(@urls) ? \@urls : undef
242         }) // [];
243 }
244
245 sub base_url {
246         my ($self, $env) = @_; # env - PSGI env
247         if ($env) {
248                 my $url = PublicInbox::Git::host_prefix_url($env, '');
249                 # for mount in Plack::Builder
250                 $url .= '/' if $url !~ m!/\z!;
251                 return $url .= $self->{name} . '/';
252         }
253         # called from a non-PSGI environment (e.g. NNTP/POP3):
254         $self->{-base_url} ||= do {
255                 my $url = $self->{url}->[0] or return undef;
256                 # expand protocol-relative URLs to HTTPS if we're
257                 # not inside a web server
258                 $url = "https:$url" if $url =~ m!\A//!;
259                 $url .= '/' if $url !~ m!/\z!;
260                 $url;
261         };
262 }
263
264 sub nntp_url {
265         my ($self) = @_;
266         $self->{-nntp_url} ||= do {
267                 # no checking for nntp_usable here, we can point entirely
268                 # to non-local servers or users run by a different user
269                 my $ns = $self->{nntpserver};
270                 my $group = $self->{newsgroup};
271                 my @urls;
272                 if ($ns && $group) {
273                         $ns = [ $ns ] if ref($ns) ne 'ARRAY';
274                         @urls = map {
275                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
276                                 $u .= '/' if $u !~ m!/\z!;
277                                 $u.$group;
278                         } @$ns;
279                 }
280
281                 my $mirrors = $self->{nntpmirror};
282                 if ($mirrors) {
283                         my @m;
284                         foreach (@$mirrors) {
285                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
286                                 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
287                                         if ($group) {
288                                                 $u .= '/' if $u !~ m!/\z!;
289                                                 $u .= $group;
290                                         } else {
291                                                 warn
292 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
293                                         }
294                                 }
295                                 # else: allow full URLs like:
296                                 # nntp://news.example.com/alt.example
297                                 push @m, $u;
298                         }
299
300                         # List::Util::uniq requires Perl 5.26+, maybe we
301                         # can use it by 2030 or so
302                         my %seen;
303                         @urls = grep { !$seen{$_}++ } (@urls, @m);
304                 }
305                 \@urls;
306         };
307 }
308
309 sub nntp_usable {
310         my ($self) = @_;
311         my $ret = mm($self) && over($self);
312         $self->{mm} = $self->{over} = $self->{search} = undef;
313         $ret;
314 }
315
316 # for v1 users w/o SQLite only
317 sub msg_by_path ($$) {
318         my ($self, $path) = @_;
319         git($self)->cat_file('HEAD:'.$path);
320 }
321
322 sub msg_by_smsg ($$) {
323         my ($self, $smsg) = @_;
324
325         # ghosts may have undef smsg (from SearchThread.node) or
326         # no {blob} field
327         return unless defined $smsg;
328         defined(my $blob = $smsg->{blob}) or return;
329
330         git($self)->cat_file($blob);
331 }
332
333 sub smsg_eml {
334         my ($self, $smsg) = @_;
335         my $bref = msg_by_smsg($self, $smsg) or return;
336         my $eml = PublicInbox::Eml->new($bref);
337         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
338         $eml;
339 }
340
341 sub mid2num($$) {
342         my ($self, $mid) = @_;
343         my $mm = mm($self) or return;
344         $mm->num_for($mid);
345 }
346
347 sub smsg_by_mid ($$) {
348         my ($self, $mid) = @_;
349         my $over = over($self) or return;
350         # favor the Message-ID we used for the NNTP article number:
351         defined(my $num = mid2num($self, $mid)) or return;
352         my $smsg = $over->get_art($num) or return;
353         PublicInbox::Smsg::psgi_cull($smsg);
354 }
355
356 sub msg_by_mid ($$) {
357         my ($self, $mid) = @_;
358
359         over($self) or
360                 return msg_by_path($self, mid2path($mid));
361
362         my $smsg = smsg_by_mid($self, $mid);
363         $smsg ? msg_by_smsg($self, $smsg) : undef;
364 }
365
366 sub recent {
367         my ($self, $opts, $after, $before) = @_;
368         over($self)->recent($opts, $after, $before);
369 }
370
371 sub modified {
372         my ($self) = @_;
373         if (my $over = over($self)) {
374                 my $msgs = $over->recent({limit => 1});
375                 if (my $smsg = $msgs->[0]) {
376                         return $smsg->{ts};
377                 }
378                 return time;
379         }
380         git($self)->modified; # v1
381 }
382
383 # returns prefix => pathname mapping
384 # (pathname is NOT public, but prefix is used for Xapian queries)
385 sub altid_map ($) {
386         my ($self) = @_;
387         $self->{-altid_map} //= eval {
388                 require PublicInbox::AltId;
389                 my $altid = $self->{altid} or return {};
390                 my %h = map {;
391                         my $x = PublicInbox::AltId->new($self, $_);
392                         "$x->{prefix}" => $x->{filename}
393                 } @$altid;
394                 \%h;
395         } // {};
396 }
397
398 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
399 sub subscribe_unlock {
400         my ($self, $ident, $obj) = @_;
401         $self->{unlock_subs}->{$ident} = $obj;
402 }
403
404 sub unsubscribe_unlock {
405         my ($self, $ident) = @_;
406         delete $self->{unlock_subs}->{$ident};
407 }
408
409 sub check_inodes ($) {
410         my ($self) = @_;
411         for (qw(over mm)) { # TODO: search
412                 $self->{$_}->check_inodes if $self->{$_};
413         }
414 }
415
416 # called by inotify
417 sub on_unlock {
418         my ($self) = @_;
419         check_inodes($self);
420         my $subs = $self->{unlock_subs} or return;
421         for (values %$subs) {
422                 eval { $_->on_inbox_unlock($self) };
423                 warn "E: $@ ($self->{inboxdir})\n" if $@;
424         }
425 }
426
427 1;