1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 package PublicInbox::GzipFilter;
7 use parent qw(Exporter);
8 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
9 our @EXPORT_OK = qw(gzip_maybe);
10 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
12 sub new { bless {}, shift }
14 # for Qspawn if using $env->{'pi-httpd.async'}
23 return if (($env->{HTTP_ACCEPT_ENCODING}) // '') !~ /\bgzip\b/;
25 # in case Plack::Middleware::Deflater is loaded:
26 $env->{'plack.skip-deflater'} = 1;
28 my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
29 $err == Z_OK ? $gz : undef;
32 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
36 # allocate the zlib context lazily here, instead of in ->new.
37 # Deflate contexts are memory-intensive and this object may
38 # be sitting in the Qspawn limiter queue for a while.
39 my $gz = $self->{gz} //= do {
40 my ($g, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
41 $err == Z_OK or die "Deflate->new failed: $err";
44 my $zbuf = delete($self->{zbuf});
45 if (defined $_[1]) { # my $buf = $_[1];
46 my $err = $gz->deflate($_[1], $zbuf);
47 die "gzip->deflate: $err" if $err != Z_OK;
48 return $zbuf if length($zbuf) >= 8192;
50 $self->{zbuf} = $zbuf;
52 } else { # undef == EOF
53 my $err = $gz->flush($zbuf, Z_FINISH);
54 die "gzip->flush: $err" if $err != Z_OK;
60 # my $ret = bytes::length($_[1]); # XXX does anybody care?
61 $_[0]->{fh}->write(translate($_[0], $_[1]));
66 my $fh = delete $self->{fh};
67 $fh->write(translate($self, undef));