From 728f7bb4a5a923cb6a8ff67d694e72cd3d742b31 Mon Sep 17 00:00:00 2001 From: Keith Solomon Date: Wed, 5 Aug 2026 09:55:01 -0500 Subject: [PATCH] fetchLiveVaultBalance: split production/test cache paths so production caching works --- includes/utilities.php | 56 +++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/includes/utilities.php b/includes/utilities.php index 1826f39..c27820e 100644 --- a/includes/utilities.php +++ b/includes/utilities.php @@ -352,39 +352,51 @@ function backfillRunningBalances($pdo, $user) { * @return int|null The vault amount in pennies, or null on failure. */ function fetchLiveVaultBalance($user) { - static $cache = null; - - if ($cache === null) { - $cache = new WeakMap(); - } - - $hook = $GLOBALS['liveBalanceTestHook'] ?? null; - $cacheKey = $hook ?? true; - - if (isset($cache[$cacheKey]) && array_key_exists($user, $cache[$cacheKey])) { - return $cache[$cacheKey][$user]; - } + static $prodCache = []; // production: hook is null, plain per-request array + static $testCache = null; // test: keyed by hook closure (weakly held) if (!array_key_exists($user, USER_KEYS)) { return null; } - $url = 'https://api.torn.com/v2/user?selections=money'; - try { - $responseData = $hook !== null - ? $hook($url, USER_KEYS[$user]) - : executeApiCall($url, USER_KEYS[$user]); + $hook = $GLOBALS['liveBalanceTestHook'] ?? null; - if (!isset($responseData['money']['vault'])) { + if ($hook === null) { + // Production path: plain array cache. + if (array_key_exists($user, $prodCache)) { + return $prodCache[$user]; + } + try { + $responseData = executeApiCall('https://api.torn.com/v2/user?selections=money', USER_KEYS[$user]); + if (!isset($responseData['money']['vault'])) { + $prodCache[$user] = null; + return null; + } + $prodCache[$user] = (int)$responseData['money']['vault']; + return $prodCache[$user]; + } catch (Exception $e) { + $prodCache[$user] = null; return null; } + } - if (!isset($cache[$cacheKey])) { - $cache[$cacheKey] = []; + // Test path: key by hook identity so test scenarios get fresh fetches. + if ($testCache === null) { + $testCache = new \WeakMap(); + } + if (isset($testCache[$hook]) && array_key_exists($user, $testCache[$hook])) { + return $testCache[$hook][$user]; + } + try { + $responseData = $hook('https://api.torn.com/v2/user?selections=money', USER_KEYS[$user]); + if (!isset($responseData['money']['vault'])) { + $testCache[$hook] = [$user => null]; + return null; } - $cache[$cacheKey][$user] = (int)$responseData['money']['vault']; - return $cache[$cacheKey][$user]; + $testCache[$hook] = [$user => (int)$responseData['money']['vault']]; + return $testCache[$hook][$user]; } catch (Exception $e) { + $testCache[$hook] = [$user => null]; return null; } }