|
| 1 | +import { Logger } from '@nestjs/common'; |
| 2 | +import { HttpErrorCode } from '@teable/core'; |
| 3 | +import { thresholdConfig } from '../configs/threshold.config'; |
| 4 | +import { CustomHttpException } from '../custom.exception'; |
| 5 | + |
| 6 | +interface IRetryOptions { |
| 7 | + maxRetries?: number; |
| 8 | + initialBackoff?: number; |
| 9 | + jitter?: number; |
| 10 | +} |
| 11 | + |
| 12 | +interface IRetryConfig { |
| 13 | + errorCodes: string[]; |
| 14 | + errorMessage: string; |
| 15 | + errorCode: HttpErrorCode; |
| 16 | + loggerName: string; |
| 17 | +} |
| 18 | + |
| 19 | +function createRetryDecorator(config: IRetryConfig) { |
| 20 | + const logger = new Logger(config.loggerName); |
| 21 | + |
| 22 | + return function (opt?: IRetryOptions) { |
| 23 | + const { dbDeadlock } = thresholdConfig(); |
| 24 | + const { |
| 25 | + maxRetries = dbDeadlock.maxRetries, |
| 26 | + initialBackoff = dbDeadlock.initialBackoff, |
| 27 | + jitter = dbDeadlock.jitter, |
| 28 | + } = opt ?? {}; |
| 29 | + |
| 30 | + return function (_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) { |
| 31 | + const originalMethod = descriptor.value; |
| 32 | + |
| 33 | + descriptor.value = async function (...args: unknown[]) { |
| 34 | + let retries = 0; |
| 35 | + let backoff = initialBackoff + Math.random() * jitter; |
| 36 | + |
| 37 | + while (retries <= maxRetries) { |
| 38 | + try { |
| 39 | + return await originalMethod.apply(this, args); |
| 40 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 41 | + } catch (error: any) { |
| 42 | + const { errorCodes, errorMessage, errorCode } = config; |
| 43 | + if ( |
| 44 | + errorCodes.includes(error.code) || |
| 45 | + (error.meta?.code && errorCodes.includes(error.meta.code as string)) |
| 46 | + ) { |
| 47 | + if (retries === maxRetries) { |
| 48 | + logger.error(`${errorMessage} after ${retries} retries`, error.stack); |
| 49 | + throw new CustomHttpException(errorMessage, errorCode); |
| 50 | + } |
| 51 | + await new Promise((resolve) => setTimeout(resolve, backoff)); |
| 52 | + backoff *= 1.5 + Math.random() * jitter; |
| 53 | + } else { |
| 54 | + throw error; |
| 55 | + } |
| 56 | + } |
| 57 | + retries++; |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + return descriptor; |
| 62 | + }; |
| 63 | + }; |
| 64 | +} |
| 65 | + |
| 66 | +export const retryOnDeadlock = createRetryDecorator({ |
| 67 | + errorCodes: ['40P01', 'P2034'], |
| 68 | + errorMessage: 'Database deadlock detected', |
| 69 | + errorCode: HttpErrorCode.DATABASE_CONNECTION_UNAVAILABLE, |
| 70 | + loggerName: 'DeadlockRetryDecorator', |
| 71 | +}); |
| 72 | + |
| 73 | +export const retryOnUniqueViolation = createRetryDecorator({ |
| 74 | + errorCodes: ['23505'], |
| 75 | + errorMessage: 'Database unique violation detected', |
| 76 | + errorCode: HttpErrorCode.DATABASE_CONNECTION_UNAVAILABLE, |
| 77 | + loggerName: 'UniqueViolationRetryDecorator', |
| 78 | +}); |
0 commit comments