blib/lib/Object/Configure.pm

filter: Statementstmt 97.9% 333 / 340 Branchbran 92.7% 154 / 166 Conditioncond 81.5% 93 / 114 MC/DCmcdc 68.5% 48 / 70 Subroutinesub 97.4% 38 / 39 Podpod 100% 8 / 8 totaltotal 91.4% 674 / 737 CC 138 SCAR 30.2
CC
138
Cov
94%
configure
50.1
_reload_object_config
20.1
_find_class_config_file
13.0
CRAP 20.5
↑ Summary
1 package Object::Configure;
2  
3 39 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 39 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 39 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 39 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 39 ▶use Config::Abstraction 0.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 39 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 39 ▶use Log::Abstraction 0.41;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 39 ▶use mro;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 39 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 39 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 39 ▶use Return::Set;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 39 ▶use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 39 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 39 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 39 ▶use File::stat;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 39 ▶use POSIX qw(WNOHANG);
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # Avoid magic literals scattered across hot paths and signal handlers.
22 # Centralising here makes global search-replace safe and self-documents intent.
23 39 Readonly my $OS_WINDOWS => 'MSWin32';
24 39 Readonly my $LOGGER_NULL => 'NULL';
25 39 Readonly my $SIG_DEFAULT => 'DEFAULT';
26 39 Readonly my $SIG_IGNORE => 'IGNORE';
27 39 Readonly my $POLL_SLEEP => 0.1; # seconds between waitpid polls in disable_hot_reload
28 39 Readonly my $KILL_TIMEOUT => 5; # seconds before SIGKILL escalation after SIGTERM
29 39 Readonly my $DEFAULT_INTERVAL => 10; # default hot-reload poll interval in seconds
30  
31 # Matches any path segment that is exactly ".." (anchored start, slash, or end).
32 # Catches: ../foo foo/../bar foo/.. and leading ../
33 # Used in two places; kept as a constant so both guards are always in sync.
34 39 Readonly my $RE_PATH_TRAVERSAL => qr{(?:\A|/)\.\.(?:/|\z)};
35  
36 # Global registry - intentionally package-level so that the END block and
37 # signal handlers installed in one call site share state with all others.
38 # This is a deliberate singleton design; see LIMITATIONS for the trade-offs.
39 39 our %_object_registry = ();
40 39 our %_config_watchers = ();
41 39 our %_config_file_stats = ();
42  
43 # Memoization caches - keyed by inputs; valid for the process lifetime because
44 # Perl @ISA hierarchies and filesystem layouts are stable after module load.
45 # Both caches include undef sentinels (use exists, not defined, to check hits).
46 39 our %_chain_cache = (); # class => [UNIVERSAL, ..., Class] (base-first)
47 39 our %_find_cache = (); # "\0"-joined key => file path or undef
48  
49 # Saved before we install our SIGUSR1 handler so we can chain and restore it.
50 39 our $_original_usr1_handler;
51  
52 =head1 NAME
53  
54 Object::Configure - Runtime Configuration for an Object
55  
56 =head1 VERSION
57  
58 0.26
59  
60 =cut
61  
62 39 our $VERSION = 0.26;
63  
64 =head1 DESCRIPTION
65  
66 C<Object::Configure> injects runtime configuration and logging into Perl class
67 constructors. It is a thin layer on top of L<Config::Abstraction> (reads config
68 files and environment variables) and L<Log::Abstraction> (logging).
69  
70 Call C<configure($class, \%params)> at the start of your C<new()> method. It:
71  
72 =over 4
73  
74 =item 1. Walks C<@ISA> and finds config files for every class in the inheritance chain.
75  
76 =item 2. Merges those files, then overlays environment variables named C<ClassName__key>.
77  
78 =item 3. Creates a L<Log::Abstraction> logger and stores it in C<$params-E<gt>{logger}>.
79  
80 =item 4. Returns a hashref ready to pass to C<bless>.
81  
82 =back
83  
84 The module also provides optional hot-reload support: a background process watches
85 config files and sends C<SIGUSR1> to trigger an in-place update of registered objects
86 without restarting the application.
87  
88 B<Hot reload is not supported on Windows> (C<SIGUSR1> does not exist there).
89  
90 =head1 SYNOPSIS
91  
92 =head2 Example 1: Add configurable logging to your own class
93  
94 package My::Module;
95 use Object::Configure;
96  
97 sub new {
98 my ($class, %args) = @_;
99  
100 # configure() reads config files + env vars, sets up a logger,
101 # and returns a hashref ready to bless.
102 my $params = Object::Configure::configure($class, \%args);
103  
104 return bless $params, $class;
105 }
106  
107 sub do_work {
108 my $self = shift;
109 $self->{logger}->info('Starting do_work');
110 # ...
111 }
112  
113 # Usage -- reads ~/.conf/my-module.yml if it exists:
114 my $obj = My::Module->new(config_file => '/etc/myapp/my-module.yml');
115 $obj->do_work;
116  
117 =head2 Example 2: Configure a third-party class you cannot modify
118  
119 use Object::Configure;
120  
121 # Wrap LWP::UserAgent so it reads its settings from a YAML file.
122 my $ua = Object::Configure::instantiate(
123 class => 'LWP::UserAgent',
124 config_file => '/etc/myapp/lwp.yml',
125 timeout => 30, # fallback if the file has no timeout key
126 );
127  
128 $ua->get('https://example.com');
129  
130 =head2 Example 3: Multi-level inheritance -- config files merge automatically
131  
132 # ~/.conf/my-base-class.yml
133 # My__Base__Class:
134 # timeout: 30
135 # retries: 3
136  
137 # ~/.conf/my-child-class.yml
138 # My__Child__Class:
139 # timeout: 60 # overrides base; retries:3 is inherited
140  
141 package My::Child::Class;
142 our @ISA = ('My::Base::Class');
143 use Object::Configure;
144  
145 sub new {
146 my ($class, %args) = @_;
147 # Walks @ISA, merges base config then child config.
148 # Result: timeout=60, retries=3
149 my $params = Object::Configure::configure($class, \%args);
150 return bless $params, $class;
151 }
152  
153 =head2 Example 4: Hot reload -- objects update when the config file changes
154  
155 package My::Service;
156 use Object::Configure;
157  
158 sub new {
159 my ($class, %args) = @_;
160 my $params = Object::Configure::configure($class, \%args);
161 my $self = bless $params, $class;
162  
163 # Register so reload_config() updates $self in-place on file change.
164 Object::Configure::register_object($class, $self)
165 if $params->{_config_file};
166  
167 return $self;
168 }
169  
170 package main;
171  
172 my $svc = My::Service->new(config_file => '/etc/myapp/service.yml');
173  
174 # Fork a background watcher; it sends SIGUSR1 when the file changes.
175 Object::Configure::enable_hot_reload(
176 interval => 5,
177 callback => sub { print "Config reloaded at ", scalar localtime, "\n" },
178 );
179  
180 while (1) { sleep 1 } # event loop
181  
182 Object::Configure::disable_hot_reload(); # clean shutdown
183  
184 =head2 Example 5: Override settings with environment variables (no file needed)
185  
186 # Shell:
187 # export My__Module__log_level=debug
188 # export My__Module__timeout=120
189  
190 package My::Module;
191 use Object::Configure;
192  
193 sub new {
194 my ($class, %args) = @_;
195 # configure() picks up My__Module__* env vars automatically.
196 my $params = Object::Configure::configure($class, \%args);
197 return bless $params, $class;
198 }
199  
200 my $obj = My::Module->new;
201 # $obj->{log_level} eq 'debug' $obj->{timeout} == 120
202  
203 =head1 CONFIGURATION
204  
205 =head2 Config file naming
206  
207 The config file name is derived from the class name by lowercasing it and replacing
208 C<::> with hyphens (C<->):
209  
210 My::Parent::Class => my-parent-class.yml
211  
212 The file is searched for in the directory of the C<config_file> argument, then in
213 any directories listed in C<config_dirs>.
214  
215 =head2 Section key naming inside the config file
216  
217 Inside the YAML (or JSON or conf) file, the section key uses double underscores in
218 place of C<::>:
219  
220 # my-parent-class.yml
221 ---
222 My__Parent__Class:
223 timeout: 30
224 retries: 3
225  
226 =head2 Configuration resolution order
227  
228 The following sources are merged from I<lowest> to I<highest> priority. A value
229 from a higher-priority source always wins over a lower-priority one.
230  
231 =over 4
232  
233 =item 1. B<Caller-supplied params> -- the hashref you pass to C<configure()>. Despite
234 the name "defaults", these are the I<lowest> priority and are overridden by everything
235 else.
236  
237 =item 2. B<UNIVERSAL section> -- the C<UNIVERSAL:> block in C<universal.yml> (or
238 C<universal.conf>, C<universal.json>) in your config directories, if the file exists.
239  
240 =item 3. B<Ancestor class config files> -- walked base-first through C<@ISA> using
241 the class's Method Resolution Order (MRO).
242  
243 =item 4. B<Primary config file> -- the file named by the C<config_file> argument.
244  
245 =item 5. B<Environment variables> -- named C<ClassName__key=value>, where C<::> in
246 the class name is replaced by C<__>. These are the I<highest> priority.
247  
248 =back
249  
250 =head2 UNIVERSAL configuration
251  
252 If you create C<universal.yml> in your config directory with a C<UNIVERSAL:> section,
253 those settings apply to every class that uses C<Object::Configure> unless a
254 more-specific source overrides them:
255  
256 # ~/.conf/universal.yml
257 ---
258 UNIVERSAL:
259 timeout: 30
260 logger:
261 level: warning
262  
263 =head2 Logging
264  
265 C<configure()> always sets C<$params-E<gt>{logger}> to a L<Log::Abstraction>
266 instance. You can control it by passing a C<logger> key:
267  
268 # Arrayref: messages are captured into @log (protected from merge override)
269 configure($class, { logger => \@log });
270  
271 # Hashref: options forwarded to Log::Abstraction::new()
272 configure($class, { logger => { level => 'debug', file => '/var/log/app.log' } });
273  
274 # String 'NULL': disables all logging
275 configure($class, { logger => 'NULL' });
276  
277 # Existing Log::Abstraction object: used as-is
278 configure($class, { logger => $my_logger });
279  
280 B<Note:> only arrayref loggers are stashed before the config merge and are guaranteed
281 to survive it. C<'NULL'> and blessed logger objects can be overridden by a
282 C<UNIVERSAL:> section in C<universal.yml>. See L</COMMON PITFALLS>.
283  
284 =head2 Environment variable format
285  
286 Environment variable names are constructed as:
287  
288 ClassName__key
289  
290 where C<::> in the class name is replaced by two underscores.
291  
292 export My__Module__timeout=60
293 export My__Module__logger__level=debug
294  
295 =head1 HOT RELOAD
296  
297 Hot reload lets you edit a config file and have all live objects update themselves
298 without restarting the program.
299  
300 =head2 How it works
301  
302 =over 4
303  
304 =item 1. Your constructor calls C<register_object($class, $self)> to opt in.
305  
306 =item 2. Your main program calls C<enable_hot_reload()> to fork a background watcher.
307  
308 =item 3. The watcher polls config files every C<interval> seconds and sends
309 C<SIGUSR1> to the parent when it detects a change.
310  
311 =item 4. The C<SIGUSR1> handler calls C<reload_config()>, which re-reads files and
312 updates every registered object in-place.
313  
314 =item 5. Your main program calls C<disable_hot_reload()> on shutdown.
315  
316 =back
317  
318 Private keys (those whose names start with C<_>) are never overwritten during
319 reload, so internal bookkeeping is safe.
320  
321 B<Hot reload is not supported on Windows.>
322  
323 =head1 COMMON PITFALLS
324  
325 =head2 Only arrayref loggers survive the config merge
326  
327 If you pass C<logger =E<gt> 'NULL'> or C<logger =E<gt> $existing_logger>, the
328 C<UNIVERSAL:> section in C<universal.yml> (or a site-local config file) can
329 silently override your logger during the config merge.
330  
331 Only arrayref loggers are stashed before the merge and are guaranteed to survive:
332  
333 # Protected -- will NOT be overridden by universal.yml
334 configure($class, { logger => \@captured });
335  
336 # NOT protected -- universal.yml can override these
337 configure($class, { logger => 'NULL' });
338 configure($class, { logger => $existing_obj });
339  
340 =head2 Caller-supplied keys are the LOWEST priority
341  
342 Despite being called "defaults", keys you pass directly to C<configure()> are
343 overridden by config files and environment variables:
344  
345 # My__Module__timeout=60 is set in the shell.
346 # $params->{timeout} will be 60, not 30.
347 configure('My::Module', { timeout => 30 });
348  
349 Use caller-supplied keys only as a last-resort fallback.
350  
351 =head2 register_object() pushes; it does not replace
352  
353 Calling C<register_object()> twice for the same class registers B<two> entries.
354 Both objects receive updates on every reload. The second call does not remove the
355 first.
356  
357 Object::Configure::register_object('My::Class', $obj_a);
358 Object::Configure::register_object('My::Class', $obj_b);
359 # reload_config() now updates BOTH $obj_a and $obj_b
360  
361 =head2 Private keys are never updated on hot reload
362  
363 Any key whose name begins with C<_> is skipped during C<reload_config()>.
364 A config key named C<_my_setting> in your YAML file will be ignored at reload time.
365  
366 =head2 The 'class' key appears on objects created by instantiate()
367  
368 C<instantiate()> intentionally leaves the C<class> key in the hashref passed to
369 C<$class-E<gt>new()> as a debugging aid. Your object will have a C<class>
370 attribute set to the class name:
371  
372 my $obj = Object::Configure::instantiate(class => 'My::Thing', ...);
373 print $obj->{class}; # prints 'My::Thing'
374  
375 =head2 Memoization caches are not invalidated during a run
376  
377 C<_get_inheritance_chain()> and C<_find_class_config_file()> cache their results
378 for the lifetime of the process. If you alter C<@ISA> or add config files after
379 the first C<configure()> call for a given class, the cache returns stale results.
380  
381 =head2 disable_hot_reload() blocks for up to five seconds
382  
383 It waits for the watcher process to exit (SIGTERM first, then SIGKILL). Do not
384 call it from inside a signal handler or a timing-sensitive loop.
385  
386 =head2 config_file must be developer-controlled
387  
388 The C<config_file> path is validated against directory traversal (C<../>) but is
389 not otherwise restricted. It must always be a developer-supplied path, never raw
390 user input.
391  
392 =head1 SUBROUTINES/METHODS
393  
394 =head2 configure($class, \%params)
395  
396 Merge configuration for C<$class> from all available sources and return a hashref
397 ready to pass to C<bless>. This is the core function; call it at the start of your
398 C<new()> method.
399  
400 =head3 Arguments
401  
402 =over 4
403  
404 =item * C<$class> (Required, string)
405  
406 The fully-qualified Perl class name to configure (e.g., C<'My::Module'>). Must
407 start with a letter or underscore; each C<::>-separated component must also start
408 with a letter or underscore. Digits, newlines, and shell metacharacters are rejected.
409  
410 =item * C<\%params> (Optional, hashref; defaults to C<{}>)
411  
412 Caller-supplied values. These have the I<lowest> priority and are overridden by
413 config files and environment variables. Recognized special keys:
414  
415 =over 4
416  
417 =item * C<config_file> (string, optional) -- path to the primary YAML/JSON/conf file.
418  
419 =item * C<config_dirs> (arrayref of strings, optional) -- additional directories to
420 search when C<config_file> is a bare filename with no directory component.
421  
422 =item * C<logger> (various, optional) -- see L</Logging>.
423  
424 =item * C<carp_on_warn> (boolean, optional, default 0) -- if true, the logger uses
425 C<Carp::carp> instead of C<warn>.
426  
427 =item * C<croak_on_error> (boolean, optional, default 1) -- if true, the logger uses
428 C<Carp::croak> instead of C<die>.
429  
430 =back
431  
432 =back
433  
434 =head3 Returns
435  
436 A hashref containing all merged configuration keys plus:
437  
438 =over 4
439  
440 =item * C<logger> -- a L<Log::Abstraction> instance, or the string C<'NULL'>.
441  
442 =item * C<_config_file> -- path of the primary config file (only if one was loaded).
443  
444 =item * C<_config_files> -- arrayref of every config file that was loaded (only if
445 at least one was loaded).
446  
447 =back
448  
449 =head3 Error messages
450  
451 =over 4
452  
453 =item * C<Object::Configure: configure: what class do you want to configure?> --
454 C<$class> was C<undef> or an empty string. Pass C<ref($self)> or C<__PACKAGE__>.
455  
456 =item * C<Object::Configure: configure: invalid class name (must be a valid Perl package name): CLASS> --
457 C<$class> contains characters not allowed in a Perl package name (for example, a
458 digit as the first character of a C<::>-component, a newline, or a semicolon).
459  
460 =item * C<CLASS: config_file contains path traversal sequences: FILE> --
461 C<config_file> contains a C<..> segment (e.g., C<../../etc/passwd>). The
462 C<config_file> argument must always be a developer-controlled path.
463  
464 =item * C<CLASS: FILE: OS-ERROR> --
465 C<config_file> is not readable and no C<config_dirs> were supplied. Check file
466 permissions or add C<config_dirs>.
467  
468 =item * C<Warning: Can't load configuration from FILE: DETAIL> --
469 L<Config::Abstraction> rejected the file (typically a YAML/JSON syntax error).
470 This is a warning, not fatal; C<configure()> continues with an empty config.
471  
472 =item * C<Object::Configure: config_path contains path traversal sequences: PATH> --
473 An environment variable set a C<config_path> value containing C<..>.
474  
475 =back
476  
477 =head3 API Specification
478  
479 =head4 Input
480  
481 schema => {
482 class => {
483 type => 'string',
484 required => 1,
485 description => 'Fully-qualified Perl class name',
486 pattern => qr/\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/,
487 },
488 params => {
489 type => 'hashref',
490 optional => 1,
491 default => {},
492 description => 'Caller-supplied defaults (lowest priority)',
493 schema => {
494 config_file => {
495 type => 'string',
496 optional => 1,
497 description => 'Primary config file path',
498 },
499 config_dirs => {
500 type => 'arrayref',
501 optional => 1,
502 description => 'Extra directories to search for config files',
503 },
504 logger => {
505 type => [qw(undef string arrayref hashref object)],
506 optional => 1,
507 description => 'Logger spec -- see CONFIGURATION/Logging',
508 },
509 carp_on_warn => {
510 type => 'boolean',
511 optional => 1,
512 default => 0,
513 description => 'Use Carp::carp for logger warnings',
514 },
515 croak_on_error => {
516 type => 'boolean',
517 optional => 1,
518 default => 1,
519 description => 'Use Carp::croak for logger errors',
520 },
521 },
522 },
523 }
524  
525 =head4 Output
526  
527 type => 'hashref',
528 description => 'Merged configuration hashref, ready to bless',
529 schema => {
530 logger => {
531 type => [qw(object string)],
532 description => 'Log::Abstraction instance or the string "NULL"',
533 },
534 _config_file => {
535 type => 'string',
536 optional => 1,
537 description => 'Path of the primary config file that was loaded',
538 },
539 _config_files => {
540 type => 'arrayref',
541 optional => 1,
542 description => 'All config file paths that were loaded, in load order',
543 },
544 }
545  
546 =cut
547  
548 872 ▶sub configure {
Subroutine configure: called CC=50 SCAR=39.1
Pod documented
549 872 my $class = $_[0];
550 872 ▶ my $params = $_[1] // {}; # caller's defaults; config file values override them
Condition100%2/2
$_[1] // {}
l!l
85319
MC/DC100%1/1
$_[1] // {}
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
551 872 my $array_logger; # stash for an arrayref logger spec (Config::Abstraction rejects refs)
552  
553 872 ▶ croak(__PACKAGE__, ': configure: what class do you want to configure?')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $class or $class eq "" 36 836 872
Condition100%3/3
not defined $class or $class eq ""
l!l&&r!l&&!r
1719836
MC/DC100%2/2
not defined $class or $class eq ""
not defined $class $class eq ""
Truth table100%3/3
not(A) or B
A= not defined $classB= $class eq ""
ABresult
1X1
011
000
554 if !defined($class) || $class eq '';
555  
556 # SECURITY: validate $class is a syntactically valid Perl package name before
557 # it propagates into env_prefix, croak messages, and %_chain_cache keys.
558 # Exploit mechanism: a class name containing \n, ;, or shell metacharacters
559 # can poison log lines, carp output, and env-variable lookups if not rejected here.
560 # Under Perl taint mode (-T) an unvalidated external value would also fail the
561 # taint check inside Config::Abstraction when used as an env_prefix substring.
562 836 ▶ croak(__PACKAGE__, ': configure: invalid class name (must be a valid Perl package name): ', $class)
Branch: 1 branch
BranchTrueFalseTotal
unless $class =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 149 687 836
563 unless $class =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
564  
565 # Config::Abstraction, Log::Abstraction, and Return::Set all use eval internally
566 # Protect the caller's $@ from being clobbered by our internal eval blocks.
567 687 local $@;
568  
569 # Config::Abstraction treats unknown scalar values as config file paths and will
570 # attempt to read them, corrupting coderefs and object references.
571 # Stash them here and restore after merging so callers never need this pattern.
572 687 my %stashed_values;
573 687 foreach my $key (keys %$params) {
574 1247 ▶ next if $key eq 'logger'; # logger has its own path through _build_logger
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "logger" 69 1178 1247
575 1178 my $value = $params->{$key};
576 1178 ▶ if(ref($value) eq 'CODE' || blessed($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "CODE" or builtin::blessed($value)) 57 1121 1178
Condition100%3/3
ref $value eq "CODE" or builtin::blessed($value)
l!l&&r!l&&!r
33241121
MC/DC100%2/2
ref $value eq "CODE" or builtin::blessed($value)
ref $value eq "CODE" builtin::blessed($value)
Truth table100%3/3
A or B
A= ref $value eq "CODE"B= builtin::blessed($value)
ABresult
1X1
011
000
577 57 $stashed_values{$key} = delete $params->{$key};
578 }
579 }
580  
581 675 ▶ if(exists($params->{'logger'}) && ref($params->{'logger'}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"logger"} and ref $params->{"logger"} eq "ARRAY") 20 655 675
Condition100%3/3
exists $params->{"logger"} and ref $params->{"logger"} eq "ARRAY"
!ll&&!rl&&r
6064920
MC/DC100%2/2
exists $params->{"logger"} and ref $params->{"logger"} eq "ARRAY"
exists $params->{"logger"} ref $params->{"logger"} eq "ARRAY"
Truth table100%3/3
A and B
A= exists $params->{"logger"}B= ref $params->{"logger"} eq "ARRAY"
ABresult
0X0
100
111
582 20 $array_logger = delete $params->{'logger'};
583 }
584  
585 675 my $original_class = $class;
586 675 $class =~ s/::/__/g;
587  
588 675 my $config_file = $params->{'config_file'};
589 675 my $config_dirs = $params->{'config_dirs'};
590  
591 # SECURITY (S1 - path traversal): reject config_file paths containing ".." segments
592 # before they reach Config::Abstraction. The pen-test suite confirmed C::A parses
593 # /etc/passwd as a colon-delimited conf file, injecting every user account as a
594 # config key. The ".." guard blocks the traversal vector; direct absolute paths to
595 # system files remain the caller's responsibility (document: config_file must be
596 # developer-controlled, never raw user input).
597 675 ▶ if(defined($config_file) && $config_file =~ $RE_PATH_TRAVERSAL) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config_file and $config_file =~ /$RE_PATH_TRAVERSAL/) 44 631 675
Condition100%3/3
defined $config_file and $config_file =~ /$RE_PATH_TRAVERSAL/
!ll&&!rl&&r
35327844
MC/DC100%2/2
defined $config_file and $config_file =~ /$RE_PATH_TRAVERSAL/
defined $config_file $config_file =~ /$RE_PATH_TRAVERSAL/
Truth table100%3/3
A and B
A= defined $config_fileB= $config_file =~ /$RE_PATH_TRAVERSAL/
ABresult
0X0
100
111
598 44 croak("$class: config_file contains path traversal sequences: $config_file");
599 }
600  
601 # _get_inheritance_chain returns [UNIVERSAL, ..., Base, Child] (base-first).
602 # Reversing it below gives child-first for the discovery loop; the sort
603 # that follows re-establishes base-first order for actual loading.
604 631 my @inheritance_chain = _get_inheritance_chain($original_class);
605  
606 631 my @config_files_to_load = ();
607 631 my %tracked_files = ();
608  
609 631 ▶ if($config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config_file) 254 377 631
610 # Fail early so the error message carries the OS errno string while $!
611 # is still fresh from the -r test, giving a locale-correct message.
612 254 ▶ if(!$config_dirs && !-r $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($config_dirs or -r $config_file) 17 237 254
Condition100%3/3
$config_dirs or -r $config_file
l!l&&r!l&&!r
1518617
MC/DC100%2/2
$config_dirs or -r $config_file
$config_dirs -r $config_file
Truth table100%3/3
A or B
A= $config_dirsB= -r $config_file
ABresult
1X1
011
000
613 17 croak("$class: ", $config_file, ": $!");
614 }
615  
616 237 foreach my $ancestor_class (reverse @inheritance_chain) {
617 494 my $ancestor_config_file = _find_class_config_file(
618 $ancestor_class,
619 $config_file,
620 $config_dirs
621 );
622  
623 # Primary file is added separately at the end (highest priority)
624 494 ▶ next if $ancestor_config_file && $ancestor_config_file eq $config_file;
Branch: 1 branch
BranchTrueFalseTotal
if $ancestor_config_file and $ancestor_config_file eq $config_file 57 437 494
Condition100%3/3
$ancestor_config_file and $ancestor_config_file eq $config_file
!ll&&!rl&&r
3785957
MC/DC100%2/2
$ancestor_config_file and $ancestor_config_file eq $config_file
$ancestor_config_file $ancestor_config_file eq $config_file
Truth table100%3/3
A and B
A= $ancestor_config_fileB= $ancestor_config_file eq $config_file
ABresult
0X0
100
111
625  
626 437 ▶ if($ancestor_config_file && -r $ancestor_config_file && !$tracked_files{$ancestor_config_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ancestor_config_file and -r $ancestor_config_file and not $tracked_files{$ancestor_config_file}) 58 379 437
Condition83%5/6
$ancestor_config_file and -r $ancestor_config_file and not $tracked_files{$ancestor_config_file}
!ll&&!rl&&r
379058
$ancestor_config_file and -r $ancestor_config_file
!ll&&!rl&&r
378158
MC/DC66%2/3
$ancestor_config_file and -r $ancestor_config_file and not $tracked_files{$ancestor_config_file}
$ancestor_config_file -r $ancestor_config_file not $tracked_files{$ancestor_config_file}
Truth table75%3/4
A and B and not(C)
A= $ancestor_config_fileB= -r $ancestor_config_fileC= not $tracked_files{$ancestor_config_file}
ABCresult
0XX0
10X0
1100
1111
627 58 push @config_files_to_load, { file => $ancestor_config_file, class => $ancestor_class };
628 58 $tracked_files{$ancestor_config_file} = 1;
629 58 ▶ $_config_file_stats{$ancestor_config_file} = stat($ancestor_config_file)
Branch: 1 branch
BranchTrueFalseTotal
if -f $ancestor_config_file 58 0 58
630 if -f $ancestor_config_file;
631 }
632 }
633  
634 # Premise: $config_file is true (we are inside if($config_file) above).
635 237 ▶ if(!$tracked_files{$config_file} && -r $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $tracked_files{$config_file} and -r $config_file) 97 140 237
Condition66%2/3
not $tracked_files{$config_file} and -r $config_file
!ll&&!rl&&r
014097
MC/DC50%1/2
not $tracked_files{$config_file} and -r $config_file
not $tracked_files{$config_file} -r $config_file
Truth table66%2/3
not(A) and B
A= not $tracked_files{$config_file}B= -r $config_file
ABresult
0X0
100
111
636 97 push @config_files_to_load, { file => $config_file, class => $original_class };
637 97 $tracked_files{$config_file} = 1;
638 97 ▶ $_config_file_stats{$config_file} = stat($config_file)
Branch: 1 branch
BranchTrueFalseTotal
if -f $config_file 93 4 97
639 if -f $config_file;
640 }
641  
642 237 ▶ if(!scalar(@config_files_to_load)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @config_files_to_load) 107 130 237
643 107 foreach my $dir (@{$config_dirs}) {
644 145 my $candidate = File::Spec->catfile($dir, $config_file);
645 145 ▶ if(-r $candidate) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $candidate) 89 56 145
646 89 push @config_files_to_load, { file => $candidate, class => $original_class };
647 89 last; # stop at first readable hit; later dirs are lower priority
648 }
649 }
650 }
651 }
652  
653 614 ▶ if(@config_files_to_load) {
Branch: 2 branches
BranchTrueFalseTotal
if (@config_files_to_load) { } 219 395 614
elsif (my $config = 'Config::Abstraction'->new('env_prefix', "${class}__")) { } 14 381 395
654 # Sort so that base-class files are loaded before child files.
655 # %class_order is keyed on the chain (UNIVERSAL=0, ..., Child=N).
656 219 my %class_order;
657 219 for my $i (0 .. $#inheritance_chain) {
658 458 $class_order{ $inheritance_chain[$i] } = $i;
659 }
660 @config_files_to_load = sort {
661 219 ▶ ($class_order{ $a->{class} } // 999) <=> ($class_order{ $b->{class} } // 999)
Condition50%2/4
$class_order{$Object::Configure::a->{"class"}} // 999
l!l
310
$class_order{$Object::Configure::b->{"class"}} // 999
l!l
310
MC/DC0%0/1
$class_order{$Object::Configure::a->{"class"}} // 999
$class_order{$Object::Configure::a->{"class"}}
MC/DC0%0/1
$class_order{$Object::Configure::b->{"class"}} // 999
$class_order{$Object::Configure::b->{"class"}}
Truth table50%1/2
A
A= $class_order{$Object::Configure::a->{"class"}}
Aresult
11
00
Truth table50%1/2
A
A= $class_order{$Object::Configure::b->{"class"}}
Aresult
11
00
662 } @config_files_to_load;
663  
664 219 my $merged_params = { %$params };
665  
666 219 foreach my $config_info (@config_files_to_load) {
667 244 my $cfg_file = $config_info->{file};
668 244 my $cfg_class = $config_info->{class};
669 244 my $section_name = $cfg_class;
670 244 $section_name =~ s/::/__/g;
671  
672 # Load only the specific file; do not re-pass config_dirs to avoid
673 # re-scanning directories and picking up the wrong file for this class.
674 244 my $config = Config::Abstraction->new(
675 config_file => $cfg_file,
676 env_prefix => "${section_name}__"
677 );
678  
679 244 ▶ if($config) {
Branch: 2 branches
BranchTrueFalseTotal
if ($config) { } 233 11 244
elsif ($@) { } 7 4 11
680 233 my $this_config = $config->merge_defaults(
681 defaults => {},
682 section => $section_name,
683 merge => 1,
684 deep => 1
685 );
686 233 $merged_params = _deep_merge($merged_params, $this_config);
687 } elsif($@) {
688 7 carp("Warning: Can't load configuration from $cfg_file: $@");
689 }
690 }
691  
692 219 $params = $merged_params;
693 } elsif(my $config = Config::Abstraction->new(env_prefix => "${class}__")) {
694 # No config file: honour environment variables across the full ancestor chain.
695 14 my $merged_config = {};
696  
697 # Iterate base-first so that each more-specific class overrides the more
698 # general one: UNIVERSAL -> GrandParent -> Parent -> Child.
699 14 foreach my $ancestor_class (@inheritance_chain) {
700 29 my $section_name = $ancestor_class;
701 29 $section_name =~ s/::/__/g;
702  
703 29 my $ancestor_env_config = Config::Abstraction->new(env_prefix => "${section_name}__");
704 29 ▶ if($ancestor_env_config) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ancestor_env_config) 15 14 29
705 15 my $ancestor_config = $ancestor_env_config->merge_defaults(
706 defaults => {},
707 section => $section_name,
708 merge => 1,
709 deep => 1
710 );
711 15 $merged_config = _deep_merge($merged_config, $ancestor_config);
712 }
713 }
714  
715 14 $params = $config->merge_defaults(
716 defaults => $params,
717 section => $class,
718 merge => 1,
719 deep => 1
720 );
721  
722 14 $params = _deep_merge($merged_config, $params);
723  
724 # SECURITY (S1 extension - config_path traversal + taint):
725 # config_path arrives from Config::Abstraction, which reads %ENV. Under
726 # taint mode (-T) the value is tainted; any syscall with a tainted argument
727 # is fatal. Apply the same $RE_PATH_TRAVERSAL guard as config_file (line 491)
728 # before any filesystem probe, so the two guards stay in sync.
729 # Exploit: ClassName__config_path=../../etc/shadow causes the hot-reload watcher
730 # to stat() and track an arbitrary system file, leaking mtime changes via SIGUSR1.
731 14 ▶ if($params->{config_path}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"config_path"}) 2 12 14
732 croak(__PACKAGE__, ': config_path contains path traversal sequences: ',
733 $params->{config_path})
734 2 ▶ if $params->{config_path} =~ $RE_PATH_TRAVERSAL;
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"config_path"} =~ /$RE_PATH_TRAVERSAL/ 0 2 2
735 $_config_file_stats{ $params->{config_path} } = stat($params->{config_path})
736 2 ▶ if -f $params->{config_path};
Branch: 1 branch
BranchTrueFalseTotal
if -f $params->{"config_path"} 2 0 2
737 }
738 }
739  
740 614 ▶ my $croak_on_error = exists($params->{'croak_on_error'}) ? $params->{'croak_on_error'} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'croak_on_error'} ? : 2 612 614
741 614 ▶ my $carp_on_warn = exists($params->{'carp_on_warn'}) ? $params->{'carp_on_warn'} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'carp_on_warn'} ? : 6 608 614
742  
743 # User-supplied logger always wins over config-file logger.
744 # $array_logger is defined when the caller passed an arrayref; it was deleted from
745 # $params before config merging so the merge couldn't overwrite it. Config-file logger
746 # (a hashref from YAML) is only used when the caller gave no explicit logger at all.
747 614 ▶ my $logger_spec = defined($array_logger) ? $array_logger : $params->{'logger'};
Branch: 1 branch
BranchTrueFalseTotal
defined $array_logger ? : 20 594 614
748 614 $params->{'logger'} = _build_logger($logger_spec, $carp_on_warn);
749  
750 614 ▶ if(!exists($params->{_config_file})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{"_config_file"}) 607 7 614
751 607 ▶ $params->{_config_file} = $config_file if defined $config_file;
Branch: 1 branch
BranchTrueFalseTotal
if defined $config_file 258 349 607
752 }
753 614 ▶ if(!exists($params->{_config_files})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{"_config_files"}) 608 6 614
754 608 ▶ $params->{_config_files} = [ map { $_->{file} } @config_files_to_load ]
Branch: 1 branch
BranchTrueFalseTotal
if @config_files_to_load 217 391 608
755 if @config_files_to_load;
756 }
757  
758 # Re-attach stashed coderefs/objects via hash slice
759 614 ▶ @{$params}{ keys %stashed_values } = values %stashed_values if %stashed_values;
Branch: 1 branch
BranchTrueFalseTotal
if %stashed_values 37 577 614
760  
761 614 return Return::Set::set_return($params, { 'type' => 'hashref' });
762 }
763  
764 =head2 instantiate(%params)
765  
766 Configure and instantiate a third-party class without modifying the class itself.
767  
768 C<instantiate> is a convenience wrapper: it calls C<configure>, passes the merged
769 hashref to C<$class-E<gt>new(...)>, and optionally registers the result for hot reload.
770 Use it when you need runtime configuration for a class whose source you cannot change.
771  
772 =head3 Arguments
773  
774 Takes a flat hash (not a hashref). Recognized keys:
775  
776 =over 4
777  
778 =item * C<class> (Required, string)
779  
780 The fully-qualified class name to instantiate (e.g., C<'LWP::UserAgent'>). The class
781 must already be loaded and must have a C<new> method that accepts a hashref.
782  
783 =item * All other keys
784  
785 Passed through to C<configure()> as C<\%params>. See L</configure($class, \%params)>
786 for the full list.
787  
788 =back
789  
790 =head3 Returns
791  
792 A blessed object of type C<$class>.
793  
794 B<Note:> The returned object's hash will contain a C<class> key holding the class name.
795 This is intentional -- it is left in the hash as a debugging aid so you can always
796 see which class an object came from. Do not depend on its absence.
797  
798 =head3 Side Effects
799  
800 =over 4
801  
802 =item * Calls C<configure($class, \%params)> -- see its side effects.
803  
804 =item * Calls C<$class-E<gt>new(\%merged_params)>.
805  
806 =item * If the config produced a C<_config_file>, calls C<register_object($class, $obj)>
807 so the object participates in hot reload.
808  
809 =back
810  
811 =head3 Error messages
812  
813 Same as C<configure()>. In addition:
814  
815 =over 4
816  
817 =item * Any exception thrown by C<$class-E<gt>new(...)> propagates unchanged.
818  
819 =back
820  
821 =head3 Usage Example
822  
823 use Object::Configure;
824  
825 my $ua = Object::Configure::instantiate(
826 class => 'LWP::UserAgent',
827 config_file => 'lwp.yml',
828 config_dirs => ['/etc/myapp'],
829 timeout => 30,
830 );
831  
832 =head3 API Specification
833  
834 =head4 Input
835  
836 schema => {
837 class => {
838 type => 'string',
839 required => 1,
840 description => 'Fully-qualified class name; must respond to new(hashref)',
841 },
842 # all other keys forwarded to configure()
843 }
844  
845 =head4 Output
846  
847 type => 'object',
848 description => 'Blessed instance of $class, with class key present in hash',
849 notes => 'class key intentionally left in hash as a debugging aid',
850  
851 =cut
852  
853 sub instantiate
854 33 ▶{
Subroutine instantiate: called CC=2 SCAR=6.9
Pod documented
855 33 my $params = Params::Get::get_params('class', @_);
856  
857 # 'class' is read into $class then left in $params,
858 # 'class' propagates into configure() as a spurious config key and
859 # ends up in the blessed object's hash, allowing the caller to see
860 # that has come from what, helping debugging
861 33 my $class = $params->{'class'};
862 33 $params = configure($class, $params);
863  
864 28 my $obj = $class->new($params);
865  
866 23 ▶ register_object($class, $obj) if $params->{_config_file};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"_config_file"} 12 11 23
867  
868 23 return $obj;
869 }
870  
871 =head1 HOT RELOAD FEATURES
872  
873 =head2 enable_hot_reload(%opts)
874  
875 Fork a background watcher that sends SIGUSR1 to the parent whenever a tracked
876 configuration file changes on disk. Objects registered via C<register_object()>
877 then have their configuration reloaded automatically.
878  
879 B<UNIX only.> On Windows this function is a silent no-op (SIGUSR1 does not exist).
880  
881 =head3 Arguments
882  
883 Takes a flat hash. All keys are optional.
884  
885 =over 4
886  
887 =item * C<interval> (integer E<gt>= 1, default: 10)
888  
889 Seconds between file-modification checks. Lower values detect changes faster
890 but use more CPU. Zero or negative values are silently replaced with the default.
891  
892 =item * C<callback> (coderef, optional)
893  
894 Called in the parent process after each successful config reload. Useful for
895 logging or flushing caches.
896  
897 =back
898  
899 =head3 Returns
900  
901 The PID of the watcher child process (integer E<gt> 0), or C<undef>/empty if hot
902 reload was already active (idempotent: a second call returns immediately without
903 forking again).
904  
905 =head3 Side Effects
906  
907 =over 4
908  
909 =item * Forks a child process.
910  
911 =item * The child polls C<%_config_file_stats> and sends C<SIGUSR1> to the parent
912 on mtime change.
913  
914 =item * Stores C<{pid =E<gt> $pid, callback =E<gt> $cb}> in C<%_config_watchers>.
915  
916 =back
917  
918 =head3 Error messages
919  
920 =over 4
921  
922 =item * C<Failed to fork config watcher: OS-ERROR> -- C<fork()> returned C<undef>.
923 Check system resource limits (C<ulimit -u>).
924  
925 =back
926  
927 =head3 Usage Example
928  
929 Object::Configure::enable_hot_reload(
930 interval => 5,
931 callback => sub { warn "Config reloaded at " . localtime . "\n" },
932 );
933  
934 while (1) { sleep 1 } # watcher runs in the background
935  
936 =head3 API Specification
937  
938 =head4 Input
939  
940 schema => {
941 interval => {
942 type => 'integer',
943 optional => 1,
944 default => 10,
945 minimum => 1,
946 description => 'Poll interval in seconds',
947 },
948 callback => {
949 type => 'coderef',
950 optional => 1,
951 description => 'Called in parent after each reload',
952 },
953 }
954  
955 =head4 Output
956  
957 type => [qw(integer undef)],
958 description => 'PID of watcher child; undef/empty if already active',
959 condition => 'value > 0 when defined',
960  
961 enable_hot_reload : Interval x Callback -> PID | empty
962  
963 Pre:
964 interval >= 1 (enforced: negative/zero replaced with DEFAULT_INTERVAL)
965 _config_watchers = {}
966  
967 Post:
968 _config_watchers.pid = result
969 _config_watchers.callback = callback
970 (forall t: t mod interval = 0 =>
971 (exists f in _config_file_stats: mtime(f) changed =>
972 send_signal(SIGUSR1, parent_pid)))
973  
974 =cut
975  
976 65 ▶sub enable_hot_reload {
Subroutine enable_hot_reload: called CC=6 SCAR=18.1
Pod documented
977 65 my %params = @_;
978  
979 # SECURITY (S4): use defined-or (//) not truth-or (||) so that interval=>0
980 # is not silently replaced. Then guard: a zero or negative interval would make
981 # the child busy-loop, consuming 100% CPU (internal DoS vector).
982 65 ▶ my $interval = $params{interval} // $DEFAULT_INTERVAL;
Condition66%2/3
$params{"interval"} // $DEFAULT_INTERVAL
l!l&&r!l&&!r
5708
MC/DC50%1/2
$params{"interval"} // $DEFAULT_INTERVAL
$params{"interval"} $DEFAULT_INTERVAL
Truth table66%2/3
A // B
A= $params{"interval"}B= $DEFAULT_INTERVAL
ABresult
1X1
011
000
983 65 ▶ $interval = $DEFAULT_INTERVAL unless $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval > 0 16 49 65
984 65 my $callback = $params{callback};
985  
986 65 ▶ return if %_config_watchers; # already watching; avoid double-fork
Branch: 1 branch
BranchTrueFalseTotal
if %Object::Configure::_config_watchers 6 59 65
987  
988 # Handle fork failure ourselves so the documented croak message is used
989 39 ▶ no autodie qw(fork);
Subroutine BEGIN: called CC=1 SCAR=0.0
990  
991 59 ▶ if(my $pid = fork()) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $pid = fork) { } 43 16 59
elsif (defined $pid) { } 16 0 16
992 43 $_config_watchers{pid} = $pid;
993 43 $_config_watchers{callback} = $callback;
994 43 return $pid;
995 } elsif(defined $pid) {
996 # Child: run forever, signal parent on change
997 16 _run_config_watcher($interval, $callback);
998 0 exit 0;
999 } else {
1000 0 croak("Failed to fork config watcher: $!");
1001 }
1002 }
1003  
1004 =head2 disable_hot_reload()
1005  
1006 Stop the background watcher and clear hot-reload state.
1007  
1008 Safe to call when hot reload is not active (no-op). After this call,
1009 configuration files are no longer monitored and C<%_config_watchers> is empty.
1010  
1011 =head3 Arguments
1012  
1013 None.
1014  
1015 =head3 Returns
1016  
1017 Nothing (void).
1018  
1019 =head3 Side Effects
1020  
1021 =over 4
1022  
1023 =item * Sends SIGTERM to the watcher child.
1024  
1025 =item * Polls for up to C<$KILL_TIMEOUT> seconds (default: 5); escalates to SIGKILL
1026 if the child has not exited by then.
1027  
1028 =item * Calls C<waitpid> to reap the child.
1029  
1030 =item * Clears C<%_config_watchers>.
1031  
1032 =back
1033  
1034 B<Blocking>: this function may take up to five seconds if the watcher ignores SIGTERM.
1035  
1036 =head3 API Specification
1037  
1038 =head4 Input
1039  
1040 schema => {} # no arguments
1041  
1042 =head4 Output
1043  
1044 type => 'void'
1045  
1046 =cut
1047  
1048 107 ▶sub disable_hot_reload {
Subroutine disable_hot_reload: called CC=10 SCAR=23.3
Pod documented
1049 # The watcher may already have exited, so a failed kill() is expected
1050 # and must not stop %_config_watchers from being cleared
1051 39 ▶ no autodie qw(kill);
Subroutine BEGIN: called CC=1 SCAR=0.0
1052  
1053 ## MUTANT_SKIP_BEGIN
1054 107 ▶ if(my $pid = $_config_watchers{pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = $Object::Configure::_config_watchers{"pid"}) 51 56 107
1055 # SECURITY (S3 - PID safety):
1056 # $pid > 1 excludes PID 0 (sends SIGTERM to whole process group - DoS)
1057 # and PID 1 (init - catastrophic as root).
1058 # $pid != $$ prevents self-signaling if %_config_watchers is corrupted.
1059 # Exploit mechanism: if global state is poisoned with pid=0 or pid=1,
1060 # kill('TERM', 0) signals every process in the group; kill('TERM', 1) kills
1061 # init as root. Both are now rejected at the comparison level.
1062 51 ▶ if($pid =~ /\A[0-9]+\z/ && $pid > 1 && $pid != $$) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid =~ /\A[0-9]+\z/ and $pid > 1 and $pid != $$) 44 7 51
Condition100%6/6
$pid =~ /\A[0-9]+\z/ and $pid > 1 and $pid != $$
!ll&&!rl&&r
5244
$pid =~ /\A[0-9]+\z/ and $pid > 1
!ll&&!rl&&r
2346
MC/DC100%3/3
$pid =~ /\A[0-9]+\z/ and $pid > 1 and $pid != $$
$pid =~ /\A[0-9]+\z/ $pid > 1 $pid != $$
Truth table100%4/4
A and B and C
A= $pid =~ /\A[0-9]+\z/B= $pid > 1C= $pid != $$
ABCresult
0XX0
10X0
1100
1111
1063 44 kill('TERM', $pid);
1064  
1065 # Poll up to KILL_TIMEOUT seconds; escalate to SIGKILL if SIGTERM is ignored.
1066 # SIGKILL cannot be caught or deferred so the subsequent waitpid is always safe.
1067 44 my $deadline = time() + $KILL_TIMEOUT;
1068 44 my $kid;
1069 44 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$kid == 0 and &Object::Configure::time() < $deadline and do { do { $kid = waitpid($pid, 1); if ($kid == 0 and &Object::Configure::time() < $deadline) { select undef, undef, undef, $POLL_SLEEP; } } } 248 44 292
Condition66%2/3
$kid == 0 and &Object::Configure::time() < $deadline
!ll&&!rl&&r
440248
MC/DC50%1/2
$kid == 0 and &Object::Configure::time() < $deadline
$kid == 0 &Object::Configure::time() < $deadline
Truth table66%2/3
A and B
A= $kid == 0B= &Object::Configure::time() < $deadline
ABresult
0X0
100
111
1070 292 $kid = waitpid($pid, WNOHANG);
1071 292 ▶ if($kid == 0 && time() < $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kid == 0 and &Object::Configure::time() < $deadline) 248 44 292
Condition66%2/3
$kid == 0 and &Object::Configure::time() < $deadline
!ll&&!rl&&r
440248
MC/DC50%1/2
$kid == 0 and &Object::Configure::time() < $deadline
$kid == 0 &Object::Configure::time() < $deadline
Truth table66%2/3
A and B
A= $kid == 0B= &Object::Configure::time() < $deadline
ABresult
0X0
100
111
1072 248 select undef, undef, undef, $POLL_SLEEP;
1073 }
1074 } while($kid == 0 && time() < $deadline);
1075  
1076 44 ▶ if($kid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kid == 0) 0 44 44
1077 0 kill('KILL', $pid);
1078 0 waitpid($pid, 0);
1079 }
1080 }
1081 51 %_config_watchers = ();
1082 }
1083 ## MUTANT_SKIP_END
1084 }
1085  
1086 =head2 reload_config()
1087  
1088 Immediately reload configuration from disk for every registered object.
1089  
1090 Normally called automatically by the SIGUSR1 handler. You may call it manually
1091 to force a reload (e.g., in tests or on a custom signal).
1092  
1093 =head3 Arguments
1094  
1095 None.
1096  
1097 =head3 Returns
1098  
1099 An integer E<gt>= 0: the count of objects whose configuration was successfully
1100 reloaded.
1101  
1102 =head3 Side Effects
1103  
1104 =over 4
1105  
1106 =item * Reads config files from disk for each registered object.
1107  
1108 =item * Updates non-private keys (those not starting with C<_>) in-place on
1109 each live object.
1110  
1111 =item * Prunes dead weak references from C<%_object_registry>.
1112  
1113 =item * Emits a C<carp> warning (not a croak) if reload fails for any individual
1114 object; other objects are still processed.
1115  
1116 =back
1117  
1118 =head3 API Specification
1119  
1120 =head4 Input
1121  
1122 schema => {} # no arguments
1123  
1124 =head4 Output
1125  
1126 type => 'integer',
1127 description => 'Count of objects successfully reloaded',
1128 condition => 'value >= 0',
1129  
1130 =cut
1131  
1132 80 ▶sub reload_config {
Subroutine reload_config: called CC=6 SCAR=17.9
Pod documented
1133 80 my $reloaded_count = 0;
1134  
1135 80 foreach my $class_key (keys %_object_registry) {
1136 78 my $objects = $_object_registry{$class_key};
1137  
1138 78 @$objects = grep { defined $$_ } @$objects; # prune garbage-collected weak refs (check referent, not the ref-to-scalar itself)
1139  
1140 78 foreach my $obj_ref (@$objects) {
1141 70 ▶ if(my $obj = $$obj_ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $obj = $$obj_ref) 70 0 70
1142 # Protect the caller's $@ from being clobbered by our internal eval blocks.
1143 70 local $@;
1144 70 eval {
1145 70 _reload_object_config($obj);
1146 65 $reloaded_count++;
1147 };
1148 70 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 5 65 70
1149 5 carp("Failed to reload config for object: $@");
1150 }
1151 }
1152 }
1153  
1154 78 ▶ delete $_object_registry{$class_key} unless @$objects;
Branch: 1 branch
BranchTrueFalseTotal
unless @$objects 19 59 78
1155 }
1156  
1157 80 return $reloaded_count;
1158 }
1159  
1160 =head2 register_object($class, $obj)
1161  
1162 Register a blessed object so it receives configuration updates when files change.
1163  
1164 B<Push semantics>: each call I<appends> a new entry to the registry for C<$class>.
1165 It does not replace a previous entry. Multiple objects of the same class are all
1166 tracked and all reloaded.
1167  
1168 =head3 Arguments
1169  
1170 =over 4
1171  
1172 =item * C<$class> (Required, string)
1173  
1174 The class name used to organise the registry. Typically C<ref($self)> or the
1175 calling package name.
1176  
1177 =item * C<$obj> (Required, blessed reference)
1178  
1179 The object to register. B<Must be a blessed reference.> Passing an unblessed
1180 hashref or any other unblessed value causes an immediate C<croak>.
1181  
1182 =back
1183  
1184 =head3 Returns
1185  
1186 Nothing (void).
1187  
1188 =head3 Side Effects
1189  
1190 =over 4
1191  
1192 =item * Pushes a weak reference to C<$obj> onto C<$_object_registry{$class}>.
1193  
1194 =item * On the first call ever (for any class): saves the current C<$SIG{USR1}>
1195 and installs Object::Configure's handler. On UNIX, the handler calls
1196 C<reload_config()> then chains to the prior handler. On Windows, signal
1197 installation is skipped but C<$_original_usr1_handler> is still set.
1198  
1199 =back
1200  
1201 =head3 Error messages
1202  
1203 =over 4
1204  
1205 =item * C<Object::Configure::register_object: Usage ($class, $obj)> --
1206 either C<$class> or C<$obj> was C<undef>.
1207  
1208 =item * C<Object::Configure::register_object: $obj must be a blessed reference> --
1209 C<$obj> was defined but not blessed. This guard prevents DoS via registry flooding
1210 (reloading thousands of unblessed entries on every SIGUSR1).
1211  
1212 =back
1213  
1214 =head3 Usage Example
1215  
1216 package My::Module;
1217 use Object::Configure;
1218  
1219 sub new {
1220 my ($class, %args) = @_;
1221 my $params = Object::Configure::configure($class, \%args);
1222 my $self = bless $params, $class;
1223 Object::Configure::register_object($class, $self)
1224 if $self->{_config_file};
1225 return $self;
1226 }
1227  
1228 =head3 API Specification
1229  
1230 =head4 Input
1231  
1232 schema => {
1233 class => {
1234 type => 'string',
1235 required => 1,
1236 description => 'Class name for registry key',
1237 },
1238 obj => {
1239 type => 'object',
1240 required => 1,
1241 description => 'Blessed object to register; unblessed refs are rejected',
1242 blessed => 1,
1243 },
1244 }
1245  
1246 =head4 Output
1247  
1248 type => 'void'
1249  
1250 =cut
1251  
1252 sub register_object
1253 171 ▶{
Subroutine register_object: called CC=7 SCAR=19.5
Pod documented
1254 171 my ($class, $obj) = @_;
1255  
1256 171 ▶ croak(__PACKAGE__, '::register_object: Usage ($class, $obj)')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and defined $obj 29 142 171
Condition100%3/3
defined $class and defined $obj
!ll&&!rl&&r
1613142
MC/DC100%2/2
defined $class and defined $obj
defined $class defined $obj
Truth table100%3/3
A and B
A= defined $classB= defined $obj
ABresult
0X0
100
111
1257 unless defined($class) && defined($obj);
1258  
1259 # SECURITY: enforce the API contract (POD: "$obj must be a blessed reference").
1260 # Accepting unblessed refs silently would allow DoS via registry flooding: an
1261 # adversary or buggy caller can push thousands of unblessed entries; reload_config()
1262 # iterates every entry on every SIGUSR1, degrading throughput proportionally.
1263 142 ▶ croak(__PACKAGE__, '::register_object: $obj must be a blessed reference')
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($obj) 6 136 142
1264 unless blessed($obj);
1265  
1266 136 my $obj_ref = \$obj;
1267 136 weaken($$obj_ref);
1268 136 push @{ $_object_registry{$class} }, $obj_ref;
1269  
1270 # Install SIGUSR1 handler exactly once. We save the previous handler so
1271 # we can chain to it (another module may have installed one) and restore it
1272 # on shutdown. On Windows SIGUSR1 does not exist so we skip the signal work
1273 # but still save $_original_usr1_handler so restore_signal_handlers is safe.
1274 136 ▶ if(!defined $_original_usr1_handler) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Object::Configure::_original_usr1_handler) 60 76 136
1275 60 ▶ $_original_usr1_handler = $SIG{USR1} || $SIG_DEFAULT;
Condition66%2/3
$SIG{'USR1'} || $SIG_DEFAULT
l!l&&r!l&&!r
42180
MC/DC0%0/2
$SIG{'USR1'} || $SIG_DEFAULT
$SIG{'USR1'} $SIG_DEFAULT
Truth table66%2/3
A || B
A= $SIG{'USR1'}B= $SIG_DEFAULT
ABresult
1X1
011
000
1276  
1277 60 ▶ return if $^O eq $OS_WINDOWS;
Branch: 1 branch
BranchTrueFalseTotal
if $^O eq $OS_WINDOWS 0 60 60
1278  
1279 15 ▶ $SIG{USR1} = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1280 15 reload_config();
1281 15 ▶ $_config_watchers{callback}->() if $_config_watchers{callback};
Branch: 1 branch
BranchTrueFalseTotal
if $Object::Configure::_config_watchers{"callback"} 1 14 15
1282  
1283 15 ▶ if(ref($_original_usr1_handler) eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $Object::Configure::_original_usr1_handler eq 'CODE') { } 8 7 15
elsif ($Object::Configure::_original_usr1_handler eq $SIG_DEFAULT or $Object::Configure::_original_usr1_handler eq $SIG_IGNORE) { } 5 2 7
1284 8 $_original_usr1_handler->();
1285 ▶ } elsif($_original_usr1_handler eq $SIG_DEFAULT
Condition66%2/3
$Object::Configure::_original_usr1_handler eq $SIG_DEFAULT or $Object::Configure::_original_usr1_handler eq $SIG_IGNORE
l!l&&r!l&&!r
052
MC/DC50%1/2
$Object::Configure::_original_usr1_handler eq $SIG_DEFAULT or $Object::Configure::_original_usr1_handler eq $SIG_IGNORE
$Object::Configure::_original_usr1_handler eq $SIG_DEFAULT $Object::Configure::_original_usr1_handler eq $SIG_IGNORE
Truth table66%2/3
A or B
A= $Object::Configure::_original_usr1_handler eq $SIG_DEFAULTB= $Object::Configure::_original_usr1_handler eq $SIG_IGNORE
ABresult
1X1
011
000
1286 || $_original_usr1_handler eq $SIG_IGNORE) {
1287 # DEFAULT for USR1 is typically a no-op; IGNORE means discard
1288 } else {
1289 2 carp("Object::Configure: Cannot chain to non-code USR1 handler: $_original_usr1_handler");
1290 }
1291 60 };
1292 }
1293  
1294 136 return;
1295 }
1296  
1297 =head2 restore_signal_handlers()
1298  
1299 Restore C<$SIG{USR1}> to the handler that was in place before
1300 C<register_object()> installed the hot-reload handler, and clear
1301 C<$_original_usr1_handler>.
1302  
1303 Safe to call even when Object::Configure never installed a handler (no-op).
1304 On Windows this function has no effect (SIGUSR1 does not exist there).
1305  
1306 =head3 Arguments
1307  
1308 None.
1309  
1310 =head3 Returns
1311  
1312 Nothing (void).
1313  
1314 =head3 Side Effects
1315  
1316 =over 4
1317  
1318 =item * Sets C<$SIG{USR1}> back to its saved value (UNIX only).
1319  
1320 =item * Sets C<$_original_usr1_handler> to C<undef>.
1321  
1322 =back
1323  
1324 =head3 API Specification
1325  
1326 =head4 Input
1327  
1328 schema => {} # no arguments
1329  
1330 =head4 Output
1331  
1332 type => 'void'
1333  
1334 =cut
1335  
1336 sub restore_signal_handlers
1337 92 ▶{
Subroutine restore_signal_handlers: called CC=3 SCAR=11.0
Pod documented
1338 92 ▶ if(defined $_original_usr1_handler) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Object::Configure::_original_usr1_handler) 48 44 92
1339 48 ▶ $SIG{USR1} = $_original_usr1_handler unless $^O eq $OS_WINDOWS;
Branch: 1 branch
BranchTrueFalseTotal
unless $^O eq $OS_WINDOWS 48 0 48
1340 48 $_original_usr1_handler = undef;
1341 }
1342  
1343 92 return;
1344 }
1345  
1346 =head2 get_signal_handler_info()
1347  
1348 Return a snapshot of the current signal-handler and hot-reload state.
1349 This is a debugging aid; normal application code does not need to call it.
1350  
1351 =head3 Arguments
1352  
1353 None.
1354  
1355 =head3 Returns
1356  
1357 A hashref with these keys:
1358  
1359 =over 4
1360  
1361 =item * C<original_usr1> -- the C<$SIG{USR1}> value that existed before
1362 Object::Configure installed its handler, or C<undef> if no handler was saved yet.
1363  
1364 =item * C<current_usr1> -- the currently installed C<$SIG{USR1}> handler (coderef,
1365 C<'DEFAULT'>, C<'IGNORE'>, or C<undef>).
1366  
1367 =item * C<hot_reload_active> -- C<1> if C<$_original_usr1_handler> is defined,
1368 C<''> otherwise.
1369  
1370 =item * C<watcher_pid> -- the PID of the background watcher child, or C<undef>
1371 if C<enable_hot_reload()> has not been called (or the watcher has been stopped).
1372  
1373 =back
1374  
1375 =head3 Usage Example
1376  
1377 use Object::Configure;
1378 use Data::Dumper;
1379  
1380 Object::Configure::enable_hot_reload();
1381 print Dumper(Object::Configure::get_signal_handler_info());
1382 # {
1383 # original_usr1 => 'DEFAULT',
1384 # current_usr1 => sub { ... },
1385 # hot_reload_active => 1,
1386 # watcher_pid => 12345,
1387 # }
1388  
1389 =head3 API Specification
1390  
1391 =head4 Input
1392  
1393 schema => {} # no arguments
1394  
1395 =head4 Output
1396  
1397 type => 'hashref',
1398 description => 'Snapshot of signal-handler and watcher state',
1399 schema => {
1400 original_usr1 => { type => [qw(coderef string undef)] },
1401 current_usr1 => { type => [qw(coderef string undef)] },
1402 hot_reload_active => { type => 'boolean' },
1403 watcher_pid => { type => [qw(integer undef)] },
1404 }
1405  
1406 =cut
1407  
1408 18 ▶sub get_signal_handler_info {
Subroutine get_signal_handler_info: called CC=1 SCAR=0.0
Pod documented
1409 return {
1410 original_usr1 => $_original_usr1_handler,
1411 current_usr1 => $SIG{USR1},
1412 hot_reload_active => defined $_original_usr1_handler,
1413 watcher_pid => $_config_watchers{pid},
1414 18 };
1415 }
1416  
1417 # ----------------------------------------------------------------------------
1418 # Private helpers
1419 # All routines below are implementation details; callers must not rely on them.
1420 # ----------------------------------------------------------------------------
1421  
1422 # Purpose: Consolidate all logger-creation paths into one place.
1423 # Called from configure() and _reconfigure_logger() to eliminate
1424 # the duplication that existed between the two.
1425 # Entry: $spec may be: undef (want default), the string 'NULL' (no logging),
1426 # an ARRAY ref (log-capture array), a HASH ref (options for Log::Abstraction),
1427 # a pre-built Log::Abstraction instance (pass through), or any other
1428 # scalar (treated as a logger name / file path).
1429 # $carp_on_warn is a boolean controlling Carp::carp integration.
1430 # Exit: Returns a Log::Abstraction instance, or the string 'NULL'.
1431 # Side: May allocate a new Log::Abstraction object.
1432 664 ▶sub _build_logger {
Subroutine _build_logger: called CC=9 SCAR=22.0
1433 664 my ($spec, $carp_on_warn) = @_;
1434 664 ▶ $carp_on_warn //= 0;
Condition50%1/2
$carp_on_warn //= 0
l!l
6640
MC/DC0%0/1
$carp_on_warn //= 0
$carp_on_warn
Truth table50%1/2
A
A= $carp_on_warn
Aresult
11
00
1435  
1436 664 ▶ return Log::Abstraction->new(carp_on_warn => $carp_on_warn)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 540 124 664
1437 unless defined $spec;
1438  
1439 124 ▶ return $LOGGER_NULL
Branch: 1 branch
BranchTrueFalseTotal
if not ref $spec and $spec eq $LOGGER_NULL 21 103 124
Condition100%3/3
not ref $spec and $spec eq $LOGGER_NULL
!ll&&!rl&&r
881521
MC/DC100%2/2
not ref $spec and $spec eq $LOGGER_NULL
not ref $spec $spec eq $LOGGER_NULL
Truth table100%3/3
not(A) and B
A= not ref $specB= $spec eq $LOGGER_NULL
ABresult
0X0
100
111
1440 if !ref($spec) && $spec eq $LOGGER_NULL;
1441  
1442 103 ▶ return $spec
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($spec) and $spec->isa("Log::Abstraction") 15 88 103
Condition100%3/3
builtin::blessed($spec) and $spec->isa("Log::Abstraction")
!ll&&!rl&&r
85315
MC/DC100%2/2
builtin::blessed($spec) and $spec->isa("Log::Abstraction")
builtin::blessed($spec) $spec->isa("Log::Abstraction")
Truth table100%3/3
A and B
A= builtin::blessed($spec)B= $spec->isa("Log::Abstraction")
ABresult
0X0
100
111
1443 if blessed($spec) && $spec->isa('Log::Abstraction');
1444  
1445 88 ▶ if(ref($spec) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $spec eq "ARRAY") 24 64 88
1446 24 return Log::Abstraction->new(array => $spec, carp_on_warn => $carp_on_warn);
1447 }
1448  
1449 64 ▶ if(ref($spec) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $spec eq "HASH") 43 21 64
1450 43 return Log::Abstraction->new({ carp_on_warn => $carp_on_warn, %$spec });
1451 }
1452  
1453 # Scalar: a logger name, file path, or other string identifier passed to L::A
1454 21 return Log::Abstraction->new({ carp_on_warn => $carp_on_warn, logger => $spec });
1455 }
1456  
1457 # Purpose: Build the ancestor chain needed for config-file discovery and env merging.
1458 # Uses the class's own MRO (DFS or C3) via mro::get_linear_isa, which is
1459 # more correct than a hardcoded DFS walk and handles diamond inheritance.
1460 # UNIVERSAL is added explicitly because mro::get_linear_isa does not include
1461 # it unless it appears in @ISA, yet Object::Configure supports universal.yml.
1462 # Entry: $class is a fully-qualified class name that has already been loaded.
1463 # Exit: Returns a list in base-first order: (UNIVERSAL, ..., GrandParent, Parent, Class).
1464 # Result is memoized in %_chain_cache; mro::get_linear_isa is not re-invoked
1465 # for classes already seen in this process. The cache is valid for the process
1466 # lifetime because @ISA is stable after module load in normal Perl programs.
1467 # Algorithmic cost: O(N) first call; O(1) amortised on subsequent calls.
1468 661 ▶sub _get_inheritance_chain {
Subroutine _get_inheritance_chain: called CC=3 SCAR=11.0
1469 661 my ($class) = @_;
1470  
1471 # Cache hit: return a copy of the stored list (caller may modify the returned list).
1472 661 ▶ return @{ $_chain_cache{$class} } if $_chain_cache{$class};
Branch: 1 branch
BranchTrueFalseTotal
if $Object::Configure::_chain_cache{$class} 244 417 661
1473  
1474 417 my @mro = @{ mro::get_linear_isa($class) };
1475  
1476 # mro::get_linear_isa returns child-first; reverse to get base-first.
1477 # UNIVERSAL is implicit in Perl's type system but not always in the MRO list,
1478 # so append it when absent to ensure universal.yml is picked up.
1479 # List::Util::any is XS and short-circuits on first match -- faster than grep.
1480 417 ▶ push @mro, 'UNIVERSAL' unless any { $_ eq 'UNIVERSAL' } @mro;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { $_ eq "UNIVERSAL"; } , @mro) 415 2 417
1481  
1482 417 my @chain = reverse @mro;
1483 417 $_chain_cache{$class} = \@chain; # store arrayref; return list copy below
1484 417 return @chain;
1485 }
1486  
1487 # Purpose: Find a config file for a specific ancestor class using the same
1488 # naming convention as the primary config file (directory + extension).
1489 # Entry: $class is a fully-qualified class name.
1490 # $base_config_file is the primary config file path (provides dir and ext).
1491 # $config_dirs is an optional arrayref of additional search directories.
1492 # Does NOT modify elements of $config_dirs (trailing-slash removal uses a copy).
1493 # Exit: Returns a readable file path, or undef if nothing found.
1494 # Result (including undef for "not found") is memoized in %_find_cache, keyed
1495 # by (class, base_config_file, config_dirs-elements) joined with NUL bytes.
1496 # Subsequent calls with identical arguments skip all filesystem probes.
1497 # Algorithmic cost: O(extensions) syscalls first call; O(1) amortised.
1498 527 ▶sub _find_class_config_file {
Subroutine _find_class_config_file: called CC=13 SCAR=25.7
1499 527 my ($class, $base_config_file, $config_dirs) = @_;
1500  
1501 # Build a NUL-separated cache key. NUL cannot appear in Linux file paths (the
1502 # pen-test suite confirms this: Perl's -r warns and returns undef for NUL paths).
1503 527 ▶ my $cache_key = join("\0", $class, $base_config_file,
Branch: 1 branch
BranchTrueFalseTotal
$config_dirs ? : 352 175 527
1504 $config_dirs ? @$config_dirs : ());
1505 527 ▶ return $_find_cache{$cache_key} if exists $_find_cache{$cache_key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $Object::Configure::_find_cache{$cache_key} 83 444 527
1506  
1507 444 my $class_file = lc($class);
1508 444 $class_file =~ s/::/-/g;
1509  
1510 444 my ($base_vol, $base_dir_part, $base_name_ext) = File::Spec->splitpath($base_config_file);
1511 444 my (undef, $base_ext) = $base_name_ext =~ /^(.*?)(\.[^.]+)?$/;
1512 444 ▶ $base_ext //= '';
Condition100%2/2
$base_ext //= ""
l!l
43014
MC/DC100%1/1
$base_ext //= ""
$base_ext
Truth table100%2/2
A
A= $base_ext
Aresult
11
00
1513 444 my $base_dir = File::Spec->catpath($base_vol, $base_dir_part, '');
1514  
1515 # Single-exit-point via labeled block so the cache write happens unconditionally.
1516 444 my $found;
1517 SEARCH: {
1518 # Dedup: when $base_ext is already .yml/.conf/etc the first candidate would
1519 # be a duplicate of a later one, causing a redundant filesystem probe.
1520 444 my %_seen_pat;
1521 444 foreach my $pattern (grep { !$_seen_pat{$_}++ } (
1522 File::Spec->catfile($base_dir, "${class_file}${base_ext}"),
1523 File::Spec->catfile($base_dir, "${class_file}.conf"),
1524 File::Spec->catfile($base_dir, "${class_file}.yml"),
1525 File::Spec->catfile($base_dir, "${class_file}.yaml"),
1526 File::Spec->catfile($base_dir, "${class_file}.json"),
1527 )) {
1528 1630 ▶ if(-r $pattern && -f $pattern) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $pattern and -f $pattern) 54 1576 1630
Condition66%2/3
-r $pattern and -f $pattern
!ll&&!rl&&r
1576054
MC/DC50%1/2
-r $pattern and -f $pattern
-r $pattern -f $pattern
Truth table66%2/3
A and B
A= -r $patternB= -f $pattern
ABresult
0X0
100
111
1529 54 $found = $pattern;
1530 54 last SEARCH;
1531 }
1532 }
1533  
1534 390 ▶ if($config_dirs && ref($config_dirs) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($config_dirs and ref $config_dirs eq "ARRAY") 301 89 390
Condition66%2/3
$config_dirs and ref $config_dirs eq "ARRAY"
!ll&&!rl&&r
890301
MC/DC50%1/2
$config_dirs and ref $config_dirs eq "ARRAY"
$config_dirs ref $config_dirs eq "ARRAY"
Truth table66%2/3
A and B
A= $config_dirsB= ref $config_dirs eq "ARRAY"
ABresult
0X0
100
111
1535 301 foreach my $dir (@$config_dirs) {
1536 # Use a copy so the caller's arrayref element is never mutated.
1537 382 (my $clean_dir = $dir) =~ s{/$}{};
1538 382 my %_seen_dir_pat;
1539 382 foreach my $pattern (grep { !$_seen_dir_pat{$_}++ } (
1540 "${clean_dir}/${class_file}${base_ext}",
1541 "${clean_dir}/${class_file}.conf",
1542 "${clean_dir}/${class_file}.yml",
1543 "${clean_dir}/${class_file}.yaml",
1544 "${clean_dir}/${class_file}.json",
1545 )) {
1546 1359 ▶ if(-r $pattern && -f $pattern) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $pattern and -f $pattern) 58 1301 1359
Condition66%2/3
-r $pattern and -f $pattern
!ll&&!rl&&r
1301058
MC/DC50%1/2
-r $pattern and -f $pattern
-r $pattern -f $pattern
Truth table66%2/3
A and B
A= -r $patternB= -f $pattern
ABresult
0X0
100
111
1547 58 $found = $pattern;
1548 58 last SEARCH;
1549 }
1550 }
1551 }
1552 }
1553 }
1554  
1555 # Cache stores undef for "not found"; callers must use exists, not defined.
1556 444 return ($_find_cache{$cache_key} = $found);
1557 }
1558  
1559 # Purpose: Run as the forked watcher child. Polls %_config_file_stats and
1560 # sends SIGUSR1 to the parent when any file changes.
1561 # Entry: $interval >= 1 (seconds). $callback is unused in the child (it runs
1562 # in the parent's SIGUSR1 handler).
1563 # Exit: Never returns; terminates via SIGTERM/SIGINT handlers.
1564 # Side: Modifies %_config_file_stats entries in the child's address space only.
1565 16 ▶sub _run_config_watcher {
Subroutine _run_config_watcher: called CC=10 SCAR=24.1
1566 16 my ($interval, $callback) = @_;
1567  
1568 # If the parent has gone, signalling it fails; don't die noisily in the child
1569 39 ▶ no autodie qw(kill);
Subroutine BEGIN: called CC=1 SCAR=0.0
1570  
1571 # SECURITY (S5): re-validate $interval in the child process.
1572 # If the parent's fork() fires before enable_hot_reload() applies its own guard
1573 # (race) or state is corrupted between fork and here, sleep(0) or sleep(-1) would
1574 # cause a busy-loop that saturates the CPU. int() also prevents floating-point
1575 # values like 0.001 from reaching the kernel as a near-zero sleep.
1576 16 ▶ $interval = int($interval // $DEFAULT_INTERVAL);
Condition33%1/3
$interval // $DEFAULT_INTERVAL
l!l&&r!l&&!r
1600
MC/DC0%0/2
$interval // $DEFAULT_INTERVAL
$interval $DEFAULT_INTERVAL
Truth table33%1/3
A // B
A= $intervalB= $DEFAULT_INTERVAL
ABresult
1X1
011
000
1577 16 ▶ $interval = $DEFAULT_INTERVAL unless $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval > 0 0 16 16
1578  
1579 16 ▶ local $SIG{TERM} = sub { exit 0 };
Subroutine __ANON__: called CC=1 SCAR=0.0
1580 0 ▶ local $SIG{INT} = sub { exit 0 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1581  
1582 16 while(1) {
1583 18 sleep($interval);
1584  
1585 2 my $changes_detected = 0;
1586  
1587 2 foreach my $config_file (keys %_config_file_stats) {
1588 2 ▶ if(-f $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $config_file) { } 2 0 2
1589 2 my $current_stat = stat($config_file);
1590 2 my $stored_stat = $_config_file_stats{$config_file};
1591  
1592 2 ▶ if(!$stored_stat || $current_stat->mtime > $stored_stat->mtime) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $stored_stat or $current_stat->mtime > $stored_stat->mtime) 1 1 2
Condition66%2/3
not $stored_stat or $current_stat->mtime > $stored_stat->mtime
l!l&&r!l&&!r
011
MC/DC50%1/2
not $stored_stat or $current_stat->mtime > $stored_stat->mtime
not $stored_stat $current_stat->mtime > $stored_stat->mtime
Truth table66%2/3
not(A) or B
A= not $stored_statB= $current_stat->mtime > $stored_stat->mtime
ABresult
1X1
011
000
1593 1 $_config_file_stats{$config_file} = $current_stat;
1594 1 $changes_detected = 1;
1595 }
1596 } else {
1597 0 delete $_config_file_stats{$config_file};
1598 0 $changes_detected = 1;
1599 }
1600 }
1601  
1602 2 ▶ if($changes_detected && $^O ne $OS_WINDOWS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changes_detected and $^O ne $OS_WINDOWS) 1 1 2
Condition66%2/3
$changes_detected and $^O ne $OS_WINDOWS
!ll&&!rl&&r
101
MC/DC50%1/2
$changes_detected and $^O ne $OS_WINDOWS
$changes_detected $^O ne $OS_WINDOWS
Truth table66%2/3
A and B
A= $changes_detectedB= $^O ne $OS_WINDOWS
ABresult
0X0
100
111
1603 1 ▶ if(my $parent_pid = getppid()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $parent_pid = getppid) 1 0 1
1604 1 kill('USR1', $parent_pid);
1605 }
1606 }
1607 }
1608 }
1609  
1610 # Purpose: Reload a single object's configuration from disk and update its fields.
1611 # Private properties (prefix '_') are intentionally skipped to avoid
1612 # clobbering internal bookkeeping set at construction time.
1613 # Entry: $obj must be a blessed reference with a {_config_file} or {_config_files} key.
1614 # Exit: Returns nothing; updates $obj in-place.
1615 # Side: Reads from disk. Calls $obj->_on_config_reload if the method exists.
1616 82 ▶sub _reload_object_config {
Subroutine _reload_object_config: called CC=20 SCAR=30.0
1617 82 my $obj = $_[0];
1618  
1619 82 ▶ return unless blessed($obj);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($obj) 2 80 82
1620  
1621 80 my $class = ref($obj);
1622 80 my $original_class = $class;
1623 80 $class =~ s/::/__/g;
1624  
1625 # Prefer the most-specific (last) file from the full list; fall back to scalar key
1626 80 my $config_file;
1627 80 ▶ if($obj->{_config_files} && ref($obj->{_config_files}) eq 'ARRAY' && @{ $obj->{_config_files} }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->{'_config_files'} and ref $obj->{'_config_files'} eq 'ARRAY' and @{$obj->{'_config_files'};}) { } 32 48 80
Condition83%5/6
$obj->{"_config_files"} and ref $obj->{"_config_files"} eq "ARRAY" and @{$obj->{"_config_files"};}
!ll&&!rl&&r
42632
$obj->{"_config_files"} and ref $obj->{"_config_files"} eq "ARRAY"
!ll&&!rl&&r
42038
MC/DC66%2/3
$obj->{"_config_files"} and ref $obj->{"_config_files"} eq "ARRAY" and @{$obj->{"_config_files"};}
$obj->{"_config_files"} ref $obj->{"_config_files"} eq "ARRAY" @{$obj->{"_config_files"};}
Truth table75%3/4
A and B and C
A= $obj->{"_config_files"}B= ref $obj->{"_config_files"} eq "ARRAY"C= @{$obj->{"_config_files"};}
ABCresult
0XX0
10X0
1100
1111
1628 32 $config_file = $obj->{_config_files}[-1];
1629 } else {
1630 48 ▶ $config_file = $obj->{_config_file} || $obj->{config_file};
Condition66%2/3
$obj->{'_config_file'} || $obj->{'config_file'}
l!l&&r!l&&!r
35013
MC/DC50%1/2
$obj->{'_config_file'} || $obj->{'config_file'}
$obj->{'_config_file'} $obj->{'config_file'}
Truth table66%2/3
A || B
A= $obj->{'_config_file'}B= $obj->{'config_file'}
ABresult
1X1
011
000
1631 }
1632  
1633 # SECURITY (S1 - path traversal): an attacker who modifies $obj->{_config_file}
1634 # (e.g., via a deserialization gadget or a malicious config merge) can redirect
1635 # hot-reload to read arbitrary system files. Reject paths with ".." segments here
1636 # so that even a corrupted object cannot force a traversal read.
1637 # Must come BEFORE the -f check so traversal paths for non-existent files are also rejected.
1638 80 ▶ if($config_file && $config_file =~ $RE_PATH_TRAVERSAL) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config_file and $config_file =~ /$RE_PATH_TRAVERSAL/) 7 73 80
Condition100%3/3
$config_file and $config_file =~ /$RE_PATH_TRAVERSAL/
!ll&&!rl&&r
13607
MC/DC100%2/2
$config_file and $config_file =~ /$RE_PATH_TRAVERSAL/
$config_file $config_file =~ /$RE_PATH_TRAVERSAL/
Truth table100%3/3
A and B
A= $config_fileB= $config_file =~ /$RE_PATH_TRAVERSAL/
ABresult
0X0
100
111
1639 7 carp(__PACKAGE__, ': _reload_object_config: refusing path with traversal sequences: ',
1640 $config_file);
1641 7 return;
1642 }
1643  
1644 73 ▶ return unless $config_file && -f $config_file;
Branch: 1 branch
BranchTrueFalseTotal
unless $config_file and -f $config_file 18 55 73
Condition100%3/3
$config_file and -f $config_file
!ll&&!rl&&r
13555
MC/DC100%2/2
$config_file and -f $config_file
$config_file -f $config_file
Truth table100%3/3
A and B
A= $config_fileB= -f $config_file
ABresult
0X0
100
111
1645  
1646 55 my $config = Config::Abstraction->new(
1647 config_file => $config_file,
1648 env_prefix => "${class}__"
1649 );
1650  
1651 55 ▶ if($config) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config) 55 0 55
1652 55 my $new_params = $config->merge_defaults(
1653 defaults => {},
1654 section => $class,
1655 merge => 1,
1656 deep => 1
1657 );
1658  
1659 55 foreach my $key (keys %$new_params) {
1660 81 ▶ next if $key =~ /^_/;
Branch: 1 branch
BranchTrueFalseTotal
if $key =~ /^_/ 2 79 81
1661  
1662 79 ▶ if($key eq 'logger') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq 'logger') { } 3 76 79
1663 # Only the exact 'logger' key triggers logger reconstruction.
1664 # Keys like 'logger.file' are flat config values, not logger specs.
1665 # Guard: assign directly for undef (no logger) or literal 'NULL'.
1666 # Premise 1: _build_logger handles every other spec type.
1667 # Premise 2: undef/NULL need no construction. Conclusion: rebuild only otherwise.
1668 3 my $val = $new_params->{$key};
1669 3 ▶ if(!defined($val) || (!ref($val) && $val eq $LOGGER_NULL)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $val or not ref $val and $val eq $LOGGER_NULL) { } 2 1 3
Condition66%4/6
not defined $val or not ref $val and $val eq $LOGGER_NULL
l!l&&r!l&&!r
021
not ref $val and $val eq $LOGGER_NULL
!ll&&!rl&&r
102
MC/DC33%1/3
not defined $val or not ref $val and $val eq $LOGGER_NULL
not defined $val not ref $val $val eq $LOGGER_NULL
Truth table50%2/4
not(A) or not(B) and C
A= not defined $valB= not ref $valC= $val eq $LOGGER_NULL
ABCresult
1XX1
0111
00X0
0100
1670 2 $obj->{$key} = $val;
1671 } else {
1672 1 _reconfigure_logger($obj, $key, $val);
1673 }
1674 } else {
1675 76 $obj->{$key} = $new_params->{$key};
1676 }
1677 }
1678  
1679 55 ▶ $obj->_on_config_reload($new_params) if $obj->can('_on_config_reload');
Branch: 1 branch
BranchTrueFalseTotal
if $obj->can("_on_config_reload") 15 40 55
1680  
1681 $obj->{logger}->info("Configuration reloaded for $original_class")
1682 55 ▶ if $obj->{logger} && $obj->{logger}->can('info');
Branch: 1 branch
BranchTrueFalseTotal
if $obj->{"logger"} and $obj->{"logger"}->can("info") 31 24 55
Condition100%3/3
$obj->{"logger"} and $obj->{"logger"}->can("info")
!ll&&!rl&&r
22231
MC/DC100%2/2
$obj->{"logger"} and $obj->{"logger"}->can("info")
$obj->{"logger"} $obj->{"logger"}->can("info")
Truth table100%3/3
A and B
A= $obj->{"logger"}B= $obj->{"logger"}->can("info")
ABresult
0X0
100
111
1683 }
1684  
1685 55 return;
1686 }
1687  
1688 # Purpose: Replace the logger on an already-constructed object with one
1689 # built from a new config value (typically a YAML hashref).
1690 # Delegates to _build_logger so logger-creation logic lives in one place.
1691 # Entry: $obj is a blessed hashref. $key is the hash key to update (usually 'logger').
1692 # $logger_config is the new spec from the config file.
1693 # Exit: Returns nothing; updates $obj->{$key} in-place.
1694 # Side: May allocate a new Log::Abstraction instance.
1695 sub _reconfigure_logger
1696 10 ▶{
Subroutine _reconfigure_logger: called CC=2 SCAR=6.9
1697 10 my ($obj, $key, $logger_config) = @_;
1698 10 ▶ my $carp_on_warn = $obj->{carp_on_warn} || 0;
Condition100%2/2
$obj->{'carp_on_warn'} || 0
l!l
19
MC/DC100%1/1
$obj->{'carp_on_warn'} || 0
$obj->{'carp_on_warn'}
Truth table100%2/2
A
A= $obj->{'carp_on_warn'}
Aresult
11
00
1699 10 $obj->{$key} = _build_logger($logger_config, $carp_on_warn);
1700 10 return;
1701 }
1702  
1703 # Purpose: Right-precedence deep merge of two hash references.
1704 # Scalar/arrayref values in $overlay replace those in $base entirely;
1705 # nested hashrefs are merged recursively.
1706 # Entry: Both args should be hashrefs (or undef/non-ref, handled gracefully).
1707 # Exit: Returns a new hashref; neither input is modified.
1708 401 ▶sub _deep_merge {
Subroutine _deep_merge: called CC=6 SCAR=17.9
1709 401 my ($base, $overlay) = @_;
1710  
1711 401 ▶ return $overlay unless ref($base) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $base eq "HASH" 17 384 401
1712 384 ▶ return $overlay unless ref($overlay) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $overlay eq "HASH" 20 364 384
1713  
1714 364 my $result = { %$base };
1715  
1716 364 foreach my $key (keys %$overlay) {
1717 4553 ▶ if(ref($overlay->{$key}) eq 'HASH' && ref($result->{$key}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $overlay->{$key} eq 'HASH' and ref $result->{$key} eq 'HASH') { } 61 4492 4553
Condition100%3/3
ref $overlay->{$key} eq "HASH" and ref $result->{$key} eq "HASH"
!ll&&!rl&&r
44652761
MC/DC100%2/2
ref $overlay->{$key} eq "HASH" and ref $result->{$key} eq "HASH"
ref $overlay->{$key} eq "HASH" ref $result->{$key} eq "HASH"
Truth table100%3/3
A and B
A= ref $overlay->{$key} eq "HASH"B= ref $result->{$key} eq "HASH"
ABresult
0X0
100
111
1718 61 $result->{$key} = _deep_merge($result->{$key}, $overlay->{$key});
1719 } else {
1720 4492 $result->{$key} = $overlay->{$key};
1721 }
1722 }
1723  
1724 364 return $result;
1725 }
1726  
1727 # Clean up the watcher child and restore signal state on interpreter exit.
1728 36 ▶END {
Subroutine END: called CC=1 SCAR=0.0
1729 36 disable_hot_reload();
1730 36 restore_signal_handlers();
1731 }
1732  
1733 =head1 SEE ALSO
1734  
1735 =over 4
1736  
1737 =item * L<Config::Abstraction>
1738  
1739 =item * L<Log::Abstraction>
1740  
1741 =item * L<Test Dashboard|https://nigelhorne.github.io/Object-Configure/coverage/>
1742  
1743 =back
1744  
1745 =head1 LIMITATIONS
1746  
1747 =over 4
1748  
1749 =item * B<Global singleton state.> C<%_object_registry>, C<%_config_watchers>, and
1750 C<%_config_file_stats> are package globals. Two independent subsystems in the same
1751 process share one hot-reload registry and one SIGUSR1 handler. There is no
1752 instance-level isolation. A proper fix would wrap state in an object and allow
1753 multiple independent C<Object::Configure> instances, but that would break the
1754 existing constructor-call API (C<configure($class, \%params)>).
1755  
1756 =item * B<Hot reload is UNIX-only.> SIGUSR1 does not exist on Windows.
1757 All signal-related paths are guarded with C<$^O ne 'MSWin32'>, so the module
1758 loads on Windows but silently skips hot-reload registration.
1759  
1760 =item * B<configure() is a God function.> At ~120 lines it handles arg validation,
1761 config-file discovery, MRO walking, multi-file merging, env-var merging, logger
1762 creation, and hot-reload bookkeeping. Future versions should decompose this into
1763 smaller, independently testable units.
1764  
1765 =item * B<_deep_merge reimplements CPAN.> L<Hash::Merge::Simple> or L<Hash::Merge>
1766 provide tested, feature-complete deep merge. The internal C<_deep_merge> is 15
1767 lines and correct for the current use, but does not handle arrayrefs (they are
1768 replaced wholesale, not merged). If array-merge semantics are ever needed, switch
1769 to a CPAN module.
1770  
1771 =item * B<No encapsulation enforcement.> Private helpers (C<_build_logger>,
1772 C<_get_inheritance_chain>, etc.) are accessible to any caller. L<Sub::Private>
1773 (enforce mode) would make accidental external use a compile-time error. It is not
1774 added here to avoid a smoker dependency on a less-common module.
1775  
1776 =item * B<configure() signature is positional, instantiate() is named.> The two
1777 public constructors have inconsistent calling conventions. Normalising them to named
1778 args would require a deprecation cycle.
1779  
1780 =item * B<mro::get_linear_isa and UNIVERSAL.> Perl's C<mro::get_linear_isa> does
1781 not include C<UNIVERSAL> in its output unless C<UNIVERSAL> appears explicitly in
1782 C<@ISA>. This module appends C<UNIVERSAL> manually so that C<universal.yml> is
1783 always discovered. If a future Perl version changes this behaviour the guard
1784 (C<grep { $_ eq 'UNIVERSAL' }>) remains correct.
1785  
1786 =back
1787  
1788 =head1 Formal Specification
1789  
1790 =head2 configure
1791  
1792 configure: Class x Params -> ConfigHash
1793  
1794 Given:
1795 - C: set of all class names
1796 - P: set of all parameter hashes
1797 - F: set of all file paths
1798 - H: set of all configuration hashes
1799  
1800 State:
1801 - ConfigFiles: F -> H (maps file paths to configuration content)
1802 - EnvVars: String -> String (environment variables)
1803 - InheritanceChain: C -> seq C (ordered sequence of ancestor classes)
1804  
1805 Pre-condition:
1806 forall class in C, params in P:
1807 class != empty
1808 (params.config_file != empty =>
1809 (exists dir in params.config_dirs: readable(dir/params.config_file))
1810 OR readable(params.config_file))
1811  
1812 Post-condition:
1813 forall result in H:
1814 result = params
1815 (+) (merge f in InheritanceConfigFiles(class): ConfigFiles(f))
1816 (+) (merge v in RelevantEnvVars(class): v)
1817 result.logger in Log::Abstraction
1818 (forall k in dom params:
1819 (params(k) in CodeRef OR blessed(params(k))) => result(k) = params(k))
1820  
1821 where (+) denotes hash merge with right-precedence
1822  
1823 =head2 instantiate
1824  
1825 instantiate: Params -> Object
1826  
1827 Given:
1828 - P: set of all parameter hashes
1829 - C: set of all class names
1830 - O: set of all objects
1831  
1832 Pre-condition:
1833 forall params in P:
1834 params.class in C
1835 params.class.can('new')
1836  
1837 Post-condition:
1838 forall result in O:
1839 exists config in H:
1840 config = configure(params.class, params)
1841 result = params.class.new(config)
1842 blessed(result) = params.class
1843 (config._config_file != empty =>
1844 result in _object_registry(params.class))
1845  
1846 =head2 enable_hot_reload
1847  
1848 enable_hot_reload: Interval x Callback -> PID
1849  
1850 Given:
1851 - I: set of positive integers (intervals in seconds)
1852 - CB: set of code references
1853 - PID: set of process identifiers
1854  
1855 State:
1856 - _config_watchers: {pid: PID, callback: CB}
1857 - _config_file_stats: F -> Stat
1858  
1859 Pre-condition:
1860 forall interval in I, callback in CB union {empty}:
1861 interval >= 1
1862 _config_watchers = empty
1863 OS != 'MSWin32'
1864  
1865 Post-condition:
1866 forall result in PID:
1867 result > 0
1868 _config_watchers.pid = result
1869 _config_watchers.callback = callback
1870 (forall t in Time:
1871 (t mod interval = 0) =>
1872 (exists f in dom _config_file_stats:
1873 mtime(f) > _config_file_stats(f).mtime =>
1874 send_signal(SIGUSR1, parent_process)))
1875  
1876 =head2 disable_hot_reload
1877  
1878 disable_hot_reload: () -> ()
1879  
1880 State:
1881 - _config_watchers: {pid: PID, callback: CB}
1882  
1883 Pre-condition:
1884 true
1885  
1886 Post-condition:
1887 _config_watchers = empty
1888 (forall p in PID:
1889 p = _config_watchers.pid@pre =>
1890 NOT alive(p))
1891  
1892 =head2 reload_config
1893  
1894 reload_config: () -> N
1895  
1896 State:
1897 - _object_registry: C -> seq ObjectRef
1898 - ConfigFiles: F -> H
1899  
1900 Pre-condition:
1901 true
1902  
1903 Post-condition:
1904 forall result in N:
1905 result = |{obj in flatten(ran _object_registry) |
1906 obj != empty
1907 obj._config_file in dom ConfigFiles}|
1908 (forall obj in flatten(ran _object_registry):
1909 obj != empty AND obj._config_file in dom ConfigFiles =>
1910 (forall k in dom ConfigFiles(obj._config_file):
1911 k NOT in PrivateKeys =>
1912 obj(k)@post = ConfigFiles(obj._config_file)(k)))
1913  
1914 where PrivateKeys = {k | k starts with '_'}
1915  
1916 =head2 register_object
1917  
1918 register_object: C x O -> ()
1919  
1920 Given:
1921 - C: set of class names
1922 - O: set of blessed objects
1923 - OR: C -> seq WeakRef(O) (object registry)
1924  
1925 State:
1926 - _object_registry: OR
1927 - _original_usr1_handler: SignalHandler union {empty}
1928 - $SIG{USR1}: SignalHandler
1929  
1930 Pre-condition:
1931 forall class in C, obj in O:
1932 class != empty
1933 obj != empty
1934 blessed(obj) != empty
1935  
1936 Post-condition:
1937 forall class in C, obj in O:
1938 exists ref in _object_registry(class):
1939 weak(ref) = obj
1940 (_original_usr1_handler = empty@pre =>
1941 (_original_usr1_handler@post = $SIG{USR1}@pre
1942 $SIG{USR1}@post = reload_config_handler))
1943  
1944 =head2 restore_signal_handlers
1945  
1946 restore_signal_handlers: () -> ()
1947  
1948 State:
1949 - _original_usr1_handler: SignalHandler union {empty}
1950 - $SIG{USR1}: SignalHandler
1951  
1952 Pre-condition:
1953 true
1954  
1955 Post-condition:
1956 $SIG{USR1}@post = _original_usr1_handler@pre
1957 _original_usr1_handler@post = empty
1958  
1959 =head2 get_signal_handler_info
1960  
1961 get_signal_handler_info: () -> InfoHash
1962  
1963 Given:
1964 - IH: set of all info hashes
1965  
1966 State:
1967 - _original_usr1_handler: SignalHandler union {empty}
1968 - $SIG{USR1}: SignalHandler union {empty}
1969 - _config_watchers: {pid: PID, callback: CB}
1970  
1971 Pre-condition:
1972 true
1973  
1974 Post-condition:
1975 forall result in IH:
1976 result.original_usr1 = _original_usr1_handler
1977 result.current_usr1 = $SIG{USR1}
1978 result.hot_reload_active = (_original_usr1_handler != empty)
1979 result.watcher_pid = _config_watchers.pid
1980  
1981 =head1 SUPPORT
1982  
1983 Please report bugs and feature requests at:
1984  
1985 =over 4
1986  
1987 =item * RT (CPAN bug tracker): L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Object-Configure>
1988  
1989 or by e-mail: C<bug-object-configure at rt.cpan.org>
1990  
1991 =item * GitHub issues: L<https://github.com/nigelhorne/Object-Configure/issues>
1992  
1993 =back
1994  
1995 You will be notified automatically of progress on your report.
1996  
1997 perldoc Object::Configure
1998  
1999 =head1 AUTHOR
2000  
2001 Nigel Horne, C<< <njh at nigelhorne.com> >>
2002  
2003 =head1 LICENCE AND COPYRIGHT
2004  
2005 Copyright 2025-2026 Nigel Horne.
2006  
2007 Usage is subject to GPL2 licence terms.
2008 If you use it, please let me know.
2009  
2010 =cut
2011  
2012 39 1;
↑ Summary