All files / third-parties/drizzle-adapter/src/ydb errors.ts

94.11% Statements 96/102
89.41% Branches 76/85
100% Functions 11/11
94.11% Lines 96/102

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365                                                19x                 19x                           22x               318x 152x   166x   166x 44x 44x 44x 176x 176x 38x 38x 38x       44x 22x   44x 88x   44x     122x 60x 62x   60x     62x         62x 62x 372x 372x 62x 62x           62x       62x 124x         22x       22x 22x       83x 338x 6x   332x       77x       22x       41x       22x 22x               22x 3x             19x 19x   19x                       1x     18x                   1x     17x                   2x     15x                   1x     14x                     2x     12x 11x 1x       11x       11x               22x 22x 22x 110x 42x                 22x 11x                                     22x       11x             3x       1x       1x       6x       2x       2x       1x                 11x   3x   1x   1x   2x   2x   1x   1x                 22x 22x 22x 22x   22x 11x             11x    
import { DrizzleQueryError } from 'drizzle-orm/errors'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
 
export type YdbQueryErrorKind =
	| 'authentication'
	| 'cancelled'
	| 'overloaded'
	| 'retryable'
	| 'timeout'
	| 'unavailable'
	| 'unique_constraint'
 
export interface YdbQueryErrorDetails {
	kind: YdbQueryErrorKind
	retryable: boolean
	statusCode?: number | string | undefined
}
 
type YdbErrorDiagnostics = {
	messages: string[]
	statusCodes: Set<number | string>
	retryable?: boolean
}
 
let grpcStatus = {
	CANCELLED: 1,
	DEADLINE_EXCEEDED: 4,
	PERMISSION_DENIED: 7,
	RESOURCE_EXHAUSTED: 8,
	UNAVAILABLE: 14,
	UNAUTHENTICATED: 16,
} as const
 
let retryableYdbStatusCodes = new Set<number>([
	StatusIds_StatusCode.ABORTED,
	StatusIds_StatusCode.INTERNAL_ERROR,
	StatusIds_StatusCode.UNAVAILABLE,
	StatusIds_StatusCode.OVERLOADED,
	StatusIds_StatusCode.TIMEOUT,
	StatusIds_StatusCode.BAD_SESSION,
	StatusIds_StatusCode.SESSION_EXPIRED,
	StatusIds_StatusCode.UNDETERMINED,
	StatusIds_StatusCode.SESSION_BUSY,
	StatusIds_StatusCode.EXTERNAL_ERROR,
])
 
function toError(cause: unknown): Error {
	return cause instanceof Error ? cause : new Error(String(cause))
}
 
function collectDiagnostics(
	value: unknown,
	diagnostics: YdbErrorDiagnostics,
	seen = new Set<unknown>()
): void {
	if (!value || seen.has(value)) {
		return
	}
	seen.add(value)
 
	if (value instanceof Error) {
		diagnostics.messages.push(value.name, value.message)
		let record = value as unknown as Record<string, unknown>
		for (let key of ['reason', 'code', 'status', 'statusCode']) {
			let field = record[key]
			if (typeof field === 'string' || typeof field === 'number') {
				diagnostics.messages.push(String(field))
				Eif (key !== 'reason') {
					diagnostics.statusCodes.add(field)
				}
			}
		}
		if (typeof record['retryable'] === 'boolean') {
			diagnostics.retryable = record['retryable']
		}
		for (let key of ['issues', 'cause']) {
			collectDiagnostics(record[key], diagnostics, seen)
		}
		return
	}
 
	if (Array.isArray(value)) {
		for (let item of value) {
			collectDiagnostics(item, diagnostics, seen)
		}
		return
	}
 
	Iif (typeof value !== 'object') {
		diagnostics.messages.push(String(value))
		return
	}
 
	let record = value as Record<string, unknown>
	for (let key of ['name', 'message', 'reason', 'code', 'status', 'statusCode']) {
		let field = record[key]
		if (typeof field === 'string' || typeof field === 'number') {
			diagnostics.messages.push(String(field))
			Iif (key !== 'name' && key !== 'message' && key !== 'reason') {
				diagnostics.statusCodes.add(field)
			}
		}
	}
 
	Iif (typeof record['retryable'] === 'boolean') {
		diagnostics.retryable = record['retryable']
	}
 
	for (let key of ['issues', 'cause']) {
		collectDiagnostics(record[key], diagnostics, seen)
	}
}
 
function getDiagnostics(error: unknown): YdbErrorDiagnostics {
	let diagnostics: YdbErrorDiagnostics = {
		messages: [],
		statusCodes: new Set(),
	}
	collectDiagnostics(error, diagnostics)
	return diagnostics
}
 
function hasStatus(diagnostics: YdbErrorDiagnostics, ...codes: Array<number | string>): boolean {
	for (let code of codes) {
		if (diagnostics.statusCodes.has(code)) {
			return true
		}
		Iif (typeof code === 'string' && diagnostics.statusCodes.has(code.toUpperCase())) {
			return true
		}
	}
	return false
}
 
function getStatusCode(diagnostics: YdbErrorDiagnostics): number | string | undefined {
	return diagnostics.statusCodes.values().next().value
}
 
function getDiagnosticText(diagnostics: YdbErrorDiagnostics): string {
	return diagnostics.messages.join('\n')
}
 
function isUniqueConstraintError(diagnostics: YdbErrorDiagnostics): boolean {
	let text = getDiagnosticText(diagnostics)
	return (
		/(unique|constraint).*(violation|violated|duplicate|already exists|conflict)/iu.test(
			text
		) || /(duplicate|already exists|conflict).*(key|unique|constraint)/iu.test(text)
	)
}
 
function classifyYdbQueryError(diagnostics: YdbErrorDiagnostics): YdbQueryErrorDetails | undefined {
	if (isUniqueConstraintError(diagnostics)) {
		return {
			kind: 'unique_constraint',
			retryable: false,
			statusCode: getStatusCode(diagnostics),
		}
	}
 
	let text = getDiagnosticText(diagnostics)
	let statusCode = getStatusCode(diagnostics)
 
	if (
		hasStatus(
			diagnostics,
			StatusIds_StatusCode.UNAUTHORIZED,
			grpcStatus.UNAUTHENTICATED,
			grpcStatus.PERMISSION_DENIED,
			'UNAUTHORIZED',
			'UNAUTHENTICATED',
			'PERMISSION_DENIED'
		) ||
		/(unauthorized|unauthenticated|permission denied|access denied|invalid token)/iu.test(text)
	) {
		return { kind: 'authentication', retryable: false, statusCode }
	}
 
	if (
		hasStatus(
			diagnostics,
			StatusIds_StatusCode.CANCELLED,
			grpcStatus.CANCELLED,
			'CANCELLED',
			'CANCELED'
		) ||
		/\bcancell?ed\b/iu.test(text)
	) {
		return { kind: 'cancelled', retryable: diagnostics.retryable === true, statusCode }
	}
 
	if (
		hasStatus(
			diagnostics,
			StatusIds_StatusCode.TIMEOUT,
			grpcStatus.DEADLINE_EXCEEDED,
			'TIMEOUT',
			'DEADLINE_EXCEEDED'
		) ||
		/(timeout|deadline exceeded|timed out)/iu.test(text)
	) {
		return { kind: 'timeout', retryable: true, statusCode }
	}
 
	if (
		hasStatus(
			diagnostics,
			StatusIds_StatusCode.OVERLOADED,
			grpcStatus.RESOURCE_EXHAUSTED,
			'OVERLOADED',
			'RESOURCE_EXHAUSTED'
		) ||
		/(overloaded|resource exhausted|too many requests|throttl)/iu.test(text)
	) {
		return { kind: 'overloaded', retryable: true, statusCode }
	}
 
	if (
		hasStatus(
			diagnostics,
			StatusIds_StatusCode.UNAVAILABLE,
			grpcStatus.UNAVAILABLE,
			'UNAVAILABLE'
		) ||
		/(unavailable|connection refused|connection reset|transport.*closed|no connection)/iu.test(
			text
		)
	) {
		return { kind: 'unavailable', retryable: true, statusCode }
	}
 
	for (let code of diagnostics.statusCodes) {
		if (typeof code === 'number' && retryableYdbStatusCodes.has(code)) {
			return { kind: 'retryable', retryable: true, statusCode }
		}
	}
 
	Iif (diagnostics.retryable === true) {
		return { kind: 'retryable', retryable: true, statusCode }
	}
 
	return undefined
}
 
function attachYdbErrorDetails<T extends DrizzleQueryError>(
	target: T,
	cause: unknown,
	details?: YdbQueryErrorDetails
): T {
	Eif (cause && typeof cause === 'object') {
		let record = cause as Record<string, unknown>
		for (let key of ['code', 'status', 'statusCode', 'issues', 'retryable']) {
			if (key in record) {
				Object.defineProperty(target, key, {
					configurable: true,
					enumerable: false,
					value: record[key],
				})
			}
		}
	}
 
	if (details) {
		Object.defineProperties(target, {
			kind: {
				configurable: true,
				enumerable: false,
				value: details.kind,
			},
			retryable: {
				configurable: true,
				enumerable: false,
				value: details.retryable,
			},
			statusCode: {
				configurable: true,
				enumerable: false,
				value: details.statusCode,
			},
		})
	}
 
	return target
}
 
export class YdbQueryExecutionError extends DrizzleQueryError {
	override name = 'YdbQueryExecutionError'
	declare readonly kind: YdbQueryErrorKind
	declare readonly retryable: boolean
	declare readonly statusCode?: number | string
}
 
export class YdbUniqueConstraintViolationError extends YdbQueryExecutionError {
	override name = 'YdbUniqueConstraintViolationError'
}
 
export class YdbAuthenticationError extends YdbQueryExecutionError {
	override name = 'YdbAuthenticationError'
}
 
export class YdbCancelledQueryError extends YdbQueryExecutionError {
	override name = 'YdbCancelledQueryError'
}
 
export class YdbRetryableQueryError extends YdbQueryExecutionError {
	override name = 'YdbRetryableQueryError'
}
 
export class YdbTimeoutQueryError extends YdbRetryableQueryError {
	override name = 'YdbTimeoutQueryError'
}
 
export class YdbUnavailableQueryError extends YdbRetryableQueryError {
	override name = 'YdbUnavailableQueryError'
}
 
export class YdbOverloadedQueryError extends YdbRetryableQueryError {
	override name = 'YdbOverloadedQueryError'
}
 
function createMappedError(
	query: string,
	params: unknown[],
	cause: Error,
	details: YdbQueryErrorDetails
): YdbQueryExecutionError {
	switch (details.kind) {
		case 'unique_constraint':
			return new YdbUniqueConstraintViolationError(query, params, cause)
		case 'authentication':
			return new YdbAuthenticationError(query, params, cause)
		case 'cancelled':
			return new YdbCancelledQueryError(query, params, cause)
		case 'timeout':
			return new YdbTimeoutQueryError(query, params, cause)
		case 'unavailable':
			return new YdbUnavailableQueryError(query, params, cause)
		case 'overloaded':
			return new YdbOverloadedQueryError(query, params, cause)
		case 'retryable':
			return new YdbRetryableQueryError(query, params, cause)
	}
}
 
export function mapYdbQueryError(
	query: string,
	params: unknown[],
	cause: unknown
): DrizzleQueryError {
	let error = toError(cause)
	let diagnostics = getDiagnostics(cause)
	collectDiagnostics(error, diagnostics)
	let details = classifyYdbQueryError(diagnostics)
 
	if (details) {
		return attachYdbErrorDetails(
			createMappedError(query, params, error, details),
			cause,
			details
		)
	}
 
	return attachYdbErrorDetails(new DrizzleQueryError(query, params, error), cause)
}