All files / packages/retry/src index.ts

96.87% Statements 93/96
90.9% Branches 70/77
87.5% Functions 7/8
96.8% Lines 91/94

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                                                                73x 73x           73x 73x 73x 73x   73x           632x     632x 632x               632x 632x 632x 632x           632x 632x     666x 666x 666x   666x 666x 666x   666x 666x   666x   666x         593x 593x         593x 593x   73x 73x   73x 4x 4x         4x 4x     69x 1x 1x         1x 1x       68x 15x   53x     68x 30x 30x 30x         30x 30x     38x             38x 9x   29x     38x 38x 38x 9x 9x     29x   29x   26x 8x     666x       31x   31x           31x       1667x 17x               1650x 1625x     25x 6x     19x                             1370x 1x             1369x     73x       124x 1x     123x       1x     122x 1x     121x 2x     119x 2x     117x                     73x                            
import { channel as dc, tracingChannel } from 'node:diagnostics_channel'
import { setTimeout } from 'timers/promises'
 
import { abortable, linkSignals } from '@ydbjs/abortable'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import { loggers } from '@ydbjs/debug'
import { CommitError, YDBError } from '@ydbjs/error'
import { ClientError, Status } from 'nice-grpc'
 
import type { RetryConfig } from './config.js'
import type { RetryContext } from './context.js'
import { type RetryStrategy, backoff, fixed } from './strategy.js'
 
/**
 * Per-attempt outcome:
 *   - `success`       — resolved
 *   - `retried`       — retryable failure, budget remains
 *   - `non_retryable` — policy refuses to retry
 *   - `exhausted`     — retryable failure with no budget left
 *
 * Same type tags whole-run outcomes, except `retried` (a run terminates).
 */
export type RetryOutcome = 'success' | 'retried' | 'non_retryable' | 'exhausted'
 
type RetryRunCtx = { idempotent: boolean; outcome?: RetryOutcome }
/**
 * `backoffMs` is the actual wait observed before this attempt started,
 * accounting for time already spent on the previous failed attempt.
 * Always `0` for `attempt === 1` (no preceding wait).
 */
type RetryAttemptCtx = { attempt: number; idempotent: boolean; backoffMs: number }
 
let retryRunCh = tracingChannel<RetryRunCtx, RetryRunCtx>('tracing:ydb:retry.run')
let retryAttemptCh = tracingChannel<RetryAttemptCtx, RetryAttemptCtx>('tracing:ydb:retry.attempt')
 
export * from './config.js'
export * from './context.js'
export * as strategies from './strategy.js'
 
const BACKOFF_OVERLOAD_BASE_MS = 1000
const BACKOFF_OVERLOAD_MAX_MS = 60_000
const BACKOFF_DEFAULT_BASE_MS = 10
const BACKOFF_DEFAULT_MAX_MS = 30_000
 
let dbg = loggers.retry
 
export async function retry<R>(
	cfg: RetryConfig,
	fn: (signal: AbortSignal) => R | Promise<R>
): Promise<R> {
	let idempotent = cfg.idempotent ?? false
	// runLoop mutates `runCtx.outcome` before settling so the asyncEnd
	// subscriber reads the final outcome off the same ctx object.
	let runCtx: RetryRunCtx = { idempotent }
	return retryRunCh.tracePromise(() => runLoop(cfg, fn, runCtx), runCtx)
}
 
async function runLoop<R>(
	cfg: RetryConfig,
	fn: (signal: AbortSignal) => R | Promise<R>,
	runCtx: RetryRunCtx
): Promise<R> {
	let config = Object.assign({}, defaultRetryConfig, cfg)
	let idempotent = cfg.idempotent ?? false
	let ctx: RetryContext = { attempt: 0, error: null }
	let started = performance.now()
 
	let budget: number
	// Backoff waited before the NEXT attempt — surfaced on the
	// retry.attempt ctx so the consumer can stamp `ydb.retry.backoff` on
	// the corresponding span. `0` for the first attempt.
	let pendingBackoffMs = 0
	while (
		ctx.attempt <
		(budget = typeof config.budget === 'number' ? config.budget : config.budget!(ctx, config))
	) {
		let ac = new AbortController()
		using linkedSignal = linkSignals(cfg.signal, ac.signal)
 
		let start = Date.now()
		let signal = linkedSignal.signal
		let attemptNumber = ctx.attempt + 1
 
		try {
			signal.throwIfAborted()
 
			dbg.log('attempt %d: calling retry function', attemptNumber)
			// oxlint-disable-next-line no-await-in-loop
			let result = await retryAttemptCh.tracePromise(
				() => abortable(signal, Promise.resolve(fn(signal))),
				{ attempt: attemptNumber, idempotent, backoffMs: pendingBackoffMs }
			)
 
			dbg.log('attempt %d: success', attemptNumber)
			dc('ydb:retry.attempt.completed').publish({
				attempt: attemptNumber,
				idempotent,
				outcome: 'success' satisfies RetryOutcome,
			})
			runCtx.outcome = 'success'
			return result
		} catch (error) {
			ctx.error = error
			ctx.attempt += 1
 
			if (error instanceof Error && error.name === 'AbortError') {
				dbg.log('attempt %d: abort error, not retryable', ctx.attempt)
				dc('ydb:retry.attempt.completed').publish({
					attempt: attemptNumber,
					idempotent,
					outcome: 'non_retryable' satisfies RetryOutcome,
				})
				runCtx.outcome = 'non_retryable'
				throw error
			}
 
			if (error instanceof Error && error.name === 'TimeoutError') {
				dbg.log('attempt %d: timeout error, not retryable', ctx.attempt)
				dc('ydb:retry.attempt.completed').publish({
					attempt: attemptNumber,
					idempotent,
					outcome: 'non_retryable' satisfies RetryOutcome,
				})
				runCtx.outcome = 'non_retryable'
				throw error
			}
 
			let willRetry: boolean
			if (typeof config.retry === 'boolean') {
				willRetry = config.retry
			} else {
				willRetry = config.retry?.(ctx.error, idempotent) ?? false
			}
 
			if (!willRetry || ctx.attempt >= budget) {
				dbg.log('attempt %d: not retrying, error: %O', ctx.attempt, error)
				let outcome: RetryOutcome = !willRetry ? 'non_retryable' : 'exhausted'
				dc('ydb:retry.attempt.completed').publish({
					attempt: attemptNumber,
					idempotent,
					outcome,
				})
				runCtx.outcome = outcome
				break
			}
 
			dc('ydb:retry.attempt.completed').publish({
				attempt: attemptNumber,
				idempotent,
				outcome: 'retried' satisfies RetryOutcome,
			})
 
			let delay: number
			if (typeof config.strategy === 'number') {
				delay = config.strategy
			} else {
				delay = config.strategy?.(ctx, config) ?? 0
			}
 
			let remaining = Math.max(delay - (Date.now() - start), 0)
			pendingBackoffMs = remaining
			if (!remaining) {
				dbg.log('attempt %d: no delay before next retry', ctx.attempt)
				continue
			}
 
			dbg.log('attempt %d: waiting %d ms before next retry', ctx.attempt, remaining)
			// oxlint-disable no-await-in-loop
			await setTimeout(remaining, void 0, { signal })
 
			if (config.onRetry) {
				config.onRetry(ctx)
			}
		} finally {
			ac.abort('Retry cancelled')
		}
	}
 
	dbg.log('retry failed after %d attempts, last error: %O', ctx.attempt, ctx.error)
 
	dc('ydb:retry.exhausted').publish({
		attempts: ctx.attempt,
		totalDuration: performance.now() - started,
		lastError: ctx.error,
	})
 
	throw ctx.error
}
 
export function isRetryableError(error: unknown, idempotent = false): boolean {
	if (error instanceof ClientError) {
		return (
			error.code === Status.ABORTED ||
			error.code === Status.INTERNAL ||
			error.code === Status.RESOURCE_EXHAUSTED ||
			(error.code === Status.UNAVAILABLE && idempotent)
		)
	}
 
	if (error instanceof YDBError) {
		return error.retryable === true || (error.retryable === 'conditionally' && idempotent)
	}
 
	if (error instanceof CommitError) {
		return error.retryable(idempotent)
	}
 
	return false
}
 
/**
 * Determines whether an error from a long-lived gRPC stream should trigger
 * a reconnect attempt.
 *
 * Streaming RPCs differ from unary calls: a CANCELLED or UNAVAILABLE status
 * means the transport was interrupted (e.g. the server restarted, the
 * connection pool was refreshed after a discovery round), not that the
 * *operation* was semantically cancelled by the caller.  We therefore always
 * reconnect on those codes, in addition to the errors handled by
 * {@link isRetryableError}.
 */
export function isRetryableStreamError(error: unknown): boolean {
	if (error instanceof ClientError) {
		return (
			error.code === Status.CANCELLED ||
			error.code === Status.UNAVAILABLE ||
			isRetryableError(error, true)
		)
	}
 
	return isRetryableError(error, false)
}
 
export const defaultRetryConfig: RetryConfig = {
	retry: isRetryableError,
	budget: Infinity,
	strategy: (ctx, cfg) => {
		if (ctx.error instanceof YDBError && ctx.error.code === StatusIds_StatusCode.BAD_SESSION) {
			return fixed(0)(ctx, cfg)
		}
 
		if (
			ctx.error instanceof YDBError &&
			ctx.error.code === StatusIds_StatusCode.SESSION_EXPIRED
		) {
			return fixed(0)(ctx, cfg)
		}
 
		if (ctx.error instanceof ClientError && ctx.error.code === Status.ABORTED) {
			return fixed(0)(ctx, cfg)
		}
 
		if (ctx.error instanceof YDBError && ctx.error.code === StatusIds_StatusCode.OVERLOADED) {
			return backoff(BACKOFF_OVERLOAD_BASE_MS, BACKOFF_OVERLOAD_MAX_MS)(ctx, cfg)
		}
 
		if (ctx.error instanceof ClientError && ctx.error.code === Status.RESOURCE_EXHAUSTED) {
			return backoff(BACKOFF_OVERLOAD_BASE_MS, BACKOFF_OVERLOAD_MAX_MS)(ctx, cfg)
		}
 
		return backoff(BACKOFF_DEFAULT_BASE_MS, BACKOFF_DEFAULT_MAX_MS)(ctx, cfg)
	},
}
 
/**
 * Default retry configuration for long-lived gRPC streaming connections
 * (topic reader / writer).
 *
 * Extends {@link defaultRetryConfig} with reconnect logic for transient
 * transport errors ({@link isRetryableStreamError}).
 */
export const defaultStreamRetryConfig: RetryConfig = {
	...defaultRetryConfig,
	retry: isRetryableStreamError,
	strategy: (ctx, cfg) => {
		if (
			ctx.error instanceof ClientError &&
			(ctx.error.code === Status.CANCELLED || ctx.error.code === Status.UNAVAILABLE)
		) {
			return backoff(BACKOFF_DEFAULT_BASE_MS, BACKOFF_DEFAULT_MAX_MS)(ctx, cfg)
		}
 
		return (defaultRetryConfig.strategy as RetryStrategy)(ctx, cfg)
	},
}