/
Context.pm6
373 lines (298 loc) · 9.16 KB
/
Context.pm6
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
use MONKEY-SEE-NO-EVAL;
use HTTP::Status;
use MIME::Types;
use Log;
use X::Hematite;
use Hematite::Request;
use Hematite::Response;
unit class Hematite::Context;
# static vars
my MIME::Types $MimeTypes;
# instance vars
has $.app;
has Hematite::Request $.request;
has Hematite::Response $.response;
has %!captures = (
'list' => Nil,
'named' => Nil
);
has %.stash = ();
has Log $.log;
# methods
method new($app, Hash $env) {
return self.bless(
app => $app,
env => $env,
);
}
submethod BUILD(*%args) {
$!app = %args{'app'};
$!request = Hematite::Request.new(%args{'env'});
$!response = Hematite::Response.new(200, Content-Type => 'text/html, charset=utf-8');
$!log = Log.new(
pattern => '[%d][%X{request_id}][%c] %m%n',
level => $!app.log.level,
output => $!app.log.output,
mdc => $!app.log.mdc.Hash,
ndc => $!app.log.ndc.Array,
);
self.log.mdc.put('request_id',
sprintf('%s-%s', $*PID, $*THREAD.id));
# search for the mime.types file
if (!$MimeTypes) {
my @mimetype_paths = ('/etc', '/etc/apache2');
for @mimetype_paths -> $path {
my $fullpath = $path ~ '/mime.types';
if ($fullpath.IO.e) {
$MimeTypes = MIME::Types.new($fullpath);
last;
}
}
}
self.log.debug("processing request: " ~ $!request.uri);
return self;
}
method FALLBACK(Str $name, |args) {
self.log.debug("helper { $name }");
my $helper = self.stash{"__helper_{ $name }__"};
if (!$helper) {
return;
}
return $helper(self, |@(args));
}
method !get-captures(Str $type) {
return EVAL(%!captures{$type}.perl);
}
method !set-captures(Str $type, $values) returns ::?CLASS {
if (%!captures{$type}.defined) {
self.log.debug('captures already setted, skipping it.');
return self;
}
my $copy = EVAL($values.perl);
%!captures{$type} = $copy;
return self;
}
method req() returns Hematite::Request { return self.request; }
method res() returns Hematite::Response { return self.response; }
# route captures
multi method captures() returns Array {
return self!get-captures('list');
}
# route set list capture params
multi method captures(@captures) {
return self!set-captures('list', @captures);
}
# route named captures
multi method named-captures() returns Hash {
return self!get-captures('named');
}
# route set named capture params
multi method named-captures(%captures) {
return self!set-captures('named', %captures);
}
multi method halt(*%args) {
my Int $status = %args{'status'} ||= 500;
# check for status error handler
my Callable $handler = self.app.error-handler($status);
if (!$handler) {
$handler = self.app.error-handler('halt');
}
$handler(self, |%args);
self.detach; # throw Hematite::Exception::DetachException
}
multi method halt(Int $status) {
self.halt(status => $status);
}
multi method halt(Str $body) {
self.halt(body => $body);
}
multi method halt(Int $status, Str $body) {
self.halt(status => $status, body => $body);
}
multi method halt(Int $status, %headers is copy, Str $body) {
self.halt(status => $status, headers => $(%headers), body => $body);
}
method not-found() { self.halt(404); }
method try-catch(Block :$try, Block :$catch?, Block :$finally?) returns ::?CLASS {
try {
$try();
CATCH {
my $ex = $_;
when X::Hematite::DetachException {
$ex.rethrow;
}
default {
if (!$catch) {
$ex.rethrow;
}
$catch($ex);
}
}
LEAVE {
if ($finally) {
$finally();
}
}
}
return self;
}
multi method url-for(Str $url is copy, @captures is copy, *%query) returns Str {
# if the $url hasn't the initial '/' use has context the current url
my Str $full_url = "";
if ( $url ~~ /^\// ) { # absolute
$full_url = self.request.base;
$full_url = $full_url.subst(/\/$/, "");
}
else { # relative
$full_url = self.request.uri ~ '/';
}
# replace captures :w+
while (@captures.elems > 0 && (my $match = ($url ~~ /:i (\:\w+)/))) {
my Str $group = ~($match[0]);
my $value = @captures.shift;
$url ~~ s/$group/$value/;
}
$full_url ~= $url;
# add query string
my Str $querystring = '';
for %query.kv -> $key, $value {
my $tmp_value = $value;
if (!$tmp_value.isa(Array)) {
$tmp_value = [$tmp_value];
}
for @($tmp_value) -> $vl {
if ($querystring.chars > 0) {
$querystring ~= '&';
}
$querystring ~= "$( $key )=$( $vl )";
}
}
if ($querystring.chars > 0) {
$full_url ~= '?' ~ $querystring;
}
return $full_url;
}
multi method url-for(Str $url, *%query) returns Str {
return self.url-for($url, [], |%query);
}
multi method url-for(Str $url is copy, %captures is copy, *%query) returns Str {
# replace captures
for %captures.kv -> $key, $value {
my $tmp_value = $value;
if (!$tmp_value.isa(Array)) {
$tmp_value = [$tmp_value];
}
while ($tmp_value.elems > 0 && (my $match = ($url ~~ /:i (\:$key)/))) {
my Str $group = ~($match[0]);
my $value = $tmp_value.shift;
$url ~~ s/$group/$value/;
}
}
return self.url-for($url, |%query);
}
multi method url-for-route(Str $name, $captures, *%query) {
my $route = self.app.get-route($name);
if ( !$route ) {
self.log.warn("no route found with name: { $name }");
return;
}
return self.url-for($route.pattern, $captures, |%query);
}
multi method url-for-route(Str $name, *%query) {
return self.url-for-route($name, [], |%query);
}
method !render-to-string($data, %options) returns Str {
my $type = %options{'type'};
if (!$type) {
# if is a Str, by default is a template otherwise is json
$type = $data.isa(Str) ?? 'template' !! 'json';
}
%options{'type'} = $type = lc($type);
return self.app.render-handler($type)($data, |%options);
}
method render-to-string($data, *%options) returns Str {
return self!render-to-string($data, %options);
}
method render($data, *%options) returns ::?CLASS {
my $result = self!render-to-string($data, %options);
my Str $type = %options{'type'};
my Str $format = lc(%options{'format'} // 'html');
my Str $content_type = $type eq 'template' ?? $format !! $type;
$content_type = $MimeTypes.type($content_type);
# set content-type
self.response.field(Content-Type => $content_type);
self.response.content = $result;
return self;
}
method detach() { X::Hematite::DetachException.new.throw; }
method redirect(Str $url) returns ::?CLASS {
self.response.set-code(302);
self.response.field(location => $url);
return self;
}
method redirect-and-detach(Str $url) {
self.redirect($url);
self.detach;
}
method handle-error(Str $type, *%args) returns ::?CLASS {
try {
my Callable $handler = self.app.error-handler($type);
if (!$handler) {
X::Hematite::ErrorHandlerNotFoundException.new( name => $type, ).throw;
}
$handler(self, |%args);
CATCH {
my Exception $ex = $_;
when X::Hematite::DetachException {
# don't do nothing, stop handle error process
}
}
}
return self;
}
method stream(Callable $fn) returns ::?CLASS {
my Channel $channel = Channel.new;
# check in every half a second if the client is still receving the data,
# otherwise close the channel
# we know the client is receiving is the poll is Nil
my $scheduler = $*SCHEDULER.cue(
{
$channel.close if $channel.poll;
},
every => 0.5,
);
# start a new thread and run the passed function
start {
my $orig_request_id = self.log.mdc.get('request_id');
self.log.mdc.put('request_id',
sprintf('%s-%s', $orig_request_id, $*THREAD.id));
self.try-catch(
try => sub { $fn(sub ($value) { $channel.send($value); }); },
catch => sub ($ex) {
return if $ex.isa(X::Channel::SendOnClosed);
# log the error
self.log.error($ex.gist);
},
finally => sub {
$channel.close;
self.log.debug('stream closed');
}
);
self.log.mdc.put('request_id', $orig_request_id);
}.then({
self.log.debug('stream finished, cancelling the scheduler');
$scheduler.cancel;
});
self.response.content = $channel;
return self;
}
method serve-file(Str $filepath) returns ::?CLASS {
# get file extension
my Str $ext = IO::Path.new($filepath).extension;
# guess content type
my Str $content_type = $MimeTypes.type($ext) || 'application/octect-stream';
self.response.content-type($content_type);
# serve file
self.response.content = $filepath.IO.open;
return self;
}