blib/lib/Web/VWF/Utils.pm

filter: Statementstmt 33.9% 75 / 221 Branchbran 6.9% 8 / 116 Conditioncond 2.2% 2 / 89 MC/DCmcdc 2.1% 1 / 47 Subroutinesub 46.5% 20 / 43 Podpod 100% 5 / 5 totaltotal 21.3% 111 / 521 CC 100 SCAR 46.2
CC
100
Cov
20%
distance
306.0
_validate_cache_config
272.0
_build_chi_args
110.0
CRAP 101.2
« blib/lib/Web/VWF/Display.pm ↑ Summary blib/lib/Web/VWF/CAPTCHA.pm »
1 package Web::VWF::Utils;
2  
3 # VWF is licensed under GPL2.0 for personal use only
4 # njh@nigelhorne.com
5  
6 =encoding utf-8
7  
8 =head1 NAME
9  
10 Web::VWF::Utils - Random subroutines for VWF
11  
12 =head1 DESCRIPTION
13  
14 Utility module for cache management and geospatial calculations.
15 Provides cross-driver cache initialization and Haversine formula implementation.
16  
17 =head1 VERSION
18  
19 Version 0.003.0
20  
21 =cut
22  
23 1 ▶use version; our $VERSION = version->declare('0.003.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 1 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶use feature qw(signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 1 ▶no warnings qw(experimental::signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 1 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
32 1 our @EXPORT = qw(create_disc_cache create_memory_cache distance);
33 1 our @EXPORT_OK = qw(redact_config env_cache_dir);
34  
35 1 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 1 ▶use Error::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 1 ▶use Module::Runtime qw(require_module); # Safe dynamic loading; avoids string eval
Subroutine BEGIN: called CC=1 SCAR=0.0
39 1 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 1 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
42 1 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
43 1 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 1 ▶use Scalar::Util qw(looks_like_number reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
45 1 ▶use Math::Trig qw(deg2rad rad2deg asin great_circle_distance);
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 # Constants for distance calculations
48 1 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
49 1 EARTH_RADIUS_MILES => 3959,
50 EARTH_RADIUS_KM => 6371,
51 EARTH_RADIUS_NM => 3440,
52 KM_PER_MILE => 1.609344,
53 NM_PER_MILE => 0.8684
54 1 };
55  
56 =head1 SUBROUTINES/METHODS
57  
58 =head2 FORMAL SPECIFICATION
59  
60 [STRING, HASH, LOGGER, CHI_CACHE, COORDINATE]
61  
62 CacheConfig ::= ⟨⟨ driver : STRING;
63 servers : seq STRING;
64 root_dir : STRING;
65 connect : STRING ⟩⟩
66  
67 CacheArgs ::= ⟨⟨ config : HASH;
68 logger : LOGGER;
69 namespace : STRING;
70 root_dir : STRING ⟩⟩
71  
72 Point ::= ⟨⟨ latitude : COORDINATE;
73 longitude : COORDINATE ⟩⟩
74 where
75 latitude ∈ {x : ℝ | -90 ≤ x ≤ 90} ∧
76 longitude ∈ {x : ℝ | -180 ≤ x ≤ 180}
77  
78 Unit ::= K | N | M
79  
80 CreateCache : CacheArgs → CHI_CACHE
81  
82 ∀ args : CacheArgs •
83 let driver == args.config.driver ∨ default_driver •
84 validate_driver_config(driver, args.config) ∧
85 ∃ cache : CHI_CACHE • cache = CHI.new(build_chi_args(driver, args))
86  
87 Distance : Point × Point × Unit → ℝ₊
88  
89 ∀ p1, p2 : Point; u : Unit •
90 let d == great_circle_distance(p1, p2) •
91 d ≥ 0 ∧
92 (u = K ⟹ result = d × 1.609344) ∧
93 (u = N ⟹ result = d × 0.8684) ∧
94 (u = M ⟹ result = d)
95  
96 =head2 create_disc_cache
97  
98 Initialize a disc-based cache using the CHI module.
99 Supports multiple cache drivers, including BerkeleyDB, DBI, and Redis.
100  
101 Parameters:
102 - config: Configuration hash reference (required)
103 - logger: Logger object (optional)
104 - namespace: Cache namespace (optional)
105 - root_dir: Root directory override (optional)
106  
107 File-based drivers store their files in $CACHEDIR, or failing that $CACHE_DIR,
108 when either is set (the directory is created if need be); otherwise in the
109 first of $root_dir, the root_dir argument and the configured root_dir.
110  
111 Returns: CHI cache object
112  
113 =cut
114  
115 0 ▶sub create_disc_cache {
Subroutine create_disc_cache: not called CC=1 SCAR=6.9
Pod documented
116 0 my $args = Params::Get::get_params(undef, @_);
117 0 return _create_cache('disc_cache', $args);
118 }
119  
120 =head2 create_memory_cache
121  
122 Initialize a memory-based cache using the CHI module.
123 Supports multiple cache drivers, including SharedMem, Memory, and Redis.
124  
125 Parameters:
126 - config: Configuration hash reference (required)
127 - logger: Logger object (optional)
128 - namespace: Cache namespace (optional)
129 - root_dir: Root directory override (optional)
130  
131 Returns: CHI cache object
132  
133 =cut
134  
135 0 ▶sub create_memory_cache {
Subroutine create_memory_cache: not called CC=1 SCAR=6.9
Pod documented
136 0 my $args = Params::Get::get_params(undef, @_);
137 0 return _create_cache('memory_cache', $args);
138 }
139  
140 # Private helper functions
141  
142 0 ▶sub _create_cache($cache_type, $args) {
Subroutine _create_cache: not called CC=7 SCAR=40.3
143 0 my $config = $args->{'config'};
144 0 ▶ throw Error::Simple('config is not optional') unless($config);
Branch: 1 branch
BranchTrueFalseTotal
unless $config 0 0 0
145  
146 0 _validate_cache_config($config, $cache_type);
147  
148 0 my $logger = $args->{'logger'};
149 0 ▶ my $cache_config = $config->{$cache_type} || {};
Condition0%0/2
$config->{$cache_type} || {}
l!l
00
MC/DC0%0/1
$config->{$cache_type} || {}
$config->{$cache_type}
Truth table0%0/2
A
A= $config->{$cache_type}
Aresult
11
00
150 0 my $driver = $cache_config->{driver};
151  
152 # Set default driver with fallback strategy
153 0 ▶ unless (defined $driver) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $driver) 0 0 0
154 0 $driver = _get_default_driver($cache_type, $logger);
155 0 ▶ if ($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 0 0 0
156 0 $logger->info("No driver specified for $cache_type, using $driver");
157 }
158 }
159  
160 # Validate driver is available
161 0 ▶ unless (_is_driver_available($driver)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_is_driver_available($driver)) 0 0 0
162 0 my $fallback = _get_fallback_driver($cache_type);
163 0 ▶ if ($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 0 0 0
164 0 $logger->warn("CHI driver $driver not available, falling back to $fallback");
165 }
166 0 $driver = $fallback;
167 }
168  
169 # Build CHI arguments
170 0 my %chi_args = _build_chi_args($driver, $cache_config, $args, $logger, $cache_type);
171  
172 # Create cache with error handling
173 0 my $cache;
174 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
175 0 $cache = CHI->new(%chi_args);
176 0 ▶ } catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
177 0 my $error = "Failed to create $cache_type cache with driver $driver: $_";
178 0 ▶ $logger->error($error) if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 0 0 0
179 0 throw Error::Simple($error);
180 0 };
181  
182 0 return $cache;
183 }
184  
185 0 ▶sub _validate_cache_config($config, $cache_type) {
Subroutine _validate_cache_config: not called CC=16 SCAR=56.1
186 0 ▶ return unless exists $config->{$cache_type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $config->{$cache_type} 0 0 0
187  
188 0 my $cache_config = $config->{$cache_type};
189 0 ▶ croak('Cache configuration must be a hash reference')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cache_config eq "HASH" 0 0 0
190 unless ref($cache_config) eq 'HASH';
191  
192 # Validate driver if specified
193 0 ▶ if (exists $cache_config->{driver}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cache_config->{"driver"}) 0 0 0
194 0 my $driver = $cache_config->{driver};
195 0 my @valid_drivers = qw(Memory BerkeleyDB DBI Redis Memcached SharedMem File Null);
196 croak "Invalid driver '$driver'. Valid drivers: " . join(', ', @valid_drivers)
197 0 ▶ unless grep { $_ eq $driver } @valid_drivers;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $driver;} @valid_drivers 0 0 0
198 }
199  
200 # Validate numeric parameters
201 0 for my $param (qw(port shm_size max_size)) {
202 0 ▶ next unless exists $cache_config->{$param};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cache_config->{$param} 0 0 0
203 0 my $value = $cache_config->{$param};
204 # \z rather than $: "80\n" must not pass as a number
205 0 ▶ croak "$param must be a positive integer"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A\d+\z/u and $value > 0 0 0 0
Condition0%0/6
defined $value and $value =~ /\A\d+\z/u and $value > 0
!ll&&!rl&&r
000
defined $value and $value =~ /\A\d+\z/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $value and $value =~ /\A\d+\z/u and $value > 0
defined $value $value =~ /\A\d+\z/u $value > 0
Truth table0%0/4
A and B and C
A= defined $valueB= $value =~ /\A\d+\z/uC= $value > 0
ABCresult
0XX0
10X0
1100
1111
206 unless defined $value && $value =~ /\A\d+\z/ && $value > 0;
207 }
208  
209 # Validate port range
210 0 ▶ if (exists $cache_config->{port}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cache_config->{"port"}) 0 0 0
211 0 my $port = $cache_config->{port};
212 0 ▶ croak('Port must be between 1 and 65535')
Branch: 1 branch
BranchTrueFalseTotal
unless $port >= 1 and $port <= 65535 0 0 0
Condition0%0/3
$port >= 1 and $port <= 65535
!ll&&!rl&&r
000
MC/DC0%0/2
$port >= 1 and $port <= 65535
$port >= 1 $port <= 65535
Truth table0%0/3
A and B
A= $port >= 1B= $port <= 65535
ABresult
0X0
100
111
213 unless $port >= 1 && $port <= 65535;
214 }
215  
216 # Validate memory parameters
217 0 ▶ if(exists($cache_config->{'datastore'}) && exists($cache_config->{'global'}) && $cache_config->{'driver'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cache_config->{"datastore"} and exists $cache_config->{"global"} and $cache_config->{"driver"}) 0 0 0
Condition0%0/6
exists $cache_config->{"datastore"} and exists $cache_config->{"global"} and $cache_config->{"driver"}
!ll&&!rl&&r
000
exists $cache_config->{"datastore"} and exists $cache_config->{"global"}
!ll&&!rl&&r
000
MC/DC0%0/3
exists $cache_config->{"datastore"} and exists $cache_config->{"global"} and $cache_config->{"driver"}
exists $cache_config->{"datastore"} exists $cache_config->{"global"} $cache_config->{"driver"}
Truth table0%0/4
A and B and C
A= exists $cache_config->{"datastore"}B= exists $cache_config->{"global"}C= $cache_config->{"driver"}
ABCresult
0XX0
10X0
1100
1111
218 # CHI catches this as well, but putting it here helps to track the error
219 0 croak('Memory cache cannot have both global and datastore');
220 }
221 }
222  
223 0 ▶sub _get_default_driver($cache_type, $logger) {
Subroutine _get_default_driver: not called CC=3 SCAR=24.8
224 # Allow override for testing
225 0 my $env_var = 'TEST_' . uc($cache_type) . '_DRIVER';
226 0 ▶ return $ENV{$env_var} if $ENV{$env_var};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{$env_var} 0 0 0
227  
228 # Production defaults
229 0 ▶ return $cache_type eq 'disc_cache' ? 'BerkeleyDB' : 'Memory';
Branch: 1 branch
BranchTrueFalseTotal
$cache_type eq 'disc_cache' ? : 0 0 0
230 }
231  
232 0 ▶sub _get_fallback_driver($cache_type) {
Subroutine _get_fallback_driver: not called CC=2 SCAR=17.9
233 0 ▶ return $cache_type eq 'disc_cache' ? 'File' : 'Memory';
Branch: 1 branch
BranchTrueFalseTotal
$cache_type eq 'disc_cache' ? : 0 0 0
234 }
235  
236 0 ▶sub _is_driver_available($driver) {
Subroutine _is_driver_available: not called CC=5 SCAR=34.0
237 0 ▶ return 1 if $driver =~ /^(Memory|Null)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $driver =~ /^(Memory|Null)$/u 0 0 0
238  
239 0 my %driver_modules = (
240 'DBI' => 'CHI::Driver::DBI',
241 'BerkeleyDB' => 'CHI::Driver::BerkeleyDB',
242 'File' => 'CHI::Driver::File',
243 'Memcached' => 'CHI::Driver::Memcached',
244 'SharedMem' => 'CHI::Driver::SharedMem',
245 'Redis' => 'CHI::Driver::Redis'
246 );
247  
248 0 ▶ return 1 unless exists $driver_modules{$driver};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $driver_modules{$driver} 0 0 0
249  
250 0 ▶ if($driver_modules{$driver}->can('new')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver_modules{$driver}->can("new")) 0 0 0
251 0 return 1;
252 }
253 # SECURITY - string-eval elimination:
254 # eval "require $module_name" is a string eval; if $driver ever escaped
255 # the hash-key whitelist (e.g. through a future regression in the caller),
256 # it could execute arbitrary code. A block eval with require_module() is
257 # semantically identical but has no string-eval surface.
258 0 eval { require_module($driver_modules{$driver}) };
259 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
260 0 return 0;
261 }
262 0 $driver_modules{$driver}->import();
263 0 return 1;
264 }
265  
266 0 ▶sub _build_chi_args($driver, $cache_config, $args, $logger, $cache_type) {
Subroutine _build_chi_args: not called CC=10 SCAR=47.0
267 my %chi_args = (
268 driver => $driver,
269 0 ▶ namespace => $args->{'namespace'} || 'default'
Condition0%0/2
$args->{'namespace'} || 'default'
l!l
00
MC/DC0%0/1
$args->{'namespace'} || 'default'
$args->{'namespace'}
Truth table0%0/2
A
A= $args->{'namespace'}
Aresult
11
00
270 );
271  
272 # Configure error handling
273 0 ▶ if ($logger && $logger->can('error')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger and $logger->can('error')) { } 0 0 0
Condition0%0/3
$logger and $logger->can("error")
!ll&&!rl&&r
000
MC/DC0%0/2
$logger and $logger->can("error")
$logger $logger->can("error")
Truth table0%0/3
A and B
A= $loggerB= $logger->can("error")
ABresult
0X0
100
111
274 0 ▶ $chi_args{on_get_error} = sub { $logger->warn("Cache get error: $_[0]") };
Subroutine __ANON__: not called CC=1 SCAR=6.9
275 0 ▶ $chi_args{on_set_error} = sub { $logger->error("Cache set error: $_[0]") };
Subroutine __ANON__: not called CC=1 SCAR=6.9
276 } else {
277 0 $chi_args{on_get_error} = 'warn';
278 0 $chi_args{on_set_error} = 'die';
279 }
280  
281 # Driver-specific configuration
282 0 ▶ if ($driver eq 'Redis') {
Branch: 6 branches
BranchTrueFalseTotal
if ($driver eq 'Redis') { } 0 0 0
elsif ($driver eq 'DBI') { } 0 0 0
elsif ($driver eq 'SharedMem') { } 0 0 0
elsif ($driver eq 'Memory') { } 0 0 0
elsif ($driver eq 'Memcached') { } 0 0 0
elsif (not $driver =~ /^(Null)$/u) { } 0 0 0
283 0 _configure_redis(\%chi_args, $cache_config, $args, $logger);
284 } elsif ($driver eq 'DBI') {
285 0 _configure_dbi(\%chi_args, $cache_config, $args, $logger);
286 } elsif ($driver eq 'SharedMem') {
287 0 _configure_shared_memory(\%chi_args, $cache_config, $args);
288 } elsif ($driver eq 'Memory') {
289 0 _configure_memory(\%chi_args, $cache_config);
290 } elsif ($driver eq 'Memcached') {
291 0 _configure_memcached(\%chi_args, $cache_config, $args, $logger);
292 } elsif ($driver !~ /^(Null)$/) {
293 0 _configure_file_based(\%chi_args, $cache_config, $args);
294 }
295  
296 0 return %chi_args;
297 }
298  
299 0 ▶sub _configure_redis($chi_args, $config, $args, $logger) {
Subroutine _configure_redis: not called CC=6 SCAR=37.4
300 # Parse server configuration
301 0 my @servers = _parse_server_config($config, $logger);
302 0 ▶ if (@servers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@servers) 0 0 0
303 0 $chi_args->{servers} = \@servers;
304 0 $chi_args->{server} = $servers[0]; # Primary server
305 }
306  
307 # Redis-specific options with sensible defaults
308 $chi_args->{redis_options} = {
309 reconnect => $config->{reconnect} || 60,
310 every => $config->{every} || 1_000_000,
311 encoding => $config->{encoding} || 'utf8',
312 0 ▶ %{$config->{redis_options} || {}}
Condition0%0/8
$config->{'reconnect'} || 60
l!l
00
$config->{'every'} || 1000000
l!l
00
$config->{'encoding'} || 'utf8'
l!l
00
$config->{'redis_options'} || {}
l!l
00
MC/DC0%0/1
$config->{'reconnect'} || 60
$config->{'reconnect'}
MC/DC0%0/1
$config->{'every'} || 1000000
$config->{'every'}
MC/DC0%0/1
$config->{'encoding'} || 'utf8'
$config->{'encoding'}
MC/DC0%0/1
$config->{'redis_options'} || {}
$config->{'redis_options'}
Truth table0%0/2
A
A= $config->{'reconnect'}
Aresult
11
00
Truth table0%0/2
A
A= $config->{'every'}
Aresult
11
00
Truth table0%0/2
A
A= $config->{'encoding'}
Aresult
11
00
Truth table0%0/2
A
A= $config->{'redis_options'}
Aresult
11
00
313 };
314 }
315  
316 0 ▶sub _configure_dbi($chi_args, $config, $args, $logger) {
Subroutine _configure_dbi: not called CC=3 SCAR=24.8
317 0 my $connect_string = $config->{connect};
318 0 ▶ croak "DBI driver requires 'connect' parameter" unless $connect_string;
Branch: 1 branch
BranchTrueFalseTotal
unless $connect_string 0 0 0
319  
320 0 my $dbh;
321 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
322 0 $dbh = DBI->connect($connect_string, '', '', {
323 RaiseError => 1,
324 PrintError => 0,
325 AutoCommit => 1
326 });
327 0 ▶ } catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
328 0 my $error = "Failed to connect to database: $_";
329 0 ▶ $logger->error($error) if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 0 0 0
330 0 croak $error;
331 0 };
332  
333 # CHI::Driver::DBI uses the namespace in the table's name.
334 # Keep to letters, digits and underscores, otherwise tools such as
335 # Database::BI can't open it
336 0 $chi_args->{namespace} =~ s/\W/_/g;
337 0 $chi_args->{dbh} = $dbh;
338 0 ▶ $chi_args->{create_table} = $config->{create_table} // 1;
Condition0%0/2
$config->{"create_table"} // 1
l!l
00
MC/DC0%0/1
$config->{"create_table"} // 1
$config->{"create_table"}
Truth table0%0/2
A
A= $config->{"create_table"}
Aresult
11
00
339 }
340  
341 0 ▶sub _configure_shared_memory($chi_args, $config, $args) {
Subroutine _configure_shared_memory: not called CC=7 SCAR=40.3
342 $chi_args->{shm_key} = $args->{'shm_key'} || $config->{shm_key}
343 0 ▶ || croak "SharedMem driver requires 'shm_key' parameter";
Condition0%0/5
$args->{'shm_key'} || $config->{'shm_key'} || croak(q[SharedMem driver requires 'shm_key' parameter])
l!l
00
$args->{"shm_key"} or $config->{"shm_key"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{'shm_key'} || $config->{'shm_key'} || croak(q[SharedMem driver requires 'shm_key' parameter])
$args->{"shm_key"} $config->{"shm_key"}
Truth table0%0/3
A or B
A= $args->{"shm_key"}B= $config->{"shm_key"}
ABresult
1X1
011
000
344  
345 0 ▶ $chi_args->{shm_size} = $args->{'shm_size'} || $config->{shm_size} || 16 * 1024;
Condition0%0/5
$args->{'shm_size'} || $config->{'shm_size'} || 16384
l!l
00
$args->{"shm_size"} or $config->{"shm_size"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{'shm_size'} || $config->{'shm_size'} || 16384
$args->{"shm_size"} $config->{"shm_size"}
Truth table0%0/3
A or B
A= $args->{"shm_size"}B= $config->{"shm_size"}
ABresult
1X1
011
000
346 0 ▶ $chi_args->{max_size} = $args->{'max_size'} || $config->{max_size} || 1024;
Condition0%0/5
$args->{'max_size'} || $config->{'max_size'} || 1024
l!l
00
$args->{"max_size"} or $config->{"max_size"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{'max_size'} || $config->{'max_size'} || 1024
$args->{"max_size"} $config->{"max_size"}
Truth table0%0/3
A or B
A= $args->{"max_size"}B= $config->{"max_size"}
ABresult
1X1
011
000
347 }
348  
349 0 ▶sub _configure_memory($chi_args, $config)
Subroutine _configure_memory: not called CC=2 SCAR=17.9
350 {
351 0 ▶ if(exists $config->{'global'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $config->{'global'}) { } 0 0 0
352 0 $chi_args->{'global'} = $config->{'global'};
353 } else {
354 0 $chi_args->{'datastore'} = {};
355 }
356 }
357  
358 0 ▶sub _configure_memcached($chi_args, $config, $args, $logger) {
Subroutine _configure_memcached: not called CC=3 SCAR=24.8
359 0 my @servers = _parse_server_config($config, $logger);
360 0 ▶ if (@servers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@servers) { } 0 0 0
361 0 $chi_args->{servers} = \@servers;
362 } else {
363 # Default to localhost
364 0 $chi_args->{servers} = ['127.0.0.1:11211'];
365 0 ▶ $logger->debug('Using default Memcached server: 127.0.0.1:11211') if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 0 0 0
366 }
367 }
368  
369 =head2 env_cache_dir
370  
371 The directory that the environment says the caches are to be kept in: the value
372 of C<$CACHEDIR> or, if that is unset or empty, of C<$CACHE_DIR>. Returns undef
373 when neither is set. File-based cache drivers use it in preference to
374 C<root_dir>, which lets an administrator keep the caches outside the site; it is
375 created if it does not exist. It is exported on request.
376  
377 use Web::VWF::Utils qw(env_cache_dir);
378 my $dir = env_cache_dir();
379  
380 =head3 API SPECIFICATION
381  
382 =head4 INPUT
383  
384 {}
385  
386 =head4 OUTPUT
387  
388 { type => 'string', optional => 1 }
389  
390 =cut
391  
392 # Where the environment says the caches go: $CACHEDIR, or failing that
393 # $CACHE_DIR, so that an administrator can put them somewhere better than the
394 # site's own directory without editing any configuration. Undef when neither
395 # is set, or when they are empty.
396 0 ▶sub env_cache_dir() {
Subroutine env_cache_dir: not called CC=4 SCAR=30.0
Pod documented
397 0 foreach my $name (qw(CACHEDIR CACHE_DIR)) {
398 0 my $dir = $ENV{$name};
399 0 ▶ return $dir if(defined($dir) && length($dir));
Branch: 1 branch
BranchTrueFalseTotal
if defined $dir and length $dir 0 0 0
Condition0%0/3
defined $dir and length $dir
!ll&&!rl&&r
000
MC/DC0%0/2
defined $dir and length $dir
defined $dir length $dir
Truth table0%0/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
400 }
401 0 return;
402 }
403  
404 0 ▶sub _configure_file_based($chi_args, $config, $args) {
Subroutine _configure_file_based: not called CC=10 SCAR=47.0
405 # $CACHEDIR / $CACHE_DIR come first: they are set deliberately for the
406 # cache, whereas $root_dir names the whole site and so used to drag the
407 # caches (Berkeley DB files and all) into the site's own directory.
408 0 my $env_dir = env_cache_dir();
409 0 ▶ if(defined($env_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $env_dir) 0 0 0
410 # Unlike the other sources this directory is not expected to have been
411 # made already: it is the one an administrator chose for the purpose
412 0 ▶ make_path($env_dir) unless(-d $env_dir);
Branch: 1 branch
BranchTrueFalseTotal
unless -d $env_dir 0 0 0
413 }
414 0 ▶ my $root_dir = $env_dir || $ENV{'root_dir'} || $args->{'root_dir'} || $config->{root_dir} || $args->{'config'}->{root_dir};
Condition0%0/12
$env_dir || $ENV{'root_dir'} || $args->{'root_dir'} || $config->{'root_dir'} || $args->{'config'}{'root_dir'}
l!l&&r!l&&!r
000
$env_dir or $ENV{"root_dir"} or $args->{"root_dir"} or $config->{"root_dir"}
l!l&&r!l&&!r
000
$env_dir or $ENV{"root_dir"} or $args->{"root_dir"}
l!l&&r!l&&!r
000
$env_dir or $ENV{"root_dir"}
l!l&&r!l&&!r
000
MC/DC0%0/5
$env_dir || $ENV{'root_dir'} || $args->{'root_dir'} || $config->{'root_dir'} || $args->{'config'}{'root_dir'}
$env_dir $ENV{"root_dir"} $args->{"root_dir"} $config->{"root_dir"} $args->{'config'}{'root_dir'}
Truth table0%0/6
A or B or C or D || E
A= $env_dirB= $ENV{"root_dir"}C= $args->{"root_dir"}D= $config->{"root_dir"}E= $args->{'config'}{'root_dir'}
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
415  
416 0 ▶ croak "File-based cache drivers require 'root_dir' parameter" unless $root_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $root_dir 0 0 0
417 0 ▶ croak "Root directory '$root_dir' does not exist or is not writable"
Branch: 1 branch
BranchTrueFalseTotal
unless -d $root_dir and -w $root_dir 0 0 0
Condition0%0/3
-d $root_dir and -w $root_dir
!ll&&!rl&&r
000
MC/DC0%0/2
-d $root_dir and -w $root_dir
-d $root_dir -w $root_dir
Truth table0%0/3
A and B
A= -d $root_dirB= -w $root_dir
ABresult
0X0
100
111
418 unless -d $root_dir && -w $root_dir;
419  
420 0 $chi_args->{root_dir} = $root_dir;
421 }
422  
423 0 ▶sub _parse_server_config($config, $logger) {
Subroutine _parse_server_config: not called CC=10 SCAR=47.0
424 # Handle host/server naming inconsistency
425 0 ▶ my $server_config = $config->{server} || $config->{host};
Condition0%0/3
$config->{'server'} || $config->{'host'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$config->{'server'} || $config->{'host'}
$config->{'server'} $config->{'host'}
Truth table0%0/3
A || B
A= $config->{'server'}B= $config->{'host'}
ABresult
1X1
011
000
426 0 ▶ return () unless $server_config;
Branch: 1 branch
BranchTrueFalseTotal
unless $server_config 0 0 0
427  
428 0 my @servers;
429 0 for my $server_entry (split /,/, $server_config) {
430 0 $server_entry =~ s/^\s+|\s+$//g; # trim whitespace
431  
432 # If no port specified, add default port
433 0 ▶ unless ($server_entry =~ /:/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server_entry =~ /:/u) 0 0 0
434 0 ▶ my $port = $config->{port} || croak "Port not specified for server '$server_entry'";
Condition0%0/2
$config->{'port'} || croak("Port not specified for server '${server_entry}'")
l!l
00
MC/DC0%0/1
$config->{'port'} || croak("Port not specified for server '${server_entry}'")
$config->{'port'}
Truth table0%0/2
A
A= $config->{'port'}
Aresult
11
00
435 0 $server_entry .= ":$port";
436 }
437  
438 # Validate server format
439 0 ▶ if ($server_entry =~ /\A([a-zA-Z0-9.-]+):(\d+)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($server_entry =~ /\A([a-zA-Z0-9.-]+):(\d+)\z/u) { } 0 0 0
440 0 my $port = $2;
441 0 ▶ croak "Invalid port number: $port" unless $port > 0 && $port <= 65535;
Branch: 1 branch
BranchTrueFalseTotal
unless $port > 0 and $port <= 65535 0 0 0
Condition0%0/3
$port > 0 and $port <= 65535
!ll&&!rl&&r
000
MC/DC0%0/2
$port > 0 and $port <= 65535
$port > 0 $port <= 65535
Truth table0%0/3
A and B
A= $port > 0B= $port <= 65535
ABresult
0X0
100
111
442 0 push @servers, $server_entry;
443 0 ▶ $logger->debug("Added server: $server_entry") if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 0 0 0
444 } else {
445 0 croak "Invalid server format: '$server_entry' (expected host:port)";
446 }
447 }
448  
449 0 return @servers;
450 }
451  
452 =head2 redact_config
453  
454 A copy of a configuration, safe to write to a log: the value of any key whose
455 name contains C<secret>, C<password>, C<passwd>, C<key>, C<token> or
456 C<credential> is replaced by C<[REDACTED]>, at any depth. The original is not
457 changed. Debug logs get pasted into bug reports, and the configuration holds
458 the CSRF secret, the reCAPTCHA secret and the DKIM key path.
459  
460 =head3 API SPECIFICATION
461  
462 =head4 INPUT
463  
464 { config => { type => [ 'hashref', 'arrayref', 'string', 'undef' ] } }
465  
466 =head4 OUTPUT
467  
468 { type => [ 'hashref', 'arrayref', 'string', 'undef' ] } # a plain, unblessed copy
469  
470 =cut
471  
472 1 Readonly::Scalar my $REDACTED => '[REDACTED]';
473 1 Readonly::Scalar my $MAX_REDACT_DEPTH => 20; # Stops a self-referencing configuration looping forever
474  
475 32 ▶sub redact_config($config, $depth = 0) {
Subroutine redact_config: called CC=8 SCAR=20.8
Pod documented
476 32 ▶ return '[TOO DEEP]' if($depth > $MAX_REDACT_DEPTH);
Branch: 1 branch
BranchTrueFalseTotal
if $depth > $MAX_REDACT_DEPTH 1 31 32
477  
478 31 ▶ if(ref($config) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $config eq "ARRAY") 1 30 31
479 1 return [ map { redact_config($_, $depth + 1) } @{$config} ];
480 }
481 30 ▶ if((reftype($config) // '') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::reftype($config) // "") eq "HASH") 26 4 30
Condition100%2/2
builtin::reftype($config) // ""
l!l
264
MC/DC100%1/1
builtin::reftype($config) // ""
builtin::reftype($config)
Truth table100%2/2
A
A= builtin::reftype($config)
Aresult
11
00
482 26 my %copy;
483 26 foreach my $key (keys %{$config}) {
484 $copy{$key} = ($key =~ /secret|passw(?:or)?d|key|token|credential/i)
485 ? $REDACTED
486 33 ▶ : redact_config($config->{$key}, $depth + 1);
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /secret|passw(?:or)?d|key|token|credential/iu ? : 6 27 33
487 }
488 26 return \%copy;
489 }
490  
491 4 return $config;
492 }
493  
494 =head2 distance
495  
496 Calculate the great circle distance between two points on Earth using the Haversine formula.
497 More accurate than the original implementation, especially for short distances.
498  
499 Parameters:
500 - lat1, lon1: Latitude and longitude of first point (decimal degrees)
501 - lat2, lon2: Latitude and longitude of second point (decimal degrees)
502 - unit: 'K' for kilometers, 'N' for nautical miles, 'M' or undef for statute miles
503  
504 Returns: Distance in specified units
505  
506 Throws: Error on invalid input parameters
507  
508 =cut
509  
510 0 ▶sub distance($lat1, $lon1, $lat2, $lon2, $unit = 'M') {
Subroutine distance: not called CC=17 SCAR=57.2
Pod documented
511 # Input validation
512 0 for my $coord_ref ([\$lat1, 'lat1'], [\$lon1, 'lon1'], [\$lat2, 'lat2'], [\$lon2, 'lon2']) {
513 0 my ($coord, $name) = @$coord_ref;
514 0 ▶ croak "$name must be defined" unless defined $$coord;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$coord 0 0 0
515 # NaN looks like a number but fails every range test, so would slip through
516 0 ▶ croak "$name must be numeric" unless looks_like_number($$coord) && ($$coord == $$coord);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($$coord) and $$coord == $$coord 0 0 0
Condition0%0/3
&looks_like_number($$coord) and $$coord == $$coord
!ll&&!rl&&r
000
MC/DC0%0/2
&looks_like_number($$coord) and $$coord == $$coord
&looks_like_number($$coord) $$coord == $$coord
Truth table0%0/3
A and B
A= &looks_like_number($$coord)B= $$coord == $$coord
ABresult
0X0
100
111
517 }
518  
519 # Range validation
520 0 ▶ croak('Latitude must be between -90 and 90 degrees')
Branch: 1 branch
BranchTrueFalseTotal
if abs $lat1 > 90 or abs $lat2 > 90 0 0 0
Condition0%0/3
abs $lat1 > 90 or abs $lat2 > 90
l!l&&r!l&&!r
000
MC/DC0%0/2
abs $lat1 > 90 or abs $lat2 > 90
abs $lat1 > 90 abs $lat2 > 90
Truth table0%0/3
A or B
A= abs $lat1 > 90B= abs $lat2 > 90
ABresult
1X1
011
000
521 if abs($lat1) > 90 || abs($lat2) > 90;
522 0 ▶ croak('Longitude must be between -180 and 180 degrees')
Branch: 1 branch
BranchTrueFalseTotal
if abs $lon1 > 180 or abs $lon2 > 180 0 0 0
Condition0%0/3
abs $lon1 > 180 or abs $lon2 > 180
l!l&&r!l&&!r
000
MC/DC0%0/2
abs $lon1 > 180 or abs $lon2 > 180
abs $lon1 > 180 abs $lon2 > 180
Truth table0%0/3
A or B
A= abs $lon1 > 180B= abs $lon2 > 180
ABresult
1X1
011
000
523 if abs($lon1) > 180 || abs($lon2) > 180;
524  
525 # Validate unit before any shortcut, so that a bad unit is always reported
526 0 ▶ $unit = uc($unit || 'M');
Condition0%0/2
$unit || 'M'
l!l
00
MC/DC0%0/1
$unit || 'M'
$unit
Truth table0%0/2
A
A= $unit
Aresult
11
00
527 0 ▶ croak "Unknown unit '$unit'. Use 'K', 'N', or 'M'"
Branch: 1 branch
BranchTrueFalseTotal
unless $unit =~ /\A[KNM]\z/u 0 0 0
528 unless $unit =~ /\A[KNM]\z/;
529  
530 # Handle identical points
531 0 ▶ return 0 if $lat1 == $lat2 && $lon1 == $lon2;
Branch: 1 branch
BranchTrueFalseTotal
if $lat1 == $lat2 and $lon1 == $lon2 0 0 0
Condition0%0/3
$lat1 == $lat2 and $lon1 == $lon2
!ll&&!rl&&r
000
MC/DC0%0/2
$lat1 == $lat2 and $lon1 == $lon2
$lat1 == $lat2 $lon1 == $lon2
Truth table0%0/3
A and B
A= $lat1 == $lat2B= $lon1 == $lon2
ABresult
0X0
100
111
532  
533 # Use optimized calculation with appropriate radius
534 0 ▶ my $radius = $unit eq 'K' ? EARTH_RADIUS_KM :
Branch: 2 branches
BranchTrueFalseTotal
$unit eq 'K' ? : 0 0 0
$unit eq 'N' ? : 0 0 0
535 $unit eq 'N' ? EARTH_RADIUS_NM :
536 EARTH_RADIUS_MILES;
537  
538 # Haversine formula
539 0 my $dlat = deg2rad($lat2 - $lat1);
540 0 my $dlon = deg2rad($lon2 - $lon1);
541 0 my $a = sin($dlat/2)**2 + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dlon/2)**2;
542 # Rounding can push $a fractionally above 1 for near-antipodal points,
543 # and Math::Trig::asin() then returns a Math::Complex rather than a number
544 0 ▶ $a = 1 if $a > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $a > 1 0 0 0
545 0 my $c = 2 * asin(sqrt($a));
546  
547 0 return $radius * $c;
548 }
549  
550 1 1;
551  
552 __END__
« blib/lib/Web/VWF/Display.pm ↑ Summary blib/lib/Web/VWF/CAPTCHA.pm »