refactor dotenv parsing to improve caching logic and ensure readability; update health endpoint to reflect key match status
This commit is contained in:
23
common.php
23
common.php
@ -16,22 +16,25 @@ function qdb_env_file_path(): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a dotenv file (cached per path). Does not use getenv/putenv.
|
||||
* Parse a dotenv file. Does not use getenv/putenv.
|
||||
* Not cached when unreadable (FPM workers can start before .env exists).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
function qdb_parse_env_file(string $path): array {
|
||||
static $cache = [];
|
||||
if (isset($cache[$path])) {
|
||||
return $cache[$path];
|
||||
$mtime = @filemtime($path) ?: 0;
|
||||
$cacheKey = $path . "\0" . $mtime;
|
||||
if ($mtime > 0 && isset($cache[$cacheKey])) {
|
||||
return $cache[$cacheKey];
|
||||
}
|
||||
$out = [];
|
||||
if (!is_readable($path)) {
|
||||
return $cache[$path] = $out;
|
||||
return $out;
|
||||
}
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines === false) {
|
||||
return $cache[$path] = $out;
|
||||
return $out;
|
||||
}
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
@ -56,7 +59,10 @@ function qdb_parse_env_file(string $path): array {
|
||||
}
|
||||
$out[$name] = $value;
|
||||
}
|
||||
return $cache[$path] = $out;
|
||||
if ($mtime > 0) {
|
||||
$cache[$cacheKey] = $out;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -70,6 +76,11 @@ function qdb_env_get(string $name): ?string {
|
||||
if (isset($GLOBALS['qdb_dotenv'][$name]) && $GLOBALS['qdb_dotenv'][$name] !== '') {
|
||||
return $GLOBALS['qdb_dotenv'][$name];
|
||||
}
|
||||
// Do not use getenv() for QDB_MASTER_KEY — FPM can retain a stale system value
|
||||
// when .env was missing on the worker's first request.
|
||||
if ($name === 'QDB_MASTER_KEY') {
|
||||
return null;
|
||||
}
|
||||
$v = getenv($name);
|
||||
if ($v !== false && $v !== '') {
|
||||
return $v;
|
||||
|
||||
Reference in New Issue
Block a user