TOML configuration loading
- Comparing
- v1 to v2
- Current
- Read the document
Abstract
Configuration is I will read configuration from TOML files: a main file, drop-in in overrides applied in order, ,
and one file for each enabled
enabled module, merged into a single tree with single
configuration tree with
environment variables variables interpolated. A registry hydrates registry will
hydrate configuration objects
objects from that tree in two seals, ,
core configuration configuration first so that the module system can read which modules are are
enabled,
, then each module's configuration, and produces will produce the immutable configuration configuration
catalogue.
Motivation
The panel's configuration is written in TOML files that sysadmins edit, per
as
ADR-0010 decides. The configuration component holds holds
configuration objects in
objects in a catalogue, per as
RFC-0002 describes, but has no way to read them from files.
Modules Modules provide configuration of their own. To register it, the module system needs to know know
which modules are
are enabled, and which modules are enabled is itself configuration, so it has to be readable before any any
module registers
registers anything.
Proposal
ConceptsWhere configuration is read from
| Term | Meaning |
|---|---|
| Main configuration file | config.toml, the base of the configuration. |
| Drop-in | A TOML file in config.d, applied over the main configuration file. |
| Module configuration file | A TOML file in modules-enabled, holding one module's configuration. Its presence enables the module. |
| Module identifier | A module's name, taken from its module configuration file's name without the .toml extension. |
| Configuration tree | The array produced by reading and merging every file. |
| Section | The part of the configuration tree a configuration object is hydrated from. |
| Core configuration | Configuration hydrated before the module system runs, because the module system needs it. |
| Module configuration | Configuration a module registers, hydrated once every module has registered. |
Components
| Component | Responsibility |
|---|---|
ConfigPaths |
Value object holding the paths the loader reads from. |
TomlLoader |
Reads, merges and interpolates the TOML files into a configuration tree. |
ConfigRegistry |
Mutable, and exists only during bootstrap. Hydrates configuration objects from the tree in two seals, and produces the ConfigCatalogue. |
CoreConfig |
Maps top-level keys of the tree to core configuration classes. |
ModulesEnabled |
Core configuration object holding the enabled module identifiers. |
ConfigObject |
Contract every configuration object implements, hydrated through fromArray(). |
Paths
The loader reads from three locations:
Configuration will be read from three places: the main configuration file, config.toml, which is the base of the
configuration; the drop-in directory, config.d/, whose files are applied over it; and the
module configuration directory, modules-enabled/, which holds one file for each enabled
module. A module's file being present is what enables it.
config.toml
config.d/
10-database.toml
20-secrets.toml
modules-enabled/
admin.toml
billing.toml
ConfigPaths holds will hold the absolute path of each: the main configuration file , as configFile, the drop-in directory as
configDir, and the module configuration directory as modulesEnabledDir. Bootstrap constructs it, will
construct it from the
the environment, command-line flags or compiled defaults. The , and the configuration component never works will never
work out paths a path itself.
Modules that are installed but not enabled are will be a concern of the command line that enables and disables them. Only
modules-enabled/ matters will matter to loading.
LoadingBuilding the tree
TomlLoader::load(ConfigPaths $paths): array builds the will read every file and return the
configuration tree tree, an array holding all of them. It will work in these stepsthis order:
- The main configuration file is parsed. If it cannot be read or parsed, loading throws.
- The drop-
insins are parsed in order of filename, and each is merged over the tree in turn.AA missing drop-inin directory is treated as empty. - The
modulemodule configuration files are parsed in order of filename, and each is placed inthethe tree undermodules,, keyed by its module identifier, which is the file's name without the.tomlextension. A missing module configuration directory is treated as empty. - The module identifiers, in the same order, are placed in the tree under
__enabled_modules. - Environment
variablesvariables are interpolated throughout the tree,modulemodule configuration included.
Only files with the .toml extension are will be read. The loader knows will know nothing of of
configuration objectsobjects: it translates
translates files into an array, and nothing more.
[
// keys from config.toml, with config.d/*.toml merged over them
'modules' => ['admin' => [/* admin.toml */], 'billing' => [/* billing.toml */]],
'__enabled_modules' => ['admin', 'billing'],
]
modules and __enabled_modules are will be reserved for the loader. The main configuration file or a drop-in declaring
that
declares either at its top level throwswill throw, naming the file that declared it.
A module identifier cannot contain a dot, because dots separate the parts of a a
section's path. A , so a module configuration
configuration file whose name contains a dot throwswill throw.
Merging
A drop-in is in will be merged over the tree by these rules, applied from the top level down. A key that only the tree has
is kept, and a key that only the drop-in has is added. Where both have a key:
A key only in the tree is kept, and a key only in the drop-in is added. Where both have a key andIf either value is not an array, the drop-in's value replaces the tree's.WhereIf bothvaluesare arrays and either is a non-empty list, the drop-in's value replaces the tree's. Lists,, includingarraysarrays of tables, are never merged.- Otherwise both
valuesare tables, and they are merged by these same rules.
An empty array counts as a table, so an . An empty drop-in file therefore changes nothing, and an empty array replaces a list but
list
but leaves a table as it was.
# config.toml
[database]
primary = "main"
hosts = ["a", "b"]
[database.connections.main]
host = "localhost"
port = 3306
# config.d/10-database.toml
[database]
hosts = ["c"]
[database.connections.main]
port = 3307
After merging, database.primary is main, database.hosts is ["c"], and the main connection has the host
localhost and the port 3307.
InterpolationEnvironment variables in configuration
A string in the tree may contain any number of references to to
environment variablesvariables, each replaced by the variable's
s value read from as Env, per reads it,
following ADR-0006. A reference takes one of two
forms:
| Reference | Replaced with |
|---|---|
${NAME} |
The variable's value. If the variable is not set, or is null, loading throws. |
${NAME:-default} |
The variable's value, or the default when the variable is not set or is null. |
title = "${APP_NAME}"
dsn = "${DB_HOST}:${DB_PORT}"
[database]
password = "${DB_PASSWORD}"
region = "${REGION:-eu-west}"
tags = ["${TAG_ONE}", "literal"]
A variable variable's name is made of uppercase letters, digits and underscores, and does not start with a digit. A reference
using any other name, such as ${name}, is will be left as it was written. Only strings are will be interpolated, including strings
including
strings inside lists, and the result is will always be a string. Numbers; numbers, booleans and other values are will be left as they they
are. A variable that is not set and has no default will throw, naming the variable and the path to the value, such as
database.password or database.tags[0].
A variable that is not set and has no default throwsInterpolation keeps secrets, naming the variable and the path to such as database passwords, out of configuration files, which are plain text. Because it
happens while the valuetree is loaded, such as
database.passwordEnvor database.tags[0]must be initialised before the loader runs.
Interpolation keeps secrets, such as database passwords, out of configuration files, which are plain text. Because
it happens while the tree is loaded, Env must be initialised before the loader runs.
Configuration objects
ConfigObject requires A configuration object will validate what it is given, as it is hydrated. Its typed readonly properties will enforce the
shape and types of its values by construction. Assertions in its constructor will enforce ranges, formats and the
relationships between values, so that an object created any other way, such as through a factory, fromArraymake(array $data): staticwhich creates the configuration object from its section of
is
validated the treesame way. It replaces the __set_statefromArray()of RFC-0002will assert only that the keys it needs exist and have the right shape. A failed
assertion throws.
A configuration object validates what it is given, and validation happens as it is hydrated. Its typed readonly
properties enforce the shape and types of its values by construction. Assertions in its constructor enforce ranges,
formats and the relationships between values, so an object created any other way, such as through a make()
factory, is validated the same way. fromArray() asserts only that the keys it needs exist and have the right
shape. A failed assertion throws.
Validating as configuration is hydrated
ConfigObject will require fromArray(array $data): static, which creates a
configuration object from its section of the tree. It
will replace the __set_state() of RFC-0002.
final readonly class MailConfig implements ConfigObject
{
public static function fromArray(array $data): static
{
Assert::keyExists($data, 'host', 'Host is not defined.');
Assert::keyExists($data, 'port', 'Port is not defined.');
return new self($data['host'], $data['port']);
}
private function __construct(
public string $host,
public int $port,
) {
Assert::stringNotEmpty($host, 'Host is not defined.');
Assert::range($port, 1, 65535, 'Port is out of range.');
}
}
RegistryHydrating in two seals
ConfigRegistry is will be the configuration registry, the mutable half of the configuration configuration
component, sealed into the immutable ConfigCatalogue,
per , following
ADR-0003. It is will be constructed with the
configuration tree tree and the core mapping, will exist only during bootstrap, and is will
be discarded once it has been sealed.
$tree = new TomlLoader()->load($paths);
$registry = new ConfigRegistry($tree, CoreConfig::MAPPING);
$registry->sealCore();
$enabled = $registry->for(ModulesEnabled::class);
// Each enabled module registers its configuration.
$registry->register('admin', 'main', AdminConfig::class);
$catalogue = $registry->seal();
| Method | Effect |
|---|---|
sealCore(): void |
Hydrates every core configuration object. |
for(string $class): ConfigObject |
Returns a hydrated core configuration object by its class. |
register(string $module, string $name, string $class): void |
Registers a module's configuration class under the module and a name, to be hydrated by seal(). |
seal(): ConfigCatalogue |
Hydrates every registered module configuration object, and returns the catalogue holding them and the core configuration. |
The registry passes will pass through three phases, and each method can only will be called callable only in some of them:
Hydration will happen in a fixed sequence. First, sealCore() hydrates every
core configuration object. The module system then reads
which modules are enabled, through for(string $class): ConfigObject, which returns a hydrated core configuration
object by its class. Each enabled module then registers its configuration classes, through
register(string $module, string $name, string $class), under its identifier and a name. Last,
seal(): ConfigCatalogue hydrates every registered module configuration object and returns the
catalogue holding them alongside the core configuration.
| Phase | Entered by | Permits |
|---|---|---|
| Open | Construction | sealCore() |
| Core sealed | sealCore() |
for(), register() and seal() |
| Sealed | seal() |
Nothing. The catalogue is used instead. |
A method called in a phase that does not permit it throws will throw ConfigLifecycleException.
Core configuration
Core configuration configuration is what must be hydrated and available before the module the
module system runs. CoreConfig::MAPPING maps
will map a top-level key of the tree to the class class
hydrated from it:
public const array MAPPING = [
'__enabled_modules' => ModulesEnabled::class,
];
sealCore() hydrates will hydrate each class from its key. A missing key hydrates will hydrate the class from an empty array, and a key holding
key
holding anything other than an array throwswill throw. In the catalogue, core configuration is will
be placed under the module engine, named
named by its key.
ModulesEnabled holds will hold the enabled module identifiers identifiers as a list of strings, and and
nothing else. Its
, and its has(string $module): bool returns will say whether a module is enabled. It is will be the only core core
configuration.
The module system reads will read ModulesEnabled through for(), between the two seals. It does will not scan the filesystem, filesystem or
repeat the logic that decides which modules are enabled: the configuration component is will be the single source of which
of
which modules are enabled.
Module configuration
A module registers module will register each of its configuration classes under its its
module identifier identifier and a name. seal() hydrates the
will hydrate the class from from
modules.{module}.{name} in the tree, which is the table {name} in the module's configuration file.
# modules-enabled/admin.toml
[main]
value = "${ADMIN_VALUE}"
$registry->register('admin', 'main', AdminConfig::class);
A missing table hydrates will hydrate the class from an empty array, and anything other than an array on that path throws. The
will throw.
The module name engine is will be reserved for core configuration, and registering registering
under it throwswill throw. So does will registering with a
a module identifier or a name that contains a dot.
In the catalogue, each module configuration object is will be placed under its module and name, ,
so both
both $catalogue->get('admin', 'main') and $catalogue->for(AdminConfig::class) return it.
Hydration errors
Any failure while a configuration object object is hydrated is will be wrapped in in
InvalidConfigException, naming the file, section
section and key it the problem came from, so that that
sysadmins can find the problem it without guessing:
Invalid config in modules-enabled/admin.toml at [main.value]: Value is not defined.
Database configuration
DatabaseConfig and ConnectionConfig, from RFC-0003, are will be hydrated through
fromArray(), with their validation in their constructors.
primary = "main"
persistent = false
[connections.main]
host = "127.0.0.1"
port = 3306
database = "panel"
username = "panel"
password = "${DB_PASSWORD}"
[connections.local]
socket = "/var/run/mysqld/mysqld.sock"
database = "panel"
username = "panel"
password = ""
DatabaseConfig key |
Rule |
|---|---|
primary |
Required, and not empty. A |
connections |
Required. A table of connections, keyed by name, with at least one. Each is a non-empty table hydrated into a ConnectionConfig, and a failure names the connection. |
persistent |
Optional, and a boolean. Defaults to false. |
ConnectionConfig key |
Rule |
|---|---|
database, username |
Required, and not empty. |
password |
Required, and may be empty. |
socket |
Optional. When given, it must not be empty, and the connection is made through it. |
host |
Required when no socket is given, and not empty. |
port |
Required when no socket is given, and an integer. |
options |
Optional, and a table. |
A connection through a host must will have to configure its port, which will no longer defaults default to 3306.
Errors
Every exception implements will implement ConfigException, per from RFC-0002.
| Exception | Extends | Thrown when |
|---|---|---|
InvalidConfigException |
RuntimeException |
A file cannot be read or parsed, a reserved key is declared, a module configuration file's name contains a dot, an environment variable is not set and has no default, a section is not an array, or a configuration object fails to hydrate. |
ConfigLifecycleException |
LogicException |
A registry method is called in a phase that does not permit it, a module registers as engine, or a module identifier or configuration name contains a dot. |
ConfigNotRegisteredException |
RuntimeException |
for() is asked for a class that is not core configuration. |
InvalidConfigException, a RuntimeException, will be thrown for anything wrong with the configuration itself: a file
that cannot be read or parsed, a reserved key declared, a module configuration file whose name
contains a dot, an environment variable that is not set and has no default, a
section that is not an array, or a configuration object
that fails to hydrate.
ConfigLifecycleException, a LogicException, will be thrown for misuse of the registry: a
method called in a phase that does not permit it, a module registering as engine, or a module identifier or
configuration name that contains a dot.
ConfigNotRegisteredException, a RuntimeException, will be thrown when for() is asked for a class that is not
core configuration.
Out of scope
- Where the files live, and constructing
ConfigPaths. Both belong to bootstrap. - Enabling and disabling modules. Both belong to the command line.
Alternatives considered
The decisions this This design rests on are recorded separatelyADR-0010, with the alternatives each one rejected:which writes configuration in TOML rather
than PHP, JSON or YAML; ADR-0003, which seals
a mutable registry into an immutable catalogue in phases; and
ADR-0006, which reads
environment variables only during bootstrap.
No other alternatives were weighed.
Backwards compatibility
ConfigObjectrequiresfromArray()in place of__set_state(), so configuration objects are no longer restored fromvar_export()output. Every configuration object implementsfromArray().BaseConfigObject, which restored a configuration object by passing an exported array to its constructor as named arguments, is removed.DatabaseConfigandConnectionConfigare hydrated throughfromArray(), and a connection through a host must configure its port.
Open questions
Changelog
Sources
- Issue #31, Engine - Config - TOML, original text of in its edit history: that configuration need not
be PHP files for a panel distributed as a binary, the TOML parser, and modules needing a way to define how their
configuration is loaded. This is
created. - Issue #31, rewritten on and revised on , in its edit history:
ConfigPaths, the loader and its order, module configuration namespaced by filename, the enabled module identifiers taken from filenames,ModulesEnabledas core configuration and the single source of which modules are enabled,${VAR}interpolation againstEnvkeeping secrets out of plain-text files, the two seals withfor()readable between them, validation on hydration with the file, section and key named, and the exceptions. The design follows the revision of . - Planning session, , not publicly available and first written down on : interpolation against the environment, and validation as configuration is loaded.
- PR #33, refactor(engine:config): Switch to TOML loader and two-phase registry, merged and squashed as
44b0aaa: the implementation, whose merge is
decided.ConfigRegistry,ConfigLifecycleException,CoreConfig,${VAR:-default}, the reserved keys, the merge rules, missing directories, variable names, the registry's phases, theenginemodule and the database configuration keys are described fromsrc/Configat 44b0aaa,src/Database/Configat 44b0aaa andtests/Unit/Configat 44b0aaa. - Automated review of PR #33, : checking reserved keys in each file so that the error names the file
that declared one, rejecting dots in module identifiers and names, and refusing
seal()beforesealCore(). - Commit 914a46c, "Add TOML parser and assertion helper", , on the branch of PR #33:
internal/tomlandwebmozart/assertadded. No reason is given for choosing either. - Commit bb4f014, "Move config validation into constructors", , on the branch of PR #33: validation in
constructors so that
make()cannot bypass it, and the port required for a connection through a host. - A password being allowed to be empty, and a hydration error naming the key and the file that set the value: first
written down on . The code at 44b0aaa differs: a password must not be empty, a hydration error never
names the key, and a core section's error always names
config.toml. - Issue #48, Engine - Database - Connection configuration fixes, : that forbidding an empty password rules out socket peer authentication, taken from what followed rather than anticipated.
Source rfc/0004-toml-configuration-loading.md · commit 9444a99 · published