]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GzipFilter.pm
c4858a971495449ce7e4fd35b3a0c123153ed07b
[public-inbox.git] / lib / PublicInbox / GzipFilter.pm
1 # Copyright (C) 2020-2021 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->{wcb_args} = [ $code, $res_hdr, $wcb ];
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 sub gone { # what: search/over/mm
88         my ($ctx, $what) = @_;
89         warn "W: `$ctx->{ibx}->{name}' $what went away unexpectedly\n";
90         undef;
91 }
92
93 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
94 # Also used for ->getline callbacks
95 sub translate ($$) {
96         my $self = $_[0]; # $_[1] => input
97
98         # allocate the zlib context lazily here, instead of in ->new.
99         # Deflate contexts are memory-intensive and this object may
100         # be sitting in the Qspawn limiter queue for a while.
101         my $gz = $self->{gz} //= gzip_or_die();
102         my $zbuf = delete($self->{zbuf});
103         if (defined $_[1]) { # my $buf = $_[1];
104                 my $err = $gz->deflate($_[1], $zbuf);
105                 die "gzip->deflate: $err" if $err != Z_OK;
106                 return $zbuf if length($zbuf) >= 8192;
107
108                 $self->{zbuf} = $zbuf;
109                 '';
110         } else { # undef == EOF
111                 my $err = $gz->flush($zbuf);
112                 die "gzip->flush: $err" if $err != Z_OK;
113                 $zbuf;
114         }
115 }
116
117 sub http_out ($) {
118         my ($self) = @_;
119         $self->{http_out} //= do {
120                 my $args = delete $self->{wcb_args} // return undef;
121                 pop(@$args)->($args); # $wcb->([$code, $hdr_ary])
122         };
123 }
124
125 sub write {
126         # my $ret = bytes::length($_[1]); # XXX does anybody care?
127         http_out($_[0])->write(translate($_[0], $_[1]));
128 }
129
130 # similar to ->translate; use this when we're sure we know we have
131 # more data to buffer after this
132 sub zmore {
133         my $self = $_[0]; # $_[1] => input
134         my $err = $self->{gz}->deflate($_[1], $self->{zbuf});
135         die "gzip->deflate: $err" if $err != Z_OK;
136         undef;
137 }
138
139 # flushes and returns the final bit of gzipped data
140 sub zflush ($;$) {
141         my $self = $_[0]; # $_[1] => final input (optional)
142         my $zbuf = delete $self->{zbuf};
143         my $gz = delete $self->{gz};
144         my $err;
145         if (defined $_[1]) {
146                 $err = $gz->deflate($_[1], $zbuf);
147                 die "gzip->deflate: $err" if $err != Z_OK;
148         }
149         $err = $gz->flush($zbuf);
150         die "gzip->flush: $err" if $err != Z_OK;
151         $zbuf;
152 }
153
154 sub close {
155         my ($self) = @_;
156         my $http_out = http_out($self) // return;
157         $http_out->write(zflush($self));
158         delete($self->{http_out})->close;
159 }
160
161 sub bail  {
162         my $self = shift;
163         if (my $env = $self->{env}) {
164                 warn @_, "\n";
165                 my $http = $env->{'psgix.io'} or return; # client abort
166                 eval { $http->close }; # should hit our close
167                 warn "E: error in http->close: $@" if $@;
168                 eval { $self->close }; # just in case...
169                 warn "E: error in self->close: $@" if $@;
170         } else {
171                 warn @_, "\n";
172         }
173 }
174
175 # this is public-inbox-httpd-specific
176 sub async_blob_cb { # git->cat_async callback
177         my ($bref, $oid, $type, $size, $self) = @_;
178         my $http = $self->{env}->{'psgix.io'};
179         $http->{forward} or return; # client aborted
180         my $smsg = $self->{smsg} or bail($self, 'BUG: no smsg');
181         if (!defined($oid)) {
182                 # it's possible to have TOCTOU if an admin runs
183                 # public-inbox-(edit|purge), just move onto the next message
184                 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
185                 return $http->next_step($self->can('async_next'));
186         }
187         $smsg->{blob} eq $oid or bail($self, "BUG: $smsg->{blob} != $oid");
188         eval { $self->async_eml(PublicInbox::Eml->new($bref)) };
189         bail($self, "E: async_eml: $@") if $@;
190         if ($self->{-low_prio}) {
191                 push(@{$self->{www}->{-low_prio_q}}, $self) == 1 and
192                                 PublicInbox::DS::requeue($self->{www});
193         } else {
194                 $http->next_step($self->can('async_next'));
195         }
196 }
197
198 sub smsg_blob {
199         my ($self, $smsg) = @_;
200         ibx_async_cat($self->{ibx}, $smsg->{blob}, \&async_blob_cb, $self);
201 }
202
203 1;