Don't retry transactions during development

This commit is contained in:
Konstantin Wohlwend 2024-12-12 13:48:18 -08:00
parent c33ce8ab4f
commit a80a3b241c
2 changed files with 13 additions and 8 deletions

View File

@ -19,6 +19,8 @@ if (getNodeEnvironment() !== 'production') {
export async function maybeTransactionWithRetry<T>(fn: (...args: Parameters<Parameters<typeof prismaClient.$transaction>[0]>) => Promise<T>): Promise<T> {
const isDev = getNodeEnvironment() === 'development';
const res = await Result.retry(async () => {
try {
return Result.ok(await prismaClient.$transaction(fn));
@ -29,14 +31,17 @@ export async function maybeTransactionWithRetry<T>(fn: (...args: Parameters<Para
}
throw e;
}
}, 0);
}, isDev ? 1 : 3);
if (res.status === 'ok') {
return res.data;
}
const retriesFailedWarning = new StackAssertionError("Failed to execute transaction despite retries! Falling back to non-transactional execution, which may cause data inconsistency.", { cause: res.error });
captureError('maybeTransactionWithRetry', retriesFailedWarning);
return await fn(prismaClient);
if (isDev) {
throw retriesFailedWarning;
} else {
captureError('maybeTransactionWithRetry', retriesFailedWarning);
return await fn(prismaClient);
}
}

View File

@ -128,7 +128,7 @@ class RetryError extends AggregateError {
super(
errors,
deindent`
Error after retrying ${errors.length} times.
Error after ${errors.length} attempts.
${isAllSame ? deindent`
Attempts 1-${errors.length}:
@ -151,17 +151,17 @@ RetryError.prototype.name = "RetryError";
async function retry<T>(
fn: (attempt: number) => Result<T> | Promise<Result<T>>,
retries: number,
totalAttempts: number,
{ exponentialDelayBase = 1000 } = {},
): Promise<Result<T, RetryError>> {
const errors: unknown[] = [];
for (let i = 0; i < retries; i++) {
for (let i = 0; i < totalAttempts; i++) {
const res = await fn(i);
if (res.status === "ok") {
return Result.ok(res.data);
} else {
errors.push(res.error);
if (i < retries - 1) {
if (i < totalAttempts - 1) {
await wait((Math.random() + 0.5) * exponentialDelayBase * (2 ** i));
}
}