Debian Codegraph @

lib/Dancer2/Core/App.pm

raw
1 # ABSTRACT: encapsulation of Dancer2 packages
2 package Dancer2::Core::App;
3 $Dancer2::Core::App::VERSION = '2.2.2';
4 use Moo;
5 use Carp qw<croak carp>;
6 use Scalar::Util 'blessed';
7 use List::Util ();
8 use Module::Runtime 'is_module_name';
9 use Safe::Isa;
10 use Sub::Quote;
11 use Path::Tiny ();
12 use Module::Runtime qw< require_module use_module >;
13 use Ref::Util qw< is_ref is_arrayref is_globref is_scalarref is_regexpref >;
14 use Sub::Util qw/ set_subname subname /;
15
16 use Plack::App::File;
17 use Plack::Middleware::FixMissingBodyInRedirect;
18 use Plack::Middleware::Head;
19 use Plack::Middleware::Conditional;
20 use Plack::Middleware::ConditionalGET;
21
22 use Dancer2::ConfigReader;
23 use Dancer2::Core;
24 use Dancer2::Core::Cookie;
25 use Dancer2::Core::HTTP;
26 use Dancer2::Core::Error;
27 use Dancer2::Core::Types;
28 use Dancer2::Core::Route;
29 use Dancer2::Core::Hook;
30 use Dancer2::Core::Request;
31 use Dancer2::Core::Factory;
32
33 our $EVAL_SHIM; $EVAL_SHIM ||= sub {
34 my $code = shift;
35 $code->(@_);
36 };
37
38
39 # we have hooks here
40 with qw<
41 Dancer2::Core::Role::Hookable
42 Dancer2::Core::Role::HasConfig
43 Dancer2::Core::Role::HasLocation
44 Dancer2::Core::Role::HasEnvironment
45 >;
46
47 sub supported_engines { [ qw<logger serializer session template> ] }
48
49 sub with_plugins {
50 my ( $self, @plugins ) = @_;
51 return map $self->_with_plugin($_), @plugins;
52
53 }
54
55 sub _with_plugin {
56 my( $self, $plugin ) = @_;
57
58 if ( is_ref($plugin) ) {
59 # passing the plugin as an already-created object
60
61 # already loaded?
62 if( my ( $already ) = grep { ref($plugin) eq ref $_; } @{ $self->plugins } ) {
63 die "trying to load two different objects for plugin ". ref $plugin
64 if refaddr($plugin) != refaddr $already ;
65
66 }
67 else {
68 push @{ $self->plugins }, $plugin;
69 }
70
71 return $plugin;
72 }
73
74 # short plugin names get Dancer2::Plugin:: prefix
75 # plugin names starting with a '+' are full package names
76 if ( $plugin !~ s/^\+// ) {
77 $plugin =~ s/^(?!Dancer2::Plugin::)/Dancer2::Plugin::/;
78 }
79
80 # check if it's already there
81 if( my ( $already ) = grep { $plugin eq ref $_ } @{ $self->plugins } ) {
82 return $already;
83 }
84
85 push @{ $self->plugins },
86 $plugin = use_module($plugin)->new( app => $self );
87
88 return $plugin;
89 }
90
91 sub with_plugin {
92 my( $self, $plugin ) = @_;
93
94 croak "expected a single argument"
95 unless @_ == 2;
96
97 ( $self->with_plugins($plugin) )[0];
98 }
99
100 has _factory => (
101 is => 'ro',
102 isa => InstanceOf['Dancer2::Core::Factory'],
103 lazy => 1,
104 default => sub { Dancer2::Core::Factory->new },
105 );
106
107 has logger_engine => (
108 is => 'ro',
109 isa => ConsumerOf['Dancer2::Core::Role::Logger'],
110 lazy => 1,
111 builder => '_build_logger_engine',
112 writer => 'set_logger_engine',
113 );
114
115 has session_engine => (
116 is => 'ro',
117 isa => ConsumerOf['Dancer2::Core::Role::SessionFactory'],
118 lazy => 1,
119 builder => '_build_session_engine',
120 writer => 'set_session_engine',
121 );
122
123 has template_engine => (
124 is => 'ro',
125 isa => ConsumerOf['Dancer2::Core::Role::Template'],
126 lazy => 1,
127 builder => '_build_template_engine',
128 writer => 'set_template_engine',
129 );
130
131 has serializer_engine => (
132 is => 'ro',
133 isa => ConsumerOf['Dancer2::Core::Role::Serializer'],
134 lazy => 1,
135 builder => '_build_serializer_engine',
136 writer => 'set_serializer_engine',
137 predicate => 'has_serializer_engine',
138 );
139
140 has _appdir_path => (
141 is => 'ro',
142 lazy => 1,
143 builder => '_build_appdir_path',
144 init_arg => undef,
145 );
146
147 has _views_path => (
148 is => 'ro',
149 lazy => 1,
150 builder => '_build_views_path',
151 init_arg => undef,
152 );
153
154 has _public_dir_path => (
155 is => 'ro',
156 lazy => 1,
157 builder => '_build_public_dir_path',
158 init_arg => undef,
159 );
160
161 # compile_hooks() wraps each registered hook and writes the wrappers back
162 # via replace_hook. finish() (and therefore compile_hooks) can legitimately
163 # run more than once -- to_app() calls finish() every time it's invoked --
164 # and re-wrapping an already-wrapped hook would make a single dying hook
165 # report itself once per layer, so a dying hook fired core.app.hook_exception
166 # once, then twice, then three times as to_app was called again.
167 #
168 # This records every wrapper compile_hooks has produced, keyed by address,
169 # so a later run recognises its own work and passes it through instead of
170 # wrapping it a second time. It is deliberately per-hook rather than a
171 # per-app "already compiled" flag: hooks can still be registered after the
172 # first compile -- finish() adds postponed plugin hooks immediately after
173 # calling compile_hooks -- and those must still get wrapped when a later
174 # to_app() comes round.
175 has _compiled_hooks => (
176 is => 'ro',
177 isa => HashRef,
178 default => sub { +{} },
179 init_arg => undef,
180 );
181
182 has '+local_triggers' => (
183 default => sub {
184 my $self = shift;
185 my $triggers = {
186 # general triggers we want to allow, besides engines
187 views => sub {
188 my $self = shift;
189 my $value = shift;
190 $self->template_engine->views($value);
191 },
192
193 layout => sub {
194 my $self = shift;
195 my $value = shift;
196 $self->template_engine->layout($value);
197 },
198
199 layout_dir => sub {
200 my $self = shift;
201 my $value = shift;
202 $self->template_engine->layout_dir($value);
203 },
204
205 log => sub {
206 my ( $self, $value, $config ) = @_;
207
208 # This will allow to set the log level
209 # using: set log => warning
210 $self->logger_engine->log_level($value);
211 },
212
213 default_mime_type => sub {
214 my $self = shift;
215 my $value = shift;
216 $self->mime_type->default($value);
217 },
218 };
219
220 foreach my $engine ( @{ $self->supported_engines } ) {
221 $triggers->{$engine} = sub {
222 my $self = shift;
223 my $value = shift;
224 my $config = shift;
225
226 is_ref($value) and return $value;
227
228 my $build_method = "_build_${engine}_engine";
229 my $setter_method = "set_${engine}_engine";
230 my $engine_instance = $self->$build_method( $value, $config );
231
232 # set the engine with the new value from the builder
233 $self->$setter_method($engine_instance);
234 if ( $engine eq 'serializer' && $self->has_response ) {
235 $self->response->serializer($engine_instance);
236 }
237
238 return $engine_instance;
239 };
240 }
241
242 return $triggers;
243 },
244 );
245
246 has 'mime_type' => (
247 'is' => 'ro',
248 'isa' => InstanceOf['Dancer2::Core::MIME'],
249 'default' => sub { Dancer2::Core::MIME->new() },
250 );
251
252 sub _build_logger_engine {
253 my $self = shift;
254 my $value = shift;
255 my $config = shift;
256
257 defined $config or $config = $self->config;
258 defined $value or $value = $config->{logger};
259
260 is_ref($value) and return $value;
261
262 # XXX This is needed for the tests that create an app without
263 # a runner.
264 defined $value or $value = 'console';
265
266 is_module_name($value)
267 or croak "Cannot load logger engine '$value': illegal module name";
268
269 my $engine_options =
270 $self->_get_config_for_engine( logger => $value, $config );
271
272 my $logger = $self->_factory->create(
273 logger => $value,
274 %{$engine_options},
275 location => $self->config_reader->config_location,
276 environment => $self->environment,
277 app_name => $self->name,
278 postponed_hooks => $self->postponed_hooks
279 );
280
281 exists $config->{log} and $logger->log_level($config->{log});
282
283 return $logger;
284 }
285
286 sub _build_session_engine {
287 my $self = shift;
288 my $value = shift;
289 my $config = shift;
290
291 defined $config or $config = $self->config;
292 defined $value or $value = $config->{'session'} || 'simple';
293
294 is_ref($value) and return $value;
295
296 is_module_name($value)
297 or croak "Cannot load session engine '$value': illegal module name";
298
299 my $engine_options =
300 $self->_get_config_for_engine( session => $value, $config );
301
302 Scalar::Util::weaken( my $weak_self = $self );
303
304 # Note that engine options will replace the default session_dir (if provided).
305 return $self->_factory->create(
306 session => $value,
307 session_dir => $self->_appdir_path->child('sessions')->stringify,
308 %{$engine_options},
309 postponed_hooks => $self->postponed_hooks,
310
311 log_cb => sub { $weak_self->log(@_) },
312 );
313 }
314
315 sub _build_template_engine {
316 my $self = shift;
317 my $value = shift;
318 my $config = shift;
319
320 defined $config or $config = $self->config;
321 defined $value or $value = $config->{'template'};
322
323 defined $value or return;
324 is_ref($value) and return $value;
325
326 is_module_name($value)
327 or croak "Cannot load template engine '$value': illegal module name";
328
329 my $engine_options =
330 $self->_get_config_for_engine( template => $value, $config );
331
332 my $engine_attrs = {
333 config => $engine_options,
334 layout => $config->{layout},
335 layout_dir => ( $config->{layout_dir} || 'layouts' ),
336 views => $config->{views},
337 charset => $config->{charset},
338 };
339
340 Scalar::Util::weaken( my $weak_self = $self );
341
342 return $self->_factory->create(
343 template => $value,
344 %{$engine_attrs},
345 postponed_hooks => $self->postponed_hooks,
346
347 log_cb => sub { $weak_self->log(@_) },
348 );
349 }
350
351 sub _build_serializer_engine {
352 my $self = shift;
353 my $value = shift;
354 my $config = shift;
355
356 defined $config or $config = $self->config;
357 defined $value or $value = $config->{serializer};
358
359 defined $value or return;
360 is_ref($value) and return $value;
361
362 my $engine_options =
363 $self->_get_config_for_engine( serializer => $value, $config );
364 $engine_options->{strict_utf8} //= $config->{strict_utf8};
365
366 Scalar::Util::weaken( my $weak_self = $self );
367
368 return $self->_factory->create(
369 serializer => $value,
370 config => $engine_options,
371 postponed_hooks => $self->postponed_hooks,
372
373 log_cb => sub { $weak_self->log(@_) },
374 );
375 }
376
377 sub _get_config_for_engine {
378 my $self = shift;
379 my $engine = shift;
380 my $name = shift;
381 my $config = shift;
382
383 defined $config->{'engines'} && defined $config->{'engines'}{$engine}
384 or return {};
385
386 # try name, camelized name and fully-qualified name (without plus)
387 my $full_name = $name;
388 my $was_fully_qualified = ( $full_name =~ s/^\+// ); # strip any leading '+'
389 my $engine_config = {};
390 foreach my $engine_name (
391 $name,
392 Dancer2::Core::camelize($name),
393 ( $was_fully_qualified ? $full_name : () )
394 ) {
395 if ( defined $config->{'engines'}{$engine}{$engine_name} ) {
396 $engine_config = $config->{'engines'}{$engine}{$engine_name};
397 last;
398 }
399 }
400
401 return $engine_config;
402 }
403
404 has postponed_hooks => (
405 is => 'ro',
406 isa => HashRef,
407 default => sub { {} },
408 );
409
410 # TODO I'd be happier with a HashRef, really
411 has plugins => (
412 is => 'rw',
413 isa => ArrayRef,
414 default => sub { [] },
415 );
416
417 has route_handlers => (
418 is => 'rw',
419 isa => ArrayRef,
420 default => sub { [] },
421 );
422
423 has name => (
424 is => 'ro',
425 isa => Str,
426 default => sub { (caller(1))[0] },
427 );
428
429 has request => (
430 is => 'ro',
431 isa => InstanceOf['Dancer2::Core::Request'],
432 writer => '_set_request',
433 clearer => 'clear_request',
434 predicate => 'has_request',
435 );
436
437 sub set_request {
438 my ($self, $request, $defined_engines) = @_;
439 # typically this is passed in as an optimization within the
440 # dispatch loop but may be called elsewhere
441 $defined_engines ||= $self->defined_engines;
442 # populate request in app and all engines
443 $self->_set_request($request);
444 Scalar::Util::weaken( my $weak_request = $request );
445 $_->set_request( $weak_request ) for @{$defined_engines};
446 }
447
448 has response => (
449 is => 'ro',
450 isa => InstanceOf['Dancer2::Core::Response'],
451 lazy => 1,
452 writer => 'set_response',
453 clearer => 'clear_response',
454 builder => '_build_response',
455 predicate => 'has_response',
456 );
457
458 has with_return => (
459 is => 'ro',
460 predicate => 1,
461 writer => 'set_with_return',
462 clearer => 'clear_with_return',
463 );
464
465 has session => (
466 is => 'ro',
467 isa => InstanceOf['Dancer2::Core::Session'],
468 lazy => 1,
469 builder => '_build_session',
470 writer => 'set_session',
471 clearer => 'clear_session',
472 predicate => '_has_session',
473 );
474
475 has config_reader => (
476 is => 'ro',
477 isa => InstanceOf['Dancer2::ConfigReader'],
478 lazy => 0,
479 builder => '_build_config_reader',
480 );
481
482 sub _build_config_reader {
483 my ($self) = @_;
484 my $cfgr = Dancer2::ConfigReader->new(
485 environment => $self->environment,
486 location => $ENV{DANCER_CONFDIR} || $self->location,
487 default_config => $self->_build_default_config(),
488 );
489 return $cfgr;
490 }
491
492 has '+config' => (
493 is => 'ro',
494 isa => HashRef,
495 lazy => 1,
496 builder => '_build_config',
497 );
498
499 sub _build_config {
500 my ($self) = @_;
501
502 my $config_reader = $self->config_reader;
503 my $config = $config_reader->config;
504
505 if ( $config && $config->{'engines'} ) {
506 $self->_validate_engine($_) for keys %{ $config->{'engines'} };
507 }
508
509 return $config;
510 }
511
512 sub _build_response {
513 my $self = shift;
514 return Dancer2::Core::Response->new(
515 mime_type => $self->mime_type,
516 server_tokens => !$self->config->{'no_server_tokens'},
517 charset => $self->config->{charset},
518 strict_utf8 => $self->config->{strict_utf8},
519 do {
520 Scalar::Util::weaken( my $weak_self = $self );
521 log_cb => sub { $weak_self && $weak_self->log(@_) };
522 },
523 $self->has_serializer_engine
524 ? ( serializer => $self->serializer_engine )
525 : (),
526 );
527 }
528
529 sub _build_session {
530 my $self = shift;
531 my $session;
532
533 # Find the session engine
534 my $engine = $self->session_engine;
535
536 # find the session cookie if any
537 if ( !$self->has_destroyed_session ) {
538 my $session_id;
539 my $session_cookie = $self->cookie( $engine->cookie_name );
540 defined $session_cookie and
541 $session_id = $session_cookie->value;
542
543 # if we have a session cookie, try to retrieve the session
544 if ( defined $session_id ) {
545 eval {
546 $EVAL_SHIM->(sub {
547 $session = $engine->retrieve( id => $session_id );
548 });
549 1;
550 }
551 or do {
552 my $err = $@ || "Zombie Error";
553 if ( $err !~ /Unable to retrieve session/ ) {
554 croak "Failed to retrieve session: $err"
555 } else {
556 # XXX we throw away the error entirely? Why?
557 }
558 };
559 }
560 }
561
562 # create the session if none retrieved
563 return $session ||= $engine->create();
564 }
565
566 sub has_session {
567 my $self = shift;
568
569 my $engine = $self->session_engine;
570
571 return $self->_has_session
572 || ( $self->cookie( $engine->cookie_name )
573 && !$self->has_destroyed_session );
574 }
575
576 has destroyed_session => (
577 is => 'ro',
578 isa => InstanceOf ['Dancer2::Core::Session'],
579 predicate => 1,
580 writer => 'set_destroyed_session',
581 clearer => 'clear_destroyed_session',
582 );
583
584 has 'prep_apps' => (
585 'is' => 'ro',
586 'isa' => ArrayRef,
587 'default' => sub { [] },
588 );
589
590 sub find_plugin {
591 my ( $self, $name ) = @_;
592 my $plugin = List::Util::first { ref($_) eq $name } @{ $self->plugins };
593 $plugin or return;
594 return $plugin;
595 }
596
597 sub destroy_session {
598 my $self = shift;
599
600 # Find the session engine
601 my $engine = $self->session_engine;
602
603 # Expire session, set the expired cookie and destroy the session
604 # Setting the cookie ensures client gets an expired cookie unless
605 # a new session is created and supercedes it
606 my $session = $self->session;
607 $session->expires(-86400); # yesterday
608 $engine->destroy( id => $session->id );
609
610 # Invalidate session cookie in request
611 # and clear session in app and engines
612 $self->set_destroyed_session($session);
613 $self->clear_session;
614 $_->clear_session for @{ $self->defined_engines };
615
616 return;
617 }
618
619 sub setup_session {
620 my $self = shift;
621
622 for my $engine ( @{ $self->defined_engines } ) {
623 $self->has_session ?
624 $engine->set_session( $self->session ) :
625 $engine->clear_session;
626 }
627 }
628
629 sub change_session_id {
630 my $self = shift;
631
632 my $session = $self->session;
633
634 # Find the session engine
635 my $engine = $self->session_engine;
636
637 if ($engine->can('_change_id')) {
638
639 # session engine can change session ID
640 $engine->change_id( session => $session );
641 }
642 else {
643
644 # Method order is important in here...
645 #
646 # On session build if there is no destroyed session then the session
647 # builder tries to recreate the session using the existing session
648 # cookie. We really don't want to do that in this case so it is
649 # important to create the new session before the
650 # clear_destroyed_session method is called.
651 #
652 # This sucks.
653 #
654 # Sawyer suggested:
655 #
656 # What if you take the session cookie logic out of that attribute into
657 # another attribute and clear that attribute?
658 # That would force the session rebuilt to rebuilt the attribute and
659 # get a different cookie value, no?
660 #
661 # TODO: think about this some more.
662
663 # grab data, destroy session and store data again
664 my %data = %{$session->data};
665
666 # destroy existing session
667 $self->destroy_session;
668
669 # get new session
670 $session = $self->session;
671
672 # write data from old session into new
673 # Some engines add session id to data so skip id.
674 while (my ($key, $value) = each %data ) {
675 $session->write($key => $value) unless $key eq 'id';
676 }
677
678 # clear out destroyed session - no longer relevant
679 $self->clear_destroyed_session;
680 }
681
682 return $session->id;
683 }
684
685 has prefix => (
686 is => 'rw',
687 isa => Maybe [Dancer2Prefix],
688 predicate => 1,
689 coerce => sub {
690 my $prefix = shift;
691 defined($prefix) and $prefix eq "/" and return;
692 return $prefix;
693 },
694 );
695
696 # routes registry, stored by method:
697 has routes => (
698 is => 'rw',
699 isa => HashRef,
700 default => sub {
701 { get => [],
702 head => [],
703 post => [],
704 put => [],
705 del => [],
706 options => [],
707 };
708 },
709 );
710
711 has 'route_names' => (
712 'is' => 'rw',
713 'isa' => HashRef,
714 'default' => sub { {} },
715 );
716
717 # add_hook will add the hook to the first "hook candidate" it finds that support
718 # it. If none, then it will try to add the hook to the current application.
719 around add_hook => sub {
720 my $orig = shift;
721 my $self = shift;
722
723 # saving caller information
724 my ( $package, $file, $line ) = caller(4); # deep to 4 : user's app code
725 my $add_hook_caller = [ $package, $file, $line ];
726
727 my ($hook) = @_;
728 my $name = $hook->name;
729 my $hook_aliases = $self->all_hook_aliases;
730
731 # look for an alias
732 defined $hook_aliases->{$name} and $name = $hook_aliases->{$name};
733 $hook->name($name);
734
735 # if that hook belongs to the app, register it now and return
736 $self->has_hook($name) and return $self->$orig(@_);
737
738 # at this point the hook name must be formatted like:
739 # '$type.$candidate.$name', eg: 'engine.template.before_render' or
740 # 'plugin.database.before_dbi_connect'
741 my ( $hookable_type, $hookable_name, $hook_name ) = split( /\./, $name );
742
743 ( defined $hookable_name && defined $hook_name )
744 or croak "Invalid hook name `$name'";
745
746 grep /^$hookable_type$/, qw(core engine handler plugin)
747 or croak "Unknown hook type `$hookable_type'";
748
749 # register the hooks for existing hookable candidates
750 foreach my $hookable ( $self->hook_candidates ) {
751 $hookable->has_hook($name) and $hookable->add_hook(@_);
752 }
753
754 # we register the hook for upcoming objects;
755 # that way, each components that can claim the hook will have a chance
756 # to register it.
757
758 my $postponed_hooks = $self->postponed_hooks;
759
760 # Hmm, so the hook was not claimed, at this point we'll cache it and
761 # register it when the owner is instantiated
762 $postponed_hooks->{$hookable_type}{$hookable_name} ||= {};
763 $postponed_hooks->{$hookable_type}{$hookable_name}{$name} ||= {};
764 $postponed_hooks->{$hookable_type}{$hookable_name}{$name}{hook} = $hook;
765 $postponed_hooks->{$hookable_type}{$hookable_name}{$name}{caller} =
766 $add_hook_caller;
767
768 };
769
770 around execute_hook => sub {
771 my $orig = shift;
772 my $self = shift;
773
774 local $Dancer2::Core::Route::REQUEST = $self->request;
775 local $Dancer2::Core::Route::RESPONSE = $self->response;
776
777 my ( $hook, @args ) = @_;
778 if ( !$self->has_hook($hook) ) {
779 foreach my $cand ( $self->hook_candidates ) {
780 $cand->has_hook($hook) and return $cand->execute_hook(@_);
781 }
782 }
783
784 return $self->$orig(@_);
785 };
786
787 sub _build_default_config {
788 my $self = shift;
789
790 my $public = $ENV{DANCER_PUBLIC} || $self->_location_path->child('public')->stringify;
791 return {
792 content_type => ( $ENV{DANCER_CONTENT_TYPE} || 'text/html' ),
793 charset => ( $ENV{DANCER_CHARSET} || 'UTF-8' ),
794 strict_utf8 => ( $ENV{DANCER_STRICT_UTF8} || 0 ),
795 logger => ( $ENV{DANCER_LOGGER} || 'console' ),
796 views => ( $ENV{DANCER_VIEWS}
797 || $self->_location_path->child('views')->stringify ),
798 environment => $self->environment,
799 appdir => $self->location,
800 public_dir => $public,
801 template => 'Tiny',
802 strict_config => 0, # We can look at changing this in a future version
803 route_handlers => [
804 [
805 AutoPage => 1
806 ],
807 ],
808 };
809 }
810
811 sub _build_appdir_path {
812 my $self = shift;
813 return Path::Tiny::path( $self->config->{appdir} || $self->location );
814 }
815
816 sub _build_views_path {
817 my $self = shift;
818 return Path::Tiny::path( $self->config->{views} );
819 }
820
821 sub _build_public_dir_path {
822 my $self = shift;
823 my $dir = $ENV{DANCER_PUBLIC}
824 || $self->config->{public_dir}
825 || $self->_location_path->child('public')->stringify;
826 return Path::Tiny::path($dir);
827 }
828
829 sub _init_hooks {
830 my $self = shift;
831
832 # Hook to flush the session at the end of the request,
833 # this way, we're sure we flush only once per request
834 #
835 # Note: we create a weakened copy $self
836 # before closing over the weakened copy
837 # to avoid circular memory refs.
838 Scalar::Util::weaken(my $app = $self);
839
840 $self->add_hook(
841 Dancer2::Core::Hook->new(
842 name => 'core.app.after_request',
843 code => sub {
844 my $response = $Dancer2::Core::Route::RESPONSE;
845
846 # make sure an engine is defined, if not, nothing to do
847 my $engine = $app->session_engine;
848 defined $engine or return;
849
850 # if a session has been instantiated or we already had a
851 # session, first flush the session so cookie-based sessions can
852 # update the session ID if needed, then set the session cookie
853 # in the response
854 #
855 # if there is NO session object but the request has a cookie with
856 # a session key, create a dummy session with the same ID (without
857 # actually retrieving and flushing immediately) and generate the
858 # cookie header from the dummy session. Lazy Sessions FTW!
859
860 if ( $app->has_session ) {
861 my $session;
862 if ( $app->_has_session ) { # Session object exists
863 $session = $app->session;
864 $session->is_dirty and $engine->flush( session => $session );
865 }
866 else { # Cookie header exists. Create a dummy session object
867 my $cookie = $app->cookie( $engine->cookie_name );
868 my $session_id = $cookie->value;
869 $session = Dancer2::Core::Session->new( id => $session_id );
870 }
871 $engine->set_cookie_header(
872 response => $response,
873 session => $session
874 );
875 }
876 elsif ( $app->has_destroyed_session ) {
877 my $session = $app->destroyed_session;
878 $engine->set_cookie_header(
879 response => $response,
880 session => $session,
881 destroyed => 1
882 );
883 }
884 },
885 )
886 );
887 }
888
889 sub supported_hooks {
890 qw/
891 core.app.before_request
892 core.app.after_request
893 core.app.route_exception
894 core.app.hook_exception
895 core.app.before_file_render
896 core.app.after_file_render
897 core.error.before
898 core.error.after
899 core.error.init
900 /;
901 }
902
903 sub hook_aliases {
904 my $self = shift;
905 $self->{'hook_aliases'} ||= {
906 before => 'core.app.before_request',
907 before_request => 'core.app.before_request',
908 after => 'core.app.after_request',
909 after_request => 'core.app.after_request',
910 init_error => 'core.error.init',
911 before_error => 'core.error.before',
912 after_error => 'core.error.after',
913 on_route_exception => 'core.app.route_exception',
914 on_hook_exception => 'core.app.hook_exception',
915
916 before_file_render => 'core.app.before_file_render',
917 after_file_render => 'core.app.after_file_render',
918 before_handler_file_render => 'handler.file.before_render',
919 after_handler_file_render => 'handler.file.after_render',
920
921
922 # compatibility from Dancer1
923 before_error_render => 'core.error.before',
924 after_error_render => 'core.error.after',
925 before_error_init => 'core.error.init',
926
927 # TODO: call $engine->hook_aliases as needed
928 # But.. currently there are use cases where hook_aliases
929 # are needed before the engines are intiialized :(
930 before_template_render => 'engine.template.before_render',
931 after_template_render => 'engine.template.after_render',
932 before_layout_render => 'engine.template.before_layout_render',
933 after_layout_render => 'engine.template.after_layout_render',
934 before_serializer => 'engine.serializer.before',
935 after_serializer => 'engine.serializer.after',
936 };
937 }
938
939 sub defined_engines {
940 my $self = shift;
941 return [
942 $self->template_engine,
943 $self->session_engine,
944 $self->logger_engine,
945 $self->has_serializer_engine
946 ? $self->serializer_engine
947 : (),
948 ];
949 }
950
951 sub register_plugin {
952 my $self = shift;
953 my $plugin = shift;
954
955 $self->log( core => "Registered $plugin");
956
957 push @{ $self->plugins }, $plugin;
958 }
959
960 # This method overrides the default one from Role::ConfigReader
961 sub settings {
962 my $self = shift;
963 +{ %{ Dancer2::runner()->config }, %{ $self->config } };
964 }
965
966 sub cleanup {
967 my $self = shift;
968 $self->clear_request;
969 $self->clear_response;
970 $self->clear_session;
971 $self->clear_destroyed_session;
972 # Clear engine attributes
973 for my $engine ( @{ $self->defined_engines } ) {
974 $engine->clear_session;
975 $engine->clear_request;
976 }
977 }
978
979 sub _validate_engine {
980 my $self = shift;
981 my $name = shift;
982
983 grep +( $_ eq $name ), @{ $self->supported_engines }
984 or croak "Engine '$name' is not supported.";
985 }
986
987 sub engine {
988 my $self = shift;
989 my $name = shift;
990
991 $self->_validate_engine($name);
992
993 my $attr_name = "${name}_engine";
994 return $self->$attr_name;
995 }
996
997 sub template {
998 my $self = shift;
999
1000 my $template = $self->template_engine;
1001 $template->set_settings( $self->config );
1002
1003 # A session will not exist if there is no request (global keyword)
1004 #
1005 # A session may exist but the route code may not have instantiated
1006 # the session object (sessions are lazy). If this is the case, do
1007 # that now, so the templates have the session data for rendering.
1008 $self->has_request && $self->has_session && ! $template->has_session
1009 and $self->setup_session;
1010
1011 # return content
1012 if ($self->has_with_return) {
1013 my $old_with_return = $self->with_return;
1014 my $local_response;
1015 $self->set_with_return( sub {
1016 $local_response ||= shift;
1017 });
1018 # Catch any exceptions that may happen during template processing
1019 my $content = eval { $template->process( @_ ) };
1020 my $eval_result = $@;
1021 $self->set_with_return($old_with_return);
1022 # If there was a previous response set before the exception (or set as
1023 # part of the exception handling), then use that, otherwise throw the
1024 # exception as normal
1025 if ($local_response) {
1026 $self->with_return->($local_response);
1027 } elsif ($eval_result) {
1028 die $eval_result;
1029 }
1030 return $content;
1031 }
1032 return $template->process( @_ );
1033 }
1034
1035 sub hook_candidates {
1036 my $self = shift;
1037
1038 my @engines = @{ $self->defined_engines };
1039
1040 my @route_handlers;
1041 for my $handler ( @{ $self->route_handlers } ) {
1042 my $handler_code = $handler->{handler};
1043 blessed $handler_code and $handler_code->can('supported_hooks')
1044 and push @route_handlers, $handler_code;
1045 }
1046
1047 # TODO : get the list of all plugins registered
1048 my @plugins = @{ $self->plugins };
1049
1050 ( @route_handlers, @engines, @plugins );
1051 }
1052
1053 sub all_hook_aliases {
1054 my $self = shift;
1055
1056 my $aliases = $self->hook_aliases;
1057 for my $plugin ( grep { $_->can('hook_aliases') } @{ $self->plugins } ) {
1058 $aliases = { %{$aliases}, %{ $plugin->hook_aliases } };
1059 }
1060
1061 return $aliases;
1062 }
1063
1064 sub log {
1065 my $self = shift;
1066 my $level = shift;
1067
1068 my $logger = $self->logger_engine
1069 or croak "No logger defined";
1070
1071 $logger->$level(@_);
1072 }
1073
1074 sub send_as {
1075 my $self = shift;
1076 my ( $type, $data, $options ) = @_;
1077 $options ||= {};
1078
1079 $type or croak "Can not send_as using an undefined type";
1080
1081 if ( lc($type) eq 'html' || lc($type) eq 'plain' ) {
1082 if ( $type ne lc $type ) {
1083 local $Carp::CarpLevel = 2;
1084 carp sprintf( "Please use %s as the type for 'send_as', not %s", lc($type), $type );
1085 }
1086
1087 $options->{charset} //= $self->config->{charset};
1088 my $content = $data;
1089 if ( defined $options->{charset} && length $options->{charset} ) {
1090 $content = Encode::encode( $options->{charset}, $data );
1091 }
1092 $options->{content_type} ||= join '/', 'text', lc $type;
1093 # Explicit return needed here, as if we are currently rendering a
1094 # template then with_return will not longjump
1095 return $self->send_file( \$content, %$options );
1096 }
1097
1098 # Try and load the serializer class
1099 my $serializer_class = "Dancer2::Serializer::$type";
1100 eval {
1101 $EVAL_SHIM->(sub {
1102 require_module( $serializer_class );
1103 });
1104 1;
1105 } or do {
1106 my $err = $@ || "Zombie Error";
1107 croak "Unable to load serializer class for $type: $err";
1108 };
1109
1110 # load any serializer engine config
1111 my $engine_options =
1112 $self->_get_config_for_engine( serializer => $type, $self->config ) || {};
1113 $engine_options->{strict_utf8} //= $self->config->{strict_utf8};
1114
1115 Scalar::Util::weaken( my $weak_self = $self );
1116 my $serializer = $self->_factory->create(
1117 serializer => $type,
1118 config => $engine_options,
1119 postponed_hooks => $self->postponed_hooks,
1120 log_cb => sub { $weak_self->log(@_) },
1121 );
1122 my $content = $serializer->serialize( $data );
1123 $options->{content_type} ||= $serializer->content_type;
1124 $self->send_file( \$content, %$options );
1125 }
1126
1127 sub send_error {
1128 my $self = shift;
1129 my ( $message, $status ) = @_;
1130
1131 my $err = Dancer2::Core::Error->new(
1132 message => $message,
1133 app => $self,
1134 charset => $self->config->{charset},
1135 ( status => $status )x!! $status,
1136
1137 $self->has_serializer_engine
1138 ? ( serializer => $self->serializer_engine )
1139 : (),
1140 )->throw;
1141
1142 # Immediately return to dispatch if with_return coderef exists
1143 $self->has_with_return && $self->with_return->($err);
1144 return $err;
1145 }
1146
1147 sub send_file {
1148 my $self = shift;
1149 my $thing = shift;
1150 my %options = @_;
1151
1152 my ($content_type, $charset, $file_path);
1153
1154 # are we're given a filehandle? (based on what Plack::Middleware::Lint accepts)
1155 my $is_filehandle = Plack::Util::is_real_fh($thing)
1156 || ( is_globref($thing) && *{$thing}{IO} && *{$thing}{IO}->can('getline') )
1157 || ( Scalar::Util::blessed($thing) && $thing->can('getline') );
1158 my ($fh) = ($thing)x!! $is_filehandle;
1159
1160 # if we're given an IO::Scalar object, DTRT (take the scalar ref from it)
1161 if (Scalar::Util::blessed($thing) && $thing->isa('IO::Scalar')) {
1162 $thing = $thing->sref;
1163 }
1164
1165 # if we're given a SCALAR reference, build a filehandle to it
1166 if ( is_scalarref($thing) ) {
1167 ## no critic qw(InputOutput::RequireCheckedOpen)
1168 open $fh, "<", $thing;
1169 }
1170
1171 # If we haven't got a filehandle, create one to the requested content
1172 if (! $fh) {
1173 my $path = $thing;
1174 # remove prefix from given path (if not a filehandle)
1175 my $prefix = $self->prefix;
1176 if ( $prefix && $prefix ne '/' ) {
1177 $path =~ s/^\Q$prefix\E//;
1178 }
1179 # static file dir - either system root or public_dir
1180 my $dir = $options{system_path}
1181 ? Path::Tiny->rootdir
1182 : $self->_public_dir_path;
1183
1184 my $err_response = sub {
1185 my $status = shift;
1186 $self->response->status($status);
1187 $self->response->header( 'Content-Type', 'text/plain' );
1188 $self->response->content( Dancer2::Core::HTTP->status_message($status) );
1189 $self->with_return->( $self->response );
1190 };
1191
1192 # resolve relative paths (with '../') as much as possible
1193 # On Windows, absolute paths (e.g., C:/foo) must not be joined with
1194 # the rootdir since Path::Tiny would produce an invalid /C:/foo path.
1195 my $pt_path = Path::Tiny::path($path);
1196 $file_path = ( $pt_path->is_absolute
1197 ? $pt_path
1198 : Path::Tiny::path( $dir, $path )
1199 )->realpath;
1200
1201 # We need to check whether they are trying to access
1202 # a directory outside their scope
1203 $err_response->(403) if !$dir->realpath->subsumes($file_path);
1204
1205 # other error checks
1206 $err_response->(404) if !$file_path->exists;
1207 $err_response->(403) if !$file_path->is_file;
1208 $err_response->(403) if !-r $file_path;
1209
1210 # Read file content as bytes
1211 $fh = $file_path->openr_raw();
1212 $content_type = $self->mime_type->for_file($file_path) || 'text/plain';
1213 if ( $content_type =~ m!^text/! ) {
1214 $charset = $self->config->{charset};
1215 }
1216
1217 # cleanup for other functions not assuming on Path::Tiny
1218 $file_path = $file_path->stringify;
1219 }
1220
1221 # Now we are sure we can render the file...
1222 $self->execute_hook( 'core.app.before_file_render', $file_path );
1223
1224 # response content type and charset
1225 ( exists $options{'content_type'} ) and $content_type = $options{'content_type'};
1226 ( exists $options{'charset'} ) and $charset = $options{'charset'};
1227 $content_type .= "; charset=$charset" if $content_type and $charset;
1228 ( defined $content_type )
1229 and $self->response->header('Content-Type' => $content_type );
1230
1231 # content disposition
1232 ( exists $options{filename} )
1233 and $self->response->header( 'Content-Disposition' =>
1234 ($options{content_disposition} || "attachment") . "; filename=\"$options{filename}\"" );
1235
1236 # use a delayed response unless server does not support streaming
1237 my $use_streaming = exists $options{streaming} ? $options{streaming} : 1;
1238 my $response;
1239 my $env = $self->request->env;
1240 if ( $env->{'psgi.streaming'} && $use_streaming ) {
1241 my $cb = sub {
1242 my $responder = $Dancer2::Core::Route::RESPONDER;
1243 my $res = $Dancer2::Core::Route::RESPONSE;
1244 return $responder->(
1245 [ $res->status, $res->headers_to_array, $fh ]
1246 );
1247 };
1248
1249 Scalar::Util::weaken( my $weak_self = $self );
1250
1251 $response = Dancer2::Core::Response::Delayed->new(
1252 error_cb => sub { $weak_self->logger_engine->log( warning => @_ ) },
1253 cb => $cb,
1254 request => $Dancer2::Core::Route::REQUEST,
1255 response => $Dancer2::Core::Route::RESPONSE,
1256 );
1257 }
1258 else {
1259 $response = $self->response;
1260 # direct assignment to hash element, avoids around modifier
1261 # trying to serialise this this content.
1262
1263 # optimized slurp
1264 {
1265 ## no critic qw(Variables::RequireInitializationForLocalVars)
1266 local $/;
1267 $response->{'content'} = <$fh>;
1268 }
1269
1270 $response->is_encoded(1); # bytes are already encoded
1271 }
1272
1273 $self->execute_hook( 'core.app.after_file_render', $response );
1274 $self->with_return->( $response );
1275 }
1276
1277 sub BUILD {
1278 my $self = shift;
1279 $self->init_route_handlers();
1280 $self->_init_hooks();
1281 }
1282
1283 sub finish {
1284 my $self = shift;
1285
1286 # normalize some values that require calculations
1287 defined $self->config->{'static_handler'}
1288 or $self->config->{'static_handler'} = -d $self->config->{'public_dir'};
1289
1290 $self->register_route_handlers;
1291 $self->compile_hooks;
1292
1293 @{$self->plugins}
1294 && $self->plugins->[0]->can('_add_postponed_plugin_hooks')
1295 && $self->plugins->[0]->_add_postponed_plugin_hooks(
1296 $self->postponed_hooks
1297 );
1298
1299 foreach my $prep_cb ( @{ $self->prep_apps } ) {
1300 $prep_cb->($self);
1301 }
1302 }
1303
1304 sub init_route_handlers {
1305 my $self = shift;
1306
1307 my $handlers_config = $self->config->{route_handlers};
1308 for my $handler_data ( @{$handlers_config} ) {
1309 my ($handler_name, $config) = @{$handler_data};
1310 $config = {} if !is_ref($config);
1311
1312 my $handler = $self->_factory->create(
1313 Handler => $handler_name,
1314 app => $self,
1315 %$config,
1316 postponed_hooks => $self->postponed_hooks,
1317 );
1318
1319 push @{ $self->route_handlers }, {
1320 name => $handler_name,
1321 handler => $handler,
1322 };
1323 }
1324 }
1325
1326 sub register_route_handlers {
1327 my $self = shift;
1328 for my $handler ( @{$self->route_handlers} ) {
1329 my $handler_code = $handler->{handler};
1330 $handler_code->register($self);
1331 }
1332 }
1333
1334 sub compile_hooks {
1335 my ($self) = @_;
1336
1337 for my $position ( $self->supported_hooks ) {
1338 my $compiled_hooks = [];
1339 for my $hook ( @{ $self->hooks->{$position} } ) {
1340 # Already a wrapper this method produced on an earlier run:
1341 # pass it through untouched. See _compiled_hooks.
1342 if ( $self->_compiled_hooks->{ Scalar::Util::refaddr($hook) } ) {
1343 push @{$compiled_hooks}, $hook;
1344 next;
1345 }
1346
1347 Scalar::Util::weaken( my $app = $self );
1348 my $compiled = set_subname subname($hook) => sub {
1349 # don't run the filter if halt has been used
1350 $Dancer2::Core::Route::RESPONSE &&
1351 $Dancer2::Core::Route::RESPONSE->is_halted
1352 and return;
1353
1354 eval { $EVAL_SHIM->($hook,@_); 1; }
1355 or do {
1356 my $err = $@ || "Zombie Error";
1357 my $is_hook_exception = $position eq 'core.app.hook_exception';
1358 # Don't execute the hook_exception hook if the exception
1359 # has been generated from a hook exception handler itself,
1360 # thus preventing potentially recursive code.
1361 $app->execute_hook( 'core.app.hook_exception', $app, $err, $position )
1362 unless $is_hook_exception;
1363 my $is_halted = $app->response->is_halted; # Capture before cleanup
1364 # We can't cleanup if we're in the hook for a hook
1365 # exception, as this would clear the custom response that
1366 # may have been set by the hook. However, there is no need
1367 # to do so, as the upper hook that called this hook
1368 # exception will perform the cleanup instead anyway.
1369 # Likewise, if the response has been halted, that halt
1370 # means "this response is final" -- cleanup would destroy
1371 # the request/response/session the dispatcher still needs
1372 # to read, letting the very route this halt was meant to
1373 # refuse run anyway.
1374 $app->cleanup
1375 unless $is_hook_exception || $is_halted;
1376 # Allow the hook function to halt the response, thus
1377 # retaining any response it may have set. Otherwise the
1378 # croak from this function will overwrite any content that
1379 # may have been set by the hook
1380 return if $is_halted;
1381 # Default behavior if nothing else defined
1382 $app->log('error', "Exception caught in '$position' filter: $err");
1383 croak "Exception caught in '$position' filter: $err";
1384 };
1385 };
1386
1387 # Remember the wrapper -- by address, and by holding a reference
1388 # so its address cannot be reused by a later coderef -- so a
1389 # subsequent compile_hooks run recognises and skips it.
1390 $self->_compiled_hooks->{ Scalar::Util::refaddr($compiled) }
1391 = $compiled;
1392
1393 push @{$compiled_hooks}, $compiled;
1394 }
1395 $self->replace_hook( $position, $compiled_hooks );
1396 }
1397 }
1398
1399 sub lexical_prefix {
1400 my $self = shift;
1401 my $prefix = shift;
1402 my $cb = shift;
1403
1404 $prefix eq '/' and undef $prefix;
1405
1406 # save the app prefix
1407 my $app_prefix = $self->prefix;
1408
1409 # alter the prefix for the callback
1410 my $new_prefix =
1411 ( defined $app_prefix ? $app_prefix : '' )
1412 . ( defined $prefix ? $prefix : '' );
1413
1414 # if the new prefix is empty, it's a meaningless prefix, just ignore it
1415 length $new_prefix and $self->prefix($new_prefix);
1416
1417 my $err;
1418 my $ok= eval { $EVAL_SHIM->($cb); 1 }
1419 or do { $err = $@ || "Zombie Error"; };
1420
1421 # restore app prefix
1422 $self->prefix($app_prefix);
1423
1424 $ok or croak "Unable to run the callback for prefix '$prefix': $err";
1425 }
1426
1427 sub add_route {
1428 my $self = shift;
1429 my %route_attrs = @_;
1430
1431 my $route = Dancer2::Core::Route->new(
1432 type_library => $self->config->{type_library},
1433 prefix => $self->prefix,
1434 %route_attrs,
1435 );
1436
1437 my $method = $route->method;
1438 push @{ $self->routes->{$method} }, $route;
1439
1440 if ( $method ne 'head' && $route->has_name() ) {
1441 my $name = $route->name;
1442 $self->route_names->{$name}
1443 and die "Route with this name ($name) already exists";
1444
1445 $self->route_names->{$name} = $route;
1446 }
1447
1448 return $route;
1449 }
1450
1451 sub route_exists {
1452 my $self = shift;
1453 my $route = shift;
1454
1455 my $routes = $self->routes->{ $route->method };
1456
1457 foreach my $existing_route (@$routes) {
1458 $existing_route->spec_route eq $route->spec_route
1459 and return 1;
1460 }
1461
1462 return 0;
1463 }
1464
1465 sub routes_regexps_for {
1466 my $self = shift;
1467 my $method = shift;
1468
1469 return [ map $_->regexp, @{ $self->routes->{$method} } ];
1470 }
1471
1472 sub cookie {
1473 my $self = shift;
1474
1475 @_ == 1 and return $self->request->cookies->{ $_[0] };
1476
1477 # writer
1478 my ( $name, $value, %options ) = @_;
1479 my $c =
1480 Dancer2::Core::Cookie->new( name => $name, value => $value, %options );
1481 $self->response->push_header( 'Set-Cookie' => $c->to_header );
1482 }
1483
1484 sub redirect {
1485 my $self = shift;
1486 my $destination = shift;
1487 my $status = shift;
1488
1489 if ($destination =~ m{^/(?!/)}) {
1490 # If the app is mounted to something other than "/", we must
1491 # preserve its path.
1492 my $script_name = $self->request->script_name;
1493 $script_name =~ s{/$}{}; # Remove trailing slash (if present).
1494 $destination = $script_name . $destination;
1495 }
1496
1497 $self->response->redirect( $destination, $status );
1498
1499 # Short circuit any remaining before hook / route code
1500 # ('pass' and after hooks are still processed)
1501 $self->has_with_return
1502 and $self->with_return->($self->response);
1503 }
1504
1505 sub halt {
1506 my $self = shift;
1507 $self->response->halt( @_ );
1508
1509 # Short citcuit any remaining hook/route code
1510 $self->has_with_return
1511 and $self->with_return->($self->response);
1512 }
1513
1514 sub pass {
1515 my $self = shift;
1516 $self->response->pass;
1517
1518 # Short citcuit any remaining hook/route code
1519 $self->has_with_return
1520 and $self->with_return->($self->response);
1521 }
1522
1523 sub forward {
1524 my $self = shift;
1525 my $url = shift;
1526 my $params = shift;
1527 my $options = shift;
1528
1529 my $new_request = $self->make_forward_to( $url, $params, $options );
1530
1531 $self->has_with_return
1532 and $self->with_return->($new_request);
1533
1534 # nothing else will run after this
1535 }
1536
1537 # Create a new request which is a clone of the current one, apart
1538 # from the path location, which points instead to the new location
1539 sub make_forward_to {
1540 my $self = shift;
1541 my $url = shift;
1542 my $params = shift;
1543 my $options = shift;
1544
1545 my $overrides = { PATH_INFO => $url };
1546 exists $options->{method} and
1547 $overrides->{REQUEST_METHOD} = $options->{method};
1548
1549 # "clone" the existing request
1550 my $new_request = $self->request->_shallow_clone( $params, $overrides );
1551
1552 # If a session object was created during processing of the original request
1553 # i.e. a session object exists but no cookie existed
1554 # add a cookie so the dispatcher can assign the session to the appropriate app
1555 my $engine = $self->session_engine;
1556 $engine && $self->_has_session or return $new_request;
1557 my $name = $engine->cookie_name;
1558 exists $new_request->cookies->{$name} and return $new_request;
1559 $new_request->cookies->{$name} =
1560 Dancer2::Core::Cookie->new( name => $name, value => $self->session->id );
1561
1562 return $new_request;
1563 }
1564
1565 sub app { shift }
1566
1567 # DISPATCHER
1568 sub to_app {
1569 my $self = shift;
1570
1571 # build engines
1572 {
1573 for ( qw<logger session template> ) {
1574 my $attr = "${_}_engine";
1575 $self->$attr;
1576 }
1577
1578 # the serializer engine does not have a default
1579 # and is the only engine that can actually not have a value
1580 if ( $self->config->{'serializer'} ) {
1581 $self->serializer_engine;
1582 }
1583 }
1584
1585 $self->finish;
1586
1587 my $psgi = sub {
1588 my $env = shift;
1589
1590 # pre-request sanity check
1591 my $method = uc $env->{'REQUEST_METHOD'};
1592 $Dancer2::Core::Types::supported_http_methods{$method}
1593 or return [
1594 405,
1595 [ 'Content-Type' => 'text/plain' ],
1596 [ "Method Not Allowed\n\n$method is not supported." ]
1597 ];
1598
1599 my $response;
1600 eval {
1601 $EVAL_SHIM->(sub{ $response = $self->dispatch($env)->to_psgi });
1602 1;
1603 } or do {
1604 my $err = $@ || "Zombie Error";
1605 return [
1606 500,
1607 [ 'Content-Type' => 'text/plain' ],
1608 [ "Internal Server Error\n\n$err" ],
1609 ];
1610 };
1611
1612 return $response;
1613 };
1614
1615 # Only add static content handler if required
1616 if ( $self->config->{'static_handler'} ) {
1617 # Use App::File to "serve" the static content
1618 my $static_app = Plack::App::File->new(
1619 root => $self->_public_dir_path->stringify,
1620 content_type => sub { $self->mime_type->for_file( $_[0] ) },
1621 )->to_app;
1622 # Conditionally use the static handler wrapped with ConditionalGET
1623 # when the file exists. Otherwise the request passes into our app.
1624 $psgi = Plack::Middleware::Conditional->wrap(
1625 $psgi,
1626 condition => sub {
1627 my $env = shift;
1628 # A NUL byte in PATH_INFO makes Path::Tiny warn ("Invalid \0
1629 # character in pathname for ftis") when we ask it whether the
1630 # path is a file. "ftis" is not a typo on our part: it is
1631 # perl's own internal name for the file-test ops, quoted here
1632 # verbatim so this comment can be found from the warning text.
1633 # Refuse it here, before Path::Tiny ever sees it, so the
1634 # request just falls through to the app (which 404s, as it
1635 # always has) without the warning.
1636 return 0
1637 if defined $env->{'PATH_INFO'} && $env->{'PATH_INFO'} =~ /\0/;
1638 $self->_public_dir_path->child(
1639 defined $env->{'PATH_INFO'} && length $env->{'PATH_INFO'}
1640 ? ($env->{'PATH_INFO'})
1641 : (),
1642 )->is_file;
1643 },
1644 builder => sub { Plack::Middleware::ConditionalGET->wrap( $static_app ) },
1645 );
1646 }
1647
1648 # Wrap with common middleware
1649 if ( ! $self->config->{'no_default_middleware'} ) {
1650 # FixMissingBodyInRedirect
1651 $psgi = Plack::Middleware::FixMissingBodyInRedirect->wrap( $psgi );
1652 # Apply Head. After static so a HEAD request on static content DWIM.
1653 $psgi = Plack::Middleware::Head->wrap( $psgi );
1654 }
1655
1656 return $psgi;
1657 }
1658
1659 sub dispatch {
1660 my $self = shift;
1661 my $env = shift;
1662
1663 my $runner = Dancer2::runner();
1664 my $request;
1665 my $request_built_successfully = eval {
1666 $EVAL_SHIM->(sub {
1667 $request = $runner->{'internal_request'} || $self->build_request($env);
1668 });
1669 1;
1670 };
1671 # Catch bad content causing deserialization to fail when building the request
1672 if ( ! $request_built_successfully ) {
1673 my $err = $@;
1674 Scalar::Util::weaken(my $app = $self);
1675 return Dancer2::Core::Error->new(
1676 app => $app,
1677 message => $err,
1678 status => 400, # 400 Bad request (dont send again), rather than 500
1679 charset => $self->config->{charset},
1680 )->throw;
1681 }
1682
1683 my $cname = $self->session_engine->cookie_name;
1684 my $defined_engines = $self->defined_engines;
1685
1686 DISPATCH:
1687 while (1) {
1688 my $http_method = lc $request->method;
1689 my $path_info = $request->path_info;
1690
1691 # Add request to app and engines
1692 $self->set_request($request, $defined_engines);
1693
1694 $self->log( core => "looking for $http_method $path_info" );
1695
1696 ROUTE:
1697 foreach my $route ( @{ $self->routes->{$http_method} } ) {
1698 #warn "testing route " . $route->regexp . "\n";
1699 # TODO store in route cache
1700
1701 # go to the next route if no match
1702 my $match = $route->match($request)
1703 or next ROUTE;
1704
1705 $request->_set_route_params($match);
1706 $request->_set_route_parameters($match);
1707 $request->_set_route($route);
1708
1709 # Add session to app *if* we have a session and the request
1710 # has the appropriate cookie header for _this_ app.
1711 if ( my $sess = $runner->{'internal_sessions'}{$cname} ) {
1712 $self->set_session($sess);
1713 }
1714
1715 # calling the actual route
1716 my $response;
1717
1718 # this is very evil, but allows breaking out of multiple stack
1719 # frames without throwing an exception. Avoiding exceptions means
1720 # a naive eval won't swallow our flow control mechanisms, and
1721 # avoids __DIE__ handlers. It also prevents some cleanup routines
1722 # from working, since they are expecting control to return to them
1723 # after an eval.
1724 DANCER2_CORE_APP_ROUTE_RETURN: {
1725 if (!$self->has_with_return) {
1726 $self->set_with_return(sub {
1727 $response = shift;
1728 no warnings 'exiting';
1729 last DANCER2_CORE_APP_ROUTE_RETURN;
1730 });
1731 }
1732 $response = $self->_dispatch_route($route);
1733 };
1734
1735 # ensure we clear the with_return handler
1736 $self->clear_with_return;
1737
1738 # handle forward requests
1739 if ( ref $response eq 'Dancer2::Core::Request' ) {
1740 # this is actually a request, not response
1741 # however, we need to clean up the request & response
1742 $self->clear_request;
1743 $self->clear_response;
1744
1745 # this is in case we're asked for an old-style dispatching
1746 if ( $runner->{'internal_dispatch'} ) {
1747 # Get the session object from the app before we clean up
1748 # the request context, so we can propagate this to the
1749 # next dispatch cycle (if required).
1750 $self->_has_session
1751 and $runner->{'internal_sessions'}{$cname} =
1752 $self->session;
1753
1754 $runner->{'internal_forward'} = 1;
1755 $runner->{'internal_request'} = $response;
1756 return $self->response_not_found($request);
1757 }
1758
1759 $request = $response;
1760 next DISPATCH;
1761 }
1762
1763 # from here we assume the response is a Dancer2::Core::Response
1764
1765 # halted response, don't process further
1766 if ( $response->is_halted ) {
1767 $self->cleanup;
1768 delete $runner->{'internal_request'};
1769 return $response;
1770 }
1771
1772 # pass the baton if the response says so...
1773 if ( $response->has_passed ) {
1774 ## A previous route might have used splat, failed
1775 ## this needs to be cleaned from the request.
1776 exists $request->{_params}{splat}
1777 and delete $request->{_params}{splat};
1778
1779 $response->has_passed(0); # clear for the next round
1780
1781 # clear the content because if you pass it,
1782 # the next route is in charge of catching it
1783 $response->clear_content;
1784 next ROUTE;
1785 }
1786
1787 # it's just a regular response
1788 $self->execute_hook( 'core.app.after_request', $response );
1789 $self->cleanup;
1790 delete $runner->{'internal_request'};
1791
1792 return $response;
1793 }
1794
1795 # we don't actually want to continue the loop
1796 last;
1797 }
1798
1799 # No response! ensure Core::Dispatcher recognizes this failure
1800 # so it can try the next Core::App
1801 # and set the created request so we don't create it again
1802 # (this is important so we don't ignore the previous body)
1803 if ( $runner->{'internal_dispatch'} ) {
1804 $runner->{'internal_404'} = 1;
1805 $runner->{'internal_request'} = $request;
1806 }
1807
1808 # Render 404 response, cleanup, and return the response.
1809 my $response = $self->response_not_found($request);
1810 $self->cleanup;
1811 return $response;
1812 }
1813
1814 sub build_request {
1815 my ( $self, $env ) = @_;
1816 Scalar::Util::weaken( my $weak_self = $self );
1817
1818 # If we have an app, send the serialization engine
1819 my $request = Dancer2::Core::Request->new(
1820 env => $env,
1821 is_behind_proxy => $self->settings->{'behind_proxy'} || 0,
1822 uri_for_route => sub { shift; $weak_self->uri_for_route(@_) },
1823 strict_utf8 => $self->config->{strict_utf8},
1824
1825 $self->has_serializer_engine
1826 ? ( serializer => $self->serializer_engine )
1827 : (),
1828 );
1829
1830 return $request;
1831 }
1832
1833 # Call any before hooks then the matched route.
1834 sub _dispatch_route {
1835 my ( $self, $route ) = @_;
1836
1837 local $@;
1838 eval {
1839 $EVAL_SHIM->(sub {
1840 $self->execute_hook( 'core.app.before_request', $self );
1841 });
1842 1;
1843 } or do {
1844 my $err = $@ || "Zombie Error";
1845 return $self->response_internal_error($err);
1846 };
1847 my $response = $self->response;
1848
1849 if ( $response->is_halted ) {
1850 return $self->_prep_response( $response );
1851 }
1852
1853 eval {
1854 $EVAL_SHIM->(sub{ $response = $route->execute($self) });
1855 1;
1856 } or do {
1857 my $err = $@ || "Zombie Error";
1858 return $self->response_internal_error($err);
1859 };
1860
1861 return $response;
1862 }
1863
1864 sub _prep_response {
1865 my ( $self, $response, $content ) = @_;
1866
1867 # The response object has no back references to the content or app
1868 # Update the default_content_type of the response if any value set in
1869 # config so it can be applied when the response is encoded/returned.
1870 my $config = $self->config;
1871 if ( exists $config->{content_type}
1872 and my $ct = $config->{content_type} ) {
1873 $response->default_content_type($ct);
1874 }
1875 exists $config->{charset}
1876 and $response->charset( $config->{charset} );
1877
1878 # if we were passed any content, set it in the response
1879 defined $content && $response->content($content);
1880 return $response;
1881 }
1882
1883 sub response_internal_error {
1884 my ( $self, $error ) = @_;
1885
1886 $self->execute_hook( 'core.app.route_exception', $self, $error );
1887 $self->log( error => "Route exception: $error" );
1888
1889 local $Dancer2::Core::Route::REQUEST = $self->request;
1890 local $Dancer2::Core::Route::RESPONSE = $self->response;
1891
1892 return Dancer2::Core::Error->new(
1893 app => $self,
1894 status => 500,
1895 exception => $error,
1896 charset => $self->config->{charset},
1897 )->throw;
1898 }
1899
1900 sub response_not_found {
1901 my ( $self, $request ) = @_;
1902
1903 $self->set_request($request);
1904
1905 local $Dancer2::Core::Route::REQUEST = $self->request;
1906 local $Dancer2::Core::Route::RESPONSE = $self->response;
1907
1908 my $response = Dancer2::Core::Error->new(
1909 app => $self,
1910 status => 404,
1911 message => $request->path,
1912 charset => $self->config->{charset},
1913 )->throw;
1914
1915 $self->cleanup;
1916
1917 return $response;
1918 }
1919
1920 sub uri_for_route {
1921 my ( $self, $route_name, $route_params, $query_params, $dont_escape ) = @_;
1922 my $route = $self->route_names->{$route_name}
1923 or die "Cannot find route named '$route_name'";
1924
1925 my $string = $route->spec_route;
1926 is_regexpref($string)
1927 and die "uri_for_route() does not support regexp route paths";
1928
1929 # Convert splat only to the general purpose structure
1930 if ( is_arrayref($route_params) ) {
1931 $route_params = { 'splat' => $route_params };
1932 }
1933
1934 # The regexes are taken and altered from:
1935 # Dancer2::Core::Route::_build_regexp_from_string.
1936
1937 # Replace :foo with arg (route parameters)
1938 # Not a fan of all this regex play to handle typed parameter -- SX
1939 my @params = $string =~ m{:([^/.\?]+)}xmsg;
1940
1941 foreach my $param (@params) {
1942 $param =~ s{^([^\[]+).*}{$1}xms;
1943 # A defined-but-false value is a legitimate parameter -- 0 is an
1944 # ordinary database ID, list index or page number -- so these are
1945 # tested for definedness and emptiness rather than for truth. The
1946 # empty string is refused because ':param' compiles to ([^/]+),
1947 # which matches at least one character: substituting it would
1948 # produce a URI that cannot match the route it came from.
1949 my $value = $route_params->{$param};
1950 if ( !defined $value ) {
1951 die "Route $route_name uses the parameter '${param}', which was not provided\n";
1952 }
1953 elsif ( $value eq '' ) {
1954 die "Route $route_name was given an empty value for the parameter '${param}'\n";
1955 }
1956
1957 $string =~ s!\Q:$param\E(\[[^\]]+\])?!$value!xmsg;
1958 }
1959
1960 # TODO: Can we cut this down by replacing on the spot?
1961 # I think that will be tricky because we first need all **, then *
1962
1963 $string =~ s!\Q**\E!(?#megasplat)!g;
1964 $string =~ s!\*!(?#splat)!g;
1965
1966 # TODO: Can we cut this down?
1967 my @token_or_splat =
1968 $string =~ /\(\?#((?:mega)?splat)\)/g;
1969
1970 my $splat_params = $route_params->{'splat'};
1971 if ($splat_params && @token_or_splat) {
1972 $#{$splat_params} == $#token_or_splat
1973 or die 'Mismatch in amount of splat args and splat elements';
1974
1975 for ( my $i = 0; $i < @{$splat_params}; $i++ ) {
1976 if ( is_arrayref($splat_params->[$i]) ){
1977 my $megasplat = join '/', @{ $splat_params->[$i] };
1978 $string =~ s{\Q(?#megasplat)\E}{$megasplat};
1979 } else {
1980 $string =~ s{\Q(?#splat)\E}{$splat_params->[$i]};
1981 }
1982 }
1983 }
1984
1985 return $self->request->uri_for( $string, $query_params, $dont_escape );
1986 }
1987
1988 1;
1989
1990 __END__
1991
1992 =pod
1993
1994 =encoding UTF-8
1995
1996 =head1 NAME
1997
1998 Dancer2::Core::App - encapsulation of Dancer2 packages
1999
2000 =head1 VERSION
2001
2002 version 2.2.2
2003
2004 =head1 DESCRIPTION
2005
2006 Everything a package that uses Dancer2 does is encapsulated into a
2007 C<Dancer2::Core::App> instance. This class defines all that can be done in such
2008 objects.
2009
2010 Mainly, it will contain all the route handlers, the configuration settings and
2011 the hooks that are defined in the calling package.
2012
2013 Note that with Dancer2, everything that is done within a package is scoped to
2014 that package, thanks to that encapsulation.
2015
2016 =head1 ATTRIBUTES
2017
2018 =head2 plugins
2019
2020 =head2 runner_config
2021
2022 =head2 default_config
2023
2024 =head2 with_return
2025
2026 Used to cache the coderef that will return from back to the dispatcher, across
2027 an arbitrary number of stack frames.
2028
2029 =head2 destroyed_session
2030
2031 We cache a destroyed session here; once this is set we must not attempt to
2032 retrieve the session from the cookie in the request. If no new session is
2033 created, this is set (with expiration) as a cookie to force the browser to
2034 expire the cookie.
2035
2036 =head1 METHODS
2037
2038 =head2 has_session
2039
2040 Returns true if session engine has been defined and if either a session
2041 object has been instantiated or if a session cookie was found and not
2042 subsequently invalidated.
2043
2044 =head2 change_session_id
2045
2046 Changes the session ID used by the current session. This should be used on
2047 any change of privilege level, for example on login. Returns the new session
2048 ID.
2049
2050 =head2 destroy_session
2051
2052 Destroys the current session and ensures any subsequent session is created
2053 from scratch and not from the request session cookie
2054
2055 =head2 register_plugin
2056
2057 =head2 with_plugins( @plugin_names )
2058
2059 Creates instances of the given plugins and tie them to the app.
2060 The plugin classes are automatically loaded.
2061 Returns the newly created plugins.
2062
2063 The plugin names are expected to be without the leading C<Dancer2::Plugin>.
2064 I.e., use C<Foo> to mean C<Dancer2::Plugin::Foo>.
2065
2066 If a given plugin is already tied to the app, the already-existing
2067 instance will be used and returned by C<with_plugins> (think of it
2068 as using a role).
2069
2070 my @plugins = $app->with_plugins( 'Foo', 'Bar' );
2071
2072 # now $app uses the plugins Dancer2::Plugin::Foo
2073 # and Dancer2::Plugin::Bar
2074
2075 =head2 with_plugin( $plugin_name )
2076
2077 Just like C<with_plugin>, but for a single plugin.
2078
2079 my $plugin = $app->with_plugin('Foo');
2080
2081 =head2 add_route
2082
2083 Register a new route handler.
2084
2085 $app->add_route(
2086 method => 'get',
2087 regexp => '/somewhere',
2088 code => sub { ... },
2089 options => $conditions,
2090 );
2091
2092 Returns a new L<< Dancer2::Core::Route >> object created with the passed
2093 arguments.
2094
2095 =head2 route_exists
2096
2097 Returns a true value if a route already exists, otherwise false.
2098
2099 my $route = Dancer2::Core::Route->new(...);
2100 if ($app->route_exists($route)) {
2101 ...
2102 }
2103
2104 =head2 routes_regexps_for
2105
2106 Sugar for getting the ordered list of all registered route regexps by method.
2107
2108 my $regexps = $app->routes_regexps_for( 'get' );
2109
2110 Returns an ArrayRef with the results.
2111
2112 =head2 redirect($destination, $status)
2113
2114 Sets a redirect in the response object. If $destination is not an absolute URI, then it will
2115 be made into an absolute URI, relative to the URI in the request.
2116
2117 =head2 halt
2118
2119 Flag the response object as 'halted'.
2120
2121 If called during request dispatch, immediately returns the response
2122 to the dispatcher and after hooks will not be run.
2123
2124 =head2 pass
2125
2126 Flag the response object as 'passed'.
2127
2128 If called during request dispatch, immediately returns the response
2129 to the dispatcher.
2130
2131 =head2 forward
2132
2133 Create a new request which is a clone of the current one, apart
2134 from the path location, which points instead to the new location.
2135 This is used internally to chain requests using the forward keyword.
2136
2137 This method takes 3 parameters: the url to forward to, followed by an
2138 optional hashref of parameters added to the current request parameters,
2139 followed by a hashref of options regarding the redirect, such as
2140 C<method> to change the request method.
2141
2142 For example:
2143
2144 forward '/login', { login_failed => 1 }, { method => 'GET' });
2145
2146 =head2 app
2147
2148 Returns itself. This is simply available as a shim to help transition from
2149 a previous version in which hooks were sent a context object (originally
2150 C<Dancer2::Core::Context>) which has since been removed.
2151
2152 # before
2153 hook before => sub {
2154 my $ctx = shift;
2155 my $app = $ctx->app;
2156 };
2157
2158 # after
2159 hook before => sub {
2160 my $app = shift;
2161 };
2162
2163 This meant that C<< $app->app >> would fail, so this method has been provided
2164 to make it work.
2165
2166 # now
2167 hook before => sub {
2168 my $WannaBeCtx = shift;
2169 my $app = $WannaBeContext->app; # works
2170 };
2171
2172 =head2 lexical_prefix
2173
2174 Allow for setting a lexical prefix
2175
2176 $app->lexical_prefix('/blog', sub {
2177 ...
2178 });
2179
2180 All the route defined within the callback will have a prefix appended to the
2181 current one.
2182
2183 =head2 C< $SIG{__DIE__} > Compatibility via C< $Dancer2::Core::App::EVAL_SHIM >
2184
2185 If an installation wishes to use C< $SIG{__DIE__} > hooks to enhance
2186 their error handling then it may be required to ensure that certain
2187 bookkeeping code is executed within every C<eval BLOCK> that Dancer2
2188 performs. This can be accomplished by overriding the global variable
2189 C<$Dancer2::Core::App::EVAL_SHIM> with a subroutine which does whatever
2190 logic is required.
2191
2192 This routine must perform the equivalent of the following subroutine:
2193
2194 our $EVAL_SHIM = sub {
2195 my $code = shift;
2196 return $code->(@_);
2197 };
2198
2199 An example of overriding this sub might be as follows:
2200
2201 $Dancer2::Core::App::EVAL_SHIM = sub {
2202 my $code = shift;
2203 local $IGNORE_EVAL_COUNTER = $IGNORE_EVAL_COUNTER + 1;
2204 return $code->(@_);
2205 };
2206
2207 B<Note:> that this is a GLOBAL setting, which must be set up before
2208 any form of dispatch or use of Dancer2.
2209
2210 =head1 AUTHOR
2211
2212 Dancer Core Developers
2213
2214 =head1 COPYRIGHT AND LICENSE
2215
2216 This software is copyright (c) 2026 by Alexis Sukrieh.
2217
2218 This is free software; you can redistribute it and/or modify it under
2219 the same terms as the Perl 5 programming language system itself.
2220
2221 =cut