]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GzipFilter.pm
www: $MSGID/raw: set charset in HTTP response
[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         # $code may be an HTTP response code (e.g. 200) or a CODE ref (mbox_hdr)
50         my ($self, $code, $res_hdr) = @_;
51         if ($self->{env}->{'pi-httpd.async'}) {
52                 my $http = $self->{env}->{'psgix.io'}; # PublicInbox::HTTP
53                 $http->{forward} = $self;
54                 sub {
55                         my ($wcb) = @_; # -httpd provided write callback
56                         $self->{wcb_args} = [ $code, $res_hdr, $wcb ];
57                         $self->can('async_next')->($http); # start stepping
58                 };
59         } else { # generic PSGI code path
60                 ref($code) eq 'CODE' and
61                         ($code, $res_hdr) = @{$code->($self)};
62                 $self->{gz} //= gz_or_noop($res_hdr, $self->{env});
63                 [ $code, $res_hdr, $self ];
64         }
65 }
66
67 sub qsp_maybe ($$) {
68         my ($res_hdr, $env) = @_;
69         return if ($env->{HTTP_ACCEPT_ENCODING} // '') !~ /\bgzip\b/;
70         my $hdr = join("\n", @$res_hdr);
71         return if $hdr !~ m!^Content-Type\n
72                                 (?:(?:text/(?:html|plain))|
73                                 application/atom\+xml)\b!ixsm;
74         return if $hdr =~ m!^Content-Encoding\ngzip\n!smi;
75         return if $hdr =~ m!^Content-Length\n[0-9]+\n!smi;
76         return if $hdr =~ m!^Transfer-Encoding\n!smi;
77         # in case Plack::Middleware::Deflater is loaded:
78         return if $env->{'plack.skip-deflater'}++;
79         push @$res_hdr, @GZIP_HDRS;
80         bless {}, __PACKAGE__;
81 }
82
83 sub gzip_or_die () {
84         my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
85         $err == Z_OK or die "Deflate->new failed: $err";
86         $gz;
87 }
88
89 sub gone { # what: search/over/mm
90         my ($ctx, $what) = @_;
91         warn "W: `$ctx->{ibx}->{name}' $what went away unexpectedly\n";
92         undef;
93 }
94
95 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
96 # Also used for ->getline callbacks
97 sub translate ($$) {
98         my $self = $_[0]; # $_[1] => input
99
100         # allocate the zlib context lazily here, instead of in ->new.
101         # Deflate contexts are memory-intensive and this object may
102         # be sitting in the Qspawn limiter queue for a while.
103         my $gz = $self->{gz} //= gzip_or_die();
104         my $zbuf = delete($self->{zbuf});
105         if (defined $_[1]) { # my $buf = $_[1];
106                 my $err = $gz->deflate($_[1], $zbuf);
107                 die "gzip->deflate: $err" if $err != Z_OK;
108                 return $zbuf if length($zbuf) >= 8192;
109
110                 $self->{zbuf} = $zbuf;
111                 '';
112         } else { # undef == EOF
113                 my $err = $gz->flush($zbuf);
114                 die "gzip->flush: $err" if $err != Z_OK;
115                 $zbuf;
116         }
117 }
118
119 sub http_out ($) {
120         my ($self) = @_;
121         $self->{http_out} // do {
122                 my $args = delete $self->{wcb_args} // return undef;
123                 my $wcb = pop @$args; # from PublicInbox:HTTP async
124                 # $args->[0] may be \&mbox_hdr or similar
125                 $args = $args->[0]->($self) if ref($args->[0]) eq 'CODE';
126                 $self->{gz} //= gz_or_noop($args->[1], $self->{env});
127                 $self->{http_out} = $wcb->($args); # $wcb->([$code, $hdr_ary])
128         };
129 }
130
131 sub write {
132         # my $ret = bytes::length($_[1]); # XXX does anybody care?
133         http_out($_[0])->write(translate($_[0], $_[1]));
134 }
135
136 # similar to ->translate; use this when we're sure we know we have
137 # more data to buffer after this
138 sub zmore {
139         my $self = $_[0]; # $_[1] => input
140         http_out($self);
141         my $err = $self->{gz}->deflate($_[1], $self->{zbuf});
142         die "gzip->deflate: $err" if $err != Z_OK;
143         undef;
144 }
145
146 # flushes and returns the final bit of gzipped data
147 sub zflush ($;$) {
148         my $self = $_[0]; # $_[1] => final input (optional)
149         my $zbuf = delete $self->{zbuf};
150         my $gz = delete $self->{gz};
151         my $err;
152         if (defined $_[1]) {
153                 $err = $gz->deflate($_[1], $zbuf);
154                 die "gzip->deflate: $err" if $err != Z_OK;
155         }
156         $err = $gz->flush($zbuf);
157         die "gzip->flush: $err" if $err != Z_OK;
158         $zbuf;
159 }
160
161 sub close {
162         my ($self) = @_;
163         my $http_out = http_out($self) // return;
164         $http_out->write(zflush($self));
165         delete($self->{http_out})->close;
166 }
167
168 sub bail  {
169         my $self = shift;
170         if (my $env = $self->{env}) {
171                 warn @_, "\n";
172                 my $http = $env->{'psgix.io'} or return; # client abort
173                 eval { $http->close }; # should hit our close
174                 warn "E: error in http->close: $@" if $@;
175                 eval { $self->close }; # just in case...
176                 warn "E: error in self->close: $@" if $@;
177         } else {
178                 warn @_, "\n";
179         }
180 }
181
182 # this is public-inbox-httpd-specific
183 sub async_blob_cb { # git->cat_async callback
184         my ($bref, $oid, $type, $size, $self) = @_;
185         my $http = $self->{env}->{'psgix.io'};
186         $http->{forward} or return; # client aborted
187         my $smsg = $self->{smsg} or bail($self, 'BUG: no smsg');
188         if (!defined($oid)) {
189                 # it's possible to have TOCTOU if an admin runs
190                 # public-inbox-(edit|purge), just move onto the next message
191                 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
192                 return $http->next_step($self->can('async_next'));
193         }
194         $smsg->{blob} eq $oid or bail($self, "BUG: $smsg->{blob} != $oid");
195         eval { $self->async_eml(PublicInbox::Eml->new($bref)) };
196         bail($self, "E: async_eml: $@") if $@;
197         if ($self->{-low_prio}) {
198                 push(@{$self->{www}->{-low_prio_q}}, $self) == 1 and
199                                 PublicInbox::DS::requeue($self->{www});
200         } else {
201                 $http->next_step($self->can('async_next'));
202         }
203 }
204
205 sub smsg_blob {
206         my ($self, $smsg) = @_;
207         ibx_async_cat($self->{ibx}, $smsg->{blob}, \&async_blob_cb, $self);
208 }
209
210 1;