on-demand ->new to make run_if_script safer
[catagits/Web-Simple.git] / lib / Web / Simple / Application.pm
1 package Web::Simple::Application;
2
3 use Scalar::Util 'weaken';
4 use Try::Tiny;
5
6 use Moo;
7
8 has 'config' => (
9   is => 'ro',
10   default => sub {
11     my ($self) = @_;
12     +{ $self->default_config }
13   },
14   trigger => sub {
15     my ($self, $value) = @_;
16     my %default = $self->default_config;
17     my @not = grep !exists $value->{$_}, keys %default;
18     @{$value}{@not} = @default{@not};
19   }
20 );
21
22 sub default_config { () }
23
24 has '_dispatcher' => (is => 'lazy');
25
26 sub _build__dispatcher {
27   my $self = shift;
28   require Web::Dispatch;
29   my $final = $self->_build_final_dispatcher;
30
31   # We need to weaken both the copy of $self that the
32   # app parameter will close over and the copy that'll
33   # be passed through as a node argument.
34   #
35   # To ensure that this doesn't then result in us being
36   # DESTROYed unexpectedly early, our to_psgi_app method
37   # closes back over $self
38
39   weaken($self);
40   my %dispatch_args = (
41     dispatch_app => sub { $self->dispatch_request(@_), $final },
42     dispatch_object => $self
43   );
44   weaken($dispatch_args{dispatch_object});
45   Web::Dispatch->new(%dispatch_args);
46 }
47
48 sub _build_final_dispatcher {
49   [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
50 }
51
52 sub run_if_script {
53   my ( $self, @args ) = @_;
54   # ->to_psgi_app is true for require() but also works for plackup
55   return $self->to_psgi_app(@args) if caller(1);
56   $self = ref($self) ? $self : $self->new(@args);
57   $self->run;
58 }
59
60 sub _run_cgi {
61   my $self = shift;
62   require Plack::Handler::CGI;
63   Plack::Handler::CGI->new->run($self->to_psgi_app);
64 }
65
66 sub _run_fcgi {
67   my $self = shift;
68   require Plack::Handler::FCGI;
69   Plack::Handler::FCGI->new->run($self->to_psgi_app);
70 }
71
72 sub to_psgi_app {
73   my ($invocant, @args) = @_;
74
75   unless (ref($invocant)) {
76     my $app;
77     return sub {
78       $app ||= do {
79         try { $invocant->new(@args)->to_psgi_app }
80         catch { die "Failed to auto-create new ${invocant} object for to_psgi_app: $_"; }
81       };
82       $app->(@_);
83     };
84   }
85
86   my $self = $invocant;
87   my $app = $self->_dispatcher->to_app;
88
89   # Close over $self to keep $self alive even though
90   # we weakened the copies the dispatcher has; the
91   # if 0 causes the ops to be optimised away to
92   # minimise the performance impact and avoid void
93   # context warnings while still doing the closing
94   # over part. As Mithaldu said: "Gnarly." ...
95
96   return sub { $self if 0; goto &$app; };
97 }
98
99 sub run {
100   my $self = shift;
101   if (
102     $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
103     || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
104     # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
105     ) {
106     return $self->_run_fcgi;
107   } elsif ($ENV{GATEWAY_INTERFACE}) {
108     return $self->_run_cgi;
109   }
110   unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) {
111     return $self->_run_cli(@ARGV);
112   }
113
114   my @args = @ARGV;
115
116   unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/;
117
118   $self->_run_cli_test_request(@args);
119 }
120
121 sub _test_request_spec_to_http_request {
122   my ($self, $method, $path, @rest) = @_;
123
124   # if it's a reference, assume a request object
125   return $method if ref($method);
126
127   if ($path =~ s/^(.*?)\@//) {
128     my $basic = $1;
129     require MIME::Base64;
130     unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
131   }
132
133   my $request = HTTP::Request->new($method => $path);
134
135   my @params;
136
137   while (my ($header, $value) = splice(@rest, 0, 2)) {
138     unless ($header =~ s/:$//) {
139       push @params, $header, $value;
140     }
141     $header =~ s/_/-/g;
142     if ($header eq 'Content') {
143       $request->content($value);
144     } else {
145       $request->headers->push_header($header, $value);
146     }
147   }
148
149   if (($method eq 'POST' or $method eq 'PUT') and @params) {
150     my $content = do {
151       require URI;
152       my $url = URI->new('http:');
153       $url->query_form(@params);
154       $url->query;
155     };
156     $request->header('Content-Type' => 'application/x-www-form-urlencoded');
157     $request->header('Content-Length' => length($content));
158     $request->content($content);
159   }
160
161   return $request;
162 }
163
164 sub run_test_request {
165   my ($self, @req) = @_;
166
167   require HTTP::Request;
168
169   require Plack::Test;
170
171   my $request = $self->_test_request_spec_to_http_request(@req);
172
173   Plack::Test::test_psgi(
174     $self->to_psgi_app, sub { shift->($request) }
175   );
176 }
177
178 sub _run_cli_test_request {
179   my ($self, @req) = @_;
180   my $response = $self->run_test_request(@req);
181
182   binmode(STDOUT); binmode(STDERR); # for win32
183
184   print STDERR $response->status_line."\n";
185   print STDERR $response->headers_as_string("\n")."\n";
186   my $content = $response->content;
187   $content .= "\n" if length($content) and $content !~ /\n\z/;
188   print STDOUT $content if $content;
189 }
190
191 sub _run_cli {
192   my $self = shift;
193   die $self->_cli_usage;
194 }
195
196 sub _cli_usage {
197   "To run this script in CGI test mode, pass a URL path beginning with /:\n".
198   "\n".
199   "  $0 /some/path\n".
200   "  $0 /\n"
201 }
202
203 1;
204
205 =head1 NAME
206
207 Web::Simple::Application - A base class for your Web-Simple application
208
209 =head1 DESCRIPTION
210
211 This is a base class for your L<Web::Simple> application.  You probably don't
212 need to construct this class yourself, since L<Web::Simple> does the 'heavy
213 lifting' for you in that regards.
214
215 =head1 METHODS
216
217 This class exposes the following public methods.
218
219 =head2 default_config
220
221 Merges with the C<config> initializer to provide configuration information for
222 your application.  For example:
223
224   sub default_config {
225     (
226       title => 'Bloggery',
227       posts_dir => $FindBin::Bin.'/posts',
228     );
229   }
230
231 Now, the C<config> attribute of C<$self>  will be set to a HashRef
232 containing keys 'title' and 'posts_dir'.
233
234 The keys from default_config are merged into any config supplied, so
235 if you construct your application like:
236
237   MyWebSimpleApp::Web->new(
238     config => { title => 'Spoon', environment => 'dev' }
239   )
240
241 then C<config> will contain:
242
243   {
244     title => 'Spoon',
245     posts_dir => '/path/to/myapp/posts',
246     environment => 'dev'
247   }
248
249 =head2 run_if_script
250
251 The run_if_script method is designed to be used at the end of the script
252 or .pm file where your application class is defined - for example:
253
254   ## my_web_simple_app.pl
255   #!/usr/bin/env perl
256   use Web::Simple 'HelloWorld';
257
258   {
259     package HelloWorld;
260
261     sub dispatch_request {
262       sub (GET) {
263         [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
264       },
265       sub () {
266         [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
267       }
268     }
269   }
270
271   HelloWorld->run_if_script;
272
273 This returns a true value, so your file is now valid as a module - so
274
275   require 'my_web_simple_app.pl';
276
277   my $hw = HelloWorld->new;
278
279 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
280 a real use-able module).
281
282 However, it detects if it's being run as a script (via testing $0) and if
283 so attempts to do the right thing.
284
285 If run under a CGI environment, your application will execute as a CGI.
286
287 If run under a FastCGI environment, your application will execute as a
288 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
289 and for apache FastCgiServer style setups).
290
291 If run from the commandline with a URL path, it runs a GET request against
292 that path -
293
294   $ perl -Ilib examples/hello-world/hello-world.cgi /
295   200 OK
296   Content-Type: text/plain
297   
298   Hello world!
299
300 You can also provide a method name -
301
302   $ perl -Ilib examples/hello-world/hello-world.cgi POST /
303   405 Method Not Allowed
304   Content-Type: text/plain
305   
306   Method not allowed
307
308 For a POST or PUT request, pairs on the command line will be treated
309 as form variables. For any request, pairs on the command line ending in :
310 are treated as headers, and 'Content:' will set the request body -
311
312   $ ./myapp POST / Accept: text/html form_field_name form_field_value
313   
314   $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
315
316 The body of the response is sent to STDOUT and the headers to STDERR, so
317
318   $ ./myapp GET / >index.html
319
320 will generally do the right thing.
321
322 To send basic authentication credentials, use user:pass@ syntax -
323
324   $ ./myapp GET bob:secret@/protected/path
325
326 Additionally, you can treat the file as though it were a standard PSGI
327 application file (*.psgi).  For example you can start up up with C<plackup>
328
329   plackup my_web_simple_app.pl
330
331 or C<starman>
332
333   starman my_web_simple_app.pl
334
335 =head2 to_psgi_app
336
337 This method is called by L</run_if_script> to create the L<PSGI> app coderef
338 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
339 you can override this method:
340
341   use Web::Simple 'HelloWorld';
342   use Plack::Builder;
343  
344   {
345     package HelloWorld;
346
347   
348     around 'to_psgi_app', sub {
349       my ($orig, $self) = (shift, shift);
350       my $app = $self->$orig(@_); 
351       builder {
352         enable ...; ## whatever middleware you want
353         $app;
354       };
355     };
356   }
357
358 This method can also be used to mount a Web::Simple application within
359 a separate C<*.psgi> file -
360
361   use strictures 1;
362   use Plack::Builder;
363   use WSApp;
364   use AnotherWSApp;
365
366   builder {
367     mount '/' => WSApp->to_psgi_app;
368     mount '/another' => AnotherWSApp->to_psgi_app;
369   };
370
371 This method can be called as a class method, in which case it will implicitly
372 call ->new when the PSGI coderef is first invoked, or as an object method ...
373 in which case it doesn't.
374
375 =head2 run
376
377 Used for running your application under stand-alone CGI and FCGI modes.
378
379 I should document this more extensively but run_if_script will call it when
380 you need it, so don't worry about it too much.
381
382 =head2 run_test_request
383
384   my $res = $app->run_test_request(GET => '/' => %headers);
385
386   my $res = $app->run_test_request(POST => '/' => %headers_or_form);
387
388   my $res = $app->run_test_request($http_request);
389
390 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
391 request against the application, returning an L<HTTP::Response> object.
392
393 If the HTTP method is POST or PUT, then a series of pairs can be passed after
394 this to create a form style message body. If you need to test an upload, then
395 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
396 provided by L<HTTP::Request::Common>.
397
398 If you prefix the URL with 'user:pass@' this will be converted into
399 an Authorization header for HTTP basic auth:
400
401   my $res = $app->run_test_request(
402               GET => 'bob:secret@/protected/resource'
403             );
404
405 If pairs are passed where the key ends in :, it is instead treated as a
406 headers, so:
407
408   my $res = $app->run_test_request(
409               POST => '/',
410              'Accept:' => 'text/html',
411               some_form_key => 'value'
412             );
413
414 will do what you expect. You can also pass a special key of Content: to
415 set the request body:
416
417   my $res = $app->run_test_request(
418               POST => '/',
419               'Content-Type:' => 'text/json',
420               'Content:' => '{ "json": "here" }',
421             );
422
423 =head1 AUTHORS
424
425 See L<Web::Simple> for authors.
426
427 =head1 COPYRIGHT AND LICENSE
428
429 See L<Web::Simple> for the copyright and license.
430
431 =cut