Role/PSGIServer.pm

filter: Statementstmt 100% 17 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 100% 24 / 24 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Types/PSGIServer.pm ↑ Summary
1 package POEx::Role::PSGIServer;
2 BEGIN {
3 1 ▶ $POEx::Role::PSGIServer::VERSION = '1.110670';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 }
5  
6 #ABSTRACT: Encapsulates core PSGI server behavior
7 1 ▶use MooseX::Declare;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9  
10 1 ▶role POEx::Role::PSGIServer {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶ use aliased 'POEx::Role::Event';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 use MooseX::Types::Moose(':all');
14 use POEx::Types::PSGIServer(':all');
15 use POEx::Types(':all');
16 use Moose::Autobox;
17 use HTTP::Message::PSGI;
18 use HTTP::Status qw(status_message);
19 use Plack::Util;
20 use POE::Filter::HTTP::Parser;
21 use POE::Filter::Stream;
22 use POEx::Role::PSGIServer::Streamer;
23 use POEx::Role::PSGIServer::ProxyWriter;
24  
25  
26 has psgi_app => (
27 is => 'ro',
28 isa => CodeRef,
29 writer => 'register_service',
30 );
31  
32  
33 has wheel_flushers => (
34 is => 'ro',
35 traits => ['Hash'],
36 isa => 'HashRef',
37 default => sub { {} },
38 handles => {
39 has_wheel_flusher => 'exists',
40 get_wheel_flusher => 'get',
41 set_wheel_flusher => 'set',
42 clear_wheel_flusher => 'delete',
43 }
44 );
45  
46  
47  
48 around BUILDARGS(ClassName $class: @args) {
49 my $hash = $class->$orig(@args);
50  
51 $hash->{listen_port} ||= delete $hash->{port} || 5000;
52 $hash->{listen_ip} ||= delete $hash->{host} || '0.0.0.0';
53 $hash;
54 }
55  
56  
57 after _start is Event {
58 $self->input_filter(POE::Filter::HTTP::Parser->new(type => 'server'));
59 $self->output_filter(POE::Filter::Stream->new());
60 }
61  
62  
63 method write(PSGIServerContext $c, Str $data) {
64 if($c->{chunked}) {
65 my $len = sprintf "%X", do { use bytes; length($data) };
66 $self->_write($c, "$len\r\n$data\r\n");
67 }
68 else {
69 $self->_write($c, $data);
70 }
71
72 }
73  
74  
75 method _write(PSGIServerContext $c, Str $data) {
76 $c->{wheel}->put($data);
77 }
78  
79  
80 method close(PSGIServerContext $c) {
81 if($c->{chunked}) {
82 $self->_write($c, "0\r\n\r\n");
83 }
84  
85 $c->{wheel}->flush() while $c->{wheel}->get_driver_out_octets();
86 $c->{wheel}->shutdown_output();
87 $self->delete_wheel((delete $c->{wheel})->ID);
88 }
89  
90  
91 method handle_socket_error(Str $action, Int $code, Str $message, WheelID $id) is Event {
92 $self->delete_wheel($id);
93 }
94  
95  
96 method handle_listen_error(Str $action, Int $code, Str $message, WheelID $id) is Event {
97 die "Failed to '$action' to the specified port. Code: $code, Message: $message";
98 }
99  
100  
101  
102 method process_headers(PSGIServerContext $c, PSGIResponse $response) {
103 my $headers = $response->[1];
104 $headers->keys
105 ->each(
106 sub {
107 my $index = shift;
108 return if $index == $#$headers;
109 my ($k, $v) = ($headers->[$index], $headers->[$index+1]) ;
110 $c->{keep_alive} = 0 if $k eq 'Connection' && $v eq 'close';
111 $c->{explicit_length} = 1 if $k eq 'Content-Length';
112 $self->_write($c, "$k:$v\r\n");
113 }
114 );
115
116 $c->{chunked} = ($c->{keep_alive} && !$c->{explicit_length});
117 }
118  
119  
120 method http_preamble(PSGIServerContext $c, PSGIResponse $response) {
121 $self->_write($c, "${\ $c->{protocol}} ${\ $response->[0] } ${ \status_message($response->[0]) }\r\n");
122 }
123  
124  
125 method http_body_allowed(PSGIServerContext $c, PSGIResponse $response) returns (Bool) {
126 my $code = $response->[0];
127  
128 my $no_body_allowed = ($c->{request}->method =~ /^head$/i)
129 || ($code < 200)
130 || ($code == 204)
131 || ($code == 304);
132  
133 if ($no_body_allowed) {
134 $self->_write($c, "\r\n");
135 $self->close($c);
136 return Plack::Util::FALSE;
137 }
138  
139 return Plack::Util::TRUE;
140 }
141  
142  
143 method respond(PSGIServerContext $c, PSGIResponse $response) is Event {
144 $self->http_preamble($c, $response);
145 $self->process_headers($c, $response);
146 return unless ($self->http_body_allowed($c, $response));
147  
148
149 $self->_write($c, "Transfer-Encoding: chunked\r\n") if $c->{chunked};
150 $self->_write($c, "\r\n");
151
152 my $body = $response->[2];
153 if ($body) {
154 # If we have a real filehandle, build a Streamer
155 if (Plack::Util::is_real_fh($body)) {
156 # flush and destroy the old wheel, since the Streamer will build a new one
157 $c->{wheel}->flush();
158 $self->delete_wheel($c->{wheel}->ID);
159 my $handle = (delete $c->{wheel})->get_input_handle();
160 my $streamer = POEx::Role::PSGIServer::Streamer->new(
161 input_handle => $body,
162 output_handle => $handle,
163 server_context => $c,
164 );
165 }
166 # If we don't just iterate the lines
167 else {
168 Plack::Util::foreach($body, sub{$self->write($c, @_)});
169 $self->close($c);
170 }
171  
172 return;
173 }
174  
175 # If there was no body, we need to build a push writer
176 return $self->generate_push_writer($c);
177 }
178  
179  
180 method generate_push_writer(PSGIServerContext $c) returns (Object) {
181 return POEx::Role::PSGIServer::ProxyWriter->new(server_context => $c, proxied => $self);
182 }
183  
184  
185 method generate_psgi_env(PSGIServerContext $c) returns (HashRef) {
186 return req_to_psgi(
187 $c->{request},
188 SERVER_NAME => $self->listen_ip,
189 SERVER_PORT => $self->listen_port,
190 SERVER_PROTOCOL => $c->{protocol},
191 'psgi.streaming' => Plack::Util::TRUE,
192 'psgi.nonblocking' => Plack::Util::TRUE,
193 'psgi.runonce' => Plack::Util::FALSE,
194 );
195 }
196  
197  
198 method build_server_context(HTTPRequest $req, WheelID $wheel_id) returns (PSGIServerContext) {
199 my $version = $req->header('X-HTTP-Version') || '0.9';
200 my $protocol = "HTTP/$version";
201 my $connection = $req->header('Connection') || '';
202 my $keep_alive = ($version eq '1.1' && $connection ne 'close');
203
204 my $context = {
205 request => $req,
206 wheel => $self->get_wheel($wheel_id),
207 version => $version,
208 protocol => $protocol,
209 connection => $connection,
210 keep_alive => $keep_alive,
211 explicit_length => 0,
212 };
213  
214 return $context;
215 }
216  
217  
218 method handle_inbound_data(HTTPRequest $req, WheelID $wheel_id) is Event {
219 my $context = $self->build_server_context($req, $wheel_id);
220 my $env = $self->generate_psgi_env($context);
221 my $response = Plack::Util::run_app($self->psgi_app, $env);
222  
223 if (ref($response) eq 'CODE') {
224 $response->(sub { $self->respond($context, @_) });
225 }
226 else {
227 $self->yield('respond', $context, $response);
228 }
229 }
230  
231  
232 method run(CodeRef $app) {
233 $self->register_service($app);
234 POE::Kernel->run();
235 }
236  
237 method handle_on_flushed(WheelID $id) is Event {
238 if ($self->has_wheel_flusher($id)) {
239 $self->get_wheel_flusher($id)->();
240 }
241 1;
242 }
243  
244 after delete_wheel(WheelID $id) {
245 $self->clear_wheel_flusher($id);
246 }
247  
248 with 'POEx::Role::TCPServer' => {
249 -excludes => [
250 qw/handle_socket_error handle_listen_error handle_on_flushed/
251 ]
252 };
253 }
254  
255 __END__
256 =pod
257  
258 =head1 NAME
259  
260 POEx::Role::PSGIServer - Encapsulates core PSGI server behavior
261  
262 =head1 VERSION
263  
264 version 1.110670
265  
266 =head1 SYNOPSIS
267  
268 use MooseX::Declare;
269 class MyServer with POEx::Role::PSGIServer { }
270  
271 MyServer->new()->run($some_psgi_app);
272  
273 =head1 DESCRIPTION
274  
275 POEx::Role::PSGIServer encapsulates the core L<PSGI> server behaviors into an easy to consume and extend role. It is based on previous POEx work such as POEx::Role::TCPServer which provides basic TCP socket multiplexing via POE::Wheel::SocketFactory and POE::Wheel::ReadWrite, and POEx::Role::SessionInstantiation which transforms plain Moose objects into POE sessions.
276  
277 =head2 RATIONALE
278  
279 This Role has its roots firmly planted in POE::Component::Server::PSGI which provided the initial seed with the layout and logic of the basic server. Unfortunately, POE::Component::Server::PSGI didn't provide any mechnism for extension. The main goal of this Role is to provide as many extension points as possible. The secondary goal is to provide a more reasonable abstraction for several key pieces of the stack for streaming, and push writing.
280  
281 =head1 CLASS_METHODS
282  
283 =head2 around BUILDARGS
284  
285 (ClassName $class: @args)
286  
287 BUILDARGS is wrapped to translate from the expected Plack::Handler interface to POEx::Role::TCPServer's expected interface.
288  
289 =head1 PUBLIC_ATTRIBUTES
290  
291 =head2 psgi_app
292  
293 is: ro, isa: CodeRef, writer: register_service
294  
295 This attribute stores the PSGI application to be run from this server. A writer method is provided to match the expected Plack::Handler interface
296  
297 =head1 PROTECTED_ATTRIBUTES
298  
299 =head2 wheel_flushers
300  
301 is: ro, isa: HashRef,
302 exists : has_wheel_flusher,
303 get : get_wheel_flusher,
304 set : set_wheel_flusher,
305 delete : clear_wheel_flusher
306  
307 This attribute stores coderefs to be called on a wheel's flush event
308 (necessary to properly handle poll_cb)
309  
310 =head1 PUBLIC_METHODS
311  
312 =head2 run
313  
314 (CodeRef $app)
315  
316 run is provided to complete the Plack::Handler interface and allow the server to be executed with the provided psgi app
317  
318 =head1 PROTECTED_METHODS
319  
320 =head2 after _start
321  
322 is Event
323  
324 _start is advised to supply the proper input (HTTP::Parser) and output (Stream) filters.
325  
326 =head2 write
327  
328 (PSGIServerContext $c, Str $data)
329  
330 write will alter the data if necessary for a chunked transfer encoded response and send it to the output buffer for the current context
331  
332 =head2 close
333  
334 (PSGIServerContext $c)
335  
336 close will close the connection for the current context, but flushing the output buffer first
337  
338 =head2 handle_socket_error
339  
340 (Str $action, Int $code, Str $message, WheelID $id) is Event
341  
342 handle_socket_error overridden from POEx::Role::TCPServer to delete the wheel when a socket level error happens. If more intelligent actions are required, please feel free to exclude this method and provide your own implementation
343  
344 =head2 handle_listen_error
345  
346 (Str $action, Int $code, Str $message, WheelID $id) is Event
347  
348 handle_listen_error is overridden from POEx::Role::TCPServer to die when the SocketFactory fails to listen to the provided address/port. If more intelligent actions are required, please feel free to exclude this method and provide your own implementation
349  
350 =head2 process_headers
351  
352 (PSGIServerContext $c, PSGIResponse $response)
353  
354 process_headers takes the headers from the PSGIResponse, and sends it to the output buffer for the current context. This method also determines if the response body should be transfer encoded as chunked based on the Connection and Content-Length headers.
355  
356 =head2 http_preamble
357  
358 (PSGIServerContext $c, PSGIResponse $response)
359  
360 http_preamble sends the first line of the HTTP response to the output buffer of the current context
361  
362 =head2 http_body_allowed
363  
364 (PSGIServerContext $c, PSGIResponse $response) returns (Bool)
365  
366 http_body_allowed checks the result code from the PSGIResponse to determine if a body should be allowed to be returned. Returns true if a body is allowed, false otherwise.
367  
368 =head2 respond
369  
370 (PSGIServerContext $c, PSGIResponse $response) is Event
371  
372 respond processes the PSGIResponse to write out a valid HTTP response. If the body of the response is a real filehandle, it will be streamed appropriately via L<POEx::Role::PSGIServer::Streamer>. If not, it will be iterated with which ever appropriate interface to the output buffer. If no body is provided, L</generate_push_writer> is called to generate an appropriate object for use in push responses.
373  
374 =head2 generate_push_writer
375  
376 (PSGIServerContext $c) returns (Object)
377  
378 generate_push_writer by default constructs and returns a L<POEx::Role::PSGIServer::ProxyWriter> object that implements the push-object interface defined in L<PSGI>
379  
380 =head2 generate_psgi_env
381  
382 (PSGIServerContext $c) returns (HashRef)
383  
384 generate_psgi_env returns a suitable HashRef as defined by L<PSGI> for application use. If additional application specific items need to be added to the hash, please feel free to advise this method
385  
386 =head2 build_server_context
387  
388 (HTTPRequest $req, WheelID $wheel_id) returns (PSGIServerContext)
389  
390 build_server_context constructs and returns a L<POEx::Types::PSGIServer/PSGIServerContext> for the current connection
391  
392 =head2 handle_inbound_data
393  
394 (HTTPRequest $req, WheelID $wheel_id) is Event
395  
396 handle_inbound_data implements the required method for POEx::Role::TCPServer. It builds a server context, generates a psgi env hash, runs the psgi app, and then responds to the client
397  
398 =head1 PRIVATE_METHODS
399  
400 =head2 _write
401  
402 (PSGIServerContext $c, Str $data)
403  
404 _write accesses the proper wheel for this context and puts the supplied data into the output buffer
405  
406 =head1 AUTHOR
407  
408 Nicholas Perez <nperez@cpan.org>
409  
410 =head1 COPYRIGHT AND LICENSE
411  
412 This software is copyright (c) 2011 by Infinity Interactive.
413  
414 This is free software; you can redistribute it and/or modify it under
415 the same terms as the Perl 5 programming language system itself.
416  
417 =cut
418  
« Types/PSGIServer.pm ↑ Summary