@backendkit-labs/retry 0.1.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/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ import { RetryRegistry } from './chunk-ZWXN4OXT.js';
2
+ export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter, defaultAbortCondition, defaultRetryCondition } from './chunk-ZWXN4OXT.js';
3
+
4
+ // src/retry/retry.fn.ts
5
+ var defaultRegistry = new RetryRegistry();
6
+ async function retry(task, options) {
7
+ const engine = defaultRegistry.getOrCreate("__default__");
8
+ return engine.execute(task, options);
9
+ }
10
+
11
+ // src/retry/retry.errors.ts
12
+ var RetryExhaustedError = class extends Error {
13
+ constructor(message, attempts, totalElapsedMs) {
14
+ super(message);
15
+ this.attempts = attempts;
16
+ this.totalElapsedMs = totalElapsedMs;
17
+ this.name = "RetryExhaustedError";
18
+ }
19
+ attempts;
20
+ totalElapsedMs;
21
+ };
22
+ var BudgetExhaustedError = class extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "BudgetExhaustedError";
26
+ }
27
+ };
28
+
29
+ export { BudgetExhaustedError, RetryExhaustedError, retry };
30
+ //# sourceMappingURL=index.js.map
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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;;;ACzBO,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 * 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: () => 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","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"]}
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ var chunkHOW7IDKS_cjs = require('../chunk-HOW7IDKS.cjs');
4
+ var common = require('@nestjs/common');
5
+ var core = require('@nestjs/core');
6
+ var rxjs = require('rxjs');
7
+ var operators = require('rxjs/operators');
8
+
9
+ exports.RetryService = class RetryService {
10
+ constructor(engine) {
11
+ this.engine = engine;
12
+ }
13
+ engine;
14
+ async execute(task, options) {
15
+ return this.engine.execute(task, options);
16
+ }
17
+ getEngine() {
18
+ return this.engine;
19
+ }
20
+ };
21
+ exports.RetryService = chunkHOW7IDKS_cjs.__decorateClass([
22
+ common.Injectable()
23
+ ], exports.RetryService);
24
+ var RETRY_METADATA_KEY = "retry:config";
25
+ function Retry(config) {
26
+ return common.SetMetadata(RETRY_METADATA_KEY, config);
27
+ }
28
+
29
+ // src/nestjs/retry.interceptor.ts
30
+ exports.RetryInterceptor = class RetryInterceptor {
31
+ constructor(RetryService2, reflector) {
32
+ this.RetryService = RetryService2;
33
+ this.reflector = reflector;
34
+ }
35
+ RetryService;
36
+ reflector;
37
+ intercept(context, next) {
38
+ const RetryConfig = this.reflector.get(
39
+ RETRY_METADATA_KEY,
40
+ context.getHandler()
41
+ );
42
+ if (!RetryConfig) {
43
+ return next.handle();
44
+ }
45
+ return rxjs.from(
46
+ this.RetryService.execute(() => next.handle().toPromise(), RetryConfig)
47
+ ).pipe(
48
+ operators.switchMap((result) => {
49
+ if (result.ok) {
50
+ const value = result.value;
51
+ if (value instanceof rxjs.Observable) return value;
52
+ return rxjs.from(Promise.resolve(value));
53
+ }
54
+ throw result.error;
55
+ })
56
+ );
57
+ }
58
+ };
59
+ exports.RetryInterceptor = chunkHOW7IDKS_cjs.__decorateClass([
60
+ common.Injectable()
61
+ ], exports.RetryInterceptor);
62
+
63
+ // src/nestjs/retry.constants.ts
64
+ var RETRY_ENGINE_TOKEN = /* @__PURE__ */ Symbol("RETRY_ENGINE_TOKEN");
65
+ var RETRY_REGISTRY_TOKEN = /* @__PURE__ */ Symbol("RETRY_REGISTRY_TOKEN");
66
+
67
+ // src/nestjs/retry.module.ts
68
+ exports.RetryModule = class RetryModule {
69
+ static forRoot(options) {
70
+ const engineConfig = options?.engineConfig ?? { name: "default" };
71
+ const providers = [
72
+ {
73
+ provide: RETRY_REGISTRY_TOKEN,
74
+ useFactory: () => new chunkHOW7IDKS_cjs.RetryRegistry()
75
+ },
76
+ {
77
+ provide: RETRY_ENGINE_TOKEN,
78
+ useFactory: (registry) => registry.getOrCreate(engineConfig.name ?? "default", engineConfig),
79
+ inject: [RETRY_REGISTRY_TOKEN]
80
+ },
81
+ {
82
+ provide: exports.RetryService,
83
+ useFactory: (engine) => new exports.RetryService(engine),
84
+ inject: [RETRY_ENGINE_TOKEN]
85
+ }
86
+ ];
87
+ if (options?.globalInterceptor !== false) {
88
+ providers.push({
89
+ provide: core.APP_INTERCEPTOR,
90
+ useClass: exports.RetryInterceptor
91
+ });
92
+ }
93
+ return {
94
+ module: exports.RetryModule,
95
+ providers,
96
+ exports: [exports.RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN]
97
+ };
98
+ }
99
+ };
100
+ exports.RetryModule = chunkHOW7IDKS_cjs.__decorateClass([
101
+ common.Module({})
102
+ ], exports.RetryModule);
103
+
104
+ exports.RETRY_ENGINE_TOKEN = RETRY_ENGINE_TOKEN;
105
+ exports.RETRY_REGISTRY_TOKEN = RETRY_REGISTRY_TOKEN;
106
+ exports.Retry = Retry;
107
+ //# sourceMappingURL=index.cjs.map
108
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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","RetryInterceptor","from","switchMap","Observable","RetryModule","RetryRegistry","APP_INTERCEPTOR","Module"],"mappings":";;;;;;;;AAMaA,uBAAN,kBAAA,CAAmB;AAAA,EACxB,YAAoB,MAAA,EAAqB;AAArB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,E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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"]}
@@ -0,0 +1,43 @@
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-DSm8xWKJ.cjs';
3
+ import { Observable } from 'rxjs';
4
+ import { Reflector } from '@nestjs/core';
5
+ import { Result } from '@backendkit-labs/result';
6
+
7
+ interface RetryModuleOptions {
8
+ engineConfig?: Partial<RetryEngineConfig>;
9
+ globalInterceptor?: boolean;
10
+ }
11
+ declare class RetryModule {
12
+ static forRoot(options?: RetryModuleOptions): DynamicModule;
13
+ }
14
+
15
+ /**
16
+ * Decorator that marks a method for retry.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })
21
+ * async fetchData() { ... }
22
+ * ```
23
+ */
24
+ declare function Retry(config: Partial<RetryConfig>): MethodDecorator;
25
+
26
+ declare class RetryService {
27
+ private engine;
28
+ constructor(engine: RetryEngine);
29
+ execute<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
30
+ getEngine(): RetryEngine;
31
+ }
32
+
33
+ declare class RetryInterceptor implements NestInterceptor {
34
+ private readonly RetryService;
35
+ private readonly reflector;
36
+ constructor(RetryService: RetryService, reflector: Reflector);
37
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
38
+ }
39
+
40
+ declare const RETRY_ENGINE_TOKEN: unique symbol;
41
+ declare const RETRY_REGISTRY_TOKEN: unique symbol;
42
+
43
+ export { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN, Retry, RetryInterceptor, RetryModule, RetryService };
@@ -0,0 +1,43 @@
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-DSm8xWKJ.js';
3
+ import { Observable } from 'rxjs';
4
+ import { Reflector } from '@nestjs/core';
5
+ import { Result } from '@backendkit-labs/result';
6
+
7
+ interface RetryModuleOptions {
8
+ engineConfig?: Partial<RetryEngineConfig>;
9
+ globalInterceptor?: boolean;
10
+ }
11
+ declare class RetryModule {
12
+ static forRoot(options?: RetryModuleOptions): DynamicModule;
13
+ }
14
+
15
+ /**
16
+ * Decorator that marks a method for retry.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })
21
+ * async fetchData() { ... }
22
+ * ```
23
+ */
24
+ declare function Retry(config: Partial<RetryConfig>): MethodDecorator;
25
+
26
+ declare class RetryService {
27
+ private engine;
28
+ constructor(engine: RetryEngine);
29
+ execute<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
30
+ getEngine(): RetryEngine;
31
+ }
32
+
33
+ declare class RetryInterceptor implements NestInterceptor {
34
+ private readonly RetryService;
35
+ private readonly reflector;
36
+ constructor(RetryService: RetryService, reflector: Reflector);
37
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
38
+ }
39
+
40
+ declare const RETRY_ENGINE_TOKEN: unique symbol;
41
+ declare const RETRY_REGISTRY_TOKEN: unique symbol;
42
+
43
+ export { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN, Retry, RetryInterceptor, RetryModule, RetryService };
@@ -0,0 +1,104 @@
1
+ import { __decorateClass, RetryRegistry } from '../chunk-ZWXN4OXT.js';
2
+ import { Injectable, Module, SetMetadata } from '@nestjs/common';
3
+ import { APP_INTERCEPTOR } from '@nestjs/core';
4
+ import { from, Observable } from 'rxjs';
5
+ import { switchMap } from 'rxjs/operators';
6
+
7
+ var RetryService = class {
8
+ constructor(engine) {
9
+ this.engine = engine;
10
+ }
11
+ engine;
12
+ async execute(task, options) {
13
+ return this.engine.execute(task, options);
14
+ }
15
+ getEngine() {
16
+ return this.engine;
17
+ }
18
+ };
19
+ RetryService = __decorateClass([
20
+ Injectable()
21
+ ], RetryService);
22
+ var RETRY_METADATA_KEY = "retry:config";
23
+ function Retry(config) {
24
+ return SetMetadata(RETRY_METADATA_KEY, config);
25
+ }
26
+
27
+ // src/nestjs/retry.interceptor.ts
28
+ var RetryInterceptor = class {
29
+ constructor(RetryService2, reflector) {
30
+ this.RetryService = RetryService2;
31
+ this.reflector = reflector;
32
+ }
33
+ RetryService;
34
+ reflector;
35
+ intercept(context, next) {
36
+ const RetryConfig = this.reflector.get(
37
+ RETRY_METADATA_KEY,
38
+ context.getHandler()
39
+ );
40
+ if (!RetryConfig) {
41
+ return next.handle();
42
+ }
43
+ return from(
44
+ this.RetryService.execute(() => next.handle().toPromise(), RetryConfig)
45
+ ).pipe(
46
+ switchMap((result) => {
47
+ if (result.ok) {
48
+ const value = result.value;
49
+ if (value instanceof Observable) return value;
50
+ return from(Promise.resolve(value));
51
+ }
52
+ throw result.error;
53
+ })
54
+ );
55
+ }
56
+ };
57
+ RetryInterceptor = __decorateClass([
58
+ Injectable()
59
+ ], RetryInterceptor);
60
+
61
+ // src/nestjs/retry.constants.ts
62
+ var RETRY_ENGINE_TOKEN = /* @__PURE__ */ Symbol("RETRY_ENGINE_TOKEN");
63
+ var RETRY_REGISTRY_TOKEN = /* @__PURE__ */ Symbol("RETRY_REGISTRY_TOKEN");
64
+
65
+ // src/nestjs/retry.module.ts
66
+ var RetryModule = class {
67
+ static forRoot(options) {
68
+ const engineConfig = options?.engineConfig ?? { name: "default" };
69
+ const providers = [
70
+ {
71
+ provide: RETRY_REGISTRY_TOKEN,
72
+ useFactory: () => new RetryRegistry()
73
+ },
74
+ {
75
+ provide: RETRY_ENGINE_TOKEN,
76
+ useFactory: (registry) => registry.getOrCreate(engineConfig.name ?? "default", engineConfig),
77
+ inject: [RETRY_REGISTRY_TOKEN]
78
+ },
79
+ {
80
+ provide: RetryService,
81
+ useFactory: (engine) => new RetryService(engine),
82
+ inject: [RETRY_ENGINE_TOKEN]
83
+ }
84
+ ];
85
+ if (options?.globalInterceptor !== false) {
86
+ providers.push({
87
+ provide: APP_INTERCEPTOR,
88
+ useClass: RetryInterceptor
89
+ });
90
+ }
91
+ return {
92
+ module: RetryModule,
93
+ providers,
94
+ exports: [RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN]
95
+ };
96
+ }
97
+ };
98
+ RetryModule = __decorateClass([
99
+ Module({})
100
+ ], RetryModule);
101
+
102
+ export { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN, Retry, RetryInterceptor, RetryModule, RetryService };
103
+ //# sourceMappingURL=index.js.map
104
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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","Injectable"],"mappings":";;;;;;AAMO,IAAM,eAAN,MAAmB;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;AAba,YAAA,GAAN,eAAA,CAAA;AAAA,EADN,UAAA;AAAW,CAAA,EACC,YAAA,CAAA;ACHN,IAAM,kBAAA,GAAqB,cAAA;AAW3B,SAAS,MAAM,MAAA,EAA+C;AACnE,EAAA,OAAO,WAAA,CAAY,oBAAoB,MAAM,CAAA;AAC/C;;;ACFO,IAAM,mBAAN,MAAkD;AAAA,EACvD,WAAA,CACmBA,eACA,SAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,YAAA,GAAAA,aAAAA;AACA,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAChB;AAAA,EAFgB,YAAA;A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CAAC,QAAA,KACX,QAAA,CAAS,YAAY,YAAA,CAAa,IAAA,IAAQ,WAAW,YAAY,CAAA;AAAA,QACnE,MAAA,EAAQ,CAAC,oBAAoB;AAAA,OAC/B;AAAA,MACA;AAAA,QACE,OAAA,EAAS,YAAA;AAAA,QACT,UAAA,EAAY,CAAC,MAAA,KAAwB,IAAI,aAAa,MAAM,CAAA;AAAA,QAC5D,MAAA,EAAQ,CAAC,kBAAkB;AAAA;AAC7B,KACF;AAEA,IAAA,IAAI,OAAA,EAAS,sBAAsB,KAAA,EAAO;AACxC,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,OAAA,EAAS,eAAA;AAAA,QACT,QAAA,EAAU;AAAA,OACX,CAAA;AAAA,IACH;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,WAAA;AAAA,MACR,SAAA;AAAA,MACA,OAAA,EAAS,CAAC,YAAA,EAAc,kBAAA,EAAoB,oBAAoB;AAAA,KAClE;AAAA,EACF;AACF;AAnCa,WAAA,GAAN,eAAA,CAAA;AAAA,EADN,MAAA,CAAO,EAAE;AAAA,CAAA,EACG,WAAA,CAAA","file":"index.js","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"]}
@@ -0,0 +1,202 @@
1
+ import { Result } from '@backendkit-labs/result';
2
+
3
+ declare class RetryRegistry {
4
+ private readonly engines;
5
+ getOrCreate(name: string, config?: Partial<RetryEngineConfig>): RetryEngine;
6
+ get(name: string): RetryEngine | undefined;
7
+ reset(name: string): void;
8
+ resetAll(): void;
9
+ getAllMetrics(): Record<string, RetryMetricsSnapshot>;
10
+ }
11
+
12
+ type JitterType = 'full' | 'equal' | 'decorrelated';
13
+ interface BackoffStrategy {
14
+ /** Compute delay in ms for attempt number (1-based). */
15
+ nextDelay(attempt: number): number;
16
+ /** Reset internal state (for stateful strategies like decorrelated jitter). */
17
+ reset(): void;
18
+ /** Deep clone with optional overrides. */
19
+ clone(overrides?: Partial<BackoffConfig>): BackoffStrategy;
20
+ }
21
+ type BackoffConfig = {
22
+ type: 'fixed';
23
+ baseDelay: number;
24
+ } | {
25
+ type: 'linear';
26
+ baseDelay: number;
27
+ multiplier?: number;
28
+ maxDelay?: number;
29
+ } | {
30
+ type: 'exponential';
31
+ baseDelay: number;
32
+ multiplier?: number;
33
+ maxDelay?: number;
34
+ jitter?: JitterType;
35
+ };
36
+ interface RetryCondition {
37
+ shouldRetry(error: RetryErrorPayload): boolean | Promise<boolean>;
38
+ }
39
+ interface AbortCondition {
40
+ shouldAbort(error: RetryErrorPayload): boolean | Promise<boolean>;
41
+ }
42
+ type RetryConditionFn = (error: RetryErrorPayload) => boolean | Promise<boolean>;
43
+ type AbortConditionFn = (error: RetryErrorPayload) => boolean | Promise<boolean>;
44
+ interface ClassifierRule {
45
+ name: string;
46
+ priority?: number;
47
+ match: (error: RetryErrorPayload) => boolean;
48
+ classification: ErrorClassification;
49
+ }
50
+ type ErrorClassification = 'transient' | 'permanent';
51
+ interface RetryBudgetConfig {
52
+ windowMs: number;
53
+ maxRetryRatio: number;
54
+ minRequestCount: number;
55
+ }
56
+ interface TimeoutConfig {
57
+ globalTimeoutMs: number;
58
+ attemptTimeoutMs: number;
59
+ }
60
+ interface IdempotencyStore {
61
+ get(key: string): Promise<string | null>;
62
+ set(key: string, value: string, ttlMs?: number): Promise<void>;
63
+ exists(key: string): Promise<boolean>;
64
+ }
65
+ interface IdempotencyConfig {
66
+ enabled: boolean;
67
+ store?: IdempotencyStore;
68
+ idempotentMethods: string[];
69
+ headerName: string;
70
+ ttlMs: number;
71
+ }
72
+ interface RetryHooks {
73
+ beforeRetry?: (ctx: BeforeRetryContext) => void | Promise<void>;
74
+ afterRetry?: (ctx: AfterRetryContext) => void | Promise<void>;
75
+ onRetrySuccess?: (ctx: RetrySuccessContext) => void | Promise<void>;
76
+ onExhausted?: (ctx: ExhaustedContext) => void | Promise<void>;
77
+ onBudgetExhausted?: (ctx: BudgetExhaustedContext) => void | Promise<void>;
78
+ }
79
+ interface BeforeRetryContext {
80
+ attempt: number;
81
+ error: RetryErrorPayload;
82
+ delayMs: number;
83
+ correlationId?: string;
84
+ }
85
+ interface AfterRetryContext {
86
+ attempt: number;
87
+ error: RetryErrorPayload;
88
+ delayMs: number;
89
+ correlationId?: string;
90
+ }
91
+ interface RetrySuccessContext {
92
+ attempt: number;
93
+ totalAttempts: number;
94
+ totalElapsedMs: number;
95
+ correlationId?: string;
96
+ }
97
+ interface ExhaustedContext {
98
+ lastError: RetryErrorPayload;
99
+ totalAttempts: number;
100
+ totalElapsedMs: number;
101
+ correlationId?: string;
102
+ }
103
+ interface BudgetExhaustedContext {
104
+ correlationId?: string;
105
+ }
106
+ interface RetryErrorPayload {
107
+ type: ErrorType;
108
+ message: string;
109
+ status?: number;
110
+ cause?: unknown;
111
+ attempt: number;
112
+ elapsedMs: number;
113
+ }
114
+ type ErrorType = 'http' | 'network' | 'timeout' | 'circuit-open' | 'bulkhead-rejected' | 'business' | 'unknown';
115
+ interface RetryMetadata {
116
+ attempts: number;
117
+ totalElapsedMs: number;
118
+ lastError?: RetryErrorPayload;
119
+ budgetExhausted?: boolean;
120
+ circuitOpen?: boolean;
121
+ }
122
+ type RetryError = RetryErrorPayload & {
123
+ metadata: RetryMetadata;
124
+ };
125
+ interface RetryMetricsSnapshot {
126
+ totalAttempts: number;
127
+ totalSuccesses: number;
128
+ totalFailures: number;
129
+ totalExhausted: number;
130
+ totalBudgetExhausted: number;
131
+ totalTimeouts: number;
132
+ }
133
+ interface RetryConfig {
134
+ maxAttempts: number;
135
+ backoff: BackoffConfig | BackoffStrategy;
136
+ retryIf?: RetryCondition | RetryConditionFn;
137
+ abortIf?: AbortCondition | AbortConditionFn;
138
+ timeout?: Partial<TimeoutConfig>;
139
+ budget?: Partial<RetryBudgetConfig>;
140
+ idempotency?: Partial<IdempotencyConfig>;
141
+ classifiers?: ClassifierRule[];
142
+ /** Dynamic delay based on error (overrides backoff). */
143
+ dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number;
144
+ hooks?: RetryHooks;
145
+ /** Fallback value/function when retries exhausted. */
146
+ fallback?: (error: RetryErrorPayload) => unknown | Promise<unknown>;
147
+ correlationId?: string;
148
+ }
149
+ interface RetryEngineConfig {
150
+ name: string;
151
+ /** Reference to registry (optional, for shared config across services). */
152
+ registry?: RetryRegistry;
153
+ /** Default config applied to all execute() calls. */
154
+ defaultConfig?: Partial<RetryConfig>;
155
+ /** External integrations (optional -- duck-typed at runtime). */
156
+ integrations?: {
157
+ circuitBreaker?: CircuitBreakerLike;
158
+ bulkhead?: BulkheadLike;
159
+ observability?: {
160
+ logger?: BkLoggerLike;
161
+ metrics?: MetricsEmitterLike;
162
+ };
163
+ };
164
+ }
165
+ interface CircuitBreakerLike {
166
+ canAttempt(): boolean;
167
+ onSuccess(durationMs: number): void;
168
+ onError(error: unknown): void;
169
+ getState(): unknown;
170
+ }
171
+ interface BulkheadLike {
172
+ execute<T>(fn: () => Promise<T>): Promise<T>;
173
+ isFull(): boolean;
174
+ }
175
+ interface BkLoggerLike {
176
+ info(msg: string, meta?: unknown): void;
177
+ warn(msg: string, meta?: unknown): void;
178
+ error(msg: string, meta?: unknown): void;
179
+ }
180
+ interface MetricsEmitterLike {
181
+ emit(event: MetricEvent): void;
182
+ }
183
+ interface MetricEvent {
184
+ name: string;
185
+ value: number;
186
+ tags?: Record<string, string | number>;
187
+ }
188
+
189
+ declare class RetryEngine {
190
+ private config;
191
+ private metrics;
192
+ constructor(config: RetryEngineConfig);
193
+ execute<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
194
+ executeWithContext<T>(task: () => Promise<T>, context: {
195
+ correlationId?: string;
196
+ }, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
197
+ updateDefaults(partial: Partial<RetryConfig>): void;
198
+ getMetrics(): RetryMetricsSnapshot;
199
+ resetMetrics(): void;
200
+ }
201
+
202
+ export { type AbortCondition as A, type BackoffStrategy as B, type ClassifierRule as C, type ErrorClassification as E, type IdempotencyConfig as I, type JitterType as J, type MetricEvent as M, type RetryConfig as R, type TimeoutConfig as T, type RetryError as a, type BackoffConfig as b, type RetryCondition as c, type RetryErrorPayload as d, type RetryBudgetConfig as e, type IdempotencyStore as f, type AbortConditionFn as g, type AfterRetryContext as h, type BeforeRetryContext as i, type BkLoggerLike as j, type BudgetExhaustedContext as k, type BulkheadLike as l, type CircuitBreakerLike as m, type ErrorType as n, type ExhaustedContext as o, type MetricsEmitterLike as p, type RetryConditionFn as q, RetryEngine as r, type RetryEngineConfig as s, type RetryHooks as t, type RetryMetadata as u, type RetryMetricsSnapshot as v, RetryRegistry as w, type RetrySuccessContext as x };