Debian Codegraph @

lib/Dancer2/ConfigReader.pm

raw
1 # ABSTRACT: Config reader for Dancer2 App
2 package Dancer2::ConfigReader;
3 $Dancer2::ConfigReader::VERSION = '2.2.2';
4 use Moo;
5
6 use Config::Any;
7 use Hash::Merge::Simple;
8 use Carp 'croak';
9 use Module::Runtime qw{ use_module };
10 use Ref::Util qw/ is_arrayref is_hashref /;
11 use Scalar::Util qw/ blessed /;
12 use Path::Tiny ();
13
14 use Dancer2::Core::Factory;
15 use Dancer2::Core;
16 use Dancer2::Core::Types;
17 use Dancer2::ConfigUtils 'normalize_config_entry';
18
19 our $MAX_CONFIGS = $ENV{DANCER_MAX_CONFIGS} || 100;
20
21 my %KNOWN_CORE_KEYS = map +( $_ => 1 ), qw(
22 additional_config_readers
23 appdir
24 apphandler
25 appname
26 auto_page
27 behind_proxy
28 charset
29 content_type
30 default_mime_type
31 engines
32 environment
33 error_template
34 host
35 layout
36 layout_dir
37 log
38 logger
39 no_default_middleware
40 no_server_tokens
41 plugins
42 port
43 public_dir
44 route_handlers
45 serializer
46 session
47 show_errors
48 show_stacktrace
49 startup_info
50 static_handler
51 template
52 timeout
53 traces
54 type_library
55 views
56 strict_config
57 strict_config_allow
58 );
59
60 my %KNOWN_ENGINE_CONFIG = (
61 'logger' => {
62 'base_keys' => {
63 'app_name' => 1,
64 'auto_encoding_charset' => 1,
65 'log_format' => 1,
66 'log_level' => 1,
67 },
68 'engines' => {
69 'capture' => { keys => {} },
70 'console' => { keys => {} },
71 'diag' => { keys => {} },
72 'file' => {
73 'keys' => {
74 'file_name' => 1,
75 'log_dir' => 1,
76 },
77 },
78 'note' => { keys => {} },
79 'null' => { keys => {} },
80 },
81 },
82 'serializer' => {
83 'engines' => {
84 'dumper' => { keys => {} },
85 'json' => { allow_any => 1 },
86 'mutable' => {
87 keys => {
88 mapping => 1,
89 },
90 },
91 'yaml' => { keys => {} },
92 },
93 },
94 'session' => {
95 'base_keys' => {
96 'cookie_domain' => 1,
97 'cookie_duration' => 1,
98 'cookie_name' => 1,
99 'cookie_path' => 1,
100 'cookie_same_site' => 1,
101 'is_http_only' => 1,
102 'is_secure' => 1,
103 'session_duration' => 1,
104 },
105 'engines' => {
106 'simple' => { keys => {} },
107 'yaml' => {
108 'keys' => {
109 'session_dir' => 1,
110 },
111 },
112 },
113 },
114 'template' => {
115 'engines' => {
116 'templatetoolkit' => { allow_any => 1 },
117 'tiny' => { allow_any => 1 },
118 },
119 },
120 );
121
122 has location => (
123 is => 'ro',
124 isa => Str,
125 required => 1,
126 );
127
128 has default_config => (
129 is => 'ro',
130 isa => HashRef,
131 required => 1,
132 );
133
134 has config_location => (
135 is => 'ro',
136 isa => ReadableFilePath,
137 lazy => 1,
138 default => sub { $_[0]->location },
139 );
140
141 # The type for this attribute is Str because we don't require
142 # an existing directory with configuration files for the
143 # environments. An application without environments is still
144 # valid and works.
145 has environments_location => (
146 is => 'ro',
147 isa => Str,
148 lazy => 1,
149 default => sub {
150 # short circuit
151 defined $ENV{'DANCER_ENVDIR'}
152 and return $ENV{'DANCER_ENVDIR'};
153
154 my $self = shift;
155
156 foreach my $maybe_path ( $self->config_location, $self->location ) {
157 my $path = Path::Tiny::path($maybe_path, 'environments');
158 $path->exists && $path->is_dir
159 and return $path->stringify;
160 }
161
162 return '';
163 },
164 );
165
166 has _config_location_path => (
167 is => 'ro',
168 lazy => 1,
169 builder => '_build_config_location_path',
170 init_arg => undef,
171 );
172
173 has _environments_location_path => (
174 is => 'ro',
175 lazy => 1,
176 builder => '_build_environments_location_path',
177 init_arg => undef,
178 );
179
180 sub _build_config_location_path {
181 my $self = shift;
182 return Path::Tiny::path( $self->config_location );
183 }
184
185 sub _build_environments_location_path {
186 my $self = shift;
187 return Path::Tiny::path( $self->environments_location );
188 }
189
190 has config => (
191 is => 'ro',
192 isa => HashRef,
193 lazy => 1,
194 builder => '_build_config',
195 );
196
197 has environment => (
198 is => 'ro',
199 isa => Str,
200 required => 1,
201 );
202
203 has config_readers => (
204 is => 'ro',
205 lazy => 1,
206 isa => ArrayRef,
207 builder => '_build_config_readers',
208 );
209
210 # The config builder
211 sub _build_config {
212 my ($self) = @_;
213
214 my $config = $self->default_config;
215
216 my $nbr_config = 0;
217
218 my @readers = @{ $self->config_readers };
219
220 my $config_to_object = sub {
221 my $thing = $_;
222
223 return $thing if blessed $thing;
224
225 $thing = { $thing => {} } unless ref $thing;
226
227 die "additional_config_readers entry must have exactly one key\n"
228 if keys %$thing != 1;
229
230 my( $class, $args ) = %$thing;
231
232 return use_module($class)->new(
233 location => $self->location,
234 environment => $self->environment,
235 %$args,
236 );
237 };
238
239 while( my $r = shift @readers ) {
240 die <<"END" if $nbr_config++ >= $MAX_CONFIGS;
241 MAX_CONFIGS exceeded: read over $MAX_CONFIGS configurations
242
243 Looks like you have an infinite recursion in your configuration system.
244 Re-run with DANCER_CONFIG_VERBOSE=1 to see what is going on.
245
246 If your application really read that many configs (may \$dog have mercy
247 on your soul), you can increase the limit via the environment variable
248 DANCER_MAX_CONFIGS.
249
250 END
251 warn "Reading config from @{[ $r->name() ]}\n" if $ENV{DANCER_CONFIG_VERBOSE};
252 my $local_config = $r->read_config;
253
254 if( my $additionals = delete $local_config->{additional_config_readers} ) {
255
256 warn "Additional config readers found\n" if $ENV{DANCER_CONFIG_VERBOSE};
257
258 unshift @readers, map { $config_to_object->($_) } is_arrayref($additionals) ? @$additionals : ($additionals);
259 }
260
261 $config = Hash::Merge::Simple->merge(
262 $config, $local_config
263 );
264 }
265
266 return $self->_normalize_config($config);
267 }
268
269 sub _normalize_config {
270 my ( $self, $config ) = @_;
271
272 foreach my $key ( keys %{$config} ) {
273 my $value = $config->{$key};
274 $config->{$key} = normalize_config_entry( $key, $value );
275 }
276
277 $self->_strict_config_keys($config);
278
279 return $config;
280 }
281
282 sub _build_config_readers {
283 my ($self) = @_;
284
285 my @config_reader_names = $ENV{'DANCER_CONFIG_READERS'}
286 ? (split qr{,}msx, $ENV{'DANCER_CONFIG_READERS'})
287 : ( q{Dancer2::ConfigReader::Config::Any} );
288
289 warn "ConfigReaders to use: @config_reader_names\n" if $ENV{DANCER_CONFIG_VERBOSE};
290 return [
291 map use_module($_)->new(
292 location => $self->location,
293 environment => $self->environment,
294 ), @config_reader_names
295 ];
296 }
297
298 sub _strict_config_keys {
299 my ( $self, $config ) = @_;
300
301 return
302 if exists $config->{'strict_config'}
303 && !$config->{'strict_config'};
304
305 my %allowed_keys;
306 if ( exists $config->{'strict_config_allow'} ) {
307 my $allow = $config->{'strict_config_allow'};
308 if ( is_arrayref($allow) ) {
309 %allowed_keys = map +( $_ => 1 ), @{$allow};
310 } else {
311 croak('strict_config_allow can only be arrayref');
312 }
313 }
314
315 my @warnings = map +(
316 $KNOWN_CORE_KEYS{$_} || $allowed_keys{$_}
317 ? ()
318 : "Unknown configuration key '$_'"
319 ), sort keys %{$config};
320
321 if ( my $engines = $config->{'engines'} ) {
322 push @warnings, $self->_warn_unknown_engine_config_keys($engines);
323 }
324
325 @warnings or return;
326
327 warn join(
328 "\n",
329 @warnings,
330 'Set strict_config => 0 to silence these warnings.'
331 ) . "\n";
332 }
333
334 sub _warn_unknown_engine_config_keys {
335 my ( $self, $engines ) = @_;
336 is_hashref($engines)
337 or return;
338
339 my @warnings;
340
341 for my $engine_type ( sort keys %{$engines} ) {
342 my $type_config = $engines->{$engine_type};
343 is_hashref($type_config)
344 or next;
345
346 my $known_type = $KNOWN_ENGINE_CONFIG{$engine_type}
347 or next;
348
349 my $base_keys = $known_type->{'base_keys'} || {};
350 my $known_engines = $known_type->{'engines'} || {};
351
352 for my $engine_name ( sort keys %{$type_config} ) {
353 my $engine_config = $type_config->{$engine_name};
354 is_hashref($engine_config)
355 or next;
356
357 my $normalized = _normalize_engine_name($engine_name);
358 defined $normalized
359 or next;
360
361 my $known_engine = $known_engines->{$normalized} or next;
362 next if $known_engine->{'allow_any'};
363
364 my %allowed = (%{$base_keys}, %{ $known_engine->{keys} || {} });
365
366 for my $key ( sort keys %{$engine_config} ) {
367 next if $allowed{$key};
368 push @warnings,
369 "Unknown configuration key '$key' for engine '$engine_type/$engine_name'";
370 }
371 }
372 }
373
374 return @warnings;
375 }
376
377 sub _normalize_engine_name {
378 my ($name) = @_;
379
380 return if !defined $name;
381 return if $name =~ /::/xms;
382
383 my $normalized = lc $name;
384 $normalized =~ s/_//xmsg;
385 return $normalized;
386 }
387
388 1;
389
390 __END__
391
392 =pod
393
394 =encoding UTF-8
395
396 =head1 NAME
397
398 Dancer2::ConfigReader - Config reader for Dancer2 App
399
400 =head1 VERSION
401
402 version 2.2.2
403
404 =head1 DESCRIPTION
405
406 This class provides a C<config> attribute which is populated by executing
407 one or more B<ConfigReader> packages.
408
409 The default ConfigReader used is L<Dancer2::ConfigReader::Config::Any>.
410
411 Also provides a C<setting()> method which is supposed to be used by externals to
412 read/write config entries.
413
414 If more than one config reader is used, their configurations are merged
415 in left-to-write order where the previous config items get overwritten by subsequent ones.
416
417 For example, assuming we are using 3 config readers,
418 if the first config reader returns
419
420 item1: content1
421 item2: content2
422 item3:
423 subitem1: subcontent1
424 subitem2: subcontent2
425 subitem3:
426 subsubitem1:
427 subsubcontent1
428 item4:
429 subitem1: subcontent1
430 subitem2: subcontent2
431
432 and the second returns
433
434 item2: content9
435 item3:
436 subitem2: subcontent8
437 subitem3:
438 subsubitem1:
439 subsubcontent7
440 subitem4:
441 subsubitem5: subsubcontent5
442 item4: content4
443
444 then the final config is
445
446 item1: content1
447 item2: content9
448 item3:
449 subitem1: subcontent1
450 subitem2: subcontent8
451 subitem3:
452 subsubitem1:
453 subsubcontent7
454 subitem4:
455 subsubitem5: subsubcontent5
456 item4: content4
457
458 The default B<ConfigReader> is C<Dancer2::ConfigReader::Config::Any>.
459
460 =head2 Configuring the ConfigReaders via DANCER_CONFIG_READERS
461
462 You can control which B<ConfigReader>
463 class or classes to use to create the config
464 via the C<DANCER_CONFIG_READERS> environment.
465
466 DANCER_CONFIG_READERS='Dancer2::ConfigReader::Config::Any,Dancer2::ConfigReader::CustomConfig'
467
468 If you want several, separate them with a comma (",").
469
470 =head2 Bootstrapping the ConfigReaders via C<additional_config_readers>
471
472 If the key C<additional_config_readers> is found in one in one or more of the configurations provided by the ConfigReaders, it'll be
473 instantiated and added to the list of configurations to merge. This way you can, for example, create a basic F<config.yml> that is
474
475 additional_config_readers:
476 - Dancer2::ConfigReader::SQLite:
477 path: /path/to/sqlite.db
478 table: config
479
480 The default ConfigReader L<Dancer2::ConfigReader::Config::Any> will pick that file and proceed to instantiate C<Dancer2::ConfigReader::SQLite>
481 with the provided parameters.
482
483 C<additional_config_readers> can take one or a list of reader configurations, which can be either the name of the ConfigReader's class, or the
484 key/value pair of the class name and its constructor's arguments.
485
486 =head2 Creating your own custom B<ConfigReader> classes.
487
488 Here's an example extending class C<Dancer2::ConfigReader::Config::Any>.
489
490 package Dancer2::ConfigReader::FileExtended;
491 use Moo;
492 extends 'Dancer2::ConfigReader::Config::Any';
493 has name => (
494 is => 'ro',
495 default => sub {'FileExtended'},
496 );
497 around read_config => sub {
498 my ($orig, $self) = @_;
499 my $config = $orig->($self, @_);
500 $config->{'dummy'}->{'item'} = 123;
501 return $config;
502 };
503
504 Another (more complex) example is in class C<Dancer2::ConfigReader::Config::Any>.
505
506 =head1 ATTRIBUTES
507
508 =head2 location
509
510 Absolute path to the directory where the server started.
511
512 =head2 config_location
513
514 Gets the location from the configuration. Same as C<< $object->location >>.
515
516 =head2 environments_location
517
518 Gets the directory where the environment files are stored.
519
520 =head2 config
521
522 Returns the whole configuration.
523 This must not be used directly.
524 Instead, use this via C<Dancer2::Core::Role::HasConfig> role
525 which manages configuration after it is created.
526
527 =head2 environment
528
529 Returns the name of the environment.
530
531 =head1 AUTHOR
532
533 Dancer Core Developers
534
535 =head1 COPYRIGHT AND LICENSE
536
537 This software is copyright (c) 2026 by Alexis Sukrieh.
538
539 This is free software; you can redistribute it and/or modify it under
540 the same terms as the Perl 5 programming language system itself.
541
542 =cut