fix(redlock): use redlock.using for stability

This commit is contained in:
Gergő Móricz 2024-09-25 22:47:42 +02:00
parent 250c3bb5c6
commit 9bdd344b36
2 changed files with 11 additions and 9 deletions

View File

@ -40,27 +40,29 @@ function normalizedApiIsUuid(potentialUuid: string): boolean {
export async function setCachedACUC(api_key: string, acuc: AuthCreditUsageChunk | ((acuc: AuthCreditUsageChunk) => 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
try { try {
const lock = await redlock.acquire([redLockKey], lockTTL); await redlock.using([redLockKey], 10000, {}, async signal => {
try {
if (typeof acuc === "function") { if (typeof acuc === "function") {
acuc = acuc(JSON.parse(await getValue(cacheKeyACUC))); acuc = acuc(JSON.parse(await getValue(cacheKeyACUC)));
if (acuc === null) { if (acuc === null) {
await lock.release(); if (signal.aborted) {
throw signal.error;
}
return; return;
} }
} }
if (signal.aborted) {
throw signal.error;
}
// 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);
} finally { });
await lock.release();
}
} catch (error) { } catch (error) {
Logger.error(`Error updating cached ACUC: ${error}`); Logger.error(`Error updating cached ACUC: ${error}`);
Sentry.captureException(error); Sentry.captureException(error);

View File

@ -11,7 +11,7 @@ export const redlock = new Redlock(
driftFactor: 0.01, // multiplied by lock ttl to determine drift time driftFactor: 0.01, // multiplied by lock ttl to determine drift time
retryCount: 200, retryCount: 200,
retryDelay: 100, retryDelay: 100,
// the max time in ms randomly added to retries // the max time in ms randomly added to retries