@backendkit-labs/retry 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -20
- package/dist/{chunk-MTBUSC7V.cjs → chunk-BX4TTYBY.cjs} +122 -79
- package/dist/chunk-BX4TTYBY.cjs.map +1 -0
- package/dist/{chunk-6UD5URCQ.js → chunk-NV6QXLUR.js} +122 -78
- package/dist/chunk-NV6QXLUR.js.map +1 -0
- package/dist/index.cjs +52 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -8
- package/dist/index.d.ts +17 -8
- package/dist/index.js +37 -3
- package/dist/index.js.map +1 -1
- package/dist/nestjs/index.cjs +25 -8
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.d.cts +23 -2
- package/dist/nestjs/index.d.ts +23 -2
- package/dist/nestjs/index.js +23 -6
- package/dist/nestjs/index.js.map +1 -1
- package/dist/{retry.engine-ETXna-Ud.d.cts → retry.engine-DZPAMpkR.d.cts} +15 -2
- package/dist/{retry.engine-ETXna-Ud.d.ts → retry.engine-DZPAMpkR.d.ts} +15 -2
- package/package.json +2 -1
- package/dist/chunk-6UD5URCQ.js.map +0 -1
- package/dist/chunk-MTBUSC7V.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/timeout/timeout.errors.ts","../src/retry/retry.budget.ts","../src/conditions/error.classifier.ts","../src/timeout/timeout.manager.ts","../src/idempotency/memory.store.ts","../src/idempotency/idempotency.manager.ts","../src/backoff/fixed.backoff.ts","../src/backoff/linear.backoff.ts","../src/backoff/jitter.decorator.ts","../src/backoff/exponential.backoff.ts","../../result/src/result/constructors.ts","../src/retry/retry.executor.ts","../src/retry/retry.hooks.ts","../src/retry/retry.engine.ts","../src/retry/retry.registry.ts"],"names":["message","payload"],"mappings":";;;;;;;;;;;;;AAAO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAA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,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,IAAA,EAAoB;AACxB,IAAA,IAAA,CAAK,OAAA,CAAQ,OAAO,IAAI,CAAA;AAAA,EAC1B;AAAA,EAEA,QAAA,GAAiB;AACf,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AAAA,EACrB;AAAA,EAEA,aAAA,GAAsD;AACpD,IAAA,MAAM,UAAgD,EAAC;AACvD,IAAA,KAAA,MAAW,CAAC,IAAA,EAAM,MAAM,CAAA,IAAK,KAAK,OAAA,EAAS;AACzC,MAAA,OAAA,CAAQ,IAAI,CAAA,GAAI,MAAA,CAAO,UAAA,EAAW;AAAA,IACpC;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF","file":"chunk-NV6QXLUR.js","sourcesContent":["export class AttemptTimeoutError extends Error {\n constructor(public readonly timeoutMs: number) {\n super(`Attempt timed out after ${timeoutMs}ms`);\n this.name = 'AttemptTimeoutError';\n }\n}\n\nexport class GlobalTimeoutError extends Error {\n constructor(\n public readonly timeoutMs: number,\n public readonly elapsedMs: number,\n ) {\n super(`Global timeout of ${timeoutMs}ms exceeded (elapsed: ${elapsedMs}ms)`);\n this.name = 'GlobalTimeoutError';\n }\n}\n","import type { RetryBudgetConfig } from './types.js';\n\nexport interface SlidingWindowBudget {\n tryConsume(): boolean;\n recordSuccess(): void;\n recordFailure(): void;\n recordCall(): void;\n getMetrics(): BudgetMetrics;\n}\n\nexport interface BudgetMetrics {\n allowed: boolean;\n retryCount: number;\n successCount: number;\n failureCount: number;\n totalCalls: number;\n currentRatio: number;\n}\n\nexport class SlidingWindowBudgetImpl implements SlidingWindowBudget {\n private calls: number[] = [];\n private retries: number[] = [];\n private successes = 0;\n private failures = 0;\n\n constructor(private config: RetryBudgetConfig) {}\n\n private evict(): void {\n const cutoff = Date.now() - this.config.windowMs;\n this.calls = this.calls.filter(t => t > cutoff);\n this.retries = this.retries.filter(t => t > cutoff);\n }\n\n recordCall(): void {\n this.calls.push(Date.now());\n }\n\n recordSuccess(): void {\n this.successes++;\n }\n\n recordFailure(): void {\n this.failures++;\n }\n\n tryConsume(): boolean {\n this.evict();\n const total = this.calls.length;\n\n if (total < this.config.minRequestCount) return true;\n\n const ratio = this.retries.length / total;\n if (ratio >= this.config.maxRetryRatio) return false;\n\n this.retries.push(Date.now());\n return true;\n }\n\n getMetrics(): BudgetMetrics {\n this.evict();\n const total = this.calls.length;\n const retries = this.retries.length;\n const ratio = total > 0 ? retries / total : 0;\n return {\n allowed: total < this.config.minRequestCount || ratio < this.config.maxRetryRatio,\n retryCount: retries,\n successCount: this.successes,\n failureCount: this.failures,\n totalCalls: total,\n currentRatio: ratio,\n };\n }\n}\n","import type { RetryErrorPayload, ClassifierRule, ErrorClassification } from '../retry/types.js';\n\n/**\n * Default error classifier with built-in rules and custom rule injection.\n *\n * Built-in rules (highest priority first):\n * 401, 403, 404, 422, 400, 413 -> permanent\n * 429, 5xx, network, timeout -> transient\n * circuit-open, bulkhead-rejected -> transient\n * fallback -> permanent\n *\n * Custom rules are evaluated before the fallback, after built-in defaults.\n */\nexport class DefaultErrorClassifier {\n private rules: ClassifierRule[];\n\n constructor(customRules?: ClassifierRule[]) {\n this.rules = [\n // Built-in rules (priority 0-99)\n { name: 'http-401', priority: 10, match: (e) => e.type === 'http' && e.status === 401, classification: 'permanent' },\n { name: 'http-403', priority: 10, match: (e) => e.type === 'http' && e.status === 403, classification: 'permanent' },\n { name: 'http-404', priority: 10, match: (e) => e.type === 'http' && e.status === 404, classification: 'permanent' },\n { name: 'http-400', priority: 10, match: (e) => e.type === 'http' && e.status === 400, classification: 'permanent' },\n { name: 'http-413', priority: 10, match: (e) => e.type === 'http' && e.status === 413, classification: 'permanent' },\n { name: 'http-422', priority: 10, match: (e) => e.type === 'http' && e.status === 422, classification: 'permanent' },\n { name: 'http-429', priority: 20, match: (e) => e.type === 'http' && e.status === 429, classification: 'transient' },\n { name: 'http-5xx', priority: 20, match: (e) => e.type === 'http' && e.status != null && e.status >= 500, classification: 'transient' },\n { name: 'network', priority: 20, match: (e) => e.type === 'network', classification: 'transient' },\n { name: 'timeout', priority: 20, match: (e) => e.type === 'timeout', classification: 'transient' },\n { name: 'circuit-open', priority: 20, match: (e) => e.type === 'circuit-open', classification: 'transient' },\n { name: 'bulkhead-rejected', priority: 20, match: (e) => e.type === 'bulkhead-rejected', classification: 'transient' },\n // Fallback: business and unknown are permanent\n { name: 'business', priority: 100, match: (e) => e.type === 'business', classification: 'permanent' },\n { name: 'unknown', priority: 100, match: () => true, classification: 'permanent' },\n ];\n\n if (customRules) {\n this.rules.push(...customRules);\n }\n\n // Sort by priority ascending\n this.rules.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));\n }\n\n classify(error: RetryErrorPayload): ErrorClassification {\n for (const rule of this.rules) {\n if (rule.match(error)) {\n return rule.classification;\n }\n }\n return 'permanent';\n }\n}\n","import type { TimeoutConfig } from '../retry/types.js';\nimport { AttemptTimeoutError, GlobalTimeoutError } from './timeout.errors.js';\n\n/** Shared signal for the no-timeouts-configured fast path -- never aborts. */\nconst NEVER_ABORTS: AbortSignal = new AbortController().signal;\n\n/** `AbortSignal.reason` is typed `any` -- narrow it to a real Error to throw. */\nfunction abortReason(signal: AbortSignal): Error {\n const reason: unknown = signal.reason;\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\nexport class TimeoutManager {\n private startTime: number;\n private readonly globalController: AbortController | undefined;\n private readonly globalTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(private config: TimeoutConfig) {\n this.startTime = Date.now();\n\n if (this.config.globalTimeoutMs && this.config.globalTimeoutMs > 0) {\n this.globalController = new AbortController();\n this.globalTimer = setTimeout(() => {\n this.globalController!.abort(\n new GlobalTimeoutError(this.config.globalTimeoutMs!, this.config.globalTimeoutMs!),\n );\n }, this.config.globalTimeoutMs);\n this.globalTimer.unref?.();\n }\n }\n\n /**\n * Execute a task with a per-attempt timeout, passing it an `AbortSignal`\n * that fires when the attempt (or the overall global timeout) expires.\n *\n * A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)\n * keeps running in the background after we give up waiting on it -- we\n * can only abandon the wait, not force JS execution to stop.\n */\n async executeWithAttemptTimeout<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> {\n if (this.globalController?.signal.aborted) {\n throw abortReason(this.globalController.signal);\n }\n\n // Fast path: no timeout configured at all -- skip the AbortController/Promise\n // wrapper machinery entirely.\n if (!this.globalController && (!this.config.attemptTimeoutMs || this.config.attemptTimeoutMs <= 0)) {\n return task(NEVER_ABORTS);\n }\n\n const attemptController = new AbortController();\n const forwardGlobalAbort = (): void => {\n attemptController.abort(this.globalController!.signal.reason);\n };\n this.globalController?.signal.addEventListener('abort', forwardGlobalAbort, { once: true });\n\n const attemptTimeoutMs = this.config.attemptTimeoutMs;\n const timer = attemptTimeoutMs && attemptTimeoutMs > 0\n ? setTimeout(() => attemptController.abort(new AttemptTimeoutError(attemptTimeoutMs)), attemptTimeoutMs)\n : undefined;\n timer?.unref?.();\n\n try {\n return await new Promise<T>((resolve, reject) => {\n attemptController.signal.addEventListener(\n 'abort',\n () => reject(abortReason(attemptController.signal)),\n { once: true },\n );\n task(attemptController.signal).then(resolve, reject);\n });\n } finally {\n if (timer) clearTimeout(timer);\n this.globalController?.signal.removeEventListener('abort', forwardGlobalAbort);\n }\n }\n\n /**\n * Check if the global timeout has already fired. Called at the start of\n * each attempt loop iteration -- the AbortSignal handles cutting off an\n * attempt that's already in flight when the deadline hits.\n */\n checkGlobalTimeout(): void {\n if (this.globalController?.signal.aborted) {\n throw abortReason(this.globalController.signal);\n }\n }\n\n /**\n * Get the remaining time before global timeout (ms).\n * Returns Infinity if no global timeout is configured.\n */\n getRemainingTime(): number {\n if (!this.config.globalTimeoutMs || this.config.globalTimeoutMs <= 0) return Infinity;\n const elapsed = Date.now() - this.startTime;\n return Math.max(0, this.config.globalTimeoutMs - elapsed);\n }\n\n /** Reset the start time (for reuse across retry cycles). */\n reset(): void {\n this.startTime = Date.now();\n }\n\n /** Release the global timeout timer. Call once the retry loop is done. */\n dispose(): void {\n if (this.globalTimer) clearTimeout(this.globalTimer);\n }\n}\n","import type { IdempotencyStore } from '../retry/types.js';\n\ninterface StoreEntry {\n value: string;\n expiresAt: number;\n}\n\nexport class InMemoryIdempotencyStore implements IdempotencyStore {\n private store = new Map<string, StoreEntry>();\n\n get(key: string): Promise<string | null> {\n const entry = this.store.get(key);\n if (!entry) return Promise.resolve(null);\n if (Date.now() > entry.expiresAt) {\n this.store.delete(key);\n return Promise.resolve(null);\n }\n return Promise.resolve(entry.value);\n }\n\n set(key: string, value: string, ttlMs?: number): Promise<void> {\n this.store.set(key, {\n value,\n expiresAt: Date.now() + (ttlMs ?? 24 * 60 * 60 * 1000),\n });\n return Promise.resolve();\n }\n\n exists(key: string): Promise<boolean> {\n const entry = this.store.get(key);\n if (!entry) return Promise.resolve(false);\n if (Date.now() > entry.expiresAt) {\n this.store.delete(key);\n return Promise.resolve(false);\n }\n return Promise.resolve(true);\n }\n}\n","import type { IdempotencyConfig, IdempotencyStore } from '../retry/types.js';\nimport { InMemoryIdempotencyStore } from './memory.store.js';\n\nexport class IdempotencyManager {\n private store: IdempotencyStore;\n\n constructor(private config: IdempotencyConfig) {\n this.store = config.store ?? new InMemoryIdempotencyStore();\n }\n\n /**\n * Generate an idempotency key from the request context.\n */\n generateKey(method: string, path: string, bodyHash?: string): string {\n return `${method}:${path}:${bodyHash ?? ''}`;\n }\n\n /**\n * Check if a key already exists in the store.\n */\n async hasResult(key: string): Promise<boolean> {\n return this.store.exists(key);\n }\n\n /**\n * Store a result for a given key.\n */\n async storeResult(key: string, result: string): Promise<void> {\n await this.store.set(key, result, this.config.ttlMs);\n }\n\n /**\n * Retrieve a stored result.\n */\n async getResult(key: string): Promise<string | null> {\n return this.store.get(key);\n }\n\n /**\n * Check if the HTTP method should be idempotent.\n */\n isIdempotentMethod(method: string): boolean {\n return this.config.idempotentMethods.includes(method.toUpperCase());\n }\n}\n","import type { BackoffStrategy, BackoffConfig } from '../retry/types.js';\n\nexport class FixedBackoff implements BackoffStrategy {\n constructor(private config: { baseDelay: number }) {}\n\n nextDelay(_attempt: number): number {\n return this.config.baseDelay;\n }\n\n reset(): void {\n // No state to reset\n }\n\n clone(overrides?: Partial<BackoffConfig>): FixedBackoff {\n return new FixedBackoff({\n baseDelay: overrides?.baseDelay ?? this.config.baseDelay,\n });\n }\n}\n","import type { BackoffStrategy, BackoffConfig } from '../retry/types.js';\n\nexport class LinearBackoff implements BackoffStrategy {\n constructor(\n private config: {\n baseDelay: number;\n multiplier?: number;\n maxDelay?: number;\n },\n ) {\n this.config.multiplier ??= 1;\n this.config.maxDelay ??= Infinity;\n }\n\n nextDelay(attempt: number): number {\n const delay = this.config.baseDelay * attempt * (this.config.multiplier ?? 1);\n return Math.min(delay, this.config.maxDelay ?? Infinity);\n }\n\n reset(): void {\n // No state to reset\n }\n\n clone(overrides?: Partial<BackoffConfig>): LinearBackoff {\n return new LinearBackoff({\n baseDelay: overrides?.baseDelay ?? this.config.baseDelay,\n multiplier: this.config.multiplier,\n maxDelay: this.config.maxDelay,\n });\n }\n}\n","import type { BackoffStrategy, BackoffConfig, JitterType } from '../retry/types.js';\n\n/**\n * Apply jitter to a delay value.\n * - 'full': random between 0 and delay\n * - 'equal': random between delay/2 and delay\n * - 'decorrelated': random between baseDelay and delay * 3 (stateful)\n */\nexport function applyJitter(delay: number, type: JitterType): number {\n switch (type) {\n case 'full':\n return Math.random() * delay;\n case 'equal':\n return delay / 2 + Math.random() * (delay / 2);\n case 'decorrelated':\n // Simplified: random between delay and delay * 3\n return delay + Math.random() * (delay * 2);\n }\n}\n\n/**\n * Decorator that wraps any BackoffStrategy with jitter.\n */\nexport class JitterDecorator implements BackoffStrategy {\n constructor(\n private inner: BackoffStrategy,\n private jitterType: JitterType,\n ) {}\n\n nextDelay(attempt: number): number {\n const delay = this.inner.nextDelay(attempt);\n return applyJitter(delay, this.jitterType);\n }\n\n reset(): void {\n this.inner.reset();\n }\n\n clone(overrides?: Partial<BackoffConfig>): JitterDecorator {\n return new JitterDecorator(this.inner.clone(overrides), this.jitterType);\n }\n}\n","import type { BackoffStrategy, BackoffConfig, JitterType } from '../retry/types.js';\nimport { applyJitter } from './jitter.decorator.js';\n\nexport class ExponentialBackoff implements BackoffStrategy {\n constructor(\n private config: {\n baseDelay: number;\n multiplier?: number;\n maxDelay?: number;\n jitter?: JitterType;\n },\n ) {\n this.config.multiplier ??= 2;\n this.config.maxDelay ??= Infinity;\n }\n\n nextDelay(attempt: number): number {\n const delay = this.config.baseDelay * Math.pow(this.config.multiplier ?? 2, attempt - 1);\n const capped = Math.min(delay, this.config.maxDelay ?? Infinity);\n if (this.config.jitter) {\n // 'decorrelated' can multiply capped by up to 3x -- re-clamp so\n // maxDelay is an actual upper bound, not just a pre-jitter target.\n return Math.min(applyJitter(capped, this.config.jitter), this.config.maxDelay ?? Infinity);\n }\n return capped;\n }\n\n reset(): void {\n // No state to reset\n }\n\n clone(overrides?: Partial<BackoffConfig>): ExponentialBackoff {\n return new ExponentialBackoff({\n baseDelay: overrides?.baseDelay ?? this.config.baseDelay,\n multiplier: this.config.multiplier,\n maxDelay: this.config.maxDelay,\n jitter: this.config.jitter,\n });\n }\n}\n","import type { Result } from './types.js';\n\n/** Creates a successful Result. */\nexport const ok = <T, E = never>(value: T): Result<T, E> =>\n ({ ok: true, value });\n\n/** Creates a failed Result. */\nexport const fail = <T = never, E = Error>(error: E): Result<T, E> =>\n ({ ok: false, error });\n\n/**\n * Wraps a synchronous throwable function. Catches any thrown value and\n * passes it through `errorTransform` (defaults to identity cast).\n *\n * @example\n * const result = fromThrowable(() => JSON.parse(raw), (e) => new ParseError(e));\n */\nexport function fromThrowable<T, E = Error>(\n fn: () => T,\n errorTransform?: (caught: unknown) => E,\n): Result<T, E> {\n try {\n return ok(fn());\n } catch (caught) {\n return fail(errorTransform ? errorTransform(caught) : (caught as E));\n }\n}\n\n/**\n * Converts a Promise to a `Promise<Result<T, E>>`, catching rejections.\n *\n * @example\n * const result = await fromPromise(fetch(url), (e) => new NetworkError(e));\n */\nexport async function fromPromise<T, E = Error>(\n promise: Promise<T>,\n errorTransform?: (caught: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await promise);\n } catch (caught) {\n return fail(errorTransform ? errorTransform(caught) : (caught as E));\n }\n}\n\n/**\n * Converts a nullable value to a Result.\n * Returns `ok(value)` if non-null/undefined, `fail(error)` otherwise.\n *\n * @example\n * const result = fromNullable(user, new NotFoundError('user'));\n */\nexport function fromNullable<T, E>(\n value: T | null | undefined,\n error: E,\n): Result<T, E> {\n return value != null ? ok(value) : fail(error);\n}\n","import { ok, fail, type Result } from '@backendkit-labs/result';\nimport type {\n RetryConfig,\n RetryError,\n RetryErrorPayload,\n BackoffStrategy,\n RetryCondition,\n AbortCondition,\n CircuitBreakerLike,\n BulkheadLike,\n BkLoggerLike,\n MetricsEmitterLike,\n} from './types.js';\nimport type { SlidingWindowBudget } from './retry.budget.js';\nimport type { DefaultErrorClassifier } from '../conditions/error.classifier.js';\nimport type { TimeoutManager } from '../timeout/timeout.manager.js';\nimport type { IdempotencyManager } from '../idempotency/idempotency.manager.js';\nimport { HookRunner } from './retry.hooks.js';\nimport { AttemptTimeoutError, GlobalTimeoutError } from '../timeout/timeout.errors.js';\n\nexport interface ExecutorDependencies {\n backoff: BackoffStrategy;\n budget?: SlidingWindowBudget;\n classifier: DefaultErrorClassifier;\n timeoutManager: TimeoutManager;\n idempotency?: IdempotencyManager;\n RetryCondition: RetryCondition;\n abortCondition: AbortCondition;\n hooks: HookRunner;\n circuitBreaker?: CircuitBreakerLike;\n bulkhead?: BulkheadLike;\n logger?: BkLoggerLike;\n metrics?: MetricsEmitterLike;\n correlationId?: string;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nconst NETWORK_CODES = new Set([\n 'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'ETIMEDOUT',\n 'EAI_AGAIN', 'ECONNABORTED', 'EPIPE',\n 'ERR_NETWORK', // axios, no response received\n]);\n\nfunction getHttpStatus(err: unknown): number | undefined {\n if (err == null || typeof err !== 'object') return undefined;\n const e = err as Record<string, unknown>;\n if (typeof e['status'] === 'number') return e['status'];\n if (typeof e['statusCode'] === 'number') return e['statusCode'];\n if (typeof e['getStatus'] === 'function') {\n const status = (e['getStatus'] as () => unknown)();\n if (typeof status === 'number') return status;\n }\n const response = e['response'];\n if (response != null && typeof response === 'object') {\n const r = response as Record<string, unknown>;\n if (typeof r['status'] === 'number') return r['status'];\n }\n return undefined;\n}\n\n/**\n * Reads `.code`, falling back to `.cause.code` -- native `fetch()` wraps the\n * real network error (e.g. `ECONNREFUSED`) in `TypeError('fetch failed', { cause })`.\n */\nfunction getErrorCode(err: unknown): string | undefined {\n if (err == null || typeof err !== 'object') return undefined;\n const e = err as Record<string, unknown>;\n if (typeof e['code'] === 'string') return e['code'];\n const cause = e['cause'];\n if (cause != null && typeof cause === 'object') {\n const causeCode = (cause as Record<string, unknown>)['code'];\n if (typeof causeCode === 'string') return causeCode;\n }\n return undefined;\n}\n\nfunction normalizeError(err: unknown, attempt: number, startTime: number): RetryErrorPayload {\n const elapsedMs = Date.now() - startTime;\n\n if (err instanceof AttemptTimeoutError || err instanceof GlobalTimeoutError) {\n return { type: 'timeout', message: err.message, attempt, elapsedMs, cause: err };\n }\n\n const status = getHttpStatus(err);\n if (status !== undefined) {\n const message = err instanceof Error ? err.message : `HTTP ${status}`;\n return { type: 'http', message, status, attempt, elapsedMs, cause: err };\n }\n\n const code = getErrorCode(err);\n if (code !== undefined && NETWORK_CODES.has(code)) {\n const message = err instanceof Error ? err.message : 'Network error';\n return { type: 'network', message, attempt, elapsedMs, cause: err };\n }\n\n const message = err instanceof Error ? err.message : String(err);\n return { type: 'unknown', message, attempt, elapsedMs, cause: err };\n}\n\nfunction makeRetryError(\n payload: RetryErrorPayload,\n attempts: number,\n totalElapsedMs: number,\n budgetExhausted?: boolean,\n): RetryError {\n return {\n ...payload,\n metadata: { attempts, totalElapsedMs, lastError: payload, budgetExhausted },\n };\n}\n\n// ─── Executor ────────────────────────────────────────────────────────────────\n\nexport class RetryExecutor {\n constructor(\n private deps: ExecutorDependencies,\n private config: RetryConfig,\n ) {}\n\n async run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<Result<T, RetryError>> {\n try {\n return await this.attempt(task);\n } finally {\n this.deps.timeoutManager.dispose();\n }\n }\n\n private async attempt<T>(task: (signal: AbortSignal) => Promise<T>): Promise<Result<T, RetryError>> {\n const {\n backoff, budget, classifier, timeoutManager,\n RetryCondition, abortCondition, hooks,\n circuitBreaker, bulkhead, logger, metrics, correlationId,\n idempotency,\n } = this.deps;\n const { maxAttempts = 3, dynamicDelay, fallback } = this.config;\n const idempotencyKey = this.config.idempotency?.key;\n\n const startTime = Date.now();\n let lastError: RetryErrorPayload | undefined;\n\n // Return cached result for duplicate requests. Cached as { value } rather\n // than the bare value -- JSON.stringify(undefined) is `undefined`, not a\n // string, so a task resolving `undefined` would otherwise fail to\n // round-trip through the store.\n if (idempotency && idempotencyKey) {\n const cached = await idempotency.getResult(idempotencyKey);\n if (cached !== null) {\n return ok((JSON.parse(cached) as { value: T }).value);\n }\n }\n\n budget?.recordCall();\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Global timeout check at the start of each attempt\n try {\n timeoutManager.checkGlobalTimeout();\n } catch (err) {\n const payload = normalizeError(err, attempt, startTime);\n await hooks.onExhausted({ lastError: payload, totalAttempts: attempt - 1, totalElapsedMs: Date.now() - startTime });\n return fail(makeRetryError(payload, attempt - 1, Date.now() - startTime));\n }\n\n // Circuit breaker check\n if (circuitBreaker && !circuitBreaker.canAttempt()) {\n const payload: RetryErrorPayload = {\n type: 'circuit-open',\n message: 'Circuit breaker is open',\n attempt,\n elapsedMs: Date.now() - startTime,\n };\n if (attempt >= maxAttempts || await abortCondition.shouldAbort(payload)) {\n await hooks.onExhausted({ lastError: payload, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });\n return fail(makeRetryError(payload, attempt, Date.now() - startTime));\n }\n lastError = payload;\n const delay = dynamicDelay?.(payload, attempt) ?? backoff.nextDelay(attempt);\n await hooks.beforeRetry({ attempt, error: payload, delayMs: delay });\n await sleep(delay);\n await hooks.afterRetry({ attempt, error: payload, delayMs: delay });\n continue;\n }\n\n // Execute the task (with optional bulkhead + per-attempt timeout)\n const attemptStart = Date.now();\n try {\n const executeTask = (): Promise<T> => timeoutManager.executeWithAttemptTimeout(task);\n const value = await (bulkhead ? bulkhead.execute(executeTask) : executeTask());\n\n // SUCCESS -- duration is for this attempt alone, not the cumulative\n // time across earlier failed attempts and their backoff delays.\n circuitBreaker?.onSuccess(Date.now() - attemptStart);\n budget?.recordSuccess();\n\n if (attempt > 1) {\n await hooks.onRetrySuccess({ attempt, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });\n }\n metrics?.emit({ name: 'Retry.success', value: 1, tags: { attempt: String(attempt) } });\n if (idempotency && idempotencyKey) {\n await idempotency.storeResult(idempotencyKey, JSON.stringify({ value }));\n }\n return ok(value);\n\n } catch (err) {\n const payload = normalizeError(err, attempt, startTime);\n lastError = payload;\n\n const classification = classifier.classify(payload);\n\n // Only notify the circuit breaker of transient (infrastructure-shaped)\n // failures -- a permanent/business failure (e.g. 404, 422) says nothing\n // about whether the dependency itself is healthy.\n if (classification === 'transient') {\n circuitBreaker?.onError(err);\n }\n budget?.recordFailure();\n\n logger?.warn('Retry: attempt failed', { attempt, message: payload.message, type: payload.type, classification, correlationId });\n metrics?.emit({ name: 'Retry.attempt_failed', value: 1, tags: { attempt: String(attempt), type: payload.type, classification } });\n\n // Abort condition — stop immediately, no fallback\n if (await abortCondition.shouldAbort(payload)) {\n return fail(makeRetryError(payload, attempt, Date.now() - startTime));\n }\n\n // Retry condition — if false, treat as exhausted\n if (!(await RetryCondition.shouldRetry(payload))) {\n await hooks.onExhausted({ lastError: payload, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });\n if (fallback) return ok((await fallback(payload)) as T);\n return fail(makeRetryError(payload, attempt, Date.now() - startTime));\n }\n\n // Max attempts reached\n if (attempt >= maxAttempts) {\n await hooks.onExhausted({ lastError: payload, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });\n if (fallback) return ok((await fallback(payload)) as T);\n return fail(makeRetryError(payload, attempt, Date.now() - startTime));\n }\n\n // Budget check before scheduling the retry\n if (budget && !budget.tryConsume()) {\n await hooks.onBudgetExhausted();\n metrics?.emit({ name: 'Retry.budget_exhausted', value: 1 });\n if (fallback) return ok((await fallback(payload)) as T);\n return fail(makeRetryError(payload, attempt, Date.now() - startTime, true));\n }\n\n // Schedule retry with backoff\n const delay = dynamicDelay?.(payload, attempt) ?? backoff.nextDelay(attempt);\n await hooks.beforeRetry({ attempt, error: payload, delayMs: delay });\n await sleep(delay);\n await hooks.afterRetry({ attempt, error: payload, delayMs: delay });\n }\n }\n\n // Safety net — logically unreachable but satisfies TypeScript\n const payload = lastError ?? {\n type: 'unknown' as const,\n message: 'Retry loop exhausted without error',\n attempt: maxAttempts,\n elapsedMs: Date.now() - startTime,\n };\n await hooks.onExhausted({ lastError: payload, totalAttempts: maxAttempts, totalElapsedMs: Date.now() - startTime });\n if (fallback) return ok((await fallback(payload)) as T);\n return fail(makeRetryError(payload, maxAttempts, Date.now() - startTime));\n }\n}\n","import type {\n RetryHooks,\n BeforeRetryContext,\n AfterRetryContext,\n RetrySuccessContext,\n ExhaustedContext,\n} from './types.js';\n\nexport class HookRunner {\n constructor(\n private hooks: RetryHooks,\n private correlationId?: string,\n ) {}\n\n async beforeRetry(ctx: BeforeRetryContext): Promise<void> {\n if (!this.hooks.beforeRetry) return;\n try {\n await this.hooks.beforeRetry({ ...ctx, correlationId: this.correlationId });\n } catch {\n // Errors in hooks are logged but never propagated.\n // This prevents a broken hook from corrupting the retry state.\n }\n }\n\n async afterRetry(ctx: AfterRetryContext): Promise<void> {\n if (!this.hooks.afterRetry) return;\n try {\n await this.hooks.afterRetry({ ...ctx, correlationId: this.correlationId });\n } catch {\n // Silent: hook errors must not corrupt retry state\n }\n }\n\n async onRetrySuccess(ctx: RetrySuccessContext): Promise<void> {\n if (!this.hooks.onRetrySuccess) return;\n try {\n await this.hooks.onRetrySuccess({ ...ctx, correlationId: this.correlationId });\n } catch {\n // Silent\n }\n }\n\n async onExhausted(ctx: ExhaustedContext): Promise<void> {\n if (!this.hooks.onExhausted) return;\n try {\n await this.hooks.onExhausted({ ...ctx, correlationId: this.correlationId });\n } catch {\n // Silent\n }\n }\n\n async onBudgetExhausted(): Promise<void> {\n if (!this.hooks.onBudgetExhausted) return;\n try {\n await this.hooks.onBudgetExhausted({ correlationId: this.correlationId });\n } catch {\n // Silent\n }\n }\n}\n","import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryEngineConfig, RetryError, RetryMetricsSnapshot, RetryCondition, AbortCondition, RetryConditionFn, AbortConditionFn, BackoffConfig, BackoffStrategy, RetryErrorPayload, IdempotencyStore } from './types.js';\nimport type { SlidingWindowBudget } from './retry.budget.js';\nimport { RetryExecutor } from './retry.executor.js';\nimport { HookRunner } from './retry.hooks.js';\nimport { SlidingWindowBudgetImpl } from './retry.budget.js';\nimport { DefaultErrorClassifier } from '../conditions/error.classifier.js';\nimport { TimeoutManager } from '../timeout/timeout.manager.js';\nimport { IdempotencyManager } from '../idempotency/idempotency.manager.js';\nimport { InMemoryIdempotencyStore } from '../idempotency/memory.store.js';\nimport { FixedBackoff } from '../backoff/fixed.backoff.js';\nimport { LinearBackoff } from '../backoff/linear.backoff.js';\nimport { ExponentialBackoff } from '../backoff/exponential.backoff.js';\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction isBackoffStrategy(b: BackoffConfig | BackoffStrategy): b is BackoffStrategy {\n return typeof (b as BackoffStrategy).nextDelay === 'function';\n}\n\nfunction createBackoff(config: BackoffConfig): BackoffStrategy {\n switch (config.type) {\n case 'fixed':\n return new FixedBackoff({ baseDelay: config.baseDelay });\n case 'linear':\n return new LinearBackoff({ baseDelay: config.baseDelay, multiplier: config.multiplier, maxDelay: config.maxDelay });\n case 'exponential':\n return new ExponentialBackoff({ baseDelay: config.baseDelay, multiplier: config.multiplier, maxDelay: config.maxDelay, jitter: config.jitter });\n }\n}\n\n/**\n * When the caller doesn't supply `retryIf`, retry exactly the errors the\n * classifier calls 'transient' -- so a custom `classifiers` rule actually\n * changes retry behavior instead of only affecting logging/metrics tags.\n */\nfunction wrapRetryCondition(\n condition: RetryCondition | RetryConditionFn | undefined,\n classifier: DefaultErrorClassifier,\n): RetryCondition {\n if (!condition) return { shouldRetry: (error: RetryErrorPayload) => classifier.classify(error) === 'transient' };\n if (typeof condition === 'function') return { shouldRetry: condition };\n return condition;\n}\n\n/** See {@link wrapRetryCondition} -- aborts exactly what the classifier calls 'permanent'. */\nfunction wrapAbortCondition(\n condition: AbortCondition | AbortConditionFn | undefined,\n classifier: DefaultErrorClassifier,\n): AbortCondition {\n if (!condition) return { shouldAbort: (error: RetryErrorPayload) => classifier.classify(error) === 'permanent' };\n if (typeof condition === 'function') return { shouldAbort: condition };\n return condition;\n}\n\n// ─── Engine ──────────────────────────────────────────────────────────────────\n\nexport class RetryEngine {\n private metrics: RetryMetricsSnapshot = {\n totalAttempts: 0,\n totalSuccesses: 0,\n totalFailures: 0,\n totalExhausted: 0,\n totalBudgetExhausted: 0,\n totalTimeouts: 0,\n };\n\n /**\n * A budget is a *shared* sliding window -- recreating it on every execute()\n * call means it never accumulates enough history to reject anything. Built\n * lazily from whichever call first enables it, then reused for the life of\n * this engine.\n */\n private budget: SlidingWindowBudget | undefined;\n\n /**\n * Same problem for idempotency: the cache has to outlive a single\n * execute() call to do anything. Only the default in-memory store needs\n * this -- a caller-supplied store (e.g. Redis) is already persistent.\n */\n private defaultIdempotencyStore: IdempotencyStore | undefined;\n\n constructor(private config: RetryEngineConfig) {}\n\n async execute<T>(\n task: (signal: AbortSignal) => Promise<T>,\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n const merged: Partial<RetryConfig> = { ...this.config.defaultConfig, ...options };\n\n const backoffConfig: BackoffConfig = (!merged.backoff || isBackoffStrategy(merged.backoff))\n ? { type: 'fixed', baseDelay: 200 }\n : merged.backoff;\n\n const backoffStrategy = (merged.backoff && isBackoffStrategy(merged.backoff))\n ? merged.backoff.clone()\n : createBackoff(backoffConfig);\n\n const classifier = new DefaultErrorClassifier(merged.classifiers);\n\n const timeoutManager = new TimeoutManager({\n globalTimeoutMs: 0,\n attemptTimeoutMs: 0,\n ...merged.timeout,\n });\n\n if (merged.budget && !this.budget) {\n this.budget = new SlidingWindowBudgetImpl({ windowMs: 60_000, maxRetryRatio: 0.1, minRequestCount: 10, ...merged.budget });\n }\n const budget = merged.budget ? this.budget : undefined;\n\n const idempotency =\n merged.idempotency?.enabled\n ? new IdempotencyManager({\n enabled: true,\n idempotentMethods: ['POST', 'PUT', 'PATCH'],\n headerName: 'Idempotency-Key',\n ttlMs: 24 * 60 * 60 * 1000,\n ...merged.idempotency,\n store: merged.idempotency.store ?? (this.defaultIdempotencyStore ??= new InMemoryIdempotencyStore()),\n })\n : undefined;\n\n const hookRunner = new HookRunner(merged.hooks ?? {}, merged.correlationId);\n const RetryCondition = wrapRetryCondition(merged.retryIf, classifier);\n const abortCondition = wrapAbortCondition(merged.abortIf, classifier);\n\n const fullConfig: RetryConfig = {\n maxAttempts: 3,\n backoff: backoffConfig,\n ...merged,\n };\n\n const executor = new RetryExecutor(\n {\n backoff: backoffStrategy,\n budget,\n classifier,\n timeoutManager,\n idempotency,\n RetryCondition,\n abortCondition,\n hooks: hookRunner,\n circuitBreaker: this.config.integrations?.circuitBreaker,\n bulkhead: this.config.integrations?.bulkhead,\n logger: this.config.integrations?.observability?.logger,\n metrics: this.config.integrations?.observability?.metrics,\n correlationId: merged.correlationId,\n },\n fullConfig,\n );\n\n this.metrics.totalAttempts++;\n const result = await executor.run(task);\n\n if (result.ok) {\n this.metrics.totalSuccesses++;\n } else {\n this.metrics.totalFailures++;\n if (result.error.metadata.budgetExhausted) this.metrics.totalBudgetExhausted++;\n if (result.error.type === 'timeout') this.metrics.totalTimeouts++;\n if (result.error.metadata.attempts >= fullConfig.maxAttempts) this.metrics.totalExhausted++;\n }\n\n return result;\n }\n\n async executeWithContext<T>(\n task: (signal: AbortSignal) => Promise<T>,\n context: { correlationId?: string },\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n return this.execute(task, { ...options, correlationId: context.correlationId });\n }\n\n updateDefaults(partial: Partial<RetryConfig>): void {\n this.config.defaultConfig = { ...this.config.defaultConfig, ...partial };\n }\n\n getMetrics(): RetryMetricsSnapshot {\n return { ...this.metrics };\n }\n\n resetMetrics(): void {\n this.metrics = {\n totalAttempts: 0,\n totalSuccesses: 0,\n totalFailures: 0,\n totalExhausted: 0,\n totalBudgetExhausted: 0,\n totalTimeouts: 0,\n };\n }\n}\n","import type { RetryEngineConfig, RetryMetricsSnapshot } from './types.js';\nimport { RetryEngine } from './retry.engine.js';\n\nexport class RetryRegistry {\n private readonly engines = new Map<string, RetryEngine>();\n\n getOrCreate(name: string, config?: Partial<RetryEngineConfig>): RetryEngine {\n if (!this.engines.has(name)) {\n this.engines.set(\n name,\n new RetryEngine({\n name,\n ...config,\n defaultConfig: { ...config?.defaultConfig },\n integrations: config?.integrations,\n }),\n );\n }\n return this.engines.get(name)!;\n }\n\n get(name: string): RetryEngine | undefined {\n return this.engines.get(name);\n }\n\n reset(name: string): void {\n this.engines.delete(name);\n }\n\n resetAll(): void {\n this.engines.clear();\n }\n\n getAllMetrics(): Record<string, RetryMetricsSnapshot> {\n const metrics: Record<string, RetryMetricsSnapshot> = {};\n for (const [name, engine] of this.engines) {\n metrics[name] = engine.getMetrics();\n }\n return metrics;\n }\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,48 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkBX4TTYBY_cjs = require('./chunk-BX4TTYBY.cjs');
|
|
4
4
|
|
|
5
5
|
// src/retry/retry.fn.ts
|
|
6
|
-
var defaultRegistry = new
|
|
6
|
+
var defaultRegistry = new chunkBX4TTYBY_cjs.RetryRegistry();
|
|
7
7
|
async function retry(task, options) {
|
|
8
8
|
const engine = defaultRegistry.getOrCreate("__default__");
|
|
9
9
|
return engine.execute(task, options);
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
// src/conditions/http.conditions.ts
|
|
13
|
+
var defaultRetryCondition = {
|
|
14
|
+
shouldRetry(error) {
|
|
15
|
+
switch (error.type) {
|
|
16
|
+
case "http":
|
|
17
|
+
return error.status === 429 || error.status != null && error.status >= 500;
|
|
18
|
+
case "network":
|
|
19
|
+
case "timeout":
|
|
20
|
+
case "circuit-open":
|
|
21
|
+
case "bulkhead-rejected":
|
|
22
|
+
return true;
|
|
23
|
+
case "business":
|
|
24
|
+
case "unknown":
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var defaultAbortCondition = {
|
|
30
|
+
shouldAbort(error) {
|
|
31
|
+
switch (error.type) {
|
|
32
|
+
case "http":
|
|
33
|
+
return error.status != null && error.status < 500 && error.status !== 429;
|
|
34
|
+
case "business":
|
|
35
|
+
return true;
|
|
36
|
+
case "network":
|
|
37
|
+
case "timeout":
|
|
38
|
+
case "circuit-open":
|
|
39
|
+
case "bulkhead-rejected":
|
|
40
|
+
case "unknown":
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
12
46
|
// src/retry/retry.errors.ts
|
|
13
47
|
var RetryExhaustedError = class extends Error {
|
|
14
48
|
constructor(message, attempts, totalElapsedMs) {
|
|
@@ -29,70 +63,64 @@ var BudgetExhaustedError = class extends Error {
|
|
|
29
63
|
|
|
30
64
|
Object.defineProperty(exports, "AttemptTimeoutError", {
|
|
31
65
|
enumerable: true,
|
|
32
|
-
get: function () { return
|
|
66
|
+
get: function () { return chunkBX4TTYBY_cjs.AttemptTimeoutError; }
|
|
33
67
|
});
|
|
34
68
|
Object.defineProperty(exports, "DefaultErrorClassifier", {
|
|
35
69
|
enumerable: true,
|
|
36
|
-
get: function () { return
|
|
70
|
+
get: function () { return chunkBX4TTYBY_cjs.DefaultErrorClassifier; }
|
|
37
71
|
});
|
|
38
72
|
Object.defineProperty(exports, "ExponentialBackoff", {
|
|
39
73
|
enumerable: true,
|
|
40
|
-
get: function () { return
|
|
74
|
+
get: function () { return chunkBX4TTYBY_cjs.ExponentialBackoff; }
|
|
41
75
|
});
|
|
42
76
|
Object.defineProperty(exports, "FixedBackoff", {
|
|
43
77
|
enumerable: true,
|
|
44
|
-
get: function () { return
|
|
78
|
+
get: function () { return chunkBX4TTYBY_cjs.FixedBackoff; }
|
|
45
79
|
});
|
|
46
80
|
Object.defineProperty(exports, "GlobalTimeoutError", {
|
|
47
81
|
enumerable: true,
|
|
48
|
-
get: function () { return
|
|
82
|
+
get: function () { return chunkBX4TTYBY_cjs.GlobalTimeoutError; }
|
|
49
83
|
});
|
|
50
84
|
Object.defineProperty(exports, "IdempotencyManager", {
|
|
51
85
|
enumerable: true,
|
|
52
|
-
get: function () { return
|
|
86
|
+
get: function () { return chunkBX4TTYBY_cjs.IdempotencyManager; }
|
|
53
87
|
});
|
|
54
88
|
Object.defineProperty(exports, "InMemoryIdempotencyStore", {
|
|
55
89
|
enumerable: true,
|
|
56
|
-
get: function () { return
|
|
90
|
+
get: function () { return chunkBX4TTYBY_cjs.InMemoryIdempotencyStore; }
|
|
57
91
|
});
|
|
58
92
|
Object.defineProperty(exports, "JitterDecorator", {
|
|
59
93
|
enumerable: true,
|
|
60
|
-
get: function () { return
|
|
94
|
+
get: function () { return chunkBX4TTYBY_cjs.JitterDecorator; }
|
|
61
95
|
});
|
|
62
96
|
Object.defineProperty(exports, "LinearBackoff", {
|
|
63
97
|
enumerable: true,
|
|
64
|
-
get: function () { return
|
|
98
|
+
get: function () { return chunkBX4TTYBY_cjs.LinearBackoff; }
|
|
65
99
|
});
|
|
66
100
|
Object.defineProperty(exports, "RetryEngine", {
|
|
67
101
|
enumerable: true,
|
|
68
|
-
get: function () { return
|
|
102
|
+
get: function () { return chunkBX4TTYBY_cjs.RetryEngine; }
|
|
69
103
|
});
|
|
70
104
|
Object.defineProperty(exports, "RetryRegistry", {
|
|
71
105
|
enumerable: true,
|
|
72
|
-
get: function () { return
|
|
106
|
+
get: function () { return chunkBX4TTYBY_cjs.RetryRegistry; }
|
|
73
107
|
});
|
|
74
108
|
Object.defineProperty(exports, "SlidingWindowBudgetImpl", {
|
|
75
109
|
enumerable: true,
|
|
76
|
-
get: function () { return
|
|
110
|
+
get: function () { return chunkBX4TTYBY_cjs.SlidingWindowBudgetImpl; }
|
|
77
111
|
});
|
|
78
112
|
Object.defineProperty(exports, "TimeoutManager", {
|
|
79
113
|
enumerable: true,
|
|
80
|
-
get: function () { return
|
|
114
|
+
get: function () { return chunkBX4TTYBY_cjs.TimeoutManager; }
|
|
81
115
|
});
|
|
82
116
|
Object.defineProperty(exports, "applyJitter", {
|
|
83
117
|
enumerable: true,
|
|
84
|
-
get: function () { return
|
|
85
|
-
});
|
|
86
|
-
Object.defineProperty(exports, "defaultAbortCondition", {
|
|
87
|
-
enumerable: true,
|
|
88
|
-
get: function () { return chunkMTBUSC7V_cjs.defaultAbortCondition; }
|
|
89
|
-
});
|
|
90
|
-
Object.defineProperty(exports, "defaultRetryCondition", {
|
|
91
|
-
enumerable: true,
|
|
92
|
-
get: function () { return chunkMTBUSC7V_cjs.defaultRetryCondition; }
|
|
118
|
+
get: function () { return chunkBX4TTYBY_cjs.applyJitter; }
|
|
93
119
|
});
|
|
94
120
|
exports.BudgetExhaustedError = BudgetExhaustedError;
|
|
95
121
|
exports.RetryExhaustedError = RetryExhaustedError;
|
|
122
|
+
exports.defaultAbortCondition = defaultAbortCondition;
|
|
123
|
+
exports.defaultRetryCondition = defaultRetryCondition;
|
|
96
124
|
exports.retry = retry;
|
|
97
125
|
//# sourceMappingURL=index.cjs.map
|
|
98
126
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/retry/retry.fn.ts","../src/retry/retry.errors.ts"],"names":["RetryRegistry"],"mappings":";;;;;AAIA,IAAM,eAAA,GAAkB,IAAIA,+BAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;
|
|
1
|
+
{"version":3,"sources":["../src/retry/retry.fn.ts","../src/conditions/http.conditions.ts","../src/retry/retry.errors.ts"],"names":["RetryRegistry"],"mappings":";;;;;AAIA,IAAM,eAAA,GAAkB,IAAIA,+BAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACnBO,IAAM,qBAAA,GAAwC;AAAA,EACnD,YAAY,KAAA,EAAmC;AAC7C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,MAAA;AACH,QAAA,OAAO,MAAM,MAAA,KAAW,GAAA,IAAQ,MAAM,MAAA,IAAU,IAAA,IAAQ,MAAM,MAAA,IAAU,GAAA;AAAA,MAC1E,KAAK,SAAA;AAAA,MACL,KAAK,SAAA;AAAA,MACL,KAAK,cAAA;AAAA,MACL,KAAK,mBAAA;AACH,QAAA,OAAO,IAAA;AAAA,MACT,KAAK,UAAA;AAAA,MACL,KAAK,SAAA;AACH,QAAA,OAAO,KAAA;AAAA;AACX,EACF;AACF;AAMO,IAAM,qBAAA,GAAwC;AAAA,EACnD,YAAY,KAAA,EAAmC;AAC7C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,MAAA;AACH,QAAA,OAAO,MAAM,MAAA,IAAU,IAAA,IAAQ,MAAM,MAAA,GAAS,GAAA,IAAO,MAAM,MAAA,KAAW,GAAA;AAAA,MACxE,KAAK,UAAA;AACH,QAAA,OAAO,IAAA;AAAA,MACT,KAAK,SAAA;AAAA,MACL,KAAK,SAAA;AAAA,MACL,KAAK,cAAA;AAAA,MACL,KAAK,mBAAA;AAAA,MACL,KAAK,SAAA;AACH,QAAA,OAAO,KAAA;AAAA;AACX,EACF;AACF;;;AC1CO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACE,OAAA,EACgB,QAAA,EACA,cAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EALkB,QAAA;AAAA,EACA,cAAA;AAKpB;AAEO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF","file":"index.cjs","sourcesContent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * result.match(\n * (user) => res.json(user),\n * (error) => res.status(502).json({ error: error.message }),\n * );\n * ```\n */\nexport async function retry<T>(\n task: (signal: AbortSignal) => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","import type { RetryCondition, AbortCondition, RetryErrorPayload } from '../retry/types.js';\n\n/**\n * Default retry condition: retry on transient HTTP errors (429, 5xx),\n * network errors, timeouts, circuit-open, and bulkhead-rejected.\n */\nexport const defaultRetryCondition: RetryCondition = {\n shouldRetry(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status === 429 || (error.status != null && error.status >= 500);\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n return true;\n case 'business':\n case 'unknown':\n return false;\n }\n },\n};\n\n/**\n * Default abort condition: abort on 4xx client errors (except 429),\n * business errors, and permanent classifications.\n */\nexport const defaultAbortCondition: AbortCondition = {\n shouldAbort(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status != null && error.status < 500 && error.status !== 429;\n case 'business':\n return true;\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n case 'unknown':\n return false;\n }\n },\n};\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-
|
|
2
|
-
export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-
|
|
1
|
+
import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-DZPAMpkR.cjs';
|
|
2
|
+
export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-DZPAMpkR.cjs';
|
|
3
3
|
import { Result } from '@backendkit-labs/result';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -15,7 +15,7 @@ import { Result } from '@backendkit-labs/result';
|
|
|
15
15
|
* );
|
|
16
16
|
* ```
|
|
17
17
|
*/
|
|
18
|
-
declare function retry<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
|
18
|
+
declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
|
19
19
|
|
|
20
20
|
declare class FixedBackoff implements BackoffStrategy {
|
|
21
21
|
private config;
|
|
@@ -132,15 +132,22 @@ declare class SlidingWindowBudgetImpl implements SlidingWindowBudget {
|
|
|
132
132
|
declare class TimeoutManager {
|
|
133
133
|
private config;
|
|
134
134
|
private startTime;
|
|
135
|
+
private readonly globalController;
|
|
136
|
+
private readonly globalTimer;
|
|
135
137
|
constructor(config: TimeoutConfig);
|
|
136
138
|
/**
|
|
137
|
-
* Execute a task with per-attempt timeout
|
|
138
|
-
*
|
|
139
|
+
* Execute a task with a per-attempt timeout, passing it an `AbortSignal`
|
|
140
|
+
* that fires when the attempt (or the overall global timeout) expires.
|
|
141
|
+
*
|
|
142
|
+
* A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)
|
|
143
|
+
* keeps running in the background after we give up waiting on it -- we
|
|
144
|
+
* can only abandon the wait, not force JS execution to stop.
|
|
139
145
|
*/
|
|
140
|
-
executeWithAttemptTimeout<T>(task: () => Promise<T>): Promise<T>;
|
|
146
|
+
executeWithAttemptTimeout<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
|
|
141
147
|
/**
|
|
142
|
-
* Check if the global timeout has
|
|
143
|
-
*
|
|
148
|
+
* Check if the global timeout has already fired. Called at the start of
|
|
149
|
+
* each attempt loop iteration -- the AbortSignal handles cutting off an
|
|
150
|
+
* attempt that's already in flight when the deadline hits.
|
|
144
151
|
*/
|
|
145
152
|
checkGlobalTimeout(): void;
|
|
146
153
|
/**
|
|
@@ -150,6 +157,8 @@ declare class TimeoutManager {
|
|
|
150
157
|
getRemainingTime(): number;
|
|
151
158
|
/** Reset the start time (for reuse across retry cycles). */
|
|
152
159
|
reset(): void;
|
|
160
|
+
/** Release the global timeout timer. Call once the retry loop is done. */
|
|
161
|
+
dispose(): void;
|
|
153
162
|
}
|
|
154
163
|
|
|
155
164
|
declare class AttemptTimeoutError extends Error {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-
|
|
2
|
-
export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-
|
|
1
|
+
import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-DZPAMpkR.js';
|
|
2
|
+
export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-DZPAMpkR.js';
|
|
3
3
|
import { Result } from '@backendkit-labs/result';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -15,7 +15,7 @@ import { Result } from '@backendkit-labs/result';
|
|
|
15
15
|
* );
|
|
16
16
|
* ```
|
|
17
17
|
*/
|
|
18
|
-
declare function retry<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
|
18
|
+
declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
|
19
19
|
|
|
20
20
|
declare class FixedBackoff implements BackoffStrategy {
|
|
21
21
|
private config;
|
|
@@ -132,15 +132,22 @@ declare class SlidingWindowBudgetImpl implements SlidingWindowBudget {
|
|
|
132
132
|
declare class TimeoutManager {
|
|
133
133
|
private config;
|
|
134
134
|
private startTime;
|
|
135
|
+
private readonly globalController;
|
|
136
|
+
private readonly globalTimer;
|
|
135
137
|
constructor(config: TimeoutConfig);
|
|
136
138
|
/**
|
|
137
|
-
* Execute a task with per-attempt timeout
|
|
138
|
-
*
|
|
139
|
+
* Execute a task with a per-attempt timeout, passing it an `AbortSignal`
|
|
140
|
+
* that fires when the attempt (or the overall global timeout) expires.
|
|
141
|
+
*
|
|
142
|
+
* A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)
|
|
143
|
+
* keeps running in the background after we give up waiting on it -- we
|
|
144
|
+
* can only abandon the wait, not force JS execution to stop.
|
|
139
145
|
*/
|
|
140
|
-
executeWithAttemptTimeout<T>(task: () => Promise<T>): Promise<T>;
|
|
146
|
+
executeWithAttemptTimeout<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
|
|
141
147
|
/**
|
|
142
|
-
* Check if the global timeout has
|
|
143
|
-
*
|
|
148
|
+
* Check if the global timeout has already fired. Called at the start of
|
|
149
|
+
* each attempt loop iteration -- the AbortSignal handles cutting off an
|
|
150
|
+
* attempt that's already in flight when the deadline hits.
|
|
144
151
|
*/
|
|
145
152
|
checkGlobalTimeout(): void;
|
|
146
153
|
/**
|
|
@@ -150,6 +157,8 @@ declare class TimeoutManager {
|
|
|
150
157
|
getRemainingTime(): number;
|
|
151
158
|
/** Reset the start time (for reuse across retry cycles). */
|
|
152
159
|
reset(): void;
|
|
160
|
+
/** Release the global timeout timer. Call once the retry loop is done. */
|
|
161
|
+
dispose(): void;
|
|
153
162
|
}
|
|
154
163
|
|
|
155
164
|
declare class AttemptTimeoutError extends Error {
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RetryRegistry } from './chunk-
|
|
2
|
-
export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter
|
|
1
|
+
import { RetryRegistry } from './chunk-NV6QXLUR.js';
|
|
2
|
+
export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter } from './chunk-NV6QXLUR.js';
|
|
3
3
|
|
|
4
4
|
// src/retry/retry.fn.ts
|
|
5
5
|
var defaultRegistry = new RetryRegistry();
|
|
@@ -8,6 +8,40 @@ async function retry(task, options) {
|
|
|
8
8
|
return engine.execute(task, options);
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
+
// src/conditions/http.conditions.ts
|
|
12
|
+
var defaultRetryCondition = {
|
|
13
|
+
shouldRetry(error) {
|
|
14
|
+
switch (error.type) {
|
|
15
|
+
case "http":
|
|
16
|
+
return error.status === 429 || error.status != null && error.status >= 500;
|
|
17
|
+
case "network":
|
|
18
|
+
case "timeout":
|
|
19
|
+
case "circuit-open":
|
|
20
|
+
case "bulkhead-rejected":
|
|
21
|
+
return true;
|
|
22
|
+
case "business":
|
|
23
|
+
case "unknown":
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var defaultAbortCondition = {
|
|
29
|
+
shouldAbort(error) {
|
|
30
|
+
switch (error.type) {
|
|
31
|
+
case "http":
|
|
32
|
+
return error.status != null && error.status < 500 && error.status !== 429;
|
|
33
|
+
case "business":
|
|
34
|
+
return true;
|
|
35
|
+
case "network":
|
|
36
|
+
case "timeout":
|
|
37
|
+
case "circuit-open":
|
|
38
|
+
case "bulkhead-rejected":
|
|
39
|
+
case "unknown":
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
11
45
|
// src/retry/retry.errors.ts
|
|
12
46
|
var RetryExhaustedError = class extends Error {
|
|
13
47
|
constructor(message, attempts, totalElapsedMs) {
|
|
@@ -26,6 +60,6 @@ var BudgetExhaustedError = class extends Error {
|
|
|
26
60
|
}
|
|
27
61
|
};
|
|
28
62
|
|
|
29
|
-
export { BudgetExhaustedError, RetryExhaustedError, retry };
|
|
63
|
+
export { BudgetExhaustedError, RetryExhaustedError, defaultAbortCondition, defaultRetryCondition, retry };
|
|
30
64
|
//# sourceMappingURL=index.js.map
|
|
31
65
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/retry/retry.fn.ts","../src/retry/retry.errors.ts"],"names":[],"mappings":";;;;AAIA,IAAM,eAAA,GAAkB,IAAI,aAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;
|
|
1
|
+
{"version":3,"sources":["../src/retry/retry.fn.ts","../src/conditions/http.conditions.ts","../src/retry/retry.errors.ts"],"names":[],"mappings":";;;;AAIA,IAAM,eAAA,GAAkB,IAAI,aAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACnBO,IAAM,qBAAA,GAAwC;AAAA,EACnD,YAAY,KAAA,EAAmC;AAC7C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,MAAA;AACH,QAAA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ent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * result.match(\n * (user) => res.json(user),\n * (error) => res.status(502).json({ error: error.message }),\n * );\n * ```\n */\nexport async function retry<T>(\n task: (signal: AbortSignal) => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","import type { RetryCondition, AbortCondition, RetryErrorPayload } from '../retry/types.js';\n\n/**\n * Default retry condition: retry on transient HTTP errors (429, 5xx),\n * network errors, timeouts, circuit-open, and bulkhead-rejected.\n */\nexport const defaultRetryCondition: RetryCondition = {\n shouldRetry(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status === 429 || (error.status != null && error.status >= 500);\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n return true;\n case 'business':\n case 'unknown':\n return false;\n }\n },\n};\n\n/**\n * Default abort condition: abort on 4xx client errors (except 429),\n * business errors, and permanent classifications.\n */\nexport const defaultAbortCondition: AbortCondition = {\n shouldAbort(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status != null && error.status < 500 && error.status !== 429;\n case 'business':\n return true;\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n case 'unknown':\n return false;\n }\n },\n};\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
|
package/dist/nestjs/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkBX4TTYBY_cjs = require('../chunk-BX4TTYBY.cjs');
|
|
4
4
|
var common = require('@nestjs/common');
|
|
5
5
|
var core = require('@nestjs/core');
|
|
6
6
|
var rxjs = require('rxjs');
|
|
@@ -18,12 +18,27 @@ exports.RetryService = class RetryService {
|
|
|
18
18
|
return this.engine;
|
|
19
19
|
}
|
|
20
20
|
};
|
|
21
|
-
exports.RetryService =
|
|
21
|
+
exports.RetryService = chunkBX4TTYBY_cjs.__decorateClass([
|
|
22
22
|
common.Injectable()
|
|
23
23
|
], exports.RetryService);
|
|
24
24
|
var RETRY_METADATA_KEY = "retry:config";
|
|
25
|
+
var defaultRegistry = new chunkBX4TTYBY_cjs.RetryRegistry();
|
|
25
26
|
function Retry(config) {
|
|
26
|
-
return
|
|
27
|
+
return function(target, propertyKey, descriptor) {
|
|
28
|
+
const originalMethod = descriptor.value;
|
|
29
|
+
const className = target.constructor?.name ?? "anonymous";
|
|
30
|
+
const engineName = `method:${className}.${String(propertyKey)}`;
|
|
31
|
+
descriptor.value = function(...args) {
|
|
32
|
+
const registry = this.retryRegistry ?? defaultRegistry;
|
|
33
|
+
const engine = registry.getOrCreate(engineName);
|
|
34
|
+
return engine.execute(() => Promise.resolve(originalMethod.apply(this, args)), config).then((result) => {
|
|
35
|
+
if (result.ok) return result.value;
|
|
36
|
+
throw result.error;
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
common.SetMetadata(RETRY_METADATA_KEY, config)(target, propertyKey, descriptor);
|
|
40
|
+
return descriptor;
|
|
41
|
+
};
|
|
27
42
|
}
|
|
28
43
|
|
|
29
44
|
// src/nestjs/retry.interceptor.ts
|
|
@@ -56,8 +71,10 @@ exports.RetryInterceptor = class RetryInterceptor {
|
|
|
56
71
|
);
|
|
57
72
|
}
|
|
58
73
|
};
|
|
59
|
-
exports.RetryInterceptor =
|
|
60
|
-
common.Injectable()
|
|
74
|
+
exports.RetryInterceptor = chunkBX4TTYBY_cjs.__decorateClass([
|
|
75
|
+
common.Injectable(),
|
|
76
|
+
chunkBX4TTYBY_cjs.__decorateParam(0, common.Inject(exports.RetryService)),
|
|
77
|
+
chunkBX4TTYBY_cjs.__decorateParam(1, common.Inject(core.Reflector))
|
|
61
78
|
], exports.RetryInterceptor);
|
|
62
79
|
|
|
63
80
|
// src/nestjs/retry.constants.ts
|
|
@@ -71,7 +88,7 @@ exports.RetryModule = class RetryModule {
|
|
|
71
88
|
const providers = [
|
|
72
89
|
{
|
|
73
90
|
provide: RETRY_REGISTRY_TOKEN,
|
|
74
|
-
useFactory: () => new
|
|
91
|
+
useFactory: () => new chunkBX4TTYBY_cjs.RetryRegistry()
|
|
75
92
|
},
|
|
76
93
|
{
|
|
77
94
|
provide: RETRY_ENGINE_TOKEN,
|
|
@@ -84,7 +101,7 @@ exports.RetryModule = class RetryModule {
|
|
|
84
101
|
inject: [RETRY_ENGINE_TOKEN]
|
|
85
102
|
}
|
|
86
103
|
];
|
|
87
|
-
if (options?.globalInterceptor
|
|
104
|
+
if (options?.globalInterceptor === true) {
|
|
88
105
|
providers.push({
|
|
89
106
|
provide: core.APP_INTERCEPTOR,
|
|
90
107
|
useClass: exports.RetryInterceptor
|
|
@@ -97,7 +114,7 @@ exports.RetryModule = class RetryModule {
|
|
|
97
114
|
};
|
|
98
115
|
}
|
|
99
116
|
};
|
|
100
|
-
exports.RetryModule =
|
|
117
|
+
exports.RetryModule = chunkBX4TTYBY_cjs.__decorateClass([
|
|
101
118
|
common.Module({})
|
|
102
119
|
], exports.RetryModule);
|
|
103
120
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nestjs/retry.service.ts","../../src/nestjs/retry.decorator.ts","../../src/nestjs/retry.interceptor.ts","../../src/nestjs/retry.constants.ts","../../src/nestjs/retry.module.ts"],"names":["RetryService","__decorateClass","Injectable","SetMetadata","Ret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A,CAAK;AAAA,QACb,OAAA,EAASU,oBAAA;AAAA,QACT,QAAA,EAAUN;AAAA,OACX,CAAA;AAAA,IACH;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQI,mBAAA;AAAA,MACR,SAAA;AAAA,MACA,OAAA,EAAS,CAACR,oBAAA,EAAc,kBAAA,EAAoB,oBAAoB;AAAA,KAClE;AAAA,EACF;AACF;AAnCaQ,mBAAA,GAANP,iCAAA,CAAA;AAAA,EADNU,aAAA,CAAO,EAAE;AAAA,CAAA,EACGH,mBAAA,CAAA","file":"index.cjs","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport type { Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from '../retry/types.js';\nimport { RetryEngine } from '../retry/retry.engine.js';\n\n@Injectable()\nexport class RetryService {\n constructor(private engine: RetryEngine) {}\n\n async execute<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n return this.engine.execute(task, options);\n }\n\n getEngine(): RetryEngine {\n return this.engine;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\nimport type { RetryConfig } from '../retry/types.js';\n\nexport const RETRY_METADATA_KEY = 'retry:config';\n\n/**\n * Decorator that marks a method for retry.\n *\n * @example\n * ```ts\n * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })\n * async fetchData() { ... }\n * ```\n */\nexport function Retry(config: Partial<RetryConfig>): MethodDecorator {\n return SetMetadata(RETRY_METADATA_KEY, config);\n}\n","import {\n Injectable,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable, from } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\nimport { Reflector } from '@nestjs/core';\nimport { RetryService } from './retry.service.js';\nimport { RETRY_METADATA_KEY } from './retry.decorator.js';\nimport type { RetryConfig } from '../retry/types.js';\n\n@Injectable()\nexport class RetryInterceptor implements NestInterceptor {\n constructor(\n private readonly RetryService: RetryService,\n private readonly reflector: Reflector,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n const RetryConfig = this.reflector.get<Partial<RetryConfig> | undefined>(\n RETRY_METADATA_KEY,\n context.getHandler(),\n );\n\n if (!RetryConfig) {\n return next.handle();\n }\n\n return from(\n this.RetryService.execute(() => next.handle().toPromise(), RetryConfig),\n ).pipe(\n switchMap((result) => {\n if (result.ok) {\n const value = result.value;\n if (value instanceof Observable) return value;\n return from(Promise.resolve(value));\n }\n throw result.error;\n }),\n );\n }\n}\n","export const RETRY_ENGINE_TOKEN = Symbol('RETRY_ENGINE_TOKEN');\nexport const RETRY_REGISTRY_TOKEN = Symbol('RETRY_REGISTRY_TOKEN');\n","import { Module, DynamicModule, Provider } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RetryEngine } from '../retry/retry.engine.js';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport { RetryService } from './retry.service.js';\nimport { RetryInterceptor } from './retry.interceptor.js';\nimport { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN } from './retry.constants.js';\nimport type { RetryEngineConfig } from '../retry/types.js';\n\nexport interface RetryModuleOptions {\n engineConfig?: Partial<RetryEngineConfig>;\n globalInterceptor?: boolean;\n}\n\n@Module({})\nexport class RetryModule {\n static forRoot(options?: RetryModuleOptions): DynamicModule {\n const engineConfig = options?.engineConfig ?? { name: 'default' };\n\n const providers: Provider[] = [\n {\n provide: RETRY_REGISTRY_TOKEN,\n useFactory: () => new RetryRegistry(),\n },\n {\n provide: RETRY_ENGINE_TOKEN,\n useFactory: (registry: RetryRegistry) =>\n registry.getOrCreate(engineConfig.name ?? 'default', engineConfig),\n inject: [RETRY_REGISTRY_TOKEN],\n },\n {\n provide: RetryService,\n useFactory: (engine: RetryEngine) => new RetryService(engine),\n inject: [RETRY_ENGINE_TOKEN],\n },\n ];\n\n if (options?.globalInterceptor !== false) {\n providers.push({\n provide: APP_INTERCEPTOR,\n useClass: RetryInterceptor,\n });\n }\n\n return {\n module: RetryModule,\n providers,\n exports: [RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nestjs/retry.service.ts","../../src/nestjs/retry.decorator.ts","../../src/nestjs/retry.interceptor.ts","../../src/nestjs/retry.constants.ts","../../src/nestjs/retry.module.ts"],"names":["RetryService","__decorateClass","Injectable","RetryRegistry","SetMetadata","RetryInterceptor","from","switchMap","Observable","__decorateParam","Reflector","RetryModule","APP_INTERCEPTOR","Module"],"mappings":";;;;;;;;AAMaA,uBAAN,kBAAA,CAAmB;AAAA,EACxB,YAAoB,MAAA,EAAqB;AAArB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAsB;AAAA,EAAtB,MAAA;AAAA,EAEpB,MAAM,OAAA,CACJ,IAAA,EACA,OAAA,EACgC;AAChC,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC1C;AAAA,EAEA,SAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF;AAbaA,oBAAA,GAANC,iCAAA,CAAA;AAAA,EADNC,iBAAA;AAAW,CAAA,EACCF,oBAAA,CAAA;ACFN,IAAM,kBAAA,GAAqB,cAAA;AAOlC,IAAM,eAAA,GAAkB,IAAIG,+BAAA,EAAc;AAqBnC,SAAS,MAAM,MAAA,EAA+C;AACnE,EAAA,OAAO,SAAU,MAAA,EAAgB,WAAA,EAA8B,UAAA,EAAoD;AACjH,IAAA,MAAM,iBAAiB,UAAA,CAAW,KAAA;AAClC,IAAA,MAAM,SAAA,GAAa,MAAA,CAA+C,WAAA,EAAa,IAAA,IAAQ,WAAA;AACvF,IAAA,MAAM,aAAa,CAAA,OAAA,EAAU,SAAS,CAAA,CAAA,EAAI,MAAA,CAAO,WAAW,CAAC,CAAA,CAAA;AAE7D,IAAA,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AA,IAAI,OAAA,EAAS,sBAAsB,IAAA,EAAM;AACvC,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,OAAA,EAASY,oBAAA;AAAA,QACT,QAAA,EAAUP;AAAA,OACX,CAAA;AAAA,IACH;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQM,mBAAA;AAAA,MACR,SAAA;AAAA,MACA,OAAA,EAAS,CAACX,oBAAA,EAAc,kBAAA,EAAoB,oBAAoB;AAAA,KAClE;AAAA,EACF;AACF;AAnCaW,mBAAA,GAANV,iCAAA,CAAA;AAAA,EADNY,aAAA,CAAO,EAAE;AAAA,CAAA,EACGF,mBAAA,CAAA","file":"index.cjs","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport type { Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from '../retry/types.js';\nimport { RetryEngine } from '../retry/retry.engine.js';\n\n@Injectable()\nexport class RetryService {\n constructor(private engine: RetryEngine) {}\n\n async execute<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n return this.engine.execute(task, options);\n }\n\n getEngine(): RetryEngine {\n return this.engine;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport type { RetryConfig } from '../retry/types.js';\n\nexport const RETRY_METADATA_KEY = 'retry:config';\n\n/**\n * Own default registry, used when the decorated class has no `retryRegistry`\n * property injected -- mirrors the standalone `retry()` function's registry\n * so `@Retry` works without requiring DI wiring.\n */\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Wraps a method in retry logic directly -- works on any method (service or\n * controller), with or without NestJS DI. Also sets metadata for\n * introspection/RetryInterceptor, but the decorator itself is what actually\n * retries; enabling RetryModule's global interceptor on top of `@Retry`-\n * decorated methods double-retries them (see RetryModule's\n * `globalInterceptor` option, off by default for this reason).\n *\n * Optionally inject `public readonly retryRegistry: RetryRegistry` on the\n * class to get a named, shared RetryEngine per method (so budget/idempotency\n * config actually accumulates across calls, and metrics are inspectable via\n * the registry) instead of the internal default registry.\n *\n * @example\n * ```ts\n * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })\n * async fetchData() { ... }\n * ```\n */\nexport function Retry(config: Partial<RetryConfig>): MethodDecorator {\n return function (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown;\n const className = (target as { constructor?: { name?: string } }).constructor?.name ?? 'anonymous';\n const engineName = `method:${className}.${String(propertyKey)}`;\n\n descriptor.value = function (this: unknown, ...args: unknown[]) {\n const registry = (this as { retryRegistry?: RetryRegistry }).retryRegistry ?? defaultRegistry;\n const engine = registry.getOrCreate(engineName);\n\n return engine.execute(() => Promise.resolve(originalMethod.apply(this, args)), config)\n .then((result) => {\n if (result.ok) return result.value;\n throw result.error;\n });\n };\n\n SetMetadata(RETRY_METADATA_KEY, config)(target, propertyKey, descriptor);\n return descriptor;\n };\n}\n","import {\n Injectable,\n Inject,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable, from } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\nimport { Reflector } from '@nestjs/core';\nimport { RetryService } from './retry.service.js';\nimport { RETRY_METADATA_KEY } from './retry.decorator.js';\nimport type { RetryConfig } from '../retry/types.js';\n\n@Injectable()\nexport class RetryInterceptor implements NestInterceptor {\n constructor(\n @Inject(RetryService) private readonly RetryService: RetryService,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n const RetryConfig = this.reflector.get<Partial<RetryConfig> | undefined>(\n RETRY_METADATA_KEY,\n context.getHandler(),\n );\n\n if (!RetryConfig) {\n return next.handle();\n }\n\n return from(\n this.RetryService.execute(() => next.handle().toPromise(), RetryConfig),\n ).pipe(\n switchMap((result) => {\n if (result.ok) {\n const value = result.value;\n if (value instanceof Observable) return value;\n return from(Promise.resolve(value));\n }\n throw result.error;\n }),\n );\n }\n}\n","export const RETRY_ENGINE_TOKEN = Symbol('RETRY_ENGINE_TOKEN');\nexport const RETRY_REGISTRY_TOKEN = Symbol('RETRY_REGISTRY_TOKEN');\n","import { Module, DynamicModule, Provider } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RetryEngine } from '../retry/retry.engine.js';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport { RetryService } from './retry.service.js';\nimport { RetryInterceptor } from './retry.interceptor.js';\nimport { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN } from './retry.constants.js';\nimport type { RetryEngineConfig } from '../retry/types.js';\n\nexport interface RetryModuleOptions {\n engineConfig?: Partial<RetryEngineConfig>;\n /**\n * Registers RetryInterceptor as a global APP_INTERCEPTOR, retrying the\n * whole request pipeline (`next.handle()`) for handlers carrying\n * `@Retry` metadata.\n *\n * Default: `false`. `@Retry` already retries the decorated method\n * directly -- turning this on for methods that also use `@Retry` retries\n * them twice (once via the decorator's own wrapping, once via the\n * interceptor re-running the whole pipeline around it). Only enable this\n * if you specifically want pipeline-level retry instead of method-level.\n */\n globalInterceptor?: boolean;\n}\n\n@Module({})\nexport class RetryModule {\n static forRoot(options?: RetryModuleOptions): DynamicModule {\n const engineConfig = options?.engineConfig ?? { name: 'default' };\n\n const providers: Provider[] = [\n {\n provide: RETRY_REGISTRY_TOKEN,\n useFactory: () => new RetryRegistry(),\n },\n {\n provide: RETRY_ENGINE_TOKEN,\n useFactory: (registry: RetryRegistry) =>\n registry.getOrCreate(engineConfig.name ?? 'default', engineConfig),\n inject: [RETRY_REGISTRY_TOKEN],\n },\n {\n provide: RetryService,\n useFactory: (engine: RetryEngine) => new RetryService(engine),\n inject: [RETRY_ENGINE_TOKEN],\n },\n ];\n\n if (options?.globalInterceptor === true) {\n providers.push({\n provide: APP_INTERCEPTOR,\n useClass: RetryInterceptor,\n });\n }\n\n return {\n module: RetryModule,\n providers,\n exports: [RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN],\n };\n }\n}\n"]}
|