fetchLiveVaultBalance: split production/test cache paths so production caching works

This commit is contained in:
Keith Solomon
2026-08-05 09:55:01 -05:00
parent abb353a939
commit 728f7bb4a5
+35 -23
View File
@@ -352,39 +352,51 @@ function backfillRunningBalances($pdo, $user) {
* @return int|null The vault amount in pennies, or null on failure. * @return int|null The vault amount in pennies, or null on failure.
*/ */
function fetchLiveVaultBalance($user) { function fetchLiveVaultBalance($user) {
static $cache = null; static $prodCache = []; // production: hook is null, plain per-request array
static $testCache = null; // test: keyed by hook closure (weakly held)
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];
}
if (!array_key_exists($user, USER_KEYS)) { if (!array_key_exists($user, USER_KEYS)) {
return null; return null;
} }
$url = 'https://api.torn.com/v2/user?selections=money'; $hook = $GLOBALS['liveBalanceTestHook'] ?? null;
try {
$responseData = $hook !== null
? $hook($url, USER_KEYS[$user])
: executeApiCall($url, USER_KEYS[$user]);
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'])) { if (!isset($responseData['money']['vault'])) {
$prodCache[$user] = null;
return null; return null;
} }
$prodCache[$user] = (int)$responseData['money']['vault'];
if (!isset($cache[$cacheKey])) { return $prodCache[$user];
$cache[$cacheKey] = [];
}
$cache[$cacheKey][$user] = (int)$responseData['money']['vault'];
return $cache[$cacheKey][$user];
} catch (Exception $e) { } catch (Exception $e) {
$prodCache[$user] = null;
return null;
}
}
// 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;
}
$testCache[$hook] = [$user => (int)$responseData['money']['vault']];
return $testCache[$hook][$user];
} catch (Exception $e) {
$testCache[$hook] = [$user => null];
return null; return null;
} }
} }