@backendkit-labs/retry 0.2.0 → 0.2.1
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 +39 -29
- package/dist/{chunk-BX4TTYBY.cjs → chunk-VHMSEPWD.cjs} +22 -22
- package/dist/chunk-VHMSEPWD.cjs.map +1 -0
- package/dist/{chunk-NV6QXLUR.js → chunk-ZZ6WRRGP.js} +9 -9
- package/dist/chunk-ZZ6WRRGP.js.map +1 -0
- package/dist/index.cjs +16 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -6
- package/dist/index.d.ts +4 -6
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/nestjs/index.cjs +8 -8
- package/dist/nestjs/index.d.cts +1 -1
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/{retry.engine-DZPAMpkR.d.cts → retry.engine-C2SjDj64.d.cts} +15 -5
- package/dist/{retry.engine-DZPAMpkR.d.ts → retry.engine-C2SjDj64.d.ts} +15 -5
- package/package.json +7 -2
- package/dist/chunk-BX4TTYBY.cjs.map +0 -1
- package/dist/chunk-NV6QXLUR.js.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","../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;AAAA,EAC7C,YAA4B,SAAA,EAAmB;AAC7C,IAAA,KAAA,CAAM,CAAA,wBAAA,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,IACF;AACA,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AAAA,EAC9B;AAAA,EAEA,IAAI,IAAA,EAAuC;AACzC,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-ZZ6WRRGP.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 { 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\n/** Error names thrown by `Bulkhead` from `@backendkit-labs/bulkhead` when it turns a call away. */\nconst BULKHEAD_REJECTIONS = new Set(['BulkheadRejectedError', 'BulkheadTimeoutError']);\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 // Duck-typed by name so retry does not depend on @backendkit-labs/bulkhead.\n if (err instanceof Error && BULKHEAD_REJECTIONS.has(err.name)) {\n return { type: 'bulkhead-rejected', 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. Neither does a local\n // bulkhead rejection: the call never reached the dependency.\n if (classification === 'transient' && payload.type !== 'bulkhead-rejected') {\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,9 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkVHMSEPWD_cjs = require('./chunk-VHMSEPWD.cjs');
|
|
4
4
|
|
|
5
5
|
// src/retry/retry.fn.ts
|
|
6
|
-
var defaultRegistry = new
|
|
6
|
+
var defaultRegistry = new chunkVHMSEPWD_cjs.RetryRegistry();
|
|
7
7
|
async function retry(task, options) {
|
|
8
8
|
const engine = defaultRegistry.getOrCreate("__default__");
|
|
9
9
|
return engine.execute(task, options);
|
|
@@ -63,59 +63,59 @@ var BudgetExhaustedError = class extends Error {
|
|
|
63
63
|
|
|
64
64
|
Object.defineProperty(exports, "AttemptTimeoutError", {
|
|
65
65
|
enumerable: true,
|
|
66
|
-
get: function () { return
|
|
66
|
+
get: function () { return chunkVHMSEPWD_cjs.AttemptTimeoutError; }
|
|
67
67
|
});
|
|
68
68
|
Object.defineProperty(exports, "DefaultErrorClassifier", {
|
|
69
69
|
enumerable: true,
|
|
70
|
-
get: function () { return
|
|
70
|
+
get: function () { return chunkVHMSEPWD_cjs.DefaultErrorClassifier; }
|
|
71
71
|
});
|
|
72
72
|
Object.defineProperty(exports, "ExponentialBackoff", {
|
|
73
73
|
enumerable: true,
|
|
74
|
-
get: function () { return
|
|
74
|
+
get: function () { return chunkVHMSEPWD_cjs.ExponentialBackoff; }
|
|
75
75
|
});
|
|
76
76
|
Object.defineProperty(exports, "FixedBackoff", {
|
|
77
77
|
enumerable: true,
|
|
78
|
-
get: function () { return
|
|
78
|
+
get: function () { return chunkVHMSEPWD_cjs.FixedBackoff; }
|
|
79
79
|
});
|
|
80
80
|
Object.defineProperty(exports, "GlobalTimeoutError", {
|
|
81
81
|
enumerable: true,
|
|
82
|
-
get: function () { return
|
|
82
|
+
get: function () { return chunkVHMSEPWD_cjs.GlobalTimeoutError; }
|
|
83
83
|
});
|
|
84
84
|
Object.defineProperty(exports, "IdempotencyManager", {
|
|
85
85
|
enumerable: true,
|
|
86
|
-
get: function () { return
|
|
86
|
+
get: function () { return chunkVHMSEPWD_cjs.IdempotencyManager; }
|
|
87
87
|
});
|
|
88
88
|
Object.defineProperty(exports, "InMemoryIdempotencyStore", {
|
|
89
89
|
enumerable: true,
|
|
90
|
-
get: function () { return
|
|
90
|
+
get: function () { return chunkVHMSEPWD_cjs.InMemoryIdempotencyStore; }
|
|
91
91
|
});
|
|
92
92
|
Object.defineProperty(exports, "JitterDecorator", {
|
|
93
93
|
enumerable: true,
|
|
94
|
-
get: function () { return
|
|
94
|
+
get: function () { return chunkVHMSEPWD_cjs.JitterDecorator; }
|
|
95
95
|
});
|
|
96
96
|
Object.defineProperty(exports, "LinearBackoff", {
|
|
97
97
|
enumerable: true,
|
|
98
|
-
get: function () { return
|
|
98
|
+
get: function () { return chunkVHMSEPWD_cjs.LinearBackoff; }
|
|
99
99
|
});
|
|
100
100
|
Object.defineProperty(exports, "RetryEngine", {
|
|
101
101
|
enumerable: true,
|
|
102
|
-
get: function () { return
|
|
102
|
+
get: function () { return chunkVHMSEPWD_cjs.RetryEngine; }
|
|
103
103
|
});
|
|
104
104
|
Object.defineProperty(exports, "RetryRegistry", {
|
|
105
105
|
enumerable: true,
|
|
106
|
-
get: function () { return
|
|
106
|
+
get: function () { return chunkVHMSEPWD_cjs.RetryRegistry; }
|
|
107
107
|
});
|
|
108
108
|
Object.defineProperty(exports, "SlidingWindowBudgetImpl", {
|
|
109
109
|
enumerable: true,
|
|
110
|
-
get: function () { return
|
|
110
|
+
get: function () { return chunkVHMSEPWD_cjs.SlidingWindowBudgetImpl; }
|
|
111
111
|
});
|
|
112
112
|
Object.defineProperty(exports, "TimeoutManager", {
|
|
113
113
|
enumerable: true,
|
|
114
|
-
get: function () { return
|
|
114
|
+
get: function () { return chunkVHMSEPWD_cjs.TimeoutManager; }
|
|
115
115
|
});
|
|
116
116
|
Object.defineProperty(exports, "applyJitter", {
|
|
117
117
|
enumerable: true,
|
|
118
|
-
get: function () { return
|
|
118
|
+
get: function () { return chunkVHMSEPWD_cjs.applyJitter; }
|
|
119
119
|
});
|
|
120
120
|
exports.BudgetExhaustedError = BudgetExhaustedError;
|
|
121
121
|
exports.RetryExhaustedError = RetryExhaustedError;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
1
|
+
{"version":3,"sources":["../src/retry/retry.fn.ts","../src/conditions/http.conditions.ts","../src/retry/retry.errors.ts"],"names":["RetryRegistry"],"mappings":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G,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 * if (result.ok) res.json(result.value);\n * else res.status(502).json({ error: result.error.message });\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-C2SjDj64.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-C2SjDj64.cjs';
|
|
3
3
|
import { Result } from '@backendkit-labs/result';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -9,10 +9,8 @@ import { Result } from '@backendkit-labs/result';
|
|
|
9
9
|
* @example
|
|
10
10
|
* ```ts
|
|
11
11
|
* const result = await retry(() => fetchUser(id), { maxAttempts: 3 });
|
|
12
|
-
* result.
|
|
13
|
-
*
|
|
14
|
-
* (error) => res.status(502).json({ error: error.message }),
|
|
15
|
-
* );
|
|
12
|
+
* if (result.ok) res.json(result.value);
|
|
13
|
+
* else res.status(502).json({ error: result.error.message });
|
|
16
14
|
* ```
|
|
17
15
|
*/
|
|
18
16
|
declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
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-C2SjDj64.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-C2SjDj64.js';
|
|
3
3
|
import { Result } from '@backendkit-labs/result';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -9,10 +9,8 @@ import { Result } from '@backendkit-labs/result';
|
|
|
9
9
|
* @example
|
|
10
10
|
* ```ts
|
|
11
11
|
* const result = await retry(() => fetchUser(id), { maxAttempts: 3 });
|
|
12
|
-
* result.
|
|
13
|
-
*
|
|
14
|
-
* (error) => res.status(502).json({ error: error.message }),
|
|
15
|
-
* );
|
|
12
|
+
* if (result.ok) res.json(result.value);
|
|
13
|
+
* else res.status(502).json({ error: result.error.message });
|
|
16
14
|
* ```
|
|
17
15
|
*/
|
|
18
16
|
declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
|
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 } from './chunk-
|
|
1
|
+
import { RetryRegistry } from './chunk-ZZ6WRRGP.js';
|
|
2
|
+
export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter } from './chunk-ZZ6WRRGP.js';
|
|
3
3
|
|
|
4
4
|
// src/retry/retry.fn.ts
|
|
5
5
|
var defaultRegistry = new RetryRegistry();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AAa1C,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;;;ACjBO,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.js","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 * if (result.ok) res.json(result.value);\n * else res.status(502).json({ error: result.error.message });\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 chunkVHMSEPWD_cjs = require('../chunk-VHMSEPWD.cjs');
|
|
4
4
|
var common = require('@nestjs/common');
|
|
5
5
|
var core = require('@nestjs/core');
|
|
6
6
|
var rxjs = require('rxjs');
|
|
@@ -18,11 +18,11 @@ exports.RetryService = class RetryService {
|
|
|
18
18
|
return this.engine;
|
|
19
19
|
}
|
|
20
20
|
};
|
|
21
|
-
exports.RetryService =
|
|
21
|
+
exports.RetryService = chunkVHMSEPWD_cjs.__decorateClass([
|
|
22
22
|
common.Injectable()
|
|
23
23
|
], exports.RetryService);
|
|
24
24
|
var RETRY_METADATA_KEY = "retry:config";
|
|
25
|
-
var defaultRegistry = new
|
|
25
|
+
var defaultRegistry = new chunkVHMSEPWD_cjs.RetryRegistry();
|
|
26
26
|
function Retry(config) {
|
|
27
27
|
return function(target, propertyKey, descriptor) {
|
|
28
28
|
const originalMethod = descriptor.value;
|
|
@@ -71,10 +71,10 @@ exports.RetryInterceptor = class RetryInterceptor {
|
|
|
71
71
|
);
|
|
72
72
|
}
|
|
73
73
|
};
|
|
74
|
-
exports.RetryInterceptor =
|
|
74
|
+
exports.RetryInterceptor = chunkVHMSEPWD_cjs.__decorateClass([
|
|
75
75
|
common.Injectable(),
|
|
76
|
-
|
|
77
|
-
|
|
76
|
+
chunkVHMSEPWD_cjs.__decorateParam(0, common.Inject(exports.RetryService)),
|
|
77
|
+
chunkVHMSEPWD_cjs.__decorateParam(1, common.Inject(core.Reflector))
|
|
78
78
|
], exports.RetryInterceptor);
|
|
79
79
|
|
|
80
80
|
// src/nestjs/retry.constants.ts
|
|
@@ -88,7 +88,7 @@ exports.RetryModule = class RetryModule {
|
|
|
88
88
|
const providers = [
|
|
89
89
|
{
|
|
90
90
|
provide: RETRY_REGISTRY_TOKEN,
|
|
91
|
-
useFactory: () => new
|
|
91
|
+
useFactory: () => new chunkVHMSEPWD_cjs.RetryRegistry()
|
|
92
92
|
},
|
|
93
93
|
{
|
|
94
94
|
provide: RETRY_ENGINE_TOKEN,
|
|
@@ -114,7 +114,7 @@ exports.RetryModule = class RetryModule {
|
|
|
114
114
|
};
|
|
115
115
|
}
|
|
116
116
|
};
|
|
117
|
-
exports.RetryModule =
|
|
117
|
+
exports.RetryModule = chunkVHMSEPWD_cjs.__decorateClass([
|
|
118
118
|
common.Module({})
|
|
119
119
|
], exports.RetryModule);
|
|
120
120
|
|
package/dist/nestjs/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DynamicModule, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
|
|
2
|
-
import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-
|
|
2
|
+
import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-C2SjDj64.cjs';
|
|
3
3
|
import { Observable } from 'rxjs';
|
|
4
4
|
import { Reflector } from '@nestjs/core';
|
|
5
5
|
import { Result } from '@backendkit-labs/result';
|
package/dist/nestjs/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DynamicModule, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
|
|
2
|
-
import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-
|
|
2
|
+
import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-C2SjDj64.js';
|
|
3
3
|
import { Observable } from 'rxjs';
|
|
4
4
|
import { Reflector } from '@nestjs/core';
|
|
5
5
|
import { Result } from '@backendkit-labs/result';
|
package/dist/nestjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { __decorateClass, RetryRegistry, __decorateParam } from '../chunk-
|
|
1
|
+
import { __decorateClass, RetryRegistry, __decorateParam } from '../chunk-ZZ6WRRGP.js';
|
|
2
2
|
import { Injectable, Inject, Module, SetMetadata } from '@nestjs/common';
|
|
3
3
|
import { Reflector, APP_INTERCEPTOR } from '@nestjs/core';
|
|
4
4
|
import { from, Observable } from 'rxjs';
|
|
@@ -118,6 +118,7 @@ interface RetryMetadata {
|
|
|
118
118
|
totalElapsedMs: number;
|
|
119
119
|
lastError?: RetryErrorPayload;
|
|
120
120
|
budgetExhausted?: boolean;
|
|
121
|
+
/** @deprecated Never set. A circuit-open stop is reported as `error.type === 'circuit-open'`. */
|
|
121
122
|
circuitOpen?: boolean;
|
|
122
123
|
}
|
|
123
124
|
type RetryError = RetryErrorPayload & {
|
|
@@ -140,8 +141,8 @@ interface RetryConfig {
|
|
|
140
141
|
budget?: Partial<RetryBudgetConfig>;
|
|
141
142
|
idempotency?: Partial<IdempotencyConfig>;
|
|
142
143
|
classifiers?: ClassifierRule[];
|
|
143
|
-
/**
|
|
144
|
-
dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number;
|
|
144
|
+
/** Delay in ms before the next attempt. Return `undefined` to use the backoff strategy; `0` retries with no delay. */
|
|
145
|
+
dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number | undefined;
|
|
145
146
|
hooks?: RetryHooks;
|
|
146
147
|
/** Fallback value/function when retries exhausted. */
|
|
147
148
|
fallback?: (error: RetryErrorPayload) => unknown | Promise<unknown>;
|
|
@@ -169,14 +170,23 @@ interface CircuitBreakerLike {
|
|
|
169
170
|
onError(error: unknown): void;
|
|
170
171
|
getState(): unknown;
|
|
171
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* Satisfied by `Bulkhead` from `@backendkit-labs/bulkhead`. A rejection is
|
|
175
|
+
* recognised by the error's `name` (`BulkheadRejectedError` /
|
|
176
|
+
* `BulkheadTimeoutError`) and reported as `bulkhead-rejected`.
|
|
177
|
+
*/
|
|
172
178
|
interface BulkheadLike {
|
|
173
179
|
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
174
|
-
isFull(): boolean;
|
|
175
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Retry only calls `warn(msg, meta)` (one line per failed attempt); `console` satisfies it.
|
|
183
|
+
* `LoggerService` from `@backendkit-labs/observability` takes a context string as its second
|
|
184
|
+
* argument, so wrap it: `{ warn: (msg, meta) => loggerService.warn(`${msg} ${JSON.stringify(meta)}`, 'Retry') }`.
|
|
185
|
+
*/
|
|
176
186
|
interface BkLoggerLike {
|
|
177
|
-
info(msg: string, meta?: unknown): void;
|
|
178
187
|
warn(msg: string, meta?: unknown): void;
|
|
179
|
-
|
|
188
|
+
info?(msg: string, meta?: unknown): void;
|
|
189
|
+
error?(msg: string, meta?: unknown): void;
|
|
180
190
|
}
|
|
181
191
|
interface MetricsEmitterLike {
|
|
182
192
|
emit(event: MetricEvent): void;
|
|
@@ -118,6 +118,7 @@ interface RetryMetadata {
|
|
|
118
118
|
totalElapsedMs: number;
|
|
119
119
|
lastError?: RetryErrorPayload;
|
|
120
120
|
budgetExhausted?: boolean;
|
|
121
|
+
/** @deprecated Never set. A circuit-open stop is reported as `error.type === 'circuit-open'`. */
|
|
121
122
|
circuitOpen?: boolean;
|
|
122
123
|
}
|
|
123
124
|
type RetryError = RetryErrorPayload & {
|
|
@@ -140,8 +141,8 @@ interface RetryConfig {
|
|
|
140
141
|
budget?: Partial<RetryBudgetConfig>;
|
|
141
142
|
idempotency?: Partial<IdempotencyConfig>;
|
|
142
143
|
classifiers?: ClassifierRule[];
|
|
143
|
-
/**
|
|
144
|
-
dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number;
|
|
144
|
+
/** Delay in ms before the next attempt. Return `undefined` to use the backoff strategy; `0` retries with no delay. */
|
|
145
|
+
dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number | undefined;
|
|
145
146
|
hooks?: RetryHooks;
|
|
146
147
|
/** Fallback value/function when retries exhausted. */
|
|
147
148
|
fallback?: (error: RetryErrorPayload) => unknown | Promise<unknown>;
|
|
@@ -169,14 +170,23 @@ interface CircuitBreakerLike {
|
|
|
169
170
|
onError(error: unknown): void;
|
|
170
171
|
getState(): unknown;
|
|
171
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* Satisfied by `Bulkhead` from `@backendkit-labs/bulkhead`. A rejection is
|
|
175
|
+
* recognised by the error's `name` (`BulkheadRejectedError` /
|
|
176
|
+
* `BulkheadTimeoutError`) and reported as `bulkhead-rejected`.
|
|
177
|
+
*/
|
|
172
178
|
interface BulkheadLike {
|
|
173
179
|
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
174
|
-
isFull(): boolean;
|
|
175
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Retry only calls `warn(msg, meta)` (one line per failed attempt); `console` satisfies it.
|
|
183
|
+
* `LoggerService` from `@backendkit-labs/observability` takes a context string as its second
|
|
184
|
+
* argument, so wrap it: `{ warn: (msg, meta) => loggerService.warn(`${msg} ${JSON.stringify(meta)}`, 'Retry') }`.
|
|
185
|
+
*/
|
|
176
186
|
interface BkLoggerLike {
|
|
177
|
-
info(msg: string, meta?: unknown): void;
|
|
178
187
|
warn(msg: string, meta?: unknown): void;
|
|
179
|
-
|
|
188
|
+
info?(msg: string, meta?: unknown): void;
|
|
189
|
+
error?(msg: string, meta?: unknown): void;
|
|
180
190
|
}
|
|
181
191
|
interface MetricsEmitterLike {
|
|
182
192
|
emit(event: MetricEvent): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backendkit-labs/retry",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "BackendKit Labs",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"test": "vitest run",
|
|
35
35
|
"test:watch": "vitest",
|
|
36
36
|
"test:coverage": "vitest run --coverage",
|
|
37
|
-
"typecheck": "tsc --noEmit",
|
|
37
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
|
|
38
38
|
"lint": "eslint src/",
|
|
39
39
|
"format": "prettier --write src/",
|
|
40
40
|
"prepublishOnly": "npm run build && npm run test && npm run lint"
|
|
@@ -67,6 +67,9 @@
|
|
|
67
67
|
"engines": {
|
|
68
68
|
"node": ">=18"
|
|
69
69
|
},
|
|
70
|
+
"dependencies": {
|
|
71
|
+
"@backendkit-labs/result": "^0.2.1"
|
|
72
|
+
},
|
|
70
73
|
"peerDependencies": {
|
|
71
74
|
"@nestjs/common": ">=10.0.0",
|
|
72
75
|
"@nestjs/core": ">=10.0.0",
|
|
@@ -84,6 +87,8 @@
|
|
|
84
87
|
}
|
|
85
88
|
},
|
|
86
89
|
"devDependencies": {
|
|
90
|
+
"@backendkit-labs/bulkhead": "^0.2.1",
|
|
91
|
+
"@backendkit-labs/circuit-breaker": "^0.4.0",
|
|
87
92
|
"@eslint/js": "^9.39.4",
|
|
88
93
|
"@nestjs/common": "^10.0.0",
|
|
89
94
|
"@nestjs/core": "^10.0.0",
|