]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
inbox: simplify v2 epoch counting
[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 PublicInbox::Git;
8 use PublicInbox::MID qw(mid2path);
9 use PublicInbox::Eml;
10 use List::Util qw(max);
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_limiter ($$$) {
78         my ($self, $pi_cfg, $pfx) = @_;
79         my $lkey = "-${pfx}_limiter";
80         $self->{$lkey} ||= do {
81                 # full key is: publicinbox.$NAME.httpbackendmax
82                 my $mkey = $pfx.'max';
83                 my $val = $self->{$mkey} or return;
84                 my $lim;
85                 if ($val =~ /\A[0-9]+\z/) {
86                         require PublicInbox::Qspawn;
87                         $lim = PublicInbox::Qspawn::Limiter->new($val);
88                 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
89                         $lim = $pi_cfg->limiter($val);
90                         warn "$mkey limiter=$val not found\n" if !$lim;
91                 } else {
92                         warn "$mkey limiter=$val not understood\n";
93                 }
94                 $lim;
95         }
96 }
97
98 sub new {
99         my ($class, $opts) = @_;
100         my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
101         my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
102         $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
103         my $pi_cfg = delete $opts->{-pi_cfg};
104         _set_limiter($opts, $pi_cfg, 'httpbackend');
105         my $fmax = $opts->{feedmax};
106         if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
107                 $opts->{feedmax} += 0;
108         } else {
109                 delete $opts->{feedmax};
110         }
111         $opts->{nntpserver} ||= $pi_cfg->{'publicinbox.nntpserver'};
112         my $dir = $opts->{inboxdir};
113         if (defined $dir && -f "$dir/inbox.lock") {
114                 $opts->{version} = 2;
115         }
116
117         # allow any combination of multi-line or comma-delimited hide entries
118         my $hide = {};
119         if (defined(my $h = $opts->{hide})) {
120                 foreach my $v (@$h) {
121                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
122                 }
123                 $opts->{-hide} = $hide;
124         }
125         bless $opts, $class;
126 }
127
128 sub version { $_[0]->{version} // 1 }
129
130 sub git_epoch {
131         my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
132         $self->{"$epoch.git"} ||= do {
133                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
134                 return unless -d $git_dir;
135                 my $g = PublicInbox::Git->new($git_dir);
136                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
137                 # no cleanup needed, we never cat-file off this, only clone
138                 $g;
139         };
140 }
141
142 sub git {
143         my ($self) = @_;
144         $self->{git} ||= do {
145                 my $git_dir = $self->{inboxdir};
146                 $git_dir .= '/all.git' if $self->version == 2;
147                 my $g = PublicInbox::Git->new($git_dir);
148                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
149                 _cleanup_later($self);
150                 $g;
151         };
152 }
153
154 sub max_git_epoch {
155         my ($self) = @_;
156         return if $self->version < 2;
157         my $cur = $self->{-max_git_epoch};
158         my $changed;
159         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
160                 git_cleanup($self) if $changed;
161                 my $gits = "$self->{inboxdir}/git";
162                 if (opendir my $dh, $gits) {
163                         my $max = max(map {
164                                 substr($_, 0, -4) + 0; # drop ".git" suffix
165                         } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
166                         $cur = $self->{-max_git_epoch} = $max;
167                 }
168         }
169         $cur;
170 }
171
172 sub mm {
173         my ($self) = @_;
174         $self->{mm} ||= eval {
175                 require PublicInbox::Msgmap;
176                 my $dir = $self->{inboxdir};
177                 if ($self->version >= 2) {
178                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
179                 } else {
180                         PublicInbox::Msgmap->new($dir);
181                 }
182         };
183 }
184
185 sub search {
186         my ($self) = @_;
187         my $srch = $self->{search} //= eval {
188                 _cleanup_later($self);
189                 require PublicInbox::Search;
190                 PublicInbox::Search->new($self);
191         };
192         (eval { $srch->xdb }) ? $srch : undef;
193 }
194
195 # isrch is preferred for read-only interfaces if available since it
196 # reduces kernel cache and FD overhead
197 sub isrch { $_[0]->{isrch} // search($_[0]) }
198
199 sub over {
200         $_[0]->{over} //= eval {
201                 my $srch = $_[0]->{search} //= eval {
202                         _cleanup_later($_[0]);
203                         require PublicInbox::Search;
204                         PublicInbox::Search->new($_[0]);
205                 };
206                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
207                 $over->dbh; # may fail
208                 $over;
209         };
210 }
211
212
213 sub try_cat {
214         my ($path) = @_;
215         my $rv = '';
216         if (open(my $fh, '<', $path)) {
217                 local $/;
218                 $rv = <$fh>;
219         }
220         $rv;
221 }
222
223 sub cat_desc ($) {
224         my $desc = try_cat($_[0]);
225         local $/ = "\n";
226         chomp $desc;
227         utf8::decode($desc);
228         $desc =~ s/\s+/ /smg;
229         $desc eq '' ? undef : $desc;
230 }
231
232 sub description {
233         my ($self) = @_;
234         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
235                 '($INBOX_DIR/description missing)';
236 }
237
238 sub cloneurl {
239         my ($self) = @_;
240         ($self->{cloneurl} //= do {
241                 my $s = try_cat("$self->{inboxdir}/cloneurl");
242                 my @urls = split(/\s+/s, $s);
243                 scalar(@urls) ? \@urls : undef
244         }) // [];
245 }
246
247 sub base_url {
248         my ($self, $env) = @_; # env - PSGI env
249         if ($env) {
250                 my $url = PublicInbox::Git::host_prefix_url($env, '');
251                 # for mount in Plack::Builder
252                 $url .= '/' if $url !~ m!/\z!;
253                 return $url .= $self->{name} . '/';
254         }
255         # called from a non-PSGI environment (e.g. NNTP/POP3):
256         $self->{-base_url} ||= do {
257                 my $url = $self->{url}->[0] or return undef;
258                 # expand protocol-relative URLs to HTTPS if we're
259                 # not inside a web server
260                 $url = "https:$url" if $url =~ m!\A//!;
261                 $url .= '/' if $url !~ m!/\z!;
262                 $url;
263         };
264 }
265
266 sub nntp_url {
267         my ($self) = @_;
268         $self->{-nntp_url} ||= do {
269                 # no checking for nntp_usable here, we can point entirely
270                 # to non-local servers or users run by a different user
271                 my $ns = $self->{nntpserver};
272                 my $group = $self->{newsgroup};
273                 my @urls;
274                 if ($ns && $group) {
275                         $ns = [ $ns ] if ref($ns) ne 'ARRAY';
276                         @urls = map {
277                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
278                                 $u .= '/' if $u !~ m!/\z!;
279                                 $u.$group;
280                         } @$ns;
281                 }
282
283                 my $mirrors = $self->{nntpmirror};
284                 if ($mirrors) {
285                         my @m;
286                         foreach (@$mirrors) {
287                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
288                                 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
289                                         if ($group) {
290                                                 $u .= '/' if $u !~ m!/\z!;
291                                                 $u .= $group;
292                                         } else {
293                                                 warn
294 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
295                                         }
296                                 }
297                                 # else: allow full URLs like:
298                                 # nntp://news.example.com/alt.example
299                                 push @m, $u;
300                         }
301
302                         # List::Util::uniq requires Perl 5.26+, maybe we
303                         # can use it by 2030 or so
304                         my %seen;
305                         @urls = grep { !$seen{$_}++ } (@urls, @m);
306                 }
307                 \@urls;
308         };
309 }
310
311 sub nntp_usable {
312         my ($self) = @_;
313         my $ret = mm($self) && over($self);
314         $self->{mm} = $self->{over} = $self->{search} = undef;
315         $ret;
316 }
317
318 # for v1 users w/o SQLite only
319 sub msg_by_path ($$) {
320         my ($self, $path) = @_;
321         git($self)->cat_file('HEAD:'.$path);
322 }
323
324 sub msg_by_smsg ($$) {
325         my ($self, $smsg) = @_;
326
327         # ghosts may have undef smsg (from SearchThread.node) or
328         # no {blob} field
329         return unless defined $smsg;
330         defined(my $blob = $smsg->{blob}) or return;
331
332         $self->git->cat_file($blob);
333 }
334
335 sub smsg_eml {
336         my ($self, $smsg) = @_;
337         my $bref = msg_by_smsg($self, $smsg) or return;
338         my $eml = PublicInbox::Eml->new($bref);
339         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
340         $eml;
341 }
342
343 sub smsg_by_mid ($$) {
344         my ($self, $mid) = @_;
345         my $over = $self->over or return;
346         my $smsg;
347         if (my $mm = $self->mm) {
348                 # favor the Message-ID we used for the NNTP article number:
349                 defined(my $num = $mm->num_for($mid)) or return;
350                 $smsg = $over->get_art($num);
351         } else {
352                 my ($id, $prev);
353                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
354         }
355         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
356 }
357
358 sub msg_by_mid ($$) {
359         my ($self, $mid) = @_;
360         my $smsg = smsg_by_mid($self, $mid);
361         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
362 }
363
364 sub recent {
365         my ($self, $opts, $after, $before) = @_;
366         $self->over->recent($opts, $after, $before);
367 }
368
369 sub modified {
370         my ($self) = @_;
371         if (my $over = $self->over) {
372                 my $msgs = $over->recent({limit => 1});
373                 if (my $smsg = $msgs->[0]) {
374                         return $smsg->{ts};
375                 }
376                 return time;
377         }
378         git($self)->modified; # v1
379 }
380
381 # returns prefix => pathname mapping
382 # (pathname is NOT public, but prefix is used for Xapian queries)
383 sub altid_map ($) {
384         my ($self) = @_;
385         $self->{-altid_map} //= eval {
386                 require PublicInbox::AltId;
387                 my $altid = $self->{altid} or return {};
388                 my %h = map {;
389                         my $x = PublicInbox::AltId->new($self, $_);
390                         "$x->{prefix}" => $x->{filename}
391                 } @$altid;
392                 \%h;
393         } // {};
394 }
395
396 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
397 sub subscribe_unlock {
398         my ($self, $ident, $obj) = @_;
399         $self->{unlock_subs}->{$ident} = $obj;
400 }
401
402 sub unsubscribe_unlock {
403         my ($self, $ident) = @_;
404         delete $self->{unlock_subs}->{$ident};
405 }
406
407 sub check_inodes ($) {
408         my ($self) = @_;
409         for (qw(over mm)) { # TODO: search
410                 $self->{$_}->check_inodes if $self->{$_};
411         }
412 }
413
414 # called by inotify
415 sub on_unlock {
416         my ($self) = @_;
417         check_inodes($self);
418         my $subs = $self->{unlock_subs} or return;
419         for (values %$subs) {
420                 eval { $_->on_inbox_unlock($self) };
421                 warn "E: $@ ($self->{inboxdir})\n" if $@;
422         }
423 }
424
425 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
426
427 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
428
429 1;