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