]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GzipFilter.pm
5f7016730810ea649374ca05140ffa9ba2890478
[public-inbox.git] / lib / PublicInbox / GzipFilter.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # In public-inbox <=1.5.0, public-inbox-httpd favored "getline"
5 # response bodies to take a "pull"-based approach to feeding
6 # slow clients (as opposed to a more common "push" model).
7 #
8 # In newer versions, public-inbox-httpd supports a backpressure-aware
9 # pull/push model which also accounts for slow git blob storage.
10 # async_next callbacks only run when the DS {wbuf} is drained
11 # async_eml callbacks only run when a blob arrives from git.
12 #
13 # We continue to support getline+close for generic PSGI servers.
14 package PublicInbox::GzipFilter;
15 use strict;
16 use parent qw(Exporter);
17 use Compress::Raw::Zlib qw(Z_OK);
18 use PublicInbox::CompressNoop;
19 use PublicInbox::Eml;
20 use PublicInbox::GitAsyncCat;
21
22 our @EXPORT_OK = qw(gzf_maybe);
23 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
24 my @GZIP_HDRS = qw(Vary Accept-Encoding Content-Encoding gzip);
25
26 sub new { bless {}, shift } # qspawn filter
27
28 # for Qspawn if using $env->{'pi-httpd.async'}
29 sub attach {
30         my ($self, $http_out) = @_;
31         $self->{http_out} = $http_out; # PublicInbox::HTTP::{Chunked,Identity}
32         $self
33 }
34
35 sub gz_or_noop {
36         my ($res_hdr, $env) = @_;
37         if (($env->{HTTP_ACCEPT_ENCODING} // '') =~ /\bgzip\b/) {
38                 $env->{'plack.skip-deflater'} = 1;
39                 push @$res_hdr, @GZIP_HDRS;
40                 gzip_or_die();
41         } else {
42                 PublicInbox::CompressNoop::new();
43         }
44 }
45
46 sub gzf_maybe ($$) { bless { gz => gz_or_noop(@_) }, __PACKAGE__ }
47
48 sub psgi_response {
49         my ($self, $code, $res_hdr) = @_;
50         my $env = $self->{env};
51         $self->{gz} //= gz_or_noop($res_hdr, $env);
52         if ($env->{'pi-httpd.async'}) {
53                 my $http = $env->{'psgix.io'}; # PublicInbox::HTTP
54                 $http->{forward} = $self;
55                 sub {
56                         my ($wcb) = @_; # -httpd provided write callback
57                         $self->{http_out} = $wcb->([$code, $res_hdr]);
58                         $self->can('async_next')->($http); # start stepping
59                 };
60         } else { # generic PSGI code path
61                 [ $code, $res_hdr, $self ];
62         }
63 }
64
65 sub qsp_maybe ($$) {
66         my ($res_hdr, $env) = @_;
67         return if ($env->{HTTP_ACCEPT_ENCODING} // '') !~ /\bgzip\b/;
68         my $hdr = join("\n", @$res_hdr);
69         return if $hdr !~ m!^Content-Type\n
70                                 (?:(?:text/(?:html|plain))|
71                                 application/atom\+xml)\b!ixsm;
72         return if $hdr =~ m!^Content-Encoding\ngzip\n!smi;
73         return if $hdr =~ m!^Content-Length\n[0-9]+\n!smi;
74         return if $hdr =~ m!^Transfer-Encoding\n!smi;
75         # in case Plack::Middleware::Deflater is loaded:
76         return if $env->{'plack.skip-deflater'}++;
77         push @$res_hdr, @GZIP_HDRS;
78         bless {}, __PACKAGE__;
79 }
80
81 sub gzip_or_die () {
82         my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
83         $err == Z_OK or die "Deflate->new failed: $err";
84         $gz;
85 }
86
87 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
88 # Also used for ->getline callbacks
89 sub translate ($$) {
90         my $self = $_[0]; # $_[1] => input
91
92         # allocate the zlib context lazily here, instead of in ->new.
93         # Deflate contexts are memory-intensive and this object may
94         # be sitting in the Qspawn limiter queue for a while.
95         my $gz = $self->{gz} //= gzip_or_die();
96         my $zbuf = delete($self->{zbuf});
97         if (defined $_[1]) { # my $buf = $_[1];
98                 my $err = $gz->deflate($_[1], $zbuf);
99                 die "gzip->deflate: $err" if $err != Z_OK;
100                 return $zbuf if length($zbuf) >= 8192;
101
102                 $self->{zbuf} = $zbuf;
103                 '';
104         } else { # undef == EOF
105                 my $err = $gz->flush($zbuf);
106                 die "gzip->flush: $err" if $err != Z_OK;
107                 $zbuf;
108         }
109 }
110
111 sub write {
112         # my $ret = bytes::length($_[1]); # XXX does anybody care?
113         $_[0]->{http_out}->write(translate($_[0], $_[1]));
114 }
115
116 # similar to ->translate; use this when we're sure we know we have
117 # more data to buffer after this
118 sub zmore {
119         my $self = $_[0]; # $_[1] => input
120         my $err = $self->{gz}->deflate($_[1], $self->{zbuf});
121         die "gzip->deflate: $err" if $err != Z_OK;
122         undef;
123 }
124
125 # flushes and returns the final bit of gzipped data
126 sub zflush ($;$) {
127         my $self = $_[0]; # $_[1] => final input (optional)
128         my $zbuf = delete $self->{zbuf};
129         my $gz = delete $self->{gz};
130         my $err;
131         if (defined $_[1]) {
132                 $err = $gz->deflate($_[1], $zbuf);
133                 die "gzip->deflate: $err" if $err != Z_OK;
134         }
135         $err = $gz->flush($zbuf);
136         die "gzip->flush: $err" if $err != Z_OK;
137         $zbuf;
138 }
139
140 sub close {
141         my ($self) = @_;
142         if (my $http_out = delete $self->{http_out}) {
143                 $http_out->write(zflush($self));
144                 $http_out->close;
145         }
146 }
147
148 sub bail  {
149         my $self = shift;
150         if (my $env = $self->{env}) {
151                 eval { $env->{'psgi.errors'}->print(@_, "\n") };
152                 warn("E: error printing to psgi.errors: $@", @_) if $@;
153                 my $http = $env->{'psgix.io'} or return; # client abort
154                 eval { $http->close }; # should hit our close
155                 warn "E: error in http->close: $@" if $@;
156                 eval { $self->close }; # just in case...
157                 warn "E: error in self->close: $@" if $@;
158         } else {
159                 warn @_, "\n";
160         }
161 }
162
163 # this is public-inbox-httpd-specific
164 sub async_blob_cb { # git->cat_async callback
165         my ($bref, $oid, $type, $size, $self) = @_;
166         my $http = $self->{env}->{'psgix.io'};
167         $http->{forward} or return; # client aborted
168         my $smsg = $self->{smsg} or bail($self, 'BUG: no smsg');
169         if (!defined($oid)) {
170                 # it's possible to have TOCTOU if an admin runs
171                 # public-inbox-(edit|purge), just move onto the next message
172                 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
173                 return $http->next_step($self->can('async_next'));
174         }
175         $smsg->{blob} eq $oid or bail($self, "BUG: $smsg->{blob} != $oid");
176         eval { $self->async_eml(PublicInbox::Eml->new($bref)) };
177         bail($self, "E: async_eml: $@") if $@;
178         $http->next_step($self->can('async_next'));
179 }
180
181 sub smsg_blob {
182         my ($self, $smsg) = @_;
183         git_async_cat($self->{ibx}->git, $smsg->{blob},
184                         \&async_blob_cb, $self);
185 }
186
187 1;