Net/Async/HTTP/Server/PSGI.pm

filter: Statementstmt 98.9% 95 / 96 Branchbran 84.0% 37 / 44 Conditioncond 50.0% 4 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 100% 16 / 16 Podpod 100% 2 / 2 totaltotal 90.0% 154 / 171 CC 29 SCAR 22.1
CC
29
Cov
92%
__ANON__
17.1
on_request
9.1
__ANON__
3.0
CRAP 9.1
« Plack/Handler/Net/Async/HTTP/Server.pm ↑ Summary Net/Async/HTTP/Server/Protocol.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2013-2024 -- leonerd@leonerd.org.uk
5  
6 package Net::Async::HTTP::Server::PSGI 0.15;
7  
8 4 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 4 ▶use base qw( Net::Async::HTTP::Server );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 4 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 4 my $CRLF = "\x0d\x0a";
18  
19 =head1 NAME
20  
21 C<Net::Async::HTTP::Server::PSGI> - use C<PSGI> applications with C<Net::Async::HTTP::Server>
22  
23 =head1 SYNOPSIS
24  
25 use Net::Async::HTTP::Server::PSGI;
26 use IO::Async::Loop;
27  
28 my $loop = IO::Async::Loop->new;
29  
30 my $httpserver = Net::Async::HTTP::Server::PSGI->new(
31 app => sub {
32 my $env = shift;
33  
34 return [
35 200,
36 [ "Content-Type" => "text/plain" ],
37 [ "Hello, world!" ],
38 ];
39 },
40 );
41  
42 $loop->add( $httpserver );
43  
44 $httpserver->listen(
45 addr => { family => "inet6", socktype => "stream", port => 8080 },
46 )->get;
47  
48 $loop->run;
49  
50 =head1 DESCRIPTION
51  
52 This subclass of L<Net::Async::HTTP::Server> allows an HTTP server to use a
53 L<PSGI> application to respond to requests. It acts as a gateway between the
54 HTTP connection from the web client, and the C<PSGI> application. Aside from
55 the use of C<PSGI> instead of the C<on_request> event, this class behaves
56 similarly to C<Net::Async::HTTP::Server>.
57  
58 To handle the content length when sending responses, the PSGI implementation
59 may add a header to the response. When sending a plain C<ARRAY> of strings, if
60 a C<Content-Length> header is absent, the length will be calculated by taking
61 the total of all the strings in the array, and setting the length header. When
62 sending content from an IO reference or using the streaming responder C<CODE>
63 reference, the C<Transfer-Encoding> header will be set to C<chunked>, and all
64 writes will be performed as C<HTTP/1.1> chunks.
65  
66 =cut
67  
68 =head1 PARAMETERS
69  
70 The following named parameters may be passed to C<new> or C<configure>:
71  
72 =over 8
73  
74 =item app => CODE
75  
76 Reference to the actual C<PSGI> application to use for responding to requests
77  
78 =back
79  
80 =cut
81  
82 sub configure
83 14 ▶{
Subroutine configure: called CC=2 SCAR=6.9
Pod documented
84 14 my $self = shift;
85 14 my %args = @_;
86  
87 14 ▶ if( exists $args{app} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"app"}) 11 3 14
88 11 $self->{app} = delete $args{app};
89 }
90  
91 14 $self->SUPER::configure( %args );
92 }
93  
94 =head1 PSGI ENVIRONMENT
95  
96 The following extra keys are supplied to the environment of the C<PSGI> app:
97  
98 =over 8
99  
100 =item C<psgix.io>
101  
102 The actual L<IO::Socket> filehandle that the request was received on.
103  
104 If the server is running under SSL for HTTPS, this will be an
105 L<IO::Socket::SSL> instance, so reading from or writing to it will happen in
106 cleartext.
107  
108 =item C<net.async.http.server>
109  
110 The C<Net::Async::HTTP::Server::PSGI> object serving the request
111  
112 =item C<net.async.http.server.req>
113  
114 The L<Net::Async::HTTP::Server::Request> object representing this particular
115 request
116  
117 =item C<io.async.loop>
118  
119 The L<IO::Async::Loop> object that the C<Net::Async::HTTP::Server::PSGI>
120 object is a member of.
121  
122 =back
123  
124 =cut
125  
126 sub on_request
127 10 ▶{
Subroutine on_request: called CC=9 SCAR=22.1
Pod documented
128 10 my $self = shift;
129 10 my ( $req ) = @_;
130  
131 # Much of this code stolen fro^W^Winspired by Plack::Handler::Net::FastCGI
132  
133 10 open my $stdin, "<", \$req->body;
134  
135 10 my $socket = $req->stream->read_handle;
136  
137 10 my $path_info = $req->path;
138 10 ▶ $path_info = "" if $path_info eq "/";
Branch: 1 branch
BranchTrueFalseTotal
if $path_info eq "/" 9 1 10
139  
140 10 ▶ my %env = (
Condition50%1/2
$req->query_string // ""
l!l
010
MC/DC0%0/1
$req->query_string // ""
$req->query_string
Truth table50%1/2
A
A= $req->query_string
Aresult
11
00
141 SERVER_PROTOCOL => $req->protocol,
142 SCRIPT_NAME => '',
143 PATH_INFO => $path_info,
144 QUERY_STRING => $req->query_string // "",
145 REQUEST_METHOD => $req->method,
146 REQUEST_URI => $req->path,
147 'psgi.version' => [1,0],
148 'psgi.url_scheme' => "http",
149 'psgi.input' => $stdin,
150 'psgi.errors' => \*STDERR,
151 'psgi.multithread' => 0,
152 'psgi.multiprocess' => 0,
153 'psgi.run_once' => 0,
154 'psgi.nonblocking' => 1,
155 'psgi.streaming' => 1,
156  
157 # Extensions
158 'psgix.io' => $socket,
159 'psgix.input.buffered' => 1, # we're using a PerlIO scalar handle
160 'net.async.http.server' => $self,
161 'net.async.http.server.req' => $req,
162 'io.async.loop' => $self->get_loop,
163 );
164  
165 10 ▶ if( $socket->can( "sockport" ) ) { # INET or IP
Branch: 2 branches
BranchTrueFalseTotal
if ($socket->can('sockport')) { } 10 0 10
elsif ($socket->can('hostpath')) { } 0 0 0
166 10 %env = ( %env,
167 SERVER_PORT => $socket->sockport,
168 SERVER_NAME => $socket->sockhost,
169 REMOTE_ADDR => $socket->peerhost,
170 REMOTE_PORT => $socket->peerport,
171 );
172 }
173 elsif( $socket->can( "hostpath" ) ) { # UNIX
174 0 %env = ( %env,
175 SERVER_PORT => $socket->hostpath,
176 SERVER_NAME => "localhost", # not really but we can lie
177 # no REMOTE_*
178 );
179 }
180  
181 10 foreach ( $req->headers ) {
182 4 my ( $name, $value ) = @$_;
183 4 $name =~ s/-/_/g;
184 4 $name = uc $name;
185  
186 # Content-Length and Content-Type don't get HTTP_ prefix
187 4 ▶ $name = "HTTP_$name" unless $name =~ m/^CONTENT_(?:LENGTH|TYPE)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^CONTENT_(?:LENGTH|TYPE)$/u 2 2 4
188  
189 4 $env{$name} = $value;
190 }
191  
192 10 my $resp = $self->{app}->( \%env );
193  
194 10 ▶ my $responder = sub {
Subroutine __ANON__: called CC=17 SCAR=28.4
195 10 my ( $status, $headers, $body ) = @{ +shift };
196  
197 10 my $response = HTTP::Response->new( $status );
198 10 $response->protocol( $req->protocol );
199  
200 10 my $has_content_length = 0;
201 10 my $use_chunked_transfer;
202 10 ▶ while( my ( $key, $value ) = splice @$headers, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@$headers, 0, 2)) 14 10 24
203 14 $response->push_header( $key, $value );
204  
205 14 ▶ $has_content_length = 1 if $key eq "Content-Length";
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "Content-Length" 2 12 14
206 14 ▶ $use_chunked_transfer++ if $key eq "Transfer-Encoding" and $value eq "chunked";
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "Transfer-Encoding" and $value eq "chunked" 0 14 14
Condition33%1/3
$key eq "Transfer-Encoding" and $value eq "chunked"
!ll&&!rl&&r
1400
MC/DC0%0/2
$key eq "Transfer-Encoding" and $value eq "chunked"
$key eq "Transfer-Encoding" $value eq "chunked"
Truth table33%1/3
A and B
A= $key eq "Transfer-Encoding"B= $value eq "chunked"
ABresult
0X0
100
111
207 }
208  
209 10 ▶ if( !defined $body ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $body) { } 2 8 10
elsif (ref $body eq 'ARRAY') { } 6 2 8
210 2 ▶ croak "Responder given no body in void context" unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 2 2
211  
212 2 ▶ unless( $has_content_length ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_length) 1 1 2
213 1 $response->header( "Transfer-Encoding" => "chunked" );
214 1 $use_chunked_transfer++;
215 }
216  
217 2 $req->write( $response->as_string( $CRLF ) );
218  
219 2 ▶ return $use_chunked_transfer ?
Branch: 1 branch
BranchTrueFalseTotal
$use_chunked_transfer ? : 1 1 2
220 Net::Async::HTTP::Server::PSGI::ChunkWriterStream->new( $req ) :
221 Net::Async::HTTP::Server::PSGI::WriterStream->new( $req );
222 }
223 elsif( ref $body eq "ARRAY" ) {
224 6 ▶ unless( $has_content_length ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_length) 6 0 6
225 6 my $len = 0;
226 6 my $found_undef;
227 6 ▶ $len += length( $_ // ( $found_undef++, "" ) ) for @$body;
Condition66%2/3
$_ // (++$found_undef, "")
l!l&&r!l&&!r
510
MC/DC0%0/2
$_ // (++$found_undef, "")
$_ (++$found_undef, "")
Truth table66%2/3
A // B
A= $_B= (++$found_undef, "")
ABresult
1X1
011
000
228 6 ▶ carp "Found undefined value in PSGI body" if $found_undef;
Branch: 1 branch
BranchTrueFalseTotal
if $found_undef 1 5 6
229  
230 6 $response->content_length( $len );
231 }
232  
233 6 $req->write( $response->as_string( $CRLF ) );
234  
235 6 $req->write( $_ ) for @$body;
236 6 $req->done;
237 }
238 else {
239 2 ▶ unless( $has_content_length ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_length) 1 1 2
240 1 $response->header( "Transfer-Encoding" => "chunked" );
241 1 $use_chunked_transfer++;
242 }
243  
244 2 $req->write( $response->as_string( $CRLF ) );
245  
246 2 ▶ if( $use_chunked_transfer ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_chunked_transfer) { } 1 1 2
247 3 ▶ $req->write( sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
248 # We can't return the EOF chunk and set undef in one go
249 # What we'll have to do is send the EOF chunk then clear $body,
250 # which indicates end
251 3 ▶ return unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 1 2 3
252  
253 2 local $/ = \8192;
254 2 my $buffer = $body->getline;
255  
256 # Form HTTP chunks out of it
257 2 ▶ defined $buffer and
Branch: 1 branch
BranchTrueFalseTotal
defined $buffer and return sprintf("%X$CRLF%s$CRLF", length $buffer, $buffer) 1 1 2
258 return sprintf( "%X$CRLF%s$CRLF", length $buffer, $buffer );
259  
260 1 $body->close;
261 1 undef $body;
262 1 return "0$CRLF$CRLF";
263 1 } );
264 }
265 else {
266 2 ▶ $req->write( sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
267 2 local $/ = \8192;
268 2 my $buffer = $body->getline;
269  
270 2 ▶ defined $buffer and return $buffer;
Branch: 1 branch
BranchTrueFalseTotal
defined $buffer and return $buffer 1 1 2
271  
272 1 $body->close;
273 1 return undef;
274 1 } );
275 }
276  
277 2 $req->done;
278 }
279 10 };
280  
281 10 ▶ if( ref $resp eq "ARRAY" ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $resp eq 'ARRAY') { } 7 3 10
elsif (ref $resp eq 'CODE') { } 3 0 3
282 7 $responder->( $resp );
283 }
284 elsif( ref $resp eq "CODE" ) {
285 3 $resp->( $responder );
286 }
287 }
288  
289 # Hide from indexer
290 package
291 Net::Async::HTTP::Server::PSGI::WriterStream;
292  
293 sub new
294 1 ▶{
Subroutine new: called CC=1 SCAR=0.0
295 1 my $class = shift;
296 1 return bless [ @_ ], $class;
297 }
298  
299 2 ▶sub write { shift->[0]->write( $_[0] ) }
Subroutine write: called CC=1 SCAR=0.0
300 1 ▶sub close { shift->[0]->done }
Subroutine close: called CC=1 SCAR=0.0
301  
302 # Hide from indexer
303 package
304 Net::Async::HTTP::Server::PSGI::ChunkWriterStream;
305  
306 sub new
307 1 ▶{
Subroutine new: called CC=1 SCAR=0.0
308 1 my $class = shift;
309 1 return bless [ @_ ], $class;
310 }
311  
312 2 ▶sub write { shift->[0]->write_chunk( $_[0] ) }
Subroutine write: called CC=1 SCAR=0.0
313 1 ▶sub close { shift->[0]->write_chunk_eof }
Subroutine close: called CC=1 SCAR=0.0
314  
315 =head1 SEE ALSO
316  
317 =over 4
318  
319 =item *
320  
321 L<PSGI> - Perl Web Server Gateway Interface Specification
322  
323 =item *
324  
325 L<Plack::Handler::Net::Async::HTTP::Server> - HTTP handler for Plack using
326 L<Net::Async::HTTP::Server>
327  
328 =back
329  
330 =head1 AUTHOR
331  
332 Paul Evans <leonerd@leonerd.org.uk>
333  
334 =cut
335  
336 4 0x55AA;
« Plack/Handler/Net/Async/HTTP/Server.pm ↑ Summary Net/Async/HTTP/Server/Protocol.pm »