150c269f78eba183c19a8f3dd1599d9888391f1e
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine.pm
1 package Catalyst::Engine;
2
3 use Moose;
4 with 'MooseX::Emulate::Class::Accessor::Fast';
5
6 use CGI::Simple::Cookie;
7 use Data::Dump qw/dump/;
8 use Errno 'EWOULDBLOCK';
9 use HTML::Entities;
10 use HTTP::Headers;
11 use Plack::Loader;
12 use Catalyst::EngineLoader;
13 use Encode 2.21 'decode_utf8', 'encode', 'decode';
14 use Plack::Request::Upload;
15 use Hash::MultiValue;
16 use namespace::clean -except => 'meta';
17 use utf8;
18
19 # Amount of data to read from input on each pass
20 our $CHUNKSIZE = 64 * 1024;
21
22 # XXX - this is only here for compat, do not use!
23 has env => ( is => 'rw', writer => '_set_env' , weak_ref=>1);
24 my $WARN_ABOUT_ENV = 0;
25 around env => sub {
26   my ($orig, $self, @args) = @_;
27   if(@args) {
28     warn "env as a writer is deprecated, you probably need to upgrade Catalyst::Engine::PSGI"
29       unless $WARN_ABOUT_ENV++;
30     return $self->_set_env(@args);
31   }
32   return $self->$orig;
33 };
34
35 # XXX - Only here for Engine::PSGI compat
36 sub prepare_connection {
37     my ($self, $ctx) = @_;
38     $ctx->request->prepare_connection;
39 }
40
41 =head1 NAME
42
43 Catalyst::Engine - The Catalyst Engine
44
45 =head1 SYNOPSIS
46
47 See L<Catalyst>.
48
49 =head1 DESCRIPTION
50
51 =head1 METHODS
52
53
54 =head2 $self->finalize_body($c)
55
56 Finalize body.  Prints the response output as blocking stream if it looks like
57 a filehandle, otherwise write it out all in one go.  If there is no body in
58 the response, we assume you are handling it 'manually', such as for nonblocking
59 style or asynchronous streaming responses.  You do this by calling L</write>
60 several times (which sends HTTP headers if needed) or you close over
61 C<< $response->write_fh >>.
62
63 See L<Catalyst::Response/write> and L<Catalyst::Response/write_fh> for more.
64
65 =cut
66
67 sub finalize_body {
68     my ( $self, $c ) = @_;
69     my $res = $c->response; # We use this all over
70
71     ## If we've asked for the write 'filehandle' that means the application is
72     ## doing something custom and is expected to close the response
73     return if $res->_has_write_fh;
74
75     my $body = $res->body; # save some typing
76     if($res->_has_response_cb) {
77         ## we have not called the response callback yet, so we are safe to send
78         ## the whole body to PSGI
79         
80         my @headers;
81         $res->headers->scan(sub { push @headers, @_ });
82
83         # We need to figure out what kind of body we have and normalize it to something
84         # PSGI can deal with
85         if(defined $body) {
86             # Handle objects first
87             if(blessed($body)) {
88                 if($body->can('getline')) {
89                     # Body is an IO handle that meets the PSGI spec.  Nothing to normalize
90                 } elsif($body->can('read')) {
91
92                     # In the past, Catalyst only looked for ->read not ->getline.  It is very possible
93                     # that one might have an object that respected read but did not have getline.
94                     # As a result, we need to handle this case for backcompat.
95                 
96                     # We will just do the old loop for now.  In a future version of Catalyst this support
97                     # will be removed and one will have to rewrite their custom object or use 
98                     # Plack::Middleware::AdaptFilehandleRead.  In anycase support for this is officially
99                     # deprecated and described as such as of 5.90060
100                    
101                     my $got;
102                     do {
103                         $got = read $body, my ($buffer), $CHUNKSIZE;
104                         $got = 0 unless $self->write($c, $buffer );
105                     } while $got > 0;
106
107                     close $body;
108                     return;
109                 } else {
110                     # Looks like for  backcompat reasons we need to be able to deal
111                     # with stringyfiable objects.
112                     $body = ["$body"]; 
113                 }
114             } elsif(ref $body) {
115                 if( (ref($body) eq 'GLOB') or (ref($body) eq 'ARRAY')) {
116                   # Again, PSGI can just accept this, no transform needed.  We don't officially
117                   # document the body as arrayref at this time (and there's not specific test
118                   # cases.  we support it because it simplifies some plack compatibility logic
119                   # and we might make it official at some point.
120                 } else {
121                    $c->log->error("${\ref($body)} is not a valid value for Response->body");
122                    return;
123                 }
124             } else {
125                 # Body is defined and not an object or reference.  We assume a simple value
126                 # and wrap it in an array for PSGI
127                 $body = [$body];
128             }
129         } else {
130             # There's no body...
131             $body = [];
132         }
133         $res->_response_cb->([ $res->status, \@headers, $body]);
134         $res->_clear_response_cb;
135
136     } else {
137         ## Now, if there's no response callback anymore, that means someone has
138         ## called ->write in order to stream 'some stuff along the way'.  I think
139         ## for backcompat we still need to handle a ->body.  I guess I could see
140         ## someone calling ->write to presend some stuff, and then doing the rest
141         ## via ->body, like in a template.
142         
143         ## We'll just use the old, existing code for this (or most of it)
144
145         if(my $body = $res->body) {
146
147           if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
148
149               ## In this case we have no choice and will fall back on the old
150               ## manual streaming stuff.  Not optimal.  This is deprecated as of 5.900560+
151
152               my $got;
153               do {
154                   $got = read $body, my ($buffer), $CHUNKSIZE;
155                   $got = 0 unless $self->write($c, $buffer );
156               } while $got > 0;
157
158               close $body;
159           }
160           else {
161               
162               # Case where body was set after calling ->write.  We'd prefer not to
163               # support this, but I can see some use cases with the way most of the
164               # views work. Since body has already been encoded, we need to do
165               # an 'unencoded_write' here.
166               $self->unencoded_write( $c, $body );
167           }
168         }
169
170         $res->_writer->close;
171         $res->_clear_writer;
172     }
173
174     return;
175 }
176
177 =head2 $self->finalize_cookies($c)
178
179 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
180 response headers.
181
182 =cut
183
184 sub finalize_cookies {
185     my ( $self, $c ) = @_;
186
187     my @cookies;
188     my $response = $c->response;
189
190     foreach my $name (keys %{ $response->cookies }) {
191
192         my $val = $response->cookies->{$name};
193
194         my $cookie = (
195             blessed($val)
196             ? $val
197             : CGI::Simple::Cookie->new(
198                 -name    => $name,
199                 -value   => $val->{value},
200                 -expires => $val->{expires},
201                 -domain  => $val->{domain},
202                 -path    => $val->{path},
203                 -secure  => $val->{secure} || 0,
204                 -httponly => $val->{httponly} || 0,
205             )
206         );
207         if (!defined $cookie) {
208             $c->log->warn("undef passed in '$name' cookie value - not setting cookie")
209                 if $c->debug;
210             next;
211         }
212
213         push @cookies, $cookie->as_string;
214     }
215
216     for my $cookie (@cookies) {
217         $response->headers->push_header( 'Set-Cookie' => $cookie );
218     }
219 }
220
221 =head2 $self->finalize_error($c)
222
223 Output an appropriate error message. Called if there's an error in $c
224 after the dispatch has finished. Will output debug messages if Catalyst
225 is in debug mode, or a `please come back later` message otherwise.
226
227 =cut
228
229 sub _dump_error_page_element {
230     my ($self, $i, $element) = @_;
231     my ($name, $val)  = @{ $element };
232
233     # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
234     # scrolling. Suggestions for more pleasant ways to do this welcome.
235     local $val->{'__MOP__'} = "Stringified: "
236         . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
237
238     my $text = encode_entities( dump( $val ));
239     sprintf <<"EOF", $name, $text;
240 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
241 <div id="dump_$i">
242     <pre wrap="">%s</pre>
243 </div>
244 EOF
245 }
246
247 sub finalize_error {
248     my ( $self, $c ) = @_;
249
250     $c->res->content_type('text/html; charset=utf-8');
251     my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
252     
253     # Prevent Catalyst::Plugin::Unicode::Encoding from running.
254     # This is a little nasty, but it's the best way to be clean whether or
255     # not the user has an encoding plugin.
256
257     if ($c->can('encoding')) {
258       $c->{encoding} = '';
259     }
260
261     my ( $title, $error, $infos );
262     if ( $c->debug ) {
263
264         # For pretty dumps
265         $error = join '', map {
266                 '<p><code class="error">'
267               . encode_entities($_)
268               . '</code></p>'
269         } @{ $c->error };
270         $error ||= 'No output';
271         $error = qq{<pre wrap="">$error</pre>};
272         $title = $name = "$name on Catalyst $Catalyst::VERSION";
273         $name  = "<h1>$name</h1>";
274
275         # Don't show context in the dump
276         $c->res->_clear_context;
277
278         # Don't show body parser in the dump
279         $c->req->_clear_body;
280
281         my @infos;
282         my $i = 0;
283         for my $dump ( $c->dump_these ) {
284             push @infos, $self->_dump_error_page_element($i, $dump);
285             $i++;
286         }
287         $infos = join "\n", @infos;
288     }
289     else {
290         $title = $name;
291         $error = '';
292         $infos = <<"";
293 <pre>
294 (en) Please come back later
295 (fr) SVP veuillez revenir plus tard
296 (de) Bitte versuchen sie es spaeter nocheinmal
297 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
298 (no) Vennligst prov igjen senere
299 (dk) Venligst prov igen senere
300 (pl) Prosze sprobowac pozniej
301 (pt) Por favor volte mais tarde
302 (ru) Попробуйте еще раз позже
303 (ua) Спробуйте ще раз пізніше
304 (it) Per favore riprova più tardi
305 </pre>
306
307         $name = '';
308     }
309     $c->res->body( <<"" );
310 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
311     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
312 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
313 <head>
314     <meta http-equiv="Content-Language" content="en" />
315     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
316     <title>$title</title>
317     <script type="text/javascript">
318         <!--
319         function toggleDump (dumpElement) {
320             var e = document.getElementById( dumpElement );
321             if (e.style.display == "none") {
322                 e.style.display = "";
323             }
324             else {
325                 e.style.display = "none";
326             }
327         }
328         -->
329     </script>
330     <style type="text/css">
331         body {
332             font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
333                          Tahoma, Arial, helvetica, sans-serif;
334             color: #333;
335             background-color: #eee;
336             margin: 0px;
337             padding: 0px;
338         }
339         :link, :link:hover, :visited, :visited:hover {
340             color: #000;
341         }
342         div.box {
343             position: relative;
344             background-color: #ccc;
345             border: 1px solid #aaa;
346             padding: 4px;
347             margin: 10px;
348         }
349         div.error {
350             background-color: #cce;
351             border: 1px solid #755;
352             padding: 8px;
353             margin: 4px;
354             margin-bottom: 10px;
355         }
356         div.infos {
357             background-color: #eee;
358             border: 1px solid #575;
359             padding: 8px;
360             margin: 4px;
361             margin-bottom: 10px;
362         }
363         div.name {
364             background-color: #cce;
365             border: 1px solid #557;
366             padding: 8px;
367             margin: 4px;
368         }
369         code.error {
370             display: block;
371             margin: 1em 0;
372             overflow: auto;
373         }
374         div.name h1, div.error p {
375             margin: 0;
376         }
377         h2 {
378             margin-top: 0;
379             margin-bottom: 10px;
380             font-size: medium;
381             font-weight: bold;
382             text-decoration: underline;
383         }
384         h1 {
385             font-size: medium;
386             font-weight: normal;
387         }
388         /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
389         /* Browser specific (not valid) styles to make preformatted text wrap */
390         pre {
391             white-space: pre-wrap;       /* css-3 */
392             white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
393             white-space: -pre-wrap;      /* Opera 4-6 */
394             white-space: -o-pre-wrap;    /* Opera 7 */
395             word-wrap: break-word;       /* Internet Explorer 5.5+ */
396         }
397     </style>
398 </head>
399 <body>
400     <div class="box">
401         <div class="error">$error</div>
402         <div class="infos">$infos</div>
403         <div class="name">$name</div>
404     </div>
405 </body>
406 </html>
407
408     # Trick IE. Old versions of IE would display their own error page instead
409     # of ours if we'd give it less than 512 bytes.
410     $c->res->{body} .= ( ' ' x 512 );
411
412     $c->res->{body} = Encode::encode("UTF-8", $c->res->{body});
413
414     # Return 500
415     $c->res->status(500);
416 }
417
418 =head2 $self->finalize_headers($c)
419
420 Allows engines to write headers to response
421
422 =cut
423
424 sub finalize_headers {
425     my ($self, $ctx) = @_;
426
427     $ctx->finalize_headers unless $ctx->response->finalized_headers;
428     return;
429 }
430
431 =head2 $self->finalize_uploads($c)
432
433 Clean up after uploads, deleting temp files.
434
435 =cut
436
437 sub finalize_uploads {
438     my ( $self, $c ) = @_;
439
440     # N.B. This code is theoretically entirely unneeded due to ->cleanup(1)
441     #      on the HTTP::Body object.
442     my $request = $c->request;
443     foreach my $key (keys %{ $request->uploads }) {
444         my $upload = $request->uploads->{$key};
445         unlink grep { -e $_ } map { $_->tempname }
446           (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
447     }
448
449 }
450
451 =head2 $self->prepare_body($c)
452
453 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
454
455 =cut
456
457 sub prepare_body {
458     my ( $self, $c ) = @_;
459
460     $c->request->prepare_body;
461 }
462
463 =head2 $self->prepare_body_chunk($c)
464
465 Add a chunk to the request body.
466
467 =cut
468
469 # XXX - Can this be deleted?
470 sub prepare_body_chunk {
471     my ( $self, $c, $chunk ) = @_;
472
473     $c->request->prepare_body_chunk($chunk);
474 }
475
476 =head2 $self->prepare_body_parameters($c)
477
478 Sets up parameters from body.
479
480 =cut
481
482 sub prepare_body_parameters {
483     my ( $self, $c ) = @_;
484
485     $c->request->prepare_body_parameters;
486 }
487
488 =head2 $self->prepare_parameters($c)
489
490 Sets up parameters from query and post parameters.
491 If parameters have already been set up will clear
492 existing parameters and set up again.
493
494 =cut
495
496 sub prepare_parameters {
497     my ( $self, $c ) = @_;
498
499     $c->request->_clear_parameters;
500     return $c->request->parameters;
501 }
502
503 =head2 $self->prepare_path($c)
504
505 abstract method, implemented by engines.
506
507 =cut
508
509 sub prepare_path {
510     my ($self, $ctx) = @_;
511
512     my $env = $ctx->request->env;
513
514     my $scheme    = $ctx->request->secure ? 'https' : 'http';
515     my $host      = $env->{HTTP_HOST} || $env->{SERVER_NAME};
516     my $port      = $env->{SERVER_PORT} || 80;
517     my $base_path = $env->{SCRIPT_NAME} || "/";
518
519     # set the request URI
520     my $path;
521     if (!$ctx->config->{use_request_uri_for_path}) {
522         my $path_info = $env->{PATH_INFO};
523         if ( exists $env->{REDIRECT_URL} ) {
524             $base_path = $env->{REDIRECT_URL};
525             $base_path =~ s/\Q$path_info\E$//;
526         }
527         $path = $base_path . $path_info;
528         $path =~ s{^/+}{};
529         $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
530         $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
531     }
532     else {
533         my $req_uri = $env->{REQUEST_URI};
534         $req_uri =~ s/\?.*$//;
535         $path = $req_uri;
536         $path =~ s{^/+}{};
537     }
538
539     # Using URI directly is way too slow, so we construct the URLs manually
540     my $uri_class = "URI::$scheme";
541
542     # HTTP_HOST will include the port even if it's 80/443
543     $host =~ s/:(?:80|443)$//;
544
545     if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
546         $host .= ":$port";
547     }
548
549     my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
550     my $uri   = $scheme . '://' . $host . '/' . $path . $query;
551
552     $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
553
554     # set the base URI
555     # base must end in a slash
556     $base_path .= '/' unless $base_path =~ m{/$};
557
558     my $base_uri = $scheme . '://' . $host . $base_path;
559
560     $ctx->request->base( bless \$base_uri, $uri_class );
561
562     return;
563 }
564
565 =head2 $self->prepare_request($c)
566
567 =head2 $self->prepare_query_parameters($c)
568
569 process the query string and extract query parameters.
570
571 =cut
572
573 sub prepare_query_parameters {
574     my ($self, $c) = @_;
575     my $env = $c->request->env;
576     my $do_not_decode_query = $c->config->{do_not_decode_query};
577
578     my $old_encoding;
579     if(my $new = $c->config->{default_query_encoding}) {
580       $old_encoding = $c->encoding;
581       $c->encoding($new);
582     }
583
584     my $check = $c->config->{do_not_check_query_encoding} ? undef :$c->_encode_check;
585     my $decoder = sub {
586       my $str = shift;
587       return $str if $do_not_decode_query;
588       return $c->_handle_param_unicode_decoding($str, $check);
589     };
590
591     my $query_string = exists $env->{QUERY_STRING}
592         ? $env->{QUERY_STRING}
593         : '';
594
595     # Check for keywords (no = signs)
596     # (yes, index() is faster than a regex :))
597     if ( index( $query_string, '=' ) < 0 ) {
598         my $keywords = $self->unescape_uri($query_string);
599         $keywords = $decoder->($keywords);
600         $c->request->query_keywords($keywords);
601         return;
602     }
603
604     $query_string =~ s/\A[&;]+//;
605
606     my $p = Hash::MultiValue->new(
607         map { defined $_ ? $decoder->($self->unescape_uri($_)) : $_ }
608         map { ( split /=/, $_, 2 )[0,1] } # slice forces two elements
609         split /[&;]+/, $query_string
610     );
611
612     $c->encoding($old_encoding) if $old_encoding;
613     $c->request->query_parameters( $c->request->_use_hash_multivalue ? $p : $p->mixed );
614 }
615
616 =head2 $self->prepare_read($c)
617
618 Prepare to read by initializing the Content-Length from headers.
619
620 =cut
621
622 sub prepare_read {
623     my ( $self, $c ) = @_;
624
625     # Initialize the amount of data we think we need to read
626     $c->request->_read_length;
627 }
628
629 =head2 $self->prepare_request(@arguments)
630
631 Populate the context object from the request object.
632
633 =cut
634
635 sub prepare_request {
636     my ($self, $ctx, %args) = @_;
637     $ctx->log->psgienv($args{env}) if $ctx->log->can('psgienv');
638     $ctx->request->_set_env($args{env});
639     $self->_set_env($args{env}); # Nasty back compat!
640     $ctx->response->_set_response_cb($args{response_cb});
641 }
642
643 =head2 $self->prepare_uploads($c)
644
645 =cut
646
647 sub prepare_uploads {
648     my ( $self, $c ) = @_;
649
650     my $request = $c->request;
651     return unless $request->_body;
652
653     my $enc = $c->encoding;
654     my $uploads = $request->_body->upload;
655     my $parameters = $request->parameters;
656     foreach my $name (keys %$uploads) {
657         my $files = $uploads->{$name};
658         $name = $c->_handle_unicode_decoding($name) if $enc;
659         my @uploads;
660         for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
661             my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
662             my $filename = $upload->{filename};
663             $filename = $c->_handle_unicode_decoding($filename) if $enc;
664
665             my $u = Catalyst::Request::Upload->new
666               (
667                size => $upload->{size},
668                type => scalar $headers->content_type,
669                charset => scalar $headers->content_type_charset,
670                headers => $headers,
671                tempname => $upload->{tempname},
672                filename => $filename,
673               );
674             push @uploads, $u;
675         }
676         $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
677
678         # support access to the filename as a normal param
679         my @filenames = map { $_->{filename} } @uploads;
680         # append, if there's already params with this name
681         if (exists $parameters->{$name}) {
682             if (ref $parameters->{$name} eq 'ARRAY') {
683                 push @{ $parameters->{$name} }, @filenames;
684             }
685             else {
686                 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
687             }
688         }
689         else {
690             $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
691         }
692     }
693 }
694
695 =head2 $self->write($c, $buffer)
696
697 Writes the buffer to the client.
698
699 =cut
700
701 sub write {
702     my ( $self, $c, $buffer ) = @_;
703
704     $c->response->write($buffer);
705 }
706
707 =head2 $self->unencoded_write($c, $buffer)
708
709 Writes the buffer to the client without encoding. Necessary for
710 already encoded buffers. Used when a $c->write has been done
711 followed by $c->res->body.
712
713 =cut
714
715 sub unencoded_write {
716     my ( $self, $c, $buffer ) = @_;
717
718     $c->response->unencoded_write($buffer);
719 }
720
721 =head2 $self->read($c, [$maxlength])
722
723 Reads from the input stream by calling C<< $self->read_chunk >>.
724
725 Maintains the read_length and read_position counters as data is read.
726
727 =cut
728
729 sub read {
730     my ( $self, $c, $maxlength ) = @_;
731
732     $c->request->read($maxlength);
733 }
734
735 =head2 $self->read_chunk($c, \$buffer, $length)
736
737 Each engine implements read_chunk as its preferred way of reading a chunk
738 of data. Returns the number of bytes read. A return of 0 indicates that
739 there is no more data to be read.
740
741 =cut
742
743 sub read_chunk {
744     my ($self, $ctx) = (shift, shift);
745     return $ctx->request->read_chunk(@_);
746 }
747
748 =head2 $self->run($app, $server)
749
750 Start the engine. Builds a PSGI application and calls the
751 run method on the server passed in, which then causes the
752 engine to loop, handling requests..
753
754 =cut
755
756 sub run {
757     my ($self, $app, $psgi, @args) = @_;
758     # @args left here rather than just a $options, $server for back compat with the
759     # old style scripts which send a few args, then a hashref
760
761     # They should never actually be used in the normal case as the Plack engine is
762     # passed in got all the 'standard' args via the loader in the script already.
763
764     # FIXME - we should stash the options in an attribute so that custom args
765     # like Gitalist's --git_dir are possible to get from the app without stupid tricks.
766     my $server = pop @args if (scalar @args && blessed $args[-1]);
767     my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH');
768     # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI.
769     if (scalar @args && !ref($args[0])) {
770         if (my $listen = shift @args) {
771             $options->{listen} ||= [$listen];
772         }
773     }
774     if (! $server ) {
775         $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options);
776         # We're not being called from a script, so auto detect what backend to
777         # run on.  This should never happen, as mod_perl never calls ->run,
778         # instead the $app->handle method is called per request.
779         $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)")
780     }
781     $app->run_options($options);
782     $server->run($psgi, $options);
783 }
784
785 =head2 build_psgi_app ($app, @args)
786
787 Builds and returns a PSGI application closure. (Raw, not wrapped in middleware)
788
789 =cut
790
791 sub build_psgi_app {
792     my ($self, $app, @args) = @_;
793
794     return sub {
795         my ($env) = @_;
796
797         return sub {
798             my ($respond) = @_;
799             confess("Did not get a response callback for writer, cannot continue") unless $respond;
800             $app->handle_request(env => $env, response_cb => $respond);
801         };
802     };
803 }
804
805 =head2 $self->unescape_uri($uri)
806
807 Unescapes a given URI using the most efficient method available.  Engines such
808 as Apache may implement this using Apache's C-based modules, for example.
809
810 =cut
811
812 sub unescape_uri {
813     my ( $self, $str ) = @_;
814
815     $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
816
817     return $str;
818 }
819
820 =head2 $self->finalize_output
821
822 <obsolete>, see finalize_body
823
824 =head2 $self->env
825
826 Hash containing environment variables including many special variables inserted
827 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
828
829 Before accessing environment variables consider whether the same information is
830 not directly available via Catalyst objects $c->request, $c->engine ...
831
832 BEWARE: If you really need to access some environment variable from your Catalyst
833 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
834 as in some environments the %ENV hash does not contain what you would expect.
835
836 =head1 AUTHORS
837
838 Catalyst Contributors, see Catalyst.pm
839
840 =head1 COPYRIGHT
841
842 This library is free software. You can redistribute it and/or modify it under
843 the same terms as Perl itself.
844
845 =cut
846
847 __PACKAGE__->meta->make_immutable;
848
849 1;