diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts index 2298430e..91bfef1f 100644 --- a/apps/api/src/controllers/auth.ts +++ b/apps/api/src/controllers/auth.ts @@ -40,27 +40,29 @@ function normalizedApiIsUuid(potentialUuid: string): boolean { 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 try { - const lock = await redlock.acquire([redLockKey], lockTTL); - - try { + await redlock.using([redLockKey], 10000, {}, async signal => { if (typeof acuc === "function") { acuc = acuc(JSON.parse(await getValue(cacheKeyACUC))); if (acuc === null) { - await lock.release(); + if (signal.aborted) { + throw signal.error; + } + return; } } + if (signal.aborted) { + throw signal.error; + } + // 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); - } finally { - await lock.release(); - } + }); } catch (error) { Logger.error(`Error updating cached ACUC: ${error}`); Sentry.captureException(error); diff --git a/apps/api/src/services/redlock.ts b/apps/api/src/services/redlock.ts index cb275736..4ece058a 100644 --- a/apps/api/src/services/redlock.ts +++ b/apps/api/src/services/redlock.ts @@ -11,7 +11,7 @@ export const redlock = new Redlock( driftFactor: 0.01, // multiplied by lock ttl to determine drift time retryCount: 200, - + retryDelay: 100, // the max time in ms randomly added to retries