| 1 | package Test::CPAN::Health::Cache; | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use autodie qw(:all); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | use Carp qw(croak carp); | ||
| 8 | use DBI; | ||
| 9 | use File::Path qw(make_path); | ||
| 10 | use File::Spec; | ||
| 11 | use JSON::MaybeXS qw(encode_json decode_json); | ||
| 12 | use Readonly; | ||
| 13 | use Params::Validate::Strict qw(validate_strict); | ||
| 14 | |||
| 15 | our $VERSION = '0.1.0'; | ||
| 16 | |||
| 17 | # Default TTLs in seconds, keyed by check id prefix convention. | ||
| 18 | # Network-heavy checks have shorter TTLs so stale data is not kept too long; | ||
| 19 | # package metadata is stable enough for 24 hours. | ||
| 20 | Readonly::Hash my %DEFAULT_TTLS => ( | ||
| 21 | cpan_testers => 3_600, # 1 hour -- changes as smoke results arrive | ||
| 22 | security_advisories => 3_600, # 1 hour -- advisory DB updated frequently | ||
| 23 | stale_deps => 86_400, # 24 hours -- release cadence is daily at most | ||
| 24 | abandoned_deps => 86_400, # 24 hours | ||
| 25 | reverse_deps => 86_400, # 24 hours | ||
| 26 | kwalitee => 86_400, # 24 hours | ||
| 27 | DEFAULT => 86_400, # 24 hours for everything else | ||
| 28 | ); | ||
| 29 | |||
| 30 | Readonly::Scalar my $SCHEMA_VERSION => 1; | ||
| 31 | |||
| 32 | =head1 NAME | ||
| 33 | |||
| 34 | Test::CPAN::Health::Cache - Persistent SQLite cache for network check results | ||
| 35 | |||
| 36 | =head1 SYNOPSIS | ||
| 37 | |||
| 38 | use Test::CPAN::Health::Cache; | ||
| 39 | |||
| 40 | my $cache = Test::CPAN::Health::Cache->new( | ||
| 41 | cache_dir => "$ENV{HOME}/.cache/cpan-health", | ||
| 42 | ); | ||
| 43 | |||
| 44 | $cache->store('sem_ver:Foo-Bar:1.00', { status => 'pass', score => 100 }); | ||
| 45 | my $data = $cache->get('sem_ver:Foo-Bar:1.00'); | ||
| 46 | |||
| 47 | =head1 DESCRIPTION | ||
| 48 | |||
| 49 | A lightweight SQLite-backed key/value store that persists health check | ||
| 50 | results between runs to avoid hammering rate-limited external APIs. | ||
| 51 | |||
| 52 | Each entry has a TTL (seconds); C<get> returns C<undef> and behaves as a | ||
| 53 | cache miss for expired entries. TTLs are keyed by check id prefix against | ||
| 54 | the C<%DEFAULT_TTLS> table; unknown checks fall back to 24 hours. | ||
| 55 | |||
| 56 | The database is created automatically on first use under C<cache_dir>. | ||
| 57 | |||
| 58 | =head1 LIMITATIONS | ||
| 59 | |||
| 60 | =over 4 | ||
| 61 | |||
| 62 | =item * No row-level locking; concurrent processes writing the same key may | ||
| 63 | race. SQLite's journal mode provides transaction safety but not write ordering. | ||
| 64 | |||
| 65 | =item * Expired rows are pruned lazily on C<get> and on a scheduled sweep; | ||
| 66 | disk usage may grow unboundedly if C<purge> is never called. | ||
| 67 | |||
| 68 | =back | ||
| 69 | |||
| 70 | =cut | ||
| 71 | |||
| 72 | sub new { | ||
| 73 | my ($class, %args) = @_; | ||
| 74 | |||
| 75 | %args = %{ validate_strict( | ||
| 76 | schema => { | ||
| 77 | cache_dir => { type => 'string', optional => 1, default => _default_cache_dir() }, | ||
| 78 | ttls => { type => 'hashref', optional => 1 }, | ||
| 79 | }, | ||
| 80 | input => \%args, | ||
| 81 | ) }; | ||
| 82 | |||
| 83 | my %ttls = (%DEFAULT_TTLS, %{ $args{ttls} // {} }); | ||
| 84 | |||
| 85 | my $self = bless { | ||
| 86 | _cache_dir => $args{cache_dir}, | ||
| 87 | _ttls => \%ttls, | ||
| 88 | _dbh => undef, | ||
| 89 | }, $class; | ||
| 90 | |||
| 91 | return $self; | ||
| 92 | } | ||
| 93 | |||
| 94 | =head2 get | ||
| 95 | |||
| 96 | Retrieve a cached value by key. Returns C<undef> on cache miss or if the | ||
| 97 | entry has expired. | ||
| 98 | |||
| 99 | =head3 API SPECIFICATION | ||
| 100 | |||
| 101 | =head4 INPUT | ||
| 102 | |||
| 103 | key Scalar required opaque cache key (e.g. 'sem_ver:Foo-Bar:1.00') | ||
| 104 | |||
| 105 | =head4 OUTPUT | ||
| 106 | |||
| 107 | Hashref of the stored data, or C<undef> on miss/expiry. | ||
| 108 | |||
| 109 | =head3 MESSAGES | ||
| 110 | |||
| 111 | Code | Severity | Message | Resolution | ||
| 112 | ------+----------+------------------------------------+--------------------- | ||
| 113 | CAC01 | WARNING | Cache read error: {msg} | Check DB permissions | ||
| 114 | |||
| 115 | =head3 FORMAL SPECIFICATION | ||
| 116 | |||
| 117 | -- Z schema (placeholder) -- | ||
| 118 | GetOp | ||
| 119 | key? : String | ||
| 120 | value! : Hashref | undefined | ||
| 121 | now : Timestamp | ||
| 122 | ------------------------------------------------------- | ||
| 123 | key? /= "" | ||
| 124 | value! /= undefined <=> exists entry(key?) /\ entry(key?).expires > now | ||
| 125 | |||
| 126 | =head3 SIDE EFFECTS | ||
| 127 | |||
| 128 | May delete expired rows from the SQLite database. | ||
| 129 | |||
| 130 | =head3 USAGE EXAMPLE | ||
| 131 | |||
| 132 | my $data = $cache->get('security_advisories:Foo-Bar:1.00'); | ||
| 133 | |||
| 134 | =cut | ||
| 135 | |||
| 136 | sub get { | ||
| 137 | my ($self, $key) = @_; | ||
| 138 | |||
| 139 | croak 'key is required' unless defined $key && length $key; | ||
| 140 | |||
| 141 | my $dbh = $self->_dbh; | ||
| 142 | my $now = time; | ||
| 143 | |||
| 144 | my $row = eval { | ||
| 145 | $dbh->selectrow_hashref( | ||
| 146 | 'SELECT value FROM cache WHERE key = ? AND expires > ?', | ||
| 147 | undef, $key, $now, | ||
| 148 | ); | ||
| 149 | }; | ||
| 150 | |||
| 151 | if ($@) { | ||
| 152 | carp "Cache read error: $@"; | ||
| 153 | return; | ||
| 154 | } | ||
| 155 | |||
| 156 | return unless defined $row; | ||
| 157 | |||
| 158 | my $data = eval { decode_json($row->{value}); }; | ||
| 159 | if ($@) { | ||
| 160 | carp "Cache JSON decode error for key '$key': $@"; | ||
| 161 | return; | ||
| 162 | } | ||
| 163 | |||
| 164 | return $data; | ||
| 165 | } | ||
| 166 | |||
| 167 | =head2 store | ||
| 168 | |||
| 169 | =head3 PURPOSE | ||
| 170 | |||
| 171 | Store a value in the cache under the given key. The TTL is determined | ||
| 172 | automatically from the check id embedded in the key (first colon-delimited | ||
| 173 | segment) using the C<%DEFAULT_TTLS> table. | ||
| 174 | |||
| 175 | =head3 API SPECIFICATION | ||
| 176 | |||
| 177 | =head4 INPUT | ||
| 178 | |||
| 179 | key Scalar required | ||
| 180 | value Hashref required | ||
| 181 | ttl Scalar optional override TTL in seconds | ||
| 182 | |||
| 183 | =head4 OUTPUT | ||
| 184 | |||
| 185 | Returns C<$self>. | ||
| 186 | |||
| 187 | =head3 MESSAGES | ||
| 188 | |||
| 189 | Code | Severity | Message | Resolution | ||
| 190 | ------+----------+------------------------------------+--------------------- | ||
| 191 | CAC02 | WARNING | Cache write error: {msg} | Check DB permissions/disk space | ||
| 192 | |||
| 193 | =head3 FORMAL SPECIFICATION | ||
| 194 | |||
| 195 | -- Z schema (placeholder) -- | ||
| 196 | SetOp | ||
| 197 | Cache | ||
| 198 | Cache' | ||
| 199 | key? : String | ||
| 200 | value? : Hashref | ||
| 201 | ttl? : N | undefined | ||
| 202 | now : Timestamp | ||
| 203 | ------------------------------------------------------- | ||
| 204 | Cache'.entries = Cache.entries (+) {key? |-> {value: value?, expires: now + ttl?}} | ||
| 205 | |||
| 206 | =head3 SIDE EFFECTS | ||
| 207 | |||
| 208 | Writes to the SQLite database. | ||
| 209 | |||
| 210 | =head3 USAGE EXAMPLE | ||
| 211 | |||
| 212 | $cache->store('sem_ver:Foo-Bar:1.00', { status => 'pass', score => 100 }); | ||
| 213 | |||
| 214 | =cut | ||
| 215 | |||
| 216 | sub store { | ||
| 217 | my ($self, $key, $value, $ttl) = @_; | ||
| 218 | |||
| 219 | croak 'key is required' unless defined $key && length $key; | ||
| 220 | croak 'value is required' unless defined $value && ref $value eq 'HASH'; | ||
| 221 | |||
| 222 | $ttl //= $self->_ttl_for($key); | ||
| 223 | |||
| 224 | my $json = encode_json($value); | ||
| 225 | my $expires = time + $ttl; | ||
| 226 | my $dbh = $self->_dbh; | ||
| 227 | |||
| 228 | eval { | ||
| 229 | $dbh->do( | ||
| 230 | 'INSERT OR REPLACE INTO cache (key, value, expires) VALUES (?, ?, ?)', | ||
| 231 | undef, $key, $json, $expires, | ||
| 232 | ); | ||
| 233 | 1; | ||
| 234 | } or do { | ||
| 235 | carp "Cache write error: $@"; | ||
| 236 | }; | ||
| 237 | |||
| 238 | return $self; | ||
| 239 | } | ||
| 240 | |||
| 241 | =head2 record_history | ||
| 242 | |||
| 243 | =head3 PURPOSE | ||
| 244 | |||
| 245 | Record an overall health score for a distribution version. Used by the | ||
| 246 | Runner to build a score-over-time trend. | ||
| 247 | |||
| 248 | =head3 API SPECIFICATION | ||
| 249 | |||
| 250 | =head4 INPUT | ||
| 251 | |||
| 252 | dist Scalar required Distribution name (e.g. 'LWP-UserAgent') | ||
| 253 | version Scalar required Version string | ||
| 254 | score Scalar required Integer score 0..100 | ||
| 255 | |||
| 256 | =head4 OUTPUT | ||
| 257 | |||
| 258 | Returns C<$self>. | ||
| 259 | |||
| 260 | =head3 MESSAGES | ||
| 261 | |||
| 262 | Code | Severity | Message | Resolution | ||
| 263 | ------+----------+------------------------------------+--------------------- | ||
| 264 | CAC04 | WARNING | History write error: {msg} | Check DB permissions | ||
| 265 | |||
| 266 | =head3 FORMAL SPECIFICATION | ||
| 267 | |||
| 268 | Post: score_history table gains one row (dist, version, score, time()) | ||
| 269 | |||
| 270 | =head3 SIDE EFFECTS | ||
| 271 | |||
| 272 | Writes to the SQLite database. | ||
| 273 | |||
| 274 | =head3 USAGE EXAMPLE | ||
| 275 | |||
| 276 | $cache->record_history('LWP-UserAgent', '6.77', 95); | ||
| 277 | |||
| 278 | =cut | ||
| 279 | |||
| 280 | sub record_history { | ||
| 281 | my ($self, $dist, $version, $score) = @_; | ||
| 282 | |||
| 283 | croak 'dist is required' unless defined $dist && length $dist; | ||
| 284 | croak 'version is required' unless defined $version && length $version; | ||
| 285 | croak 'score is required' unless defined $score; | ||
| 286 | |||
| 287 | eval { | ||
| 288 | $self->_dbh->do( | ||
| 289 | 'INSERT INTO score_history (dist, version, score, recorded) VALUES (?, ?, ?, ?)', | ||
| 290 | undef, $dist, $version, $score + 0, time, | ||
| 291 | ); | ||
| 292 | 1; | ||
| 293 | } or do { | ||
| 294 | carp "History write error: $@"; | ||
| 295 | }; | ||
| 296 | |||
| 297 | return $self; | ||
| 298 | } | ||
| 299 | |||
| 300 | =head2 score_history | ||
| 301 | |||
| 302 | =head3 PURPOSE | ||
| 303 | |||
| 304 | Retrieve recent score history for a distribution in reverse-chronological | ||
| 305 | order. | ||
| 306 | |||
| 307 | =head3 API SPECIFICATION | ||
| 308 | |||
| 309 | =head4 INPUT | ||
| 310 | |||
| 311 | dist Scalar required Distribution name | ||
| 312 | limit Integer optional Maximum rows to return (default: 10) | ||
| 313 | |||
| 314 | =head4 OUTPUT | ||
| 315 | |||
| 316 | Arrayref of hashrefs with keys C<dist>, C<version>, C<score>, C<recorded> | ||
| 317 | (Unix timestamp). Most-recent first. | ||
| 318 | |||
| 319 | =head3 MESSAGES | ||
| 320 | |||
| 321 | Code | Severity | Message | Resolution | ||
| 322 | ------+----------+------------------------------------+--------------------- | ||
| 323 | CAC05 | WARNING | History read error: {msg} | Check DB permissions | ||
| 324 | |||
| 325 | =head3 FORMAL SPECIFICATION | ||
| 326 | |||
| 327 | Post: result is an arrayref of at most limit rows for dist, ordered by recorded DESC | ||
| 328 | |||
| 329 | =head3 SIDE EFFECTS | ||
| 330 | |||
| 331 | Reads from the SQLite database. | ||
| 332 | |||
| 333 | =head3 USAGE EXAMPLE | ||
| 334 | |||
| 335 | for my $row (@{ $cache->score_history('LWP-UserAgent') }) { | ||
| 336 | printf "%s: %d\n", scalar localtime($row->{recorded}), $row->{score}; | ||
| 337 | } | ||
| 338 | |||
| 339 | =cut | ||
| 340 | |||
| 341 | sub score_history { | ||
| 342 | my ($self, $dist, $limit) = @_; | ||
| 343 | |||
| 344 | croak 'dist is required' unless defined $dist && length $dist; | ||
| 345 | $limit //= 10; | ||
| 346 | |||
| 347 | my $rows = eval { | ||
| 348 | $self->_dbh->selectall_arrayref( | ||
| 349 | 'SELECT dist, version, score, recorded FROM score_history' | ||
| 350 | . ' WHERE dist = ? ORDER BY recorded DESC LIMIT ?', | ||
| 351 | { Slice => {} }, $dist, $limit, | ||
| 352 | ); | ||
| 353 | }; | ||
| 354 | |||
| 355 | if ($@) { | ||
| 356 | carp "History read error: $@"; | ||
| 357 | return []; | ||
| 358 | } | ||
| 359 | |||
| 360 | return $rows // []; | ||
| 361 | } | ||
| 362 | |||
| 363 | =head2 purge | ||
| 364 | |||
| 365 | =head3 PURPOSE | ||
| 366 | |||
| 367 | Delete all expired entries from the cache database. Intended to be called | ||
| 368 | periodically (e.g. at CLI startup) to reclaim disk space. | ||
| 369 | |||
| 370 | =head3 API SPECIFICATION | ||
| 371 | |||
| 372 | =head4 INPUT | ||
| 373 | |||
| 374 | None. | ||
| 375 | |||
| 376 | =head4 OUTPUT | ||
| 377 | |||
| 378 | Integer: number of rows deleted. | ||
| 379 | |||
| 380 | =head3 MESSAGES | ||
| 381 | |||
| 382 | Code | Severity | Message | Resolution | ||
| 383 | ------+----------+------------------------------------+--------------------- | ||
| 384 | CAC03 | WARNING | Cache purge error: {msg} | Check DB permissions | ||
| 385 | |||
| 386 | =head3 FORMAL SPECIFICATION | ||
| 387 | |||
| 388 | -- Z schema (placeholder) -- | ||
| 389 | PurgeOp | ||
| 390 | Cache | ||
| 391 | Cache' | ||
| 392 | now : Timestamp | ||
| 393 | deleted : N | ||
| 394 | ------------------------------------------------------- | ||
| 395 | Cache'.entries = {e : Cache.entries | e.expires > now} | ||
| 396 | deleted = #Cache.entries - #Cache'.entries | ||
| 397 | |||
| 398 | =head3 SIDE EFFECTS | ||
| 399 | |||
| 400 | Deletes rows from the SQLite database. | ||
| 401 | |||
| 402 | =head3 USAGE EXAMPLE | ||
| 403 | |||
| 404 | printf "Purged %d stale cache entries\n", $cache->purge; | ||
| 405 | |||
| 406 | =cut | ||
| 407 | |||
| 408 | sub purge { | ||
| 409 | my ($self) = @_; | ||
| 410 | |||
| 411 | my $dbh = $self->_dbh; | ||
| 412 | my $deleted = 0; | ||
| 413 | |||
| 414 | eval { | ||
| 415 | $deleted = $dbh->do('DELETE FROM cache WHERE expires <= ?', undef, time); | ||
| 416 | $deleted = 0 if $deleted eq '0E0'; | ||
| 417 | 1; | ||
| 418 | } or do { | ||
| 419 | carp "Cache purge error: $@"; | ||
| 420 | }; | ||
| 421 | |||
| 422 | return $deleted; | ||
| 423 | } | ||
| 424 | |||
| 425 | # --------------------------------------------------------------------------- | ||
| 426 | # Private helpers | ||
| 427 | # --------------------------------------------------------------------------- | ||
| 428 | |||
| 429 | # Return or create the DBI handle, creating the schema on first connect. | ||
| 430 | sub _dbh { | ||
| 431 | my ($self) = @_; | ||
| 432 | |||
| 433 | return $self->{_dbh} if $self->{_dbh}; | ||
| 434 | |||
| 435 | make_path($self->{_cache_dir}) unless -d $self->{_cache_dir}; | ||
| 436 | |||
| 437 | my $db_file = File::Spec->catfile($self->{_cache_dir}, 'cpan-health.db'); | ||
| 438 | |||
| 439 | $self->{_dbh} = DBI->connect( | ||
| 440 | "dbi:SQLite:dbname=$db_file", '', '', | ||
| 441 | { | ||
| 442 | RaiseError => 1, | ||
| 443 | AutoCommit => 1, | ||
| 444 | PrintError => 0, | ||
| 445 | }, | ||
| 446 | ) or croak "Cannot open cache database '$db_file': " . DBI->errstr; | ||
| 447 | |||
| 448 | # WAL mode: allows concurrent reads while a write is in progress. | ||
| 449 | $self->{_dbh}->do('PRAGMA journal_mode=WAL'); | ||
| 450 | $self->_ensure_schema; | ||
| 451 | |||
| 452 | return $self->{_dbh}; | ||
| 453 | } | ||
| 454 | |||
| 455 | sub _ensure_schema { | ||
| 456 | my ($self) = @_; | ||
| 457 | |||
| 458 | $self->{_dbh}->do(<<'SQL'); | ||
| 459 | CREATE TABLE IF NOT EXISTS cache ( | ||
| 460 | key TEXT PRIMARY KEY, | ||
| 461 | value TEXT NOT NULL, | ||
| 462 | expires INTEGER NOT NULL | ||
| 463 | ) | ||
| 464 | SQL | ||
| 465 | |||
| 466 | $self->{_dbh}->do('CREATE INDEX IF NOT EXISTS idx_cache_expires ON cache (expires)'); | ||
| 467 | |||
| 468 | $self->{_dbh}->do(<<'SQL'); | ||
| 469 | CREATE TABLE IF NOT EXISTS score_history ( | ||
| 470 | dist TEXT NOT NULL, | ||
| 471 | version TEXT NOT NULL, | ||
| 472 | score INTEGER NOT NULL, | ||
| 473 | recorded INTEGER NOT NULL | ||
| 474 | ) | ||
| 475 | SQL | ||
| 476 | |||
| 477 | $self->{_dbh}->do( | ||
| 478 | 'CREATE INDEX IF NOT EXISTS idx_history_dist ON score_history (dist, recorded)' | ||
| 479 | ); | ||
| 480 | |||
| 481 | return; | ||
| 482 | } | ||
| 483 | |||
| 484 | # Look up TTL for a key by matching the check id (first colon-segment). | ||
| 485 | sub _ttl_for { | ||
| 486 | my ($self, $key) = @_; | ||
| 487 | |||
| 488 | my ($check_id) = split / : /x, $key, 2; | ||
| 489 | |||
| 490 | return $self->{_ttls}{$check_id} // $self->{_ttls}{DEFAULT} // 86_400; | ||
| 491 | } | ||
| 492 | |||
| 493 | sub _default_cache_dir { | ||
| 494 | my $base = $ENV{CACHEDIR} || $ENV{CACHE_DIR} | ||
| 495 | || File::Spec->catdir( | ||
| 496 | $ENV{HOME} // $ENV{USERPROFILE} // File::Spec->tmpdir(), | ||
| 497 | '.cache', | ||
| 498 | ); | ||
| 499 | return File::Spec->catdir($base, 'cpan-health'); | ||
| 500 | } | ||
| 501 | |||
| 502 | sub DESTROY { | ||
| 503 | my ($self) = @_; | ||
| 504 | |||
| 505 | if ($self->{_dbh}) { | ||
| 506 | $self->{_dbh}->disconnect; | ||
| 507 | $self->{_dbh} = undef; | ||
| 508 | } | ||
| 509 | |||
| 510 | return; | ||
| 511 | } | ||
| 512 | |||
| 513 | =head1 AUTHOR | ||
| 514 | |||
| 515 | Nigel Horne, C<< <njh at nigelhorne.com> >> | ||
| 516 | |||
| 517 | =head1 LICENSE AND COPYRIGHT | ||
| 518 | |||
| 519 | Copyright (C) 2026 Nigel Horne. | ||
| 520 | |||
| 521 | This program is free software; you can redistribute it and/or modify it | ||
| 522 | under the terms of the GNU General Public License as published by the Free | ||
| 523 | Software Foundation; either version 2 of the License, or (at your option) | ||
| 524 | any later version. | ||
| 525 | |||
| 526 | =cut | ||
| 527 | |||
| 528 | 1; | ||