-
Notifications
You must be signed in to change notification settings - Fork 3
/
App.pm
401 lines (347 loc) · 14.8 KB
/
App.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
use v6.c;
use HTTP::Status;
use Log::Any:ver('0.9.4');
use Template::Mojo;
use URI; # Used to parse log configuration
use URI::Encode;
use Bailador::Commands;
use Bailador::Configuration;
use Bailador::ContentTypes;
use Bailador::Context;
use Bailador::Exceptions;
use Bailador::Log::Adapter;
use Bailador::Log::Formatter;
use Bailador::Route;
use Bailador::Route::AutoHead;
use Bailador::Sessions;
use Bailador::Template::Mojo;
class Bailador::App does Bailador::Routing {
# has Str $.location is rw = get-app-root().absolute;
has Str $!location;
has Bool $!started = False;
has Bailador::ContentTypes $.content-types = Bailador::ContentTypes.new;
has Bailador::Context $.context = Bailador::Context.new;
has Bailador::Template $.renderer is rw = Bailador::Template::Mojo.new;
has Bailador::Sessions $!sessions;
has Bailador::Configuration $.config = Bailador::Configuration.new;
has Bailador::Commands $.commands = Bailador::Commands.new;
has Bailador::Log::Adapter $.log-adapter = Bailador::Log::Adapter.new;
has %.error_handlers;
method load-config {
if %*ENV<BAILADOR_CONFIGDIR> {
$!config.config-dir = %*ENV<BAILADOR_CONFIGDIR>;
}
if %*ENV<BAILADOR_CONFIGFILE> {
$!config.config-file = %*ENV<BAILADOR_CONFIGFILE>;
}
$!config.load-from-dir($.location);
$!config.load-from-env();
}
method request { $.context.request }
method response { $.context.response }
method !templatefile-extentions(Str:D $file) {
for ('', '.tt', '.mustache', '.html', '.template') -> $ext {
my $filename = $file ~ $ext;
return $filename if $filename.IO.e;
}
Log::Any.error("template file not found: $file");
return Str:U;
}
method template(Str $tmpl, Str :$layout, *@params, *%params) {
my $content = "";
my $content-template = self!templatefile-extentions($.location.IO.child(self.config.views).child($tmpl).Str);
$content = $!renderer.render($content-template, |@params, |%params) if $content-template;
my $use-this-layout = $layout // $.config.layout;
if $use-this-layout {
my $layout-template = self!templatefile-extentions($.location.IO.child('layout').child($use-this-layout).Str);
if $layout-template {
Log::Any.debug("Rendering with layout $use-this-layout");
$content = $!renderer.render($layout-template, $content);;
}
} else {
Log::Any.debug("Rendering without a layout");
}
return $content;
}
method render-file(Str:D $filename is copy, Str :$mime-type) {
# The supplied path in $filename should be relative to our root. By default directory traversal
# is disabled because security, so basically only relavite paths from our applications location
# is possible. The file is rendered and served by this method.
$filename = $.location.IO.child($filename).resolve.Str;
if (!$filename.starts-with($.location)) {
# File is outside our $.location
Log::Any.error("Serving file outside of root is denied: " ~ $filename);
return;
}
if ($filename.IO.e) {
if ($mime-type.defined) {
self.render(status => 200, type => $mime-type, content => $filename.IO);
}
else {
# Content type auto-detection via render()
self.render(status => 200, content => $filename.IO);
}
}
else {
Log::Any.error("File not found! " ~ $filename);
}
}
method before-add-routes() {
# this is a good place for a hook
self.load-config();
}
# do not use $!location outside of this subs
multi method location(Str $location) {
if $!location.defined {
die "can not set location, it is already defined. Set it before you add the first route";
}
$!location = $location;
# call after $!location is defined
self.before-add-routes();
}
multi method location() {
unless $!location.defined {
my $app-root;
if %*ENV<BAILADOR_APP_ROOT>:exists {
$app-root = %*ENV<BAILADOR_APP_ROOT>.IO.resolve;
} else {
my $parent = $*PROGRAM.parent.resolve;
$app-root = $parent.basename eq 'bin' ?? $parent.parent !! $parent;
}
if $*DISTRO.is-win {
$app-root.=subst(/\\/, '', :x(1));
}
self.location($app-root.Str);
}
return $!location;
}
method before-run() {
# probably a good place for a hook
# Configure logging system
use Bailador::Log;
init( config => self.config, p6w-adapter => self.log-adapter );
self!generate-head-routes(self);
}
method !generate-head-routes(Bailador::Routing $route) {
my %found-head;
my %found-get;
for $route.routes -> $child-route {
self!generate-head-routes($child-route);
if 'GET' ~~ any( $child-route.method ) && 'HEAD' !~~ any ( $child-route.method ) {
# found a route with GET but no HEAD
%found-get{ $child-route.route-spec } = $child-route;
}
if 'HEAD' ~~ any( $child-route.method ) && 'GET' !~~ any ( $child-route.method ) {
# found a route with HEAD but no GET
%found-head{ $child-route.route-spec } = 1;
}
}
for %found-get.kv -> $key, $orig-route {
unless %found-head{ $key }:exists {
my $code = sub (Match $match) {
my $result = $orig-route.execute($match);
if $result ~~ Bool {
# no need to render for a route that defines access
return $result;
}
if $.context.autorender {
# no rendering happend so far
self.render();
} else {
# rendering happend so far
# keep statuscode, content-type but discard content
self.render(
status => self.response.code,
type => self.response.headers<Content-Type> // '',
);
}
# return the old result, because if boolean this is important for route dispatching
return $result;
};
my $path = $orig-route.url-matcher;
my $head-route = Bailador::Route::AutoHead.new( method => 'HEAD', url-matcher => $path, code => $code);
$route.add_route($head-route);
}
}
}
multi method render($content) {
self.render( content => $content );
}
multi method render(Int :$status, Str :$type is copy, :$content is copy) {
# already set type manually, this type always wins
$type = self.response.headers<Content-Type> if ! $type.defined and self.response.headers<Content-Type>:exists;
if $content ~~ IO::Path {
my $fallback = self.config.file-discovery-content-type;
my $detected = $.content-types.detect-type($content, $fallback);
$type = $detected if !$type.defined and $detected;
$content = $content.slurp(:bin);
}
$type = self.config.default-content-type unless $type.defined;
# set values
$.context.autorender = False;
self.response.code = $status if $status;
self.response.headers<Content-Type> = $type if $type; # and $content.defined maybe?
self.response.content = $content if $content.defined;
}
method redirect(Str $location, Int $status = 302) {
self.response.headers<Location> = $location;
self.render(:$status, content => '', type => '');
# $.context.autorender = False;
# self.response.code = $code;
}
method add_error(Pair $x) {
self.error_handlers{$x.key} = $x.value;
}
method !sessions() {
unless $!sessions.defined {
$!sessions = Bailador::Sessions.new(:$!config);
}
return $!sessions;
}
method session() {
self!sessions.load(self.request);
}
method session-delete() {
self!sessions.delete-session(self.request);
}
method !done-rendering() {
# store session according to session engine
# good place for a Hook
self!sessions.store(self.response, self.request.env);
}
method log-request(DateTime $start, DateTime $end, Str $method, Str $uri, Int $http-code) {
my $env = self.context.env;
my $severity = 'error';
given $http-code {
when is-success($_) { $severity = 'info'; }
when is-redirect($_) { $severity = 'debug'; }
when is-client-error($_) { $severity = 'notice'; }
when is-server-error($_) { $severity = 'error'; }
# default { $severity = 'error'; }
}
# The message argument is only used in default logging format
Log::Any.log(
:msg("Serving $method $uri with $http-code in " ~ $end - $start ~ 's'),
:severity( $severity ),
:extra-fields( Hash.new( ( $env.kv, :HTTP_CODE(self.response.code) ) ) ),
:category('request')
);
}
multi method baile() {
# initialize the location if we didnt need it so far. that reads the config
$.location();
my $command;
if $.config.default-command() {
$command = $.config.default-command();
} elsif $.config.command-detection() {
$command = $.commands.detect-command();
} else {
die 'can not detect command';
}
self.baile($command);
}
multi method baile(Str $command, *@args) {
# initialize the location if we didnt need it so far. that reads the config
# in case we dont call baile() without parameters
$.location();
$.config.load-from-args(@args);
my $cmd = $.commands.get-command($command);
die 'can only baile once' if $!started;
$!started = True;
$.before-run();
$cmd.run(app => self );
}
multi method baile(Int $port, *@args) {
die qq:to/ERROR/;
baile is no longer called with the port as only argument.
Please call baile without arguments and put this line in front:
config.port = $port;
For more information, please see the Configuration section
of the Bailador manual:
https://github.com/Bailador/Bailador/blob/dev/doc/README.md#configuration
ERROR
}
method get-psgi-app {
# quotes from https://github.com/zostay/P6SGI
# draft 0.7
# * A P6SGI application is a Perl 6 routine that expects to receive an environment from an application server and returns a response each time it is called by the server.
# * An application MUST return a Promise
# * The message payload MUST be a sane Supply or an object that coerces into a sane Supply.
return sub (%env) {
start {
self.dispatch(%env).psgi;
}
}
}
method !adjust-log-adapter($env) {
if ($env<p6w.errors>:exists) {
self.log-adapter.io-handle = $env<p6w.errors>;
} else {
# this should never happen
self.log-adapter.io-handle = $*ERR;
}
}
method dispatch($env) {
my DateTime $start = DateTime.now;
self.context.env = $env;
try {
self!adjust-log-adapter($env),
my $method = $env<REQUEST_METHOD>;
my $uri = uri_decode( $env<PATH_INFO> // $env<REQUEST_URI>.split('?')[0] );
my $result = self.recurse-on-routes($method, $uri);
if $.context.autorender {
if $result.defined {
self.render: $result;
}
else {
die X::Bailador::ControllerReturnedNoResult.new(:$method, :$uri);
}
}
LEAVE {
my $http-code = self.response.code;
my DateTime $end = DateTime.now;
self.log-request($start, $end, $method, $uri, $http-code);
self!done-rendering();
}
CATCH {
when X::Bailador::ControllerReturnedNoResult {
Log::Any.warning("nothing to render, looks suspicious");
self.render();
}
when X::Bailador::NoRouteFound {
if self.error_handlers{404} {
self.render(:status(404), :type<text/html;charset=UTF-8>, content => self.error_handlers{404}());
} elsif $.location.defined && "$.location/views/404.xx".IO.e {
self.render(:status(404), :type<text/html;charset=UTF-8>, content => self.template("404.xx", []));
} else {
self.render(:status(404), :type<text/plain;charset=UTF-8>, content => 'Not found');
}
}
default {
Log::Any.error(
.gist,
:category( 'request-error' ),
:extra-fields( Hash.new( ( $env.kv, :file-and-line($?FILE~':'~$?LINE), :pid($*PID), :client-ip('-') ) ) ),
);
my $err-page;
if $!config.mode eq 'development' {
state $error-template = Template::Mojo.new(%?RESOURCES<error.template>.IO.slurp);
$err-page = $error-template.render($_, self.request());
self.render(status => 500, type => 'text/html;charset=UTF-8', content => $err-page);
} elsif self.error_handlers{500} {
self.render(:status(500), :type<text/html;charset=UTF-8>, content => self.error_handlers{500}());
} elsif $.location.defined && "$.location/views/500.xx".IO.e {
self.render(:status(500), :type<text/html;charset=UTF-8>, content => self.template("500.xx", []));
} else {
self.render(:status(500), :type<text/plain;charset=UTF-8>, content => 'Internal Server Error');
}
}
}
}
return self.response;
}
method curry(Str:D $method, *@args) {
die "Method $method not found on class " ~ self.WHAT.gist unless self.^method_table{$method}:exists;
return self.^method_table{$method}.assuming(self, |@args);
}
}