Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(billTeam): cache update race condition
Gergő Móricz0f89f5e7cb96
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.tsindex 96f94a99c..2298430e7 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. - mogeryawait 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.tsindex 56de74e52..56b02dad1 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));}})();}