## Name

Object::Configure - Runtime Configuration for an Object

## Version

0.27

## Description

`Object::Configure` lets the users of your Perl classes change how an object
behaves by editing a settings file or setting an environment variable,
without changing any code.  It also gives every object a logger.

It is a thin layer on top of two other modules: [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction), which
reads settings files and environment variables, and [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction),
which writes log messages.

You call `configure($class, \%params)` at the start of your class's `new()`
method.  It:

- 1. Finds the settings file for your class, and for every class your
class inherits from (its parent classes, through `@ISA`).
- 2. Merges those files, then applies any environment variables named
`ClassName__key`.
- 3. Creates a [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction) logger and puts it in the `logger` key.
- 4. Returns a hash reference.  You pass it to `bless` to make your object.

The module can also do _hot reload_: a background process watches the
settings files, and when one changes, every registered object is updated
while the program keeps running.

**Hot reload is not supported on Windows** (Windows has no `SIGUSR1` signal).

### Words Used in This Document

- **class** -- a Perl package that makes objects, such as `My::Module`.
- **config file** (configuration file, settings file) -- a text file,
usually YAML, that holds settings.  For example `timeout: 30`.
- **section** -- the part of a config file that belongs to one class.
Its name is the class name with `::` replaced by `__`
(`My::Module` becomes `My__Module`).
- **merge** -- combine two sets of settings into one.  When both have
the same key, the one with higher priority wins.  See
["Configuration resolution order"](#configuration-resolution-order).
- **ancestor** -- a parent class, or a parent of a parent, and so on.
`UNIVERSAL` is the ancestor of every Perl class.
- **environment variable** -- a named value set outside the program,
for example with `export NAME=value` in a Unix shell.
- **logger** -- an object with methods such as `info()`, `warn()` and
`error()` that records messages.
- **signal** -- a short message the operating system delivers to a
running program.  `SIGUSR1` is a signal with no fixed meaning; programs may
use it for anything.  This module uses it to mean "reload your settings".
- **signal handler** -- the code Perl runs when a signal arrives.  It is
stored in `$SIG{USR1}`.
- **watcher** -- a small background process, started by
`enable_hot_reload()`, that checks the config files and sends `SIGUSR1`
when one changes.
- **registry** -- the list of objects that hot reload updates.  An
object is added with `register_object()`.
- **weak reference** -- a reference that does not keep an object
alive.  The registry uses them, so registering an object never stops it
from being freed.
- **cache** -- an object that remembers results so that they do not
have to be worked out again.  See ["Caching parsed config files"](#caching-parsed-config-files).

### Before You Start

- Perl 5.26 or later.
- A parser for each config file format you use.  For YAML (`.yml`,
`.yaml`) install [YAML::XS](https://metacpan.org/pod/YAML%3A%3AXS).  Without the right parser, a file is skipped
with a warning.
- For hot reload: a Unix-like system (Linux, macOS, the BSDs).
- For the optional cache: a cache module such as [CHI](https://metacpan.org/pod/CHI).

All functions are called with their full name, for example
`Object::Configure::configure(...)`.  The module exports nothing.

## Synopsis

### Example 1: Add Configurable Logging to Your Own Class

```perl
package My::Module;
use Object::Configure;

sub new {
    my ($class, %args) = @_;

    # configure() reads config files + env vars, sets up a logger,
    # and returns a hashref ready to bless.
    my $params = Object::Configure::configure($class, \%args);

    return bless $params, $class;
}

sub do_work {
    my $self = shift;
    $self->{logger}->info('Starting do_work');
    # ...
}

# Usage -- reads /etc/myapp/my-module.yml (and any ancestor files beside it):
my $obj = My::Module->new(config_file => '/etc/myapp/my-module.yml');
$obj->do_work;
```

### Example 2: Configure a Third-Party Class You Cannot Modify

```perl
use Object::Configure;

# Wrap LWP::UserAgent so it reads its settings from a YAML file.
my $ua = Object::Configure::instantiate(
    class       => 'LWP::UserAgent',
    config_file => '/etc/myapp/lwp.yml',
    timeout     => 30,      # fallback if the file has no timeout key
);

$ua->get('https://example.com');
```

### Example 3: Multi-Level Inheritance -- Config Files Merge Automatically

```perl
# ~/.conf/my-base-class.yml
# My__Base__Class:
#   timeout: 30
#   retries: 3

# ~/.conf/my-child-class.yml
# My__Child__Class:
#   timeout: 60   # overrides base; retries:3 is inherited

package My::Child::Class;
our @ISA = ('My::Base::Class');
use Object::Configure;

sub new {
    my ($class, %args) = @_;
    # Walks @ISA, merges base config then child config.
    # Result: timeout=60, retries=3
    my $params = Object::Configure::configure($class, \%args);
    return bless $params, $class;
}
```

### Example 4: Hot Reload -- Objects Update When the Config File Changes

```perl
package My::Service;
use Object::Configure;

sub new {
    my ($class, %args) = @_;
    my $params = Object::Configure::configure($class, \%args);
    my $self   = bless $params, $class;

    # Register so reload_config() updates $self in-place on file change.
    Object::Configure::register_object($class, $self)
        if $params->{_config_file};

    return $self;
}

package main;

my $svc = My::Service->new(config_file => '/etc/myapp/service.yml');

# Fork a background watcher; it sends SIGUSR1 when the file changes.
Object::Configure::enable_hot_reload(
    interval => 5,
    callback => sub { print "Config reloaded at ", scalar localtime, "\n" },
);

while (1) { sleep 1 }          # event loop

Object::Configure::disable_hot_reload();    # clean shutdown
```

### Example 5: Override Settings With Environment Variables (No File Needed)

```perl
# Shell:
#   export My__Worker__log_level=debug
#   export My__Worker__timeout=120

package My::Worker;
use Object::Configure;

sub new {
    my ($class, %args) = @_;
    # configure() picks up My__Worker__* env vars automatically.
    my $params = Object::Configure::configure($class, \%args);
    return bless $params, $class;
}

my $obj = My::Worker->new;
# $obj->{log_level} eq 'debug'   $obj->{timeout} == 120
```

### Example 6: Make Constructors Faster With a Cache

```perl
use CHI;
use Object::Configure;

# One cache for the whole program.  Each config file is then parsed
# once, not once per object, until it (or the environment) changes.
our $cache = CHI->new(driver => 'Memory', global => 1);

package My::Request;

sub new {
    my ($class, %args) = @_;
    my $params = Object::Configure::configure($class, {
        %args,
        config_file => '/etc/myapp/my-request.yml',
        cache       => $cache,
    });
    return bless $params, $class;
}
```

### Example 7: Capture Log Messages in a Test

```perl
use Test::More;

my @log;
my $obj = My::Module->new(logger => \@log);    # messages go into @log

$obj->do_work;
ok(scalar(@log), 'do_work logged something');

# Or turn logging off completely:
my $quiet = My::Module->new(logger => 'NULL');
```

### Example 8: Keep Your Own SIGUSR1 Handler Working

```perl
# Install your handler first ...
$SIG{USR1} = sub { print "USR1 received\n" };

# ... then register objects (My::Service from Example 4 calls
# register_object()).  Object::Configure installs its own handler,
# which reloads the objects and then calls yours.
my $svc = My::Service->new(config_file => '/etc/myapp/service.yml');

# When the program ends, your handler is put back in $SIG{USR1}.
```

## Configuration

### Config File Naming

The config file name is derived from the class name by lowercasing it and replacing
`::` with hyphens (`-`):

```perl
My::Parent::Class  =>  my-parent-class.yml
```

The file is searched for in the directory of the `config_file` argument, then in
any directories listed in `config_dirs`.

### Config File Size Limit

Config files must be small.  Any config file larger than 16K (16384 bytes)
is refused before it is parsed: `configure()` croaks, and a hot reload
warns and keeps the object's current settings.  This applies to every file
that would be read, including ancestor class files and `universal.yml`.

### Caching Parsed Config Files

Every `configure()` call normally parses every config file again: with a
two-level hierarchy that is most of the time a constructor takes.  Pass a
cache object to skip the parse when nothing has changed:

```perl
use CHI;
my $cache = CHI->new(driver => 'Memory', global => 1);

my $params = Object::Configure::configure($class, {
    config_file => 'my-app.yml',
    cache       => $cache,
});
```

Any object with `get($key)` and `set($key, $value)` will do ([CHI](https://metacpan.org/pod/CHI),
[Cache::Cache](https://metacpan.org/pod/Cache%3A%3ACache), [Cache::Memcached](https://metacpan.org/pod/Cache%3A%3AMemcached), or your own).  What is cached is the
settings read from each file for each class, as plain data; the key covers
everything that can change them:

- the file itself (device, inode, size and modification time, to
sub-second precision where the filesystem keeps it);
- every other file Config::Abstraction read for it (`base.*`,
`local.*` and the like), which is checked again on every hit
(Config::Abstraction 0.44 or later; with an older one only the file itself);
- the class's `CLASS__*` environment variables (matched in any case,
as Config::Abstraction reads them), the environment name
(`CLASS__ENV`, `PLACK_ENV`, `NODE_ENV`), the encryption key settings,
`HOME`, `DOCUMENT_ROOT`, `CONFIG_DIR` and `SCRIPT_NAME`;
- `--CLASS__key=value` arguments in `@ARGV`, the current directory,
`$0`, and the versions of Object::Configure and Config::Abstraction.

So an edited file, or a changed environment variable, is simply a cache miss.
Each entry is used through a private copy, so caches that return references
(such as CHI's `RawMemory` driver) cannot be corrupted through an object.
The cache is only consulted for config files: the environment-only path, and
hot reload (which must re-read), do not use it.  If the cache dies, a warning
is given and the file is parsed normally.

Things the key cannot see, and which therefore need the cache's own expiry
(for example `CHI->new(..., expires_in => '10 min')`) if they matter
to you:

- a config file that did not exist when the entry was cached and has
appeared since (such as a new `local.yaml`);
- a new encryption key given in the same key file with the same size
and timestamp.

**Security:** the cached settings are the decrypted values.  If your config
files hold encrypted secrets, use a cache only your program can read (an
in-memory one), not a shared or file-based one.

### Section Key Naming Inside the Config File

Inside the YAML (or JSON or conf) file, the section key uses double underscores in
place of `::`:

```perl
# my-parent-class.yml
---
My__Parent__Class:
  timeout: 30
  retries: 3
```

### Configuration Resolution Order

The following sources are merged from _lowest_ to _highest_ priority.  A value
from a higher-priority source always wins over a lower-priority one.

- 1. **Caller-supplied params** -- the hashref you pass to `configure()`.  Despite
the name "defaults", these are the _lowest_ priority and are overridden by everything
else.
- 2. **UNIVERSAL section** -- the `UNIVERSAL:` block in `universal.yml` (or
`universal.conf`, `universal.json`) in your config directories, if the file exists.
- 3. **Ancestor class config files** -- walked base-first through `@ISA` using
the class's Method Resolution Order (MRO).
- 4. **Primary config file** -- the file named by the `config_file` argument.
- 5. **Environment variables** -- named `ClassName__key=value`, where `::` in
the class name is replaced by `__`.  These are the _highest_ priority.

### UNIVERSAL Configuration

If you create `universal.yml` in your config directory with a `UNIVERSAL:` section,
those settings apply to every class that uses `Object::Configure` unless a
more-specific source overrides them:

```
# ~/.conf/universal.yml
---
UNIVERSAL:
  timeout: 30
  logger:
    level: warning
```

### Logging

`configure()` always sets `$params->{logger}` to a [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction)
instance.  You can control it by passing a `logger` key:

```perl
# Arrayref: messages are captured into @log (protected from merge override)
configure($class, { logger => \@log });

# Hashref: options forwarded to Log::Abstraction::new()
configure($class, { logger => { level => 'debug', file => '/var/log/app.log' } });

# String 'NULL': disables all logging
configure($class, { logger => 'NULL' });

# Existing Log::Abstraction object: used as-is
configure($class, { logger => $my_logger });
```

**Note:** a concrete logger -- `'NULL'`, an arrayref, a logger object or a
coderef -- is set aside before the config merge and always wins.  A hashref is
treated as options and merges like any other config, so a `logger:` section
in a config file overrides individual keys.  See ["COMMON PITFALLS"](#common-pitfalls).

### Environment Variable Format

Environment variable names are constructed as:

```
ClassName__key
```

where `::` in the class name is replaced by two underscores.

```
export My__Module__timeout=60
export My__Module__logger__level=debug
```

## Hot Reload

Hot reload lets you edit a config file and have all live objects update themselves
without restarting the program.

### How It Works

- 1. Your constructor calls `register_object($class, $self)` to opt in.
- 2. Your main program calls `enable_hot_reload()` to fork a background watcher.
- 3. The watcher polls config files every `interval` seconds and sends
`SIGUSR1` to the parent when it detects a change.
- 4. The `SIGUSR1` handler calls `reload_config()`, which re-reads files and
updates every registered object in-place.
- 5. Your main program calls `disable_hot_reload()` on shutdown.

Steps 1 and 2 may happen in either order: `enable_hot_reload()` installs
the `SIGUSR1` handler itself if no object has been registered yet.  (Before
version 0.27, starting the watcher first meant the first config edit ended
the program, because nothing handled the signal.)

### Sharing SIGUSR1 With Other Code (Daisy Chaining)

Object::Configure does not take `SIGUSR1` away from code that already uses it.
When the first object is registered, whatever `$SIG{USR1}` holds is saved and
Object::Configure's handler is installed in its place.  On every signal, that
handler:

- 1. reloads the registered objects, then runs the `enable_hot_reload()`
callback, if any (a failure in either is reported with `carp`, never thrown);
- 2. calls the saved handler with the same arguments Perl passed (the
signal name), before returning.

The saved handler may be a coderef or a sub _name_, as `%SIG` allows
(`'My::Pkg::on_usr1'`, or `'on_usr1'`, which means `main::on_usr1`).
`DEFAULT` and `IGNORE` need no call.  Anything the saved handler throws
propagates as it would have without Object::Configure.

When the program ends, the previous handler is put back (in the `DESTROY`
of a small guard object that lives exactly as long as the installation).
This is only done if Object::Configure's handler is still the one in
`$SIG{USR1}`: if other code installed its own handler afterwards, that one
is left in place, and if it chains to ours the signal still reaches the
original handler.  Call `restore_signal_handlers()` to put the saved handler
back immediately and unconditionally.

Private keys (those whose names start with `_`) are never overwritten during
reload, so internal bookkeeping is safe.

**Hot reload is not supported on Windows.**

## Common Pitfalls

### Nested Settings Are Merged; Lists Are Replaced

When two sources set the same key, what happens depends on the value:

- **Two hashes** (nested settings) are merged key by key, at every level.
- **Anything else** -- a string, a number, a list (array) or `undef` --
replaces the lower-priority value completely.  Lists are never joined.

```perl
# Passed by the caller:        # In the config file:
#   nested => { b => 2 }       #   nested:
#   list   => [9, 9, 9]        #     a: 1
#                              #   list: [1, 2]
#
# Result:
#   nested => { a => 1, b => 2 }    (merged)
#   list   => [1, 2]                (replaced, not [9, 9, 9, 1, 2])
```

### Undef Is a Value, Not "No Value"

An empty value in a config file (`key: ~` or `key:` in YAML, `null` in
JSON) sets the key to `undef`, and `undef` replaces whatever a
lower-priority source gave, including the caller's value.  To keep the
lower-priority value, leave the key out of the file completely.

Passing `undef` as the whole second argument is fine: it is treated like
`{}`.

### The Section Name Must Match the Class Exactly

Inside a config file, settings must be under a section named after the
class, with `__` in place of `::` (`My__Module:`, not `My::Module:`).
With any other name there is **no warning**: the class's settings are simply
not applied, and the whole section may appear on the object as a single
key with the section's name.

### Do Not Set $SIG{USR1} to 'DEFAULT' While Hot Reload Is Running

While the watcher runs, it sends `SIGUSR1` whenever a config file changes.
Object::Configure's handler deals with it, but if other code later sets
`$SIG{USR1} = 'DEFAULT'`, the next signal **ends the program**, because that
is Perl's default action for `SIGUSR1`.  To turn hot reload off, call
`restore_signal_handlers()` or `disable_hot_reload()` instead: they stop
the watcher.

### A Hashref Logger Is Merged; Any Other Logger Always Wins

A concrete logger choice cannot be merged with config, so it is kept exactly as
given, whatever `universal.yml` or a site-local file (such as
`~/.conf/local.yaml`) says:

```perl
# Kept as given -- never overridden by config files
configure($class, { logger => 'NULL' });
configure($class, { logger => \@captured });
configure($class, { logger => $existing_obj });
```

A hashref is options for [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction) and follows the normal precedence
rules: a `logger:` section in a config file overrides the keys you pass.

```perl
# level may be replaced by a logger: section in a config file
configure($class, { logger => { level => 'debug' } });
```

Before 0.27 only arrayrefs were protected, so a site file could silently replace
an explicit `'NULL'`.

### Caller-Supplied Keys Are the LOWEST Priority

Despite being called "defaults", keys you pass directly to `configure()` are
overridden by config files and environment variables:

```perl
# My__Module__timeout=60 is set in the shell.
# $params->{timeout} will be 60, not 30.
configure('My::Module', { timeout => 30 });
```

Use caller-supplied keys only as a last-resort fallback.

### Register\_Object() Pushes; It Does Not Replace

Calling `register_object()` twice for the same class registers **two** entries.
Both objects receive updates on every reload.  The second call does not remove the
first.

```
Object::Configure::register_object('My::Class', $obj_a);
Object::Configure::register_object('My::Class', $obj_b);
# reload_config() now updates BOTH $obj_a and $obj_b
```

### Private Keys Are Never Updated on Hot Reload

Any key whose name begins with `_` is skipped during `reload_config()`.
A config key named `_my_setting` in your YAML file will be ignored at reload time.

### The 'Class' Key Appears on Objects Created by Instantiate()

`instantiate()` intentionally leaves the `class` key in the hashref passed to
`$class->new()` as a debugging aid.  Your object will have a `class`
attribute set to the class name:

```perl
my $obj = Object::Configure::instantiate(class => 'My::Thing', ...);
print $obj->{class};    # prints 'My::Thing'
```

### Memoization Caches Are Not Invalidated During a Run

`_get_inheritance_chain()` and `_find_class_config_file()` cache their results
for the lifetime of the process.  If you alter `@ISA` or add config files after
the first `configure()` call for a given class, the cache returns stale results.

### Disable\_Hot\_Reload() Blocks for Up to Five Seconds

It waits for the watcher process to exit (SIGTERM first, then SIGKILL).  Do not
call it from inside a signal handler or a timing-sensitive loop.

### Config\_File Must Be Developer-Controlled

The `config_file` path is validated against directory traversal (`../`) but is
not otherwise restricted.  On Windows, `\` also counts as a separator, and any
path component made only of dots and spaces with two or more dots (`...`,
`.. `) is refused too, because Windows strips trailing dots and spaces and
would open `..`.  It must always be a developer-supplied path, never raw
user input.

### The Cache Cannot See Brand-New Files

With the `cache` argument, a cached result is checked against every file
that was read to make it.  A file that did not exist then, and has been
created since (such as a new `local.yaml`), is not noticed until the entry
expires.  Give the cache an expiry time if this matters.  See
["Caching parsed config files"](#caching-parsed-config-files).

## Encoding

Which text can contain non-ASCII characters (accented letters, other
scripts, emoji), and in what form you get it back:

- **Values in YAML and JSON config files** -- full UTF-8 is supported,
including emoji.  Save the file as UTF-8.  The values you get back are Perl
_character_ strings: `length()` counts characters, not bytes.  Other
formats depend on the parser [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction) uses for them.
- **Values in environment variables** -- any bytes are accepted, but
they are **not decoded**.  You get the raw bytes, so `"caf\x{e9}"` set as
UTF-8 arrives as 5 bytes, not 4 characters.  Decode them yourself if you
need characters:

    ```perl
    use Encode qw(decode);
    my $name = decode('UTF-8', $obj->{name});
    ```

- **Class names** -- ASCII only: letters, digits and `_`, separated by
`::`, and each part must start with a letter or `_`.  Anything else is
refused with an error.  Environment variable names are built from the class
name, so they are ASCII too.
- **Config file paths** (`config_file`, `config_dirs`) -- passed to
the operating system unchanged, as bytes.  On Unix, non-ASCII names work if
you pass them encoded the same way the file system stores them (usually
UTF-8).  On Windows, use ASCII paths.
- **Keys** (setting names) -- use ASCII.  Environment variables can
only set ASCII keys, and hot reload compares keys exactly.
- **Log messages** -- passed to [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction) unchanged; see its
documentation for how it writes them.

## Subroutines/Methods

No public routine changes the caller's `$@`, `$!`, `$?` or `$_`, or
disturbs a pending `alarm()`.  (`$?` matters at program end, when it is
the exit status: stopping the watcher must not change it.)  This matters because `reload_config()` runs from a
`SIGUSR1` handler, at whatever point the program happened to be.

### Configure($Class, \\%Params)

Merge configuration for `$class` from all available sources and return a hashref
ready to pass to `bless`.  This is the core function; call it at the start of your
`new()` method.

#### Arguments

- `$class` (Required, string)

    The fully-qualified Perl class name to configure (e.g., `'My::Module'`).  Must
    start with a letter or underscore; each `::`-separated component must also start
    with a letter or underscore.  Digits, newlines, and shell metacharacters are rejected.

- `$params` (Optional, hash reference; `undef` means `{}`)

    Your own values for the object's settings, plus the special keys listed in
    ["Keys of $params"](#keys-of-params).  Your values have the _lowest_ priority: config files
    and environment variables override them.  The hash you pass is copied, never
    changed.

#### Keys of $Params

Any key may be used.  These keys have a special meaning:

- `config_file` (string, optional) -- path to the primary YAML/JSON/conf file.
- `config_dirs` (arrayref of strings, optional) -- additional directories to
search when `config_file` is a bare filename with no directory component.  A
directory that cannot be searched is skipped.  An empty list counts as none.
- `logger` (various, optional) -- see ["Logging"](#logging).
- `carp_on_warn` (boolean, optional, default 0) -- if true, the logger uses
`Carp::carp` instead of `warn`.
- `croak_on_error` (boolean, optional) -- passed to [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction) when
set, so that `$logger->error()` croaks.  When absent, Log::Abstraction's own
default applies (`error()` does not croak).  Ignored when you pass a ready-made
logger object.
- `cache` (object, optional) -- a cache for parsed config files, such as
a [CHI](https://metacpan.org/pod/CHI) object.  It must provide `get($key)` and `set($key, $value)`.  See
["Caching parsed config files"](#caching-parsed-config-files).  Like any object argument it is also left in
the returned hash, so it reaches the object's constructor too.

Code references and objects you pass (other than `logger`) are never read
as settings: they are returned exactly as given.

#### Returns

A hashref containing all merged configuration keys plus:

- `logger` -- a [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction) instance, or the string `'NULL'`.
- `_config_file` -- path of the primary config file that was actually read
(the full path when it was found through `config_dirs`).  Absent if no file was
loaded.
- `_config_files` -- arrayref of every config file that was loaded (only if
at least one was loaded), base class first.
- `_config_sections` -- arrayref running parallel to `_config_files`:
the section each file was read with (`UNIVERSAL`, `My__Base`, ...).  Hot
reload uses it to re-merge every file exactly as `configure()` did.  Set
together with `_config_files`, and only by `configure()`.

#### Error Messages

- `Object::Configure: configure: what class do you want to configure?` --
`$class` was `undef` or an empty string.  Pass `ref($self)` or `__PACKAGE__`.
- `Object::Configure: configure: invalid class name (must be a valid Perl package name): CLASS` --
`$class` contains characters not allowed in a Perl package name (for example, a
digit as the first character of a `::`-component, a newline, or a semicolon).
- `CLASS: config_file contains path traversal sequences: FILE` --
`config_file` contains a `..` segment (e.g., `../../etc/passwd`), or on
Windows any segment Windows would treat as `..` (`...`, `.. `, and `\`
separators).  The `config_file` argument must always be a developer-controlled
path.
- `CLASS: FILE: OS-ERROR` --
`config_file` is not readable and no `config_dirs` (or an empty list) were supplied.  OS-ERROR is
the locale's text for `ENOENT` when the file does not exist, and for `EACCES`
when it exists but cannot be read.  Check the path and permissions, or add
`config_dirs`.
- `CLASS: FILE: config file is too large (SIZE bytes; the limit is 16384 bytes)` --
a config file that would be read (the primary file, an ancestor's file or
`universal.yml`) is larger than 16K.  See ["Config file size limit"](#config-file-size-limit).
- `Warning: Can't load configuration from FILE: DETAIL` --
[Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction) rejected the file (typically a YAML/JSON syntax error).
This is a warning, not fatal; `configure()` continues with an empty config.
- `Warning: Can't load configuration from FILE: no settings could be read (is a parser for this format installed?)` --
the file was found but nothing could read it, typically because the optional
parser [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction) needs for its format is not installed (for
example [YAML::XS](https://metacpan.org/pod/YAML%3A%3AXS) for `.yml`, or [Config::IniFiles](https://metacpan.org/pod/Config%3A%3AIniFiles) for an INI-style
`.conf`).  Also a warning; that file's settings are skipped and the caller's
values are kept.
- `Object::Configure: config_path contains path traversal sequences: PATH` --
An environment variable set a `config_path` value containing `..`.
- `Object::Configure: configure: params must be a hash reference` --
the second argument was not a hashref.  Call `configure($class, \%args)`, not
`configure($class, %args)`.
- `Object::Configure: configure: config_dirs must be an array reference` --
`config_dirs` was a string or other non-arrayref.  Wrap a single directory in
brackets: `config_dirs => ['/etc/myapp']`.
- `Object::Configure: configure: cache must be an object with get() and set() methods` --
`cache` was not a blessed object, or lacks `get` or `set`.
- `Object::Configure: cache get failed: ERROR` /
`Object::Configure: cache set failed: ERROR` --
warnings: the cache itself died.  The file is parsed as if there were no
cache, so a cache outage slows `configure()` down but never breaks it.

#### Api Specification

##### Input

```perl
{
    class => {
        type        => 'string',
        optional    => 0,
        matches     => qr/\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/,
        description => 'Fully-qualified Perl class name',
    },
    params => {
        type        => 'hashref',
        optional    => 1,
        description => 'Caller-supplied values (lowest priority); undef means {}',
    },
}
```

##### Keys of Params

```perl
{
            config_file => {
                type        => 'string',
                optional    => 1,
                description => 'Primary config file path',
            },
            config_dirs => {
                type        => 'arrayref',
                optional    => 1,
                description => 'Extra directories to search for config files',
            },
            logger => {
                type        => [qw(undef string arrayref hashref object)],
                optional    => 1,
                description => 'Logger spec -- see CONFIGURATION/Logging',
            },
            carp_on_warn => {
                type        => 'boolean',
                optional    => 1,
                default     => 0,
                description => 'Use Carp::carp for logger warnings',
            },
            croak_on_error => {
                type        => 'boolean',
                optional    => 1,
                description => 'Use Carp::croak for logger errors',
            },
            cache => {
                type        => 'object',
                can         => [ qw(get set) ],
                optional    => 1,
                description => 'Cache for parsed config files (e.g. CHI)',
            },
}
```

##### Output

```perl
type        => 'hashref',
description => 'Merged configuration hashref, ready to bless',
schema => {
    logger => {
        type        => [qw(object string)],
        description => 'Log::Abstraction instance or the string "NULL"',
    },
    _config_file => {
        type        => 'string',
        optional    => 1,
        description => 'Path of the primary config file that was loaded',
    },
    _config_files => {
        type        => 'arrayref',
        optional    => 1,
        description => 'All config file paths that were loaded, in load order',
    },
    _config_sections => {
        type        => 'arrayref',
        optional    => 1,
        description => 'Section each file in _config_files was read with',
    },
}
```

### Instantiate(%Params)

Configure and instantiate a third-party class without modifying the class itself.

`instantiate` is a convenience wrapper: it calls `configure`, passes the merged
hashref to `$class->new(...)`, and optionally registers the result for hot reload.
Use it when you need runtime configuration for a class whose source you cannot change.

#### Arguments

Takes a flat hash (not a hashref).  Recognized keys:

- `class` (Required, string)

    The fully-qualified class name to instantiate (e.g., `'LWP::UserAgent'`).  The class
    must already be loaded and must have a `new` method that accepts a hashref.

- All other keys

    Passed through to `configure()` as `\%params`.  See ["configure($class, \\%params)"](#configure-class-params)
    for the full list.

#### Returns

A blessed object of type `$class`, or whatever `$class->new(...)`
returned if it was not a blessed reference (for example `undef` from a
constructor that signals failure that way).  Such a value is returned as-is
and is never registered for hot reload.

**Note:** The returned object's hash will contain a `class` key holding the class name.
This is intentional -- it is left in the hash as a debugging aid so you can always
see which class an object came from.  Do not depend on its absence.

#### Side Effects

- Calls `configure($class, \%params)` -- see its side effects.
- Calls `$class->new(\%merged_params)`.
- If the config produced a `_config_file` and `new()` returned a blessed
object, calls `register_object($class, $obj)` so the object participates in hot
reload.

#### Error Messages

Same as `configure()`.  In addition:

- `Usage: Params::Get->Object::Configure::instantiate(class => $val)` --
`instantiate()` was called with no arguments at all.  This message comes from
[Params::Get](https://metacpan.org/pod/Params%3A%3AGet).  (With other arguments but no `class`, the `configure()`
message about the missing class is given instead.)
- Any exception thrown by `$class->new(...)` propagates unchanged.

#### Usage Example

```perl
use Object::Configure;

my $ua = Object::Configure::instantiate(
    class       => 'LWP::UserAgent',
    config_file => 'lwp.yml',
    config_dirs => ['/etc/myapp'],
    timeout     => 30,
);
```

#### Api Specification

##### Input

```perl
{
    class => {
        type        => 'string',
        optional    => 0,
        description => 'Fully-qualified class name; must respond to new(hashref)',
    },
}
```

All other keys are passed to `configure()`; see ["Keys of $params"](#keys-of-params).

##### Output

```perl
type        => 'object',
description => 'Blessed instance of $class, with class key present in hash; '
             . 'otherwise the non-blessed value new() returned, unregistered',
notes       => 'class key intentionally left in hash as a debugging aid',
```

## Hot Reload Features

### Enable\_Hot\_Reload(%Opts)

Fork a background watcher that sends SIGUSR1 to the parent whenever a tracked
configuration file changes on disk.  Objects registered via `register_object()`
then have their configuration reloaded automatically.

**UNIX only.**  On Windows this function is a silent no-op (SIGUSR1 does not exist): it
forks nothing and returns empty.

#### Arguments

Takes a flat hash.  All keys are optional.

- `interval` (integer >= 1, default: 10)

    Seconds between file-modification checks.  Lower values detect changes faster
    but use more CPU.  Fractional values are truncated to whole seconds in the
    watcher, and anything that ends up below 1 (including zero and negative values)
    is silently replaced with the default.

- `callback` (coderef, optional)

    Called in the parent process after each config reload.  Useful for
    logging or flushing caches.  If it dies, the error is reported with `carp`
    (`Object::Configure: hot reload callback failed: ...`) rather than propagated,
    because it runs inside a signal handler.

#### Returns

The PID of the watcher child process (integer > 0), or `undef`/empty if hot
reload was already active (idempotent: a second call returns immediately without
forking again).

#### Side Effects

- Installs Object::Configure's `SIGUSR1` handler, if
`register_object()` has not already done so (see
["register\_object($class, $obj)"](#register_object-class-obj)), so the watcher's signals are always
handled.
- Forks a child process.
- The child polls `%_config_file_stats` and sends `SIGUSR1` to the
parent when a file's modification time, size or inode changes, or the file
appears or disappears.
- The child exits by itself within one `interval` if the parent dies
without stopping it (for example through `POSIX::_exit` or `SIGKILL`), so
it never signals whatever process adopts it.
- The child is ended at once by `SIGTERM` or `SIGINT` (their default
action, set before either can reach it), so `disable_hot_reload()` does not
wait, and none of the parent's `END` blocks or destructors run in it.
- Stores `{pid => $pid, callback => $cb}` in `%_config_watchers`.

#### Error Messages

- `Failed to fork config watcher: OS-ERROR` -- `fork()` returned `undef`.
Check system resource limits (`ulimit -u`).
- `Object::Configure::enable_hot_reload: callback must be a code reference` --
`callback` was given but is not a coderef.  It is checked here because it would
otherwise only fail later, inside the `SIGUSR1` handler.

#### Usage Example

```perl
Object::Configure::enable_hot_reload(
    interval => 5,
    callback => sub { warn "Config reloaded at " . localtime . "\n" },
);

while (1) { sleep 1 }  # watcher runs in the background
```

#### Api Specification

##### Input

```perl
{
    interval => {
        type        => 'integer',
        optional    => 1,
        default     => 10,
        min         => 1,
        description => 'Poll interval in seconds',
    },
    callback => {
        type        => 'coderef',
        optional    => 1,
        description => 'Called in parent after each reload',
    },
}
```

##### Output

```perl
type        => 'integer',
optional    => 1,
min         => 2,
description => 'PID of the watcher child; undef/empty if hot reload was '
             . 'already active, or on Windows',
```

### Disable\_Hot\_Reload()

Stop the background watcher and clear hot-reload state.

Safe to call when hot reload is not active (no-op).  After this call,
configuration files are no longer monitored and `%_config_watchers` is empty.

#### Arguments

None.

#### Returns

Nothing (void).

#### Side Effects

- Sends SIGTERM to the watcher child.
- Polls for up to `$KILL_TIMEOUT` seconds (default: 5); escalates to SIGKILL
if the child has not exited by then.  (The watcher ends at once on SIGTERM, so
this only happens if something has interfered with it.)
- Leaves `$?` unchanged, although it waits for the child: when this runs
at program end, `$?` is the program's exit status.
- Calls `waitpid` to reap the child.
- Clears `%_config_watchers`.

**Blocking**: this function may take up to five seconds if the watcher ignores SIGTERM.

#### Api Specification

##### Input

```
{}   # no arguments
```

##### Output

```perl
type => 'void'
```

### Reload\_Config()

Immediately reload configuration from disk for every registered object.

Normally called automatically by the SIGUSR1 handler.  You may call it manually
to force a reload (e.g., in tests or on a custom signal).

#### Arguments

None.

#### Returns

An integer >= 0: the count of objects whose configuration was successfully
reloaded.  Objects with no config file, or whose file could not be parsed, are
not counted.

#### Side Effects

- Re-reads every file an object was configured from (`universal.yml`,
ancestor files and its own files) and merges them base-first, as
`configure()` did, so an edit to any of them takes effect.  A file that has
been deleted is skipped: a key only it set keeps its last value, and a key it
shared with another file takes that file's value.
- Each file is parsed once per reload, however many objects use it.
The parsers are kept between reloads and refreshed with
[Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction)'s `reload()` (0.44 and later); with an older
Config::Abstraction a new parser is built each time.  Parsers no live
registered object uses are discarded at the end of each reload.
- An object without `_config_sections` (built by hand rather than by
`configure()`) re-reads only its most specific file, with its own section.
- Updates non-private keys (those not starting with `_`) in-place on
each live object.
- Logs `Configuration reloaded for CLASS` through the object's logger,
best effort: if the logger dies, the reload still counts as a success.
- Prunes dead weak references from `%_object_registry`.
- Emits a `carp` warning (not a croak) if reload fails for any individual
object; other objects are still processed.

#### Error Messages

All are warnings; none stops the remaining objects being reloaded, and an
object that cannot be reloaded is not counted.

- `Warning: Can't load configuration from FILE: DETAIL` --
a kept parser's `reload()` failed (Config::Abstraction keeps the previous
settings and reports why).  That file adds nothing to this reload, and is
parsed afresh next time.
- `Failed to reload config for object: ERROR` --
re-reading an object's file died (for example, the parser threw).  ERROR is the
exception text.
- `Object::Configure: _reload_object_config: refusing path with traversal sequences: PATH` --
the object's `_config_files`, `_config_file` or `config_file` key contains a
`..` segment, for example because the object was tampered with.  The file is
not read.
- `Object::Configure: _reload_object_config: FILE: config file is too large (SIZE bytes; the limit is 16384 bytes)` --
the object's config file has grown past 16K since it was loaded.  It is not
read and the object keeps its current settings.  See
["Config file size limit"](#config-file-size-limit).

#### Api Specification

##### Input

```
{}   # no arguments
```

##### Output

```perl
type        => 'integer',
description => 'Count of objects successfully reloaded',
condition   => 'value >= 0',
```

### Register\_Object($Class, $Obj)

Register a blessed object so it receives configuration updates when files change.

**Push semantics**: each call _appends_ a new entry to the registry for `$class`.
It does not replace a previous entry.  Multiple objects of the same class are all
tracked and all reloaded.

#### Arguments

- `$class` (Required, string)

    The class name used to organise the registry.  Typically `ref($self)` or the
    calling package name.

- `$obj` (Required, blessed reference)

    The object to register.  **Must be a blessed reference.**  Passing an unblessed
    hashref or any other unblessed value causes an immediate `croak`.

#### Returns

Nothing (void).

#### Side Effects

- Pushes a weak reference to `$obj` onto `$_object_registry{$class}`.
- Removes references to objects that no longer exist from that list
whenever it has doubled in size since the last clean-up (and has at least 64
entries).  This keeps the registry bounded in programs that register many
short-lived objects and rarely or never receive `SIGUSR1`, at an amortised
cost of O(1) per call.  Live objects are never removed.
- If Object::Configure's handler is not installed yet (by an earlier
call, or by `enable_hot_reload()`): saves the current `$SIG{USR1}`
and installs Object::Configure's handler.  On UNIX, the handler calls
`reload_config()` and the hot-reload callback, then daisy chains to the
prior handler (coderef or sub name), which is always called, even when the
reload or callback fails.  See ["Sharing SIGUSR1 with other code (daisy chaining)"](#sharing-sigusr1-with-other-code-daisy-chaining).
It also creates a guard whose `DESTROY` (run at program end, or by
`restore_signal_handlers()`) puts the prior handler back if ours is still
installed.  On Windows, signal installation is skipped but
`$_original_usr1_handler` is still set.

#### Error Messages

- `Object::Configure::register_object: Usage ($class, $obj)` --
either `$class` or `$obj` was `undef`.
- `Object::Configure::register_object: $obj must be a blessed reference` --
`$obj` was defined but not blessed.  This guard prevents DoS via registry flooding
(reloading thousands of unblessed entries on every SIGUSR1).

The `SIGUSR1` handler installed here may also warn (it never dies, since an
exception there would surface at whatever code the signal interrupted):

- `Object::Configure: hot reload failed: ERROR` --
`reload_config()` itself died.  The callback and the previous handler are
still called.
- `Object::Configure: hot reload callback failed: ERROR` --
the `callback` given to `enable_hot_reload()` died.  The reload itself has
already happened and the previous handler is still called.
- `Object::Configure: Cannot chain to non-code USR1 handler: HANDLER` --
`$SIG{USR1}` held a string other than `DEFAULT` or `IGNORE` that does not
name a defined sub (unqualified names are looked up in `main::`, as Perl
does).  Nothing is called.  Define the sub, or install a coderef.

#### Usage Example

```perl
package My::Module;
use Object::Configure;

sub new {
    my ($class, %args) = @_;
    my $params = Object::Configure::configure($class, \%args);
    my $self   = bless $params, $class;
    Object::Configure::register_object($class, $self)
        if $self->{_config_file};
    return $self;
}
```

#### Api Specification

##### Input

```perl
{
    class => {
        type        => 'string',
        optional    => 0,
        description => 'Class name for registry key',
    },
    obj => {
        type        => 'object',
        optional    => 0,
        description => 'Blessed object to register; unblessed refs are rejected',
    },
}
```

##### Output

```perl
type => 'void'
```

### Restore\_Signal\_Handlers()

Turn hot reload off: stop the watcher, if one is running, then restore
`$SIG{USR1}` to the handler that was in place before Object::Configure
installed its own, and clear `$_original_usr1_handler`.  The watcher is
stopped first because its next signal would otherwise reach the restored
handler, and if that is `DEFAULT`, end the program.

This explicit call restores unconditionally, even if other code has since
installed a handler of its own.  The automatic restore at program end is
more careful: it only puts the previous handler back if Object::Configure's
handler is still installed.  See
["Sharing SIGUSR1 with other code (daisy chaining)"](#sharing-sigusr1-with-other-code-daisy-chaining).

Safe to call even when Object::Configure never installed a handler (no-op).
On Windows this function has no effect (SIGUSR1 does not exist there).

#### Arguments

None.

#### Returns

Nothing (void).

#### Side Effects

- Stops the watcher if one is running, exactly as
`disable_hot_reload()` does (so it may wait up to five seconds).
- Sets `$SIG{USR1}` back to its saved value (UNIX only).
- Sets `$_original_usr1_handler` to `undef`.
- Releases the installation guard (its `DESTROY` then has nothing
left to do).

#### Api Specification

##### Input

```
{}   # no arguments
```

##### Output

```perl
type => 'void'
```

### Get\_Signal\_Handler\_Info()

Return a snapshot of the current signal-handler and hot-reload state.
This is a debugging aid; normal application code does not need to call it.

#### Arguments

None.

#### Returns

A hashref with these keys:

- `original_usr1` -- the `$SIG{USR1}` value that existed before
Object::Configure installed its handler, or `undef` if no handler was saved yet.
- `current_usr1` -- the currently installed `$SIG{USR1}` handler (coderef,
`'DEFAULT'`, `'IGNORE'`, or `undef`).
- `hot_reload_active` -- `1` if Object::Configure's `SIGUSR1` handler
is installed (`$_original_usr1_handler` is defined), `''` otherwise.  Always
`''` on Windows, which has no `SIGUSR1`.
- `watcher_pid` -- the PID of the background watcher child, or `undef`
if `enable_hot_reload()` has not been called (or the watcher has been stopped).

#### Usage Example

```perl
use Object::Configure;
use Data::Dumper;

# register_object() installs the SIGUSR1 handler; enable_hot_reload()
# starts the watcher.  Both are needed for every field below to be set.
Object::Configure::register_object(ref($obj), $obj);
Object::Configure::enable_hot_reload();
print Dumper(Object::Configure::get_signal_handler_info());
# {
#   original_usr1    => 'DEFAULT',
#   current_usr1     => sub { ... },
#   hot_reload_active => 1,
#   watcher_pid       => 12345,
# }
```

#### Api Specification

##### Input

```
{}   # no arguments
```

##### Output

```perl
type        => 'hashref',
description => 'Snapshot of signal-handler and watcher state',
schema => {
    original_usr1     => { type => 'string',  optional => 1 },   # or a coderef
    current_usr1      => { type => 'string',  optional => 1 },   # or a coderef
    hot_reload_active => { type => 'boolean'                },
    watcher_pid       => { type => 'integer', optional => 1 },
}
```

## See Also

- [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction)
- [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction)
- [Test Dashboard](https://nigelhorne.github.io/Object-Configure/coverage/)

## Limitations

- **Global singleton state.** `%_object_registry`, `%_config_watchers`, and
`%_config_file_stats` are package globals.  Two independent subsystems in the same
process share one hot-reload registry and one SIGUSR1 handler.  There is no
instance-level isolation.  A proper fix would wrap state in an object and allow
multiple independent `Object::Configure` instances, but that would break the
existing constructor-call API (`configure($class, \%params)`).
- **Hot reload is UNIX-only.** SIGUSR1 does not exist on Windows.
All signal-related paths are guarded with `$^O ne 'MSWin32'`, so the module
loads on Windows but silently skips hot-reload registration.
- **configure() is a God function.** At about 280 lines it handles arg validation,
config-file discovery, MRO walking, multi-file merging, caching, env-var merging,
logger creation, and hot-reload bookkeeping.  Future versions should decompose this into
smaller, independently testable units.
- **\_deep\_merge reimplements CPAN.** [Hash::Merge::Simple](https://metacpan.org/pod/Hash%3A%3AMerge%3A%3ASimple) or [Hash::Merge](https://metacpan.org/pod/Hash%3A%3AMerge)
provide tested, feature-complete deep merge.  The internal `_deep_merge` is 15
lines and correct for the current use, but does not handle arrayrefs (they are
replaced wholesale, not merged).  If array-merge semantics are ever needed, switch
to a CPAN module.
- **No encapsulation enforcement.** Private helpers (`_build_logger`,
`_get_inheritance_chain`, etc.) are accessible to any caller.  [Sub::Private](https://metacpan.org/pod/Sub%3A%3APrivate)
(enforce mode) would make accidental external use a compile-time error.  It is not
added here to avoid a smoker dependency on a less-common module.
- **configure() signature is positional, instantiate() is named.**  The two
public constructors have inconsistent calling conventions.  Normalising them to named
args would require a deprecation cycle.
- **mro::get\_linear\_isa and UNIVERSAL.**  Perl's `mro::get_linear_isa` does
not include `UNIVERSAL` in its output unless `UNIVERSAL` appears explicitly in
`@ISA`.  This module appends `UNIVERSAL` manually so that `universal.yml` is
always discovered.  If a future Perl version changes this behaviour the guard
(`any { $_ eq 'UNIVERSAL' }`) remains correct.
- **Hot reload does not re-apply caller values or environment-only
settings.**  It re-merges the object's config files (each still honours its
environment variables), but the values passed to `configure()` and settings
that came only from environment variables, with no file, are not
re-evaluated.
- **Hot reload keeps one parser per file in memory.**  For as long as a
registered object uses a file, its parsed contents stay in memory, so that
later reloads can refresh it in place.
- **The config file cache cannot see new files.**  A `cache` entry is
checked against every file its load read, but not against files that did not
exist then.  See ["Caching parsed config files"](#caching-parsed-config-files).
- **Keys removed from a config file stay on the object.**  Reload only adds
and overwrites keys; it never deletes a key that has disappeared from the file.
- **The watcher sees only files known when it was forked.**
`%_config_file_stats` is copied into the child by `fork()`.  Files first loaded
by a `configure()` call made after `enable_hot_reload()` are not watched until
you call `disable_hot_reload()` and `enable_hot_reload()` again.
- **Change detection is stat-based.**  The watcher compares mtime, size and
inode.  An edit that keeps all three the same (same size, within the same
second, rewritten in place) is not detected.  Content hashing would close this
gap at the cost of reading every file on every poll.
- **File formats depend on optional parsers.**  [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction)
loads the parser for each format only if it is installed.  Without one, a file
in that format is skipped with a warning (see ["configure($class, \\%params)"](#configure-class-params));
nothing crashes, but its settings are not applied.  Install [YAML::XS](https://metacpan.org/pod/YAML%3A%3AXS) for
YAML files.  (With [Config::Abstraction](https://metacpan.org/pod/Config%3A%3AAbstraction) 0.43, `.json` files are also misread
when [YAML::XS](https://metacpan.org/pod/YAML%3A%3AXS) is missing.)
- **Messages are English only.**  Error and warning texts are fixed strings;
there is no i18n layer.  Callers matching on them should match the stable prefix
(for example `path traversal` or `must be a hash reference`).

## Design Notes

Several checks were removed because earlier code already guarantees their
outcome.  Each rests on a short argument, repeated next to the code:

- **No sort of the files to load.**  If the class's ancestors are found
child-first and each one is put at the _front_ of the list, then the list is
base-first.  The primary file belongs to the class itself and is added last.
So the list is already in load order.
- **The primary file is never checked for duplicates.**  If the search
for ancestor files skips any path equal to `config_file`, then `config_file`
can never already be in the list.  So only its readability is tested.
- **config\_dirs is not re-checked by the private helpers.**  If
`configure()` refuses anything but `undef` or an arrayref, then the
helpers can treat `config_dirs // []` as a list without testing its type.
- **On reload, only an undef logger is special.**  The logger builder
already returns `'NULL'` unchanged, so only `undef` needs its own branch.

These are checked one partition at a time by `t/logic.t`.

## Support

Please report bugs and feature requests at:

- RT (CPAN bug tracker): [http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Object-Configure](http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Object-Configure)

    or by e-mail: `bug-object-configure at rt.cpan.org`

- GitHub issues: [https://github.com/nigelhorne/Object-Configure/issues](https://github.com/nigelhorne/Object-Configure/issues)

You will be notified automatically of progress on your report.

```
perldoc Object::Configure
```

## Author

Nigel Horne, `<njh at nigelhorne.com>`

## Formal Specification

You do not need this section to use the module.  It describes each public
function precisely, in a notation based on Z, for people who want to check
the implementation or write tests against it.

How to read it:

- `Pre-condition` must be true when the function is called;
`Post-condition` is then true when it returns.
- `x@pre` is the value of `x` before the call; `x@post` (or plain
`x` in a post-condition) is its value after.
- `(+)` is the merge described in ["Nested settings are merged; lists
are replaced"](#nested-settings-are-merged-lists-are-replaced): the right-hand side wins.
- `#s` is the number of elements in `s`; `dom` and `ran` are the
keys and the values of a mapping.

### Configure

```perl
configure: Class x Params -> ConfigHash

Given:
- C: set of all class names
- P: set of all parameter hashes
- F: set of all file paths
- H: set of all configuration hashes

State:
- ConfigFiles: F -> H (maps file paths to configuration content)
- EnvVars: String -> String (environment variables)
- InheritanceChain: C -> seq C (ordered sequence of ancestor classes)

Pre-condition:
forall class in C, params in P:
    class != empty
    (params.config_file != empty =>
        (exists dir in params.config_dirs: readable(dir/params.config_file))
        OR readable(params.config_file))

Post-condition:
forall result in H:
    result = params
             (+) (merge f in InheritanceConfigFiles(class): ConfigFiles(f))
             (+) (merge v in RelevantEnvVars(class): v)
    result.logger in Log::Abstraction
    (forall k in dom params:
        (params(k) in CodeRef OR blessed(params(k))) => result(k) = params(k))

where (+) denotes hash merge with right-precedence, and
      InheritanceConfigFiles(class) is ordered
          universal.yml, ancestors base-first, primary config_file
      (so the order of priority, lowest first, is: params, UNIVERSAL,
      ancestors, the primary file, environment variables)

With params.cache = c (an object with get and set):
    for each file f read with section s:
        let k = SHA1(Inputs(f, s))
        Settings(f, s) = copy(c.get(k).settings)
                             if c.get(k) is a valid entry and
                                forall (g, sig) in c.get(k).files:
                                    signature(g) = sig
                       = parse(f, s), then c.set(k, entry)   otherwise
    so result is the same as without c, unless a file that did not
    exist when k was stored has appeared since (see LIMITATIONS).
```

### Instantiate

```perl
instantiate: Params -> Object

Given:
- P: set of all parameter hashes
- C: set of all class names
- O: set of all objects

Pre-condition:
forall params in P:
    params.class in C
    params.class.can('new')

Post-condition:
forall result in O:
    exists config in H:
        config = configure(params.class, params)
        result = params.class.new(config)
        (config._config_file != empty AND blessed(result) != empty =>
            result in _object_registry(params.class))
        (blessed(result) = empty =>
            result NOT in _object_registry(params.class))
```

### Enable\_Hot\_Reload

```perl
enable_hot_reload: Interval x Callback -> PID

Given:
- I: set of positive integers (intervals in seconds)
- CB: set of code references
- PID: set of process identifiers

State:
- _config_watchers: {pid: PID, callback: CB}
- _config_file_stats: F -> Stat

Pre-condition:
forall interval in I, callback in CB union {empty}:
    interval >= 1
    _config_watchers = empty
    OS != 'MSWin32'

Post-condition:
forall result in PID:
    result > 0
    _config_watchers.pid = result
    _config_watchers.callback = callback
    $SIG{USR1} = reload_config_handler
      -- installed as by register_object() if it was not already
    (forall t in Time:
        (t mod interval = 0) =>
            (exists f in dom _config_file_stats:
                (mtime(f), size(f), inode(f)) !=
                    (mtime, size, ino)(_config_file_stats(f))
                OR exists(f) != exists@fork(f) =>
                    send_signal(SIGUSR1, parent_process)))
    (parent_process = $$@pre, fixed at the fork; once
     getppid() != parent_process the watcher exits, so
     no signal is ever sent to any other process)

On Windows: result = empty and the state is unchanged.
If _config_watchers != empty@pre: result = empty and the state is
unchanged (idempotent).
```

### Disable\_Hot\_Reload

```perl
disable_hot_reload: () -> ()

State:
- _config_watchers: {pid: PID, callback: CB}

Pre-condition:
true

Post-condition:
_config_watchers = empty
(forall p in PID:
    p = _config_watchers.pid@pre =>
        NOT alive(p))
```

### Reload\_Config

```perl
reload_config: () -> N

State:
- _object_registry: C -> seq ObjectRef
- ConfigFiles: F -> H

Pre-condition:
true

Post-condition:
forall result in N:
    result = |{obj in flatten(ran _object_registry) |
               obj != empty
               Merged(obj) != empty}|
    (forall obj in flatten(ran _object_registry):
        obj != empty AND Merged(obj) != empty =>
            (forall k in dom Merged(obj):
                k NOT in PrivateKeys =>
                    obj(k)@post = Merged(obj)(k)))
    dom _config_sources@post =
        {(f, s) | exists obj live: (f, s) in Sources(obj), f exists}

where PrivateKeys = {k | k starts with '_'}
      Sources(obj) = zip(obj._config_files, obj._config_sections)
                     if both present and of equal length,
                     else <(last(obj._config_files) or obj._config_file,
                             section(class(obj)))>
      Merged(obj)  = (+) over (f, s) in Sources(obj), f exists, base-first:
                         Section(ConfigFiles(f), s)
      and each (f, s) is read at most once per call
```

### Register\_Object

```perl
register_object: C x O -> ()

Given:
- C: set of class names
- O: set of blessed objects
- OR: C -> seq WeakRef(O) (object registry)

State:
- _object_registry: OR
- _original_usr1_handler: SignalHandler union {empty}
- $SIG{USR1}: SignalHandler

Pre-condition:
forall class in C, obj in O:
    class != empty
    obj != empty
    blessed(obj) != empty

Post-condition:
forall class in C, obj in O:
    exists ref in _object_registry(class):
        weak(ref) = obj
    (forall live o registered under class: o in ran _object_registry(class))
    #_object_registry(class) <= max(64, 2 * #live(class)) + 1
      -- dead entries are pruned when the list doubles (amortised O(1))
    (_original_usr1_handler = empty@pre =>
        (_original_usr1_handler@post = $SIG{USR1}@pre
         $SIG{USR1}@post = reload_config_handler))

Daisy chain (each delivery of SIGUSR1 to reload_config_handler h):
    let p = _original_usr1_handler (or, once cleared, $SIG{USR1}@install)
    h(sig) = reload_config(); callback(); call(p, sig)
    where call(p, sig) = p(sig)             if p in CodeRef
                       = (main::p)(sig)     if p names a defined sub
                       = skip               if p in {DEFAULT, IGNORE}
                       = warn               otherwise
    and failures in reload_config() and callback() are caught, so
    call(p, sig) happens exactly once per delivery.

Teardown (guard DESTROY, at END):
    $SIG{USR1}@pre = h  =>  $SIG{USR1}@post = $SIG{USR1}@install
    $SIG{USR1}@pre != h =>  $SIG{USR1}@post = $SIG{USR1}@pre
```

### Restore\_Signal\_Handlers

```perl
restore_signal_handlers: () -> ()

State:
- _original_usr1_handler: SignalHandler union {empty}
- $SIG{USR1}: SignalHandler

Pre-condition:
true

Post-condition:
_config_watchers@post = empty
(forall p: p = _config_watchers.pid@pre => NOT alive(p))
$SIG{USR1}@post = _original_usr1_handler@pre
_original_usr1_handler@post = empty
```

### Get\_Signal\_Handler\_Info

```
get_signal_handler_info: () -> InfoHash

Given:
- IH: set of all info hashes

State:
- _original_usr1_handler: SignalHandler union {empty}
- $SIG{USR1}: SignalHandler union {empty}
- _config_watchers: {pid: PID, callback: CB}

Pre-condition:
true

Post-condition:
forall result in IH:
    result.original_usr1 = _original_usr1_handler
    result.current_usr1 = $SIG{USR1}
    result.hot_reload_active = (_original_usr1_handler != empty
                                and $^O != 'MSWin32')
    result.watcher_pid = _config_watchers.pid
```

## State Diagram

Object::Configure keeps one set of hot-reload state for the whole process.
It depends on two things: whether Object::Configure's `SIGUSR1` handler is
installed (the "handler"), and whether the background process started by
`enable_hot_reload()` is running (the "watcher").  The watcher only runs
while the handler is installed, so there are three states, plus a
short-lived RELOADING state while a signal is being handled.  Use
`get_signal_handler_info()` to see the current state.

```
                 register_object() (first call)
 +--------------+ ----------------------------> +--------------+
 | S0 IDLE      |                               | S1 HANDLER   |
 | no handler   | <---------------------------- | no watcher   |
 | no watcher   |   restore_signal_handlers()   |              |
 +--------------+                               +--------------+
    |        ^                                     |   ^     |
    |        |                             enable_ |   |     | SIGUSR1
    |        | restore_signal_handlers()   hot_    |   |     | (sent by
    |        | (stops the watcher too)     reload()|   |     | kill)
    |        |                                     v   |     v
    |        |                                  +--------------+
    |        +--------------------------------- | S2 WATCHING  |
    +-----------------------------------------> | handler and  |
      enable_hot_reload() (installs the         | watcher      |
      handler, then forks the watcher)          +--------------+
                                                   |   ^  disable_hot_reload()
                a config file changes:             |   |  goes back to S1
                the watcher sends SIGUSR1          v   |
                                              +--------------+
                                              | R RELOADING  |  handler returns:
                                              | (in handler) |  back to S1 or S2
                                              +--------------+
```

### Transitions

```
FROM     TRIGGER                          TO       ACTIONS / SIDE EFFECTS
-------  -------------------------------  -------  --------------------------------
S0       register_object(), first call    S1       saves $SIG{USR1}; installs the
                                                   handler; creates the guard;
                                                   adds a weak reference to the
                                                   registry
S1, S2   register_object()                same     adds a weak reference; removes
                                                   dead ones when the class's list
                                                   has doubled
S0       enable_hot_reload()              S2       installs the handler as above
                                                   (no object needed), then forks
                                                   the watcher
S1       enable_hot_reload()              S2       forks the watcher
S2       enable_hot_reload()              S2       nothing (already watching)
S2       disable_hot_reload()             S1       SIGTERM to the watcher; SIGKILL
                                                   after 5 seconds; waits for it
S0, S1   disable_hot_reload()             same     nothing
S1       restore_signal_handlers()        S0       puts the saved handler back in
                                                   $SIG{USR1}; releases the guard
S2       restore_signal_handlers()        S0       stops the watcher (as
                                                   disable_hot_reload()), then as
                                                   from S1
S1, S2   SIGUSR1 (watcher or kill)        R        see RELOADING below
R        handler finishes                 S1/S2    back to the state it came from
S1, S2   other code assigns $SIG{USR1}    same*    *our handler is no longer live:
                                                   reloads stop unless that code
                                                   calls ours, and the watcher's
                                                   signals go to that code (if it
                                                   sets 'DEFAULT', a signal ends
                                                   the program); at program end
                                                   its handler is kept
any      reload_config(), called directly same     step 1 of RELOADING only: every
                                                   registered object is re-read;
                                                   the callback and the previous
                                                   handler are not called
any      configure() reads a file         same     the file is remembered; a
                                                   watcher started LATER checks it
S2       the program dies without END     (end)    the watcher notices within one
         (e.g. POSIX::_exit, SIGKILL)              interval and exits by itself
any      program END                      (end)    watcher stopped as by
                                                   disable_hot_reload(); then the
                                                   saved handler is put back, but
                                                   only if ours is still installed
```

On Windows there is no `SIGUSR1`, so the process stays in S0:
`register_object()` only saves `$SIG{USR1}` (so that
`restore_signal_handlers()` is safe), `enable_hot_reload()` returns without
starting a watcher, and `get_signal_handler_info()` reports
`hot_reload_active` as false.

RELOADING runs these steps, in this order, once per signal:

- 1. `reload_config()`: re-read every registered object's files and
update the object's settings.  A failure is reported with `carp`.
- 2. The `callback` given to `enable_hot_reload()`, if any.  A
failure is reported with `carp`.
- 3. The handler that was in `$SIG{USR1}` before Object::Configure's,
if it is code or the name of a sub.  This step always runs.

### Life Cycle of a Registered Object

```
[ made by configure() + bless, or by instantiate() ]
      |
      | register_object()   (instantiate() calls it for you when
      v                      a config file was loaded)
+------------------+   reload_config()   +--------------------------+
| REGISTERED       | ------------------> | UPDATED IN PLACE         |
| weak reference   | <------------------ | keys not starting with _ |
| in the registry  |      (returns)      | set from its files       |
+------------------+                     +--------------------------+
      |
      | the program drops its last reference to the object
      v
+------------------+   next reload_config(), or a register_object()
| FREED            |   for the same class once its list has doubled
| dead reference   | ---------------------------------------------> removed
+------------------+
```

## Licence and Copyright

Copyright 2025-2026 Nigel Horne.

Usage is subject to GPL2 licence terms.
If you use it, please let me know.
