]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
manifest: use ibx->git_epoch method for v2
[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                 return unless -d $git_dir;
141                 my $g = PublicInbox::Git->new($git_dir);
142                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
143                 # no cleanup needed, we never cat-file off this, only clone
144                 $g;
145         };
146 }
147
148 sub git {
149         my ($self) = @_;
150         $self->{git} ||= do {
151                 my $git_dir = $self->{inboxdir};
152                 $git_dir .= '/all.git' if $self->version == 2;
153                 my $g = PublicInbox::Git->new($git_dir);
154                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
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 = git($self)->alternates_changed;
165         if (!defined($cur) || $changed) {
166                 git_cleanup($self) if $changed;
167                 my $gits = "$self->{inboxdir}/git";
168                 if (opendir my $dh, $gits) {
169                         my $max = -1;
170                         while (defined(my $git_dir = readdir($dh))) {
171                                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
172                                 $max = $1 if $1 > $max;
173                         }
174                         $cur = $self->{-max_git_epoch} = $max if $max >= 0;
175                 } else {
176                         warn "opendir $gits failed: $!\n";
177                 }
178         }
179         $cur;
180 }
181
182 sub mm {
183         my ($self) = @_;
184         $self->{mm} ||= eval {
185                 require PublicInbox::Msgmap;
186                 my $dir = $self->{inboxdir};
187                 if ($self->version >= 2) {
188                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
189                 } else {
190                         PublicInbox::Msgmap->new($dir);
191                 }
192         };
193 }
194
195 sub search ($;$$) {
196         my ($self, $over_only, $ctx) = @_;
197         my $srch = $self->{search} ||= eval {
198                 _cleanup_later($self);
199                 require PublicInbox::Search;
200                 PublicInbox::Search->new($self);
201         };
202         ($over_only || eval { $srch->xdb }) ? $srch : do {
203                 $ctx and $ctx->{env}->{'psgi.errors'}->print(<<EOF);
204 `$self->{name}' search went away unexpectedly
205 EOF
206                 undef;
207         };
208 }
209
210 sub over {
211         $_[0]->{over} //= eval {
212                 my $srch = search($_[0], 1) or return;
213                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
214                 $over->dbh; # may fail
215                 $over;
216         };
217 }
218
219 sub try_cat {
220         my ($path) = @_;
221         my $rv = '';
222         if (open(my $fh, '<', $path)) {
223                 local $/;
224                 $rv = <$fh>;
225         }
226         $rv;
227 }
228
229 sub cat_desc ($) {
230         my $desc = try_cat($_[0]);
231         local $/ = "\n";
232         chomp $desc;
233         utf8::decode($desc);
234         $desc =~ s/\s+/ /smg;
235         $desc eq '' ? undef : $desc;
236 }
237
238 sub description {
239         my ($self) = @_;
240         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
241                 '($INBOX_DIR/description missing)';
242 }
243
244 sub cloneurl {
245         my ($self) = @_;
246         ($self->{cloneurl} //= do {
247                 my $s = try_cat("$self->{inboxdir}/cloneurl");
248                 my @urls = split(/\s+/s, $s);
249                 scalar(@urls) ? \@urls : undef
250         }) // [];
251 }
252
253 sub base_url {
254         my ($self, $env) = @_; # env - PSGI env
255         if ($env) {
256                 my $url = PublicInbox::Git::host_prefix_url($env, '');
257                 # for mount in Plack::Builder
258                 $url .= '/' if $url !~ m!/\z!;
259                 return $url .= $self->{name} . '/';
260         }
261         # called from a non-PSGI environment (e.g. NNTP/POP3):
262         $self->{-base_url} ||= do {
263                 my $url = $self->{url}->[0] or return undef;
264                 # expand protocol-relative URLs to HTTPS if we're
265                 # not inside a web server
266                 $url = "https:$url" if $url =~ m!\A//!;
267                 $url .= '/' if $url !~ m!/\z!;
268                 $url;
269         };
270 }
271
272 sub nntp_url {
273         my ($self) = @_;
274         $self->{-nntp_url} ||= do {
275                 # no checking for nntp_usable here, we can point entirely
276                 # to non-local servers or users run by a different user
277                 my $ns = $self->{nntpserver};
278                 my $group = $self->{newsgroup};
279                 my @urls;
280                 if ($ns && $group) {
281                         $ns = [ $ns ] if ref($ns) ne 'ARRAY';
282                         @urls = map {
283                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
284                                 $u .= '/' if $u !~ m!/\z!;
285                                 $u.$group;
286                         } @$ns;
287                 }
288
289                 my $mirrors = $self->{nntpmirror};
290                 if ($mirrors) {
291                         my @m;
292                         foreach (@$mirrors) {
293                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
294                                 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
295                                         if ($group) {
296                                                 $u .= '/' if $u !~ m!/\z!;
297                                                 $u .= $group;
298                                         } else {
299                                                 warn
300 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
301                                         }
302                                 }
303                                 # else: allow full URLs like:
304                                 # nntp://news.example.com/alt.example
305                                 push @m, $u;
306                         }
307
308                         # List::Util::uniq requires Perl 5.26+, maybe we
309                         # can use it by 2030 or so
310                         my %seen;
311                         @urls = grep { !$seen{$_}++ } (@urls, @m);
312                 }
313                 \@urls;
314         };
315 }
316
317 sub nntp_usable {
318         my ($self) = @_;
319         my $ret = mm($self) && over($self);
320         $self->{mm} = $self->{over} = $self->{search} = undef;
321         $ret;
322 }
323
324 # for v1 users w/o SQLite only
325 sub msg_by_path ($$) {
326         my ($self, $path) = @_;
327         git($self)->cat_file('HEAD:'.$path);
328 }
329
330 sub msg_by_smsg ($$) {
331         my ($self, $smsg) = @_;
332
333         # ghosts may have undef smsg (from SearchThread.node) or
334         # no {blob} field
335         return unless defined $smsg;
336         defined(my $blob = $smsg->{blob}) or return;
337
338         $self->git->cat_file($blob);
339 }
340
341 sub smsg_eml {
342         my ($self, $smsg) = @_;
343         my $bref = msg_by_smsg($self, $smsg) or return;
344         my $eml = PublicInbox::Eml->new($bref);
345         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
346         $eml;
347 }
348
349 sub smsg_by_mid ($$) {
350         my ($self, $mid) = @_;
351         my $over = $self->over or return;
352         my $smsg;
353         if (my $mm = $self->mm) {
354                 # favor the Message-ID we used for the NNTP article number:
355                 defined(my $num = $mm->num_for($mid)) or return;
356                 $smsg = $over->get_art($num);
357         } else {
358                 my ($id, $prev);
359                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
360         }
361         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
362 }
363
364 sub msg_by_mid ($$) {
365         my ($self, $mid) = @_;
366         my $smsg = smsg_by_mid($self, $mid);
367         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
368 }
369
370 sub recent {
371         my ($self, $opts, $after, $before) = @_;
372         $self->over->recent($opts, $after, $before);
373 }
374
375 sub modified {
376         my ($self) = @_;
377         if (my $over = $self->over) {
378                 my $msgs = $over->recent({limit => 1});
379                 if (my $smsg = $msgs->[0]) {
380                         return $smsg->{ts};
381                 }
382                 return time;
383         }
384         git($self)->modified; # v1
385 }
386
387 # returns prefix => pathname mapping
388 # (pathname is NOT public, but prefix is used for Xapian queries)
389 sub altid_map ($) {
390         my ($self) = @_;
391         $self->{-altid_map} //= eval {
392                 require PublicInbox::AltId;
393                 my $altid = $self->{altid} or return {};
394                 my %h = map {;
395                         my $x = PublicInbox::AltId->new($self, $_);
396                         "$x->{prefix}" => $x->{filename}
397                 } @$altid;
398                 \%h;
399         } // {};
400 }
401
402 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
403 sub subscribe_unlock {
404         my ($self, $ident, $obj) = @_;
405         $self->{unlock_subs}->{$ident} = $obj;
406 }
407
408 sub unsubscribe_unlock {
409         my ($self, $ident) = @_;
410         delete $self->{unlock_subs}->{$ident};
411 }
412
413 sub check_inodes ($) {
414         my ($self) = @_;
415         for (qw(over mm)) { # TODO: search
416                 $self->{$_}->check_inodes if $self->{$_};
417         }
418 }
419
420 # called by inotify
421 sub on_unlock {
422         my ($self) = @_;
423         check_inodes($self);
424         my $subs = $self->{unlock_subs} or return;
425         for (values %$subs) {
426                 eval { $_->on_inbox_unlock($self) };
427                 warn "E: $@ ($self->{inboxdir})\n" if $@;
428         }
429 }
430
431 sub uidvalidity  { $_[0]->{uidvalidity} //= $_[0]->mm->created_at }
432
433 1;