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