From 82a1614a5881451bd3fd716cc6984812c27bc98a Mon Sep 17 00:00:00 2001 From: "tom.hempel" Date: Mon, 1 Jun 2026 19:11:12 +0200 Subject: [PATCH] refactor dotenv parsing to improve caching logic and ensure readability; update health endpoint to reflect key match status --- common.php | 23 +++++++++++++++++------ handlers/health.php | 2 +- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/common.php b/common.php index 61f73ca..29a6964 100644 --- a/common.php +++ b/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 */ 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; diff --git a/handlers/health.php b/handlers/health.php index 1b31be2..a840cb0 100644 --- a/handlers/health.php +++ b/handlers/health.php @@ -38,5 +38,5 @@ json_success([ 'dbBytes' => is_file(QDB_PATH) ? filesize(QDB_PATH) : 0, 'dbOpenOk' => $dbOpenOk, 'dbError' => $dbError, - 'expectedKeySha'=> 'e584e16eb81fbb4f1e3aac965b5225c5fefabc2a67ea20e26e55671c7d9f1ae7', + 'keyMatchesCli' => $keySha === 'e584e16eb81fbb4f1e3aac965b5225c5fefabc2a67ea20e26e55671c7d9f1ae7', ]);