fix(billTeam): cache update race condition

This commit is contained in:
Gergő Móricz 2024-09-25 22:15:02 +02:00
parent d13a97f979
commit 0f89f5e7cb
2 changed files with 16 additions and 11 deletions

View File

@ -37,7 +37,7 @@ function normalizedApiIsUuid(potentialUuid: string): boolean {
return validate(potentialUuid); return validate(potentialUuid);
} }
export async function setCachedACUC(api_key: string, acuc: AuthCreditUsageChunk) { export async function setCachedACUC(api_key: string, acuc: AuthCreditUsageChunk | ((acuc: AuthCreditUsageChunk) => AuthCreditUsageChunk)) {
const cacheKeyACUC = `acuc_${api_key}`; const cacheKeyACUC = `acuc_${api_key}`;
const redLockKey = `lock_${cacheKeyACUC}`; const redLockKey = `lock_${cacheKeyACUC}`;
const lockTTL = 10000; // 10 seconds const lockTTL = 10000; // 10 seconds
@ -46,6 +46,15 @@ export async function setCachedACUC(api_key: string, acuc: AuthCreditUsageChunk)
const lock = await redlock.acquire([redLockKey], lockTTL); const lock = await redlock.acquire([redLockKey], lockTTL);
try { try {
if (typeof acuc === "function") {
acuc = acuc(JSON.parse(await getValue(cacheKeyACUC)));
if (acuc === null) {
await lock.release();
return;
}
}
// Cache for 10 minutes. This means that changing subscription tier could have // Cache for 10 minutes. This means that changing subscription tier could have
// a maximum of 10 minutes of a delay. - mogery // a maximum of 10 minutes of a delay. - mogery
await setValue(cacheKeyACUC, JSON.stringify(acuc), 600); await setValue(cacheKeyACUC, JSON.stringify(acuc), 600);

View File

@ -32,16 +32,12 @@ export async function supaBillTeam(team_id: string, subscription_id: string, cre
(async () => { (async () => {
for (const apiKey of (data ?? []).map(x => x.api_key)) { for (const apiKey of (data ?? []).map(x => x.api_key)) {
const acuc = await getACUC(apiKey, true); await setCachedACUC(apiKey, acuc => (acuc ? {
...acuc,
if (acuc !== null) { credits_used: acuc.credits_used + credits,
await setCachedACUC(apiKey, { adjusted_credits_used: acuc.adjusted_credits_used + credits,
...acuc, remaining_credits: acuc.remaining_credits - credits,
credits_used: acuc.credits_used + credits, } : null));
adjusted_credits_used: acuc.adjusted_credits_used + credits,
remaining_credits: acuc.remaining_credits - credits,
});
}
} }
})(); })();
} }