diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts index 96f94a9..2298430 100644 --- a/apps/api/src/controllers/auth.ts +++ b/apps/api/src/controllers/auth.ts @@ -37,7 +37,7 @@ function normalizedApiIsUuid(potentialUuid: string): boolean { 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 redLockKey = `lock_${cacheKeyACUC}`; 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); 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 // a maximum of 10 minutes of a delay. - mogery await setValue(cacheKeyACUC, JSON.stringify(acuc), 600); diff --git a/apps/api/src/services/billing/credit_billing.ts b/apps/api/src/services/billing/credit_billing.ts index 56de74e..56b02da 100644 --- a/apps/api/src/services/billing/credit_billing.ts +++ b/apps/api/src/services/billing/credit_billing.ts @@ -32,16 +32,12 @@ export async function supaBillTeam(team_id: string, subscription_id: string, cre (async () => { for (const apiKey of (data ?? []).map(x => x.api_key)) { - const acuc = await getACUC(apiKey, true); - - if (acuc !== null) { - await setCachedACUC(apiKey, { - ...acuc, - credits_used: acuc.credits_used + credits, - adjusted_credits_used: acuc.adjusted_credits_used + credits, - remaining_credits: acuc.remaining_credits - credits, - }); - } + await setCachedACUC(apiKey, acuc => (acuc ? { + ...acuc, + credits_used: acuc.credits_used + credits, + adjusted_credits_used: acuc.adjusted_credits_used + credits, + remaining_credits: acuc.remaining_credits - credits, + } : null)); } })(); }