@nathapp/nestjs-idempotency 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +8 -0
- package/.nax/features/nestjs-idempotency/.nax-acceptance.test.ts +766 -0
- package/.nax/features/nestjs-idempotency/.nax-suggested.test.ts +439 -0
- package/.nax/test-debug.ts +22 -0
- package/.turbo/turbo-build.log +4 -0
- package/CHANGELOG.md +15 -0
- package/README.md +54 -0
- package/dist/constant/idempotency.constants.d.ts +8 -0
- package/dist/constant/idempotency.constants.js +12 -0
- package/dist/constant/idempotency.constants.js.map +1 -0
- package/dist/constant/index.d.ts +1 -0
- package/dist/constant/index.js +18 -0
- package/dist/constant/index.js.map +1 -0
- package/dist/decorator/idempotent.decorator.d.ts +1 -0
- package/dist/decorator/idempotent.decorator.js +8 -0
- package/dist/decorator/idempotent.decorator.js.map +1 -0
- package/dist/exception/idempotency-exception-code.enum.d.ts +5 -0
- package/dist/exception/idempotency-exception-code.enum.js +10 -0
- package/dist/exception/idempotency-exception-code.enum.js.map +1 -0
- package/dist/exception/idempotency.exceptions.d.ts +7 -0
- package/dist/exception/idempotency.exceptions.js +19 -0
- package/dist/exception/idempotency.exceptions.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -0
- package/dist/interceptor/idempotency.interceptor.d.ts +16 -0
- package/dist/interceptor/idempotency.interceptor.js +127 -0
- package/dist/interceptor/idempotency.interceptor.js.map +1 -0
- package/dist/interface/idempotency-module-options.interface.d.ts +10 -0
- package/dist/interface/idempotency-module-options.interface.js +3 -0
- package/dist/interface/idempotency-module-options.interface.js.map +1 -0
- package/dist/interface/idempotency-record.interface.d.ts +12 -0
- package/dist/interface/idempotency-record.interface.js +3 -0
- package/dist/interface/idempotency-record.interface.js.map +1 -0
- package/dist/interface/idempotency-store.interface.d.ts +7 -0
- package/dist/interface/idempotency-store.interface.js +3 -0
- package/dist/interface/idempotency-store.interface.js.map +1 -0
- package/dist/module/idempotency.module.d.ts +10 -0
- package/dist/module/idempotency.module.js +61 -0
- package/dist/module/idempotency.module.js.map +1 -0
- package/dist/provider/default-principal-extractor.d.ts +2 -0
- package/dist/provider/default-principal-extractor.js +11 -0
- package/dist/provider/default-principal-extractor.js.map +1 -0
- package/dist/provider/fingerprint.d.ts +1 -0
- package/dist/provider/fingerprint.js +19 -0
- package/dist/provider/fingerprint.js.map +1 -0
- package/dist/provider/in-memory-idempotency-store.d.ts +15 -0
- package/dist/provider/in-memory-idempotency-store.js +48 -0
- package/dist/provider/in-memory-idempotency-store.js.map +1 -0
- package/dist/provider/resolve-idempotency-options.d.ts +13 -0
- package/dist/provider/resolve-idempotency-options.js +18 -0
- package/dist/provider/resolve-idempotency-options.js.map +1 -0
- package/lib/constant/idempotency.constants.ts +8 -0
- package/lib/constant/index.ts +1 -0
- package/lib/decorator/idempotent.decorator.ts +4 -0
- package/lib/exception/idempotency-exception-code.enum.ts +5 -0
- package/lib/exception/idempotency.exceptions.ts +15 -0
- package/lib/index.ts +13 -0
- package/lib/interceptor/idempotency.interceptor.ts +187 -0
- package/lib/interface/idempotency-module-options.interface.ts +21 -0
- package/lib/interface/idempotency-record.interface.ts +14 -0
- package/lib/interface/idempotency-store.interface.ts +8 -0
- package/lib/module/idempotency.module.ts +61 -0
- package/lib/provider/default-principal-extractor.ts +17 -0
- package/lib/provider/fingerprint.ts +17 -0
- package/lib/provider/in-memory-idempotency-store.ts +53 -0
- package/lib/provider/resolve-idempotency-options.ts +32 -0
- package/package.json +54 -0
- package/test/barrel/index.spec.ts +40 -0
- package/test/constant/idempotency.constants.spec.ts +10 -0
- package/test/decorator/idempotent.decorator.spec.ts +20 -0
- package/test/e2e/express.e2e.spec.ts +219 -0
- package/test/e2e/fastify.e2e.spec.ts +64 -0
- package/test/exception/idempotency.exceptions.spec.ts +24 -0
- package/test/interceptor/idempotency.interceptor.spec.ts +739 -0
- package/test/jest-nax-setup-test.js +21 -0
- package/test/jest-nax-setup.js +92 -0
- package/test/jest-nax.json +30 -0
- package/test/jest-test.json +28 -0
- package/test/module/idempotency.module.spec.ts +87 -0
- package/test/provider/fingerprint.spec.ts +27 -0
- package/test/provider/in-memory-idempotency-store.spec.ts +212 -0
- package/test/provider/resolve-idempotency-options.spec.ts +42 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
import { describe, expect, it, beforeAll, afterAll, jest } from '@jest/globals';
|
|
2
|
+
import { lastValueFrom, of, throwError } from 'rxjs';
|
|
3
|
+
import {
|
|
4
|
+
Controller,
|
|
5
|
+
Post,
|
|
6
|
+
Body,
|
|
7
|
+
INestApplication,
|
|
8
|
+
APP_INTERCEPTOR,
|
|
9
|
+
HttpStatus,
|
|
10
|
+
} from '@nestjs/common';
|
|
11
|
+
import { Test } from '@nestjs/testing';
|
|
12
|
+
import { Reflector, HttpAdapterHost } from '@nestjs/core';
|
|
13
|
+
import { CallHandler, ExecutionContext } from '@nestjs/common';
|
|
14
|
+
import { createHash } from 'crypto';
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
computeFingerprint,
|
|
18
|
+
resolveIdempotencyOptions,
|
|
19
|
+
InMemoryIdempotencyStore,
|
|
20
|
+
Idempotent,
|
|
21
|
+
IdempotencyModule,
|
|
22
|
+
IdempotencyInterceptor,
|
|
23
|
+
IdempotencyExceptionCode,
|
|
24
|
+
} from '../../../lib';
|
|
25
|
+
|
|
26
|
+
// ─── Shared test helpers ──────────────────────────────────────────────────────
|
|
27
|
+
|
|
28
|
+
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex');
|
|
29
|
+
|
|
30
|
+
const makeIdempotentReflector = (hasMetadata: boolean): Reflector =>
|
|
31
|
+
({ get: jest.fn().mockReturnValue(hasMetadata ? true : undefined) }) as unknown as Reflector;
|
|
32
|
+
|
|
33
|
+
const makeNext = (body: unknown, isError = false): CallHandler => ({
|
|
34
|
+
handle: jest.fn().mockReturnValue(isError ? throwError(() => body) : of(body)),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const makeContext = (opts: {
|
|
38
|
+
method?: string;
|
|
39
|
+
path?: string;
|
|
40
|
+
headers?: Record<string, string>;
|
|
41
|
+
body?: unknown;
|
|
42
|
+
statusCode?: number;
|
|
43
|
+
responseHeaders?: Record<string, string>;
|
|
44
|
+
handler?: object;
|
|
45
|
+
} = {}): ExecutionContext => {
|
|
46
|
+
const statusContainer = { statusCode: opts.statusCode ?? 200 };
|
|
47
|
+
const request = {
|
|
48
|
+
method: opts.method ?? 'POST',
|
|
49
|
+
path: opts.path ?? '/users',
|
|
50
|
+
url: opts.path ?? '/users',
|
|
51
|
+
headers: opts.headers ?? { 'idempotency-key': 'test-key-123' },
|
|
52
|
+
body: opts.body ?? { a: 1 },
|
|
53
|
+
};
|
|
54
|
+
const response = {
|
|
55
|
+
get statusCode() { return statusContainer.statusCode; },
|
|
56
|
+
set statusCode(v: number) { statusContainer.statusCode = v; },
|
|
57
|
+
getHeaders: () => opts.responseHeaders ?? { 'content-type': 'application/json' },
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
getHandler: () => opts.handler ?? {},
|
|
61
|
+
switchToHttp: () => ({ getRequest: () => request, getResponse: () => response }),
|
|
62
|
+
} as unknown as ExecutionContext;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const makeStoreMock = (putResult: any = undefined) => ({
|
|
66
|
+
putIfAbsent: jest.fn().mockResolvedValue(putResult),
|
|
67
|
+
complete: jest.fn().mockResolvedValue(undefined),
|
|
68
|
+
remove: jest.fn().mockResolvedValue(undefined),
|
|
69
|
+
get: jest.fn().mockResolvedValue(undefined),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const makeHttpAdapterComponents = () => {
|
|
73
|
+
const httpAdapter = { reply: jest.fn(), setHeader: jest.fn() };
|
|
74
|
+
const host = { httpAdapter } as unknown as HttpAdapterHost;
|
|
75
|
+
return { httpAdapter, host };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const defaultOptions = {
|
|
79
|
+
headerName: 'Idempotency-Key',
|
|
80
|
+
ttlMs: 86_400_000,
|
|
81
|
+
requireKey: false,
|
|
82
|
+
replayHeaders: ['content-type'],
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const buildInterceptor = (opts: {
|
|
86
|
+
hasMetadata?: boolean;
|
|
87
|
+
store?: ReturnType<typeof makeStoreMock>;
|
|
88
|
+
requireKey?: boolean;
|
|
89
|
+
replayHeaders?: string[];
|
|
90
|
+
httpAdapterHost?: HttpAdapterHost;
|
|
91
|
+
} = {}) => {
|
|
92
|
+
const reflector = makeIdempotentReflector(opts.hasMetadata ?? true);
|
|
93
|
+
const store = opts.store ?? makeStoreMock();
|
|
94
|
+
const { host } = makeHttpAdapterComponents();
|
|
95
|
+
const adapterHost = opts.httpAdapterHost ?? host;
|
|
96
|
+
const options = {
|
|
97
|
+
...defaultOptions,
|
|
98
|
+
requireKey: opts.requireKey ?? false,
|
|
99
|
+
replayHeaders: opts.replayHeaders ?? defaultOptions.replayHeaders,
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
interceptor: new IdempotencyInterceptor(reflector, store as any, adapterHost, options),
|
|
103
|
+
store,
|
|
104
|
+
adapterHost,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const runIntercept = async (
|
|
109
|
+
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
110
|
+
context: ExecutionContext,
|
|
111
|
+
next: CallHandler,
|
|
112
|
+
): Promise<unknown> => {
|
|
113
|
+
let obs: any;
|
|
114
|
+
try {
|
|
115
|
+
obs = interceptor.intercept(context, next);
|
|
116
|
+
} catch (err) {
|
|
117
|
+
throw err;
|
|
118
|
+
}
|
|
119
|
+
if (obs && typeof obs.subscribe === 'function') {
|
|
120
|
+
return lastValueFrom(obs, { defaultValue: undefined });
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const captureInterceptError = async (
|
|
126
|
+
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
127
|
+
context: ExecutionContext,
|
|
128
|
+
next: CallHandler,
|
|
129
|
+
): Promise<any> => {
|
|
130
|
+
try {
|
|
131
|
+
await runIntercept(interceptor, context, next);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return err;
|
|
134
|
+
}
|
|
135
|
+
throw new Error('Expected interceptor to throw but it did not');
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// ─── Integration controllers ──────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
let _requireKeyHandlerCount = 0;
|
|
141
|
+
|
|
142
|
+
@Controller()
|
|
143
|
+
class RequireKeyTestController {
|
|
144
|
+
@Post('test')
|
|
145
|
+
@Idempotent()
|
|
146
|
+
handle(@Body() _body: unknown) {
|
|
147
|
+
_requireKeyHandlerCount++;
|
|
148
|
+
return { ok: true };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let _replayHeaderHandlerCount = 0;
|
|
153
|
+
|
|
154
|
+
@Controller()
|
|
155
|
+
class ReplayHeaderTestController {
|
|
156
|
+
@Post('test')
|
|
157
|
+
@Idempotent()
|
|
158
|
+
handle(@Body() _body: unknown) {
|
|
159
|
+
_replayHeaderHandlerCount++;
|
|
160
|
+
return { ok: true };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
165
|
+
// Acceptance Criteria
|
|
166
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
167
|
+
|
|
168
|
+
describe('nestjs-idempotency acceptance criteria', () => {
|
|
169
|
+
|
|
170
|
+
// ── AC-1 ────────────────────────────────────────────────────────────────────
|
|
171
|
+
it('AC-1: computeFingerprint returns same 64-char hex digest for structurally equivalent nested objects with different key orders', () => {
|
|
172
|
+
const A = { nested1: { z: 1, y: 2 }, nested2: { w: 3, v: 4 } };
|
|
173
|
+
const B = { nested2: { v: 4, w: 3 }, nested1: { y: 2, z: 1 } };
|
|
174
|
+
|
|
175
|
+
const digestA = computeFingerprint(A);
|
|
176
|
+
const digestB = computeFingerprint(B);
|
|
177
|
+
|
|
178
|
+
expect(digestA).toMatch(/^[a-f0-9]{64}$/);
|
|
179
|
+
expect(digestB).toMatch(/^[a-f0-9]{64}$/);
|
|
180
|
+
expect(digestA).toBe(digestB);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// ── AC-2 ────────────────────────────────────────────────────────────────────
|
|
184
|
+
it('AC-2: resolveIdempotencyOptions preserves replayHeaders order, case, and duplicates without deduplication', () => {
|
|
185
|
+
const input = ['Content-Type', 'X-Custom-Header', 'Content-Type'];
|
|
186
|
+
const resolved = resolveIdempotencyOptions({ replayHeaders: input });
|
|
187
|
+
|
|
188
|
+
// Length: not deduplicated
|
|
189
|
+
expect(resolved.replayHeaders).toHaveLength(3);
|
|
190
|
+
|
|
191
|
+
// Order and case preserved
|
|
192
|
+
expect(resolved.replayHeaders[0]).toBe('Content-Type');
|
|
193
|
+
expect(resolved.replayHeaders[1]).toBe('X-Custom-Header');
|
|
194
|
+
expect(resolved.replayHeaders[2]).toBe('Content-Type');
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// ── AC-3 ────────────────────────────────────────────────────────────────────
|
|
198
|
+
it('AC-3: complete with non-existent key resolves without error; subsequent get returns undefined; internal Map unchanged', async () => {
|
|
199
|
+
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
200
|
+
const nonExistentKey = 'key-that-was-never-put';
|
|
201
|
+
|
|
202
|
+
// complete on a key that was never inserted resolves (no throw)
|
|
203
|
+
await expect(
|
|
204
|
+
store.complete(nonExistentKey, { status: 200, body: { ok: true }, headers: {} }),
|
|
205
|
+
).resolves.toBeUndefined();
|
|
206
|
+
|
|
207
|
+
// get returns undefined — key not present
|
|
208
|
+
const result = await store.get(nonExistentKey);
|
|
209
|
+
expect(result).toBeUndefined();
|
|
210
|
+
|
|
211
|
+
// Internal Map must not contain the key (phantom entry would block putIfAbsent)
|
|
212
|
+
const internalMap: Map<string, any> = (store as any).map;
|
|
213
|
+
expect(internalMap.has(nonExistentKey)).toBe(false);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
// ── AC-4 ────────────────────────────────────────────────────────────────────
|
|
217
|
+
it('AC-4: non-2xx handler response causes store.remove called once with storageKey and store.complete never called', async () => {
|
|
218
|
+
const method = 'POST';
|
|
219
|
+
const path = '/orders';
|
|
220
|
+
const idempotencyKey = 'idem-key-ac4';
|
|
221
|
+
const expectedStorageKey = sha256(`${method}\n${path}\n${idempotencyKey}`);
|
|
222
|
+
|
|
223
|
+
const store = makeStoreMock(undefined);
|
|
224
|
+
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
225
|
+
|
|
226
|
+
const responseBody = { error: 'bad request' };
|
|
227
|
+
const next = makeNext(responseBody);
|
|
228
|
+
const context = makeContext({
|
|
229
|
+
method,
|
|
230
|
+
path,
|
|
231
|
+
headers: { 'idempotency-key': idempotencyKey },
|
|
232
|
+
body: { data: 1 },
|
|
233
|
+
statusCode: 400,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const result = await runIntercept(interceptor, context, next);
|
|
237
|
+
|
|
238
|
+
// store.remove called exactly once with the computed storageKey
|
|
239
|
+
expect(store.remove).toHaveBeenCalledTimes(1);
|
|
240
|
+
expect((store.remove as jest.Mock).mock.calls[0][0]).toBe(expectedStorageKey);
|
|
241
|
+
|
|
242
|
+
// store.complete never called — non-2xx not cached
|
|
243
|
+
expect(store.complete).not.toHaveBeenCalled();
|
|
244
|
+
|
|
245
|
+
// Interceptor returns the original response body
|
|
246
|
+
expect(result).toEqual(responseBody);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// ── AC-5 ────────────────────────────────────────────────────────────────────
|
|
250
|
+
it('AC-5: store errors propagate; next.handle() is never called more than once; request is not retried', async () => {
|
|
251
|
+
class StoreError extends Error {
|
|
252
|
+
constructor() { super('store failure'); }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Case A: putIfAbsent throws → next.handle() must NOT be called
|
|
256
|
+
{
|
|
257
|
+
const store = {
|
|
258
|
+
putIfAbsent: jest.fn().mockRejectedValue(new StoreError()),
|
|
259
|
+
complete: jest.fn().mockResolvedValue(undefined),
|
|
260
|
+
remove: jest.fn().mockResolvedValue(undefined),
|
|
261
|
+
get: jest.fn().mockResolvedValue(undefined),
|
|
262
|
+
};
|
|
263
|
+
const { host } = makeHttpAdapterComponents();
|
|
264
|
+
const reflector = makeIdempotentReflector(true);
|
|
265
|
+
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
266
|
+
const next = makeNext({ body: 'ok' });
|
|
267
|
+
|
|
268
|
+
const err = await captureInterceptError(interceptor, makeContext(), next);
|
|
269
|
+
|
|
270
|
+
expect(err).toBeInstanceOf(StoreError);
|
|
271
|
+
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Case B: store.complete throws after 2xx → error propagates; next.handle() called exactly once
|
|
275
|
+
{
|
|
276
|
+
const store = {
|
|
277
|
+
putIfAbsent: jest.fn().mockResolvedValue(undefined),
|
|
278
|
+
complete: jest.fn().mockRejectedValue(new StoreError()),
|
|
279
|
+
remove: jest.fn().mockResolvedValue(undefined),
|
|
280
|
+
get: jest.fn().mockResolvedValue(undefined),
|
|
281
|
+
};
|
|
282
|
+
const { host } = makeHttpAdapterComponents();
|
|
283
|
+
const reflector = makeIdempotentReflector(true);
|
|
284
|
+
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
285
|
+
const next = makeNext({ ok: true });
|
|
286
|
+
|
|
287
|
+
const err = await captureInterceptError(interceptor, makeContext({ statusCode: 200 }), next);
|
|
288
|
+
|
|
289
|
+
expect(err).toBeInstanceOf(StoreError);
|
|
290
|
+
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Case C: store.remove throws on non-2xx path → error propagates; next.handle() not retried
|
|
294
|
+
{
|
|
295
|
+
const store = {
|
|
296
|
+
putIfAbsent: jest.fn().mockResolvedValue(undefined),
|
|
297
|
+
complete: jest.fn().mockResolvedValue(undefined),
|
|
298
|
+
remove: jest.fn().mockRejectedValue(new StoreError()),
|
|
299
|
+
get: jest.fn().mockResolvedValue(undefined),
|
|
300
|
+
};
|
|
301
|
+
const { host } = makeHttpAdapterComponents();
|
|
302
|
+
const reflector = makeIdempotentReflector(true);
|
|
303
|
+
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
304
|
+
const next = makeNext({ error: 'fail' });
|
|
305
|
+
|
|
306
|
+
const err = await captureInterceptError(interceptor, makeContext({ statusCode: 500 }), next);
|
|
307
|
+
|
|
308
|
+
expect(err).toBeDefined();
|
|
309
|
+
// next.handle() called once — handler was not retried
|
|
310
|
+
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// ── AC-6 ────────────────────────────────────────────────────────────────────
|
|
315
|
+
it('AC-6: replay only sets replayHeaders on adapter response; unrequested stored headers are excluded', async () => {
|
|
316
|
+
const storedResponse = {
|
|
317
|
+
status: 200,
|
|
318
|
+
body: { id: 1 },
|
|
319
|
+
headers: {
|
|
320
|
+
'content-type': 'application/json',
|
|
321
|
+
'content-length': '42',
|
|
322
|
+
'x-custom': 'value',
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
const completedRecord = {
|
|
326
|
+
state: 'completed' as const,
|
|
327
|
+
fingerprint: computeFingerprint({ a: 1 }),
|
|
328
|
+
createdAt: Date.now(),
|
|
329
|
+
response: storedResponse,
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const store = makeStoreMock(completedRecord);
|
|
333
|
+
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
334
|
+
const reflector = makeIdempotentReflector(true);
|
|
335
|
+
// replayHeaders contains only 'content-type'
|
|
336
|
+
const options = { ...defaultOptions, replayHeaders: ['content-type'] };
|
|
337
|
+
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, options);
|
|
338
|
+
|
|
339
|
+
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
340
|
+
|
|
341
|
+
// adapter.reply must have been called once
|
|
342
|
+
expect(httpAdapter.reply).toHaveBeenCalledTimes(1);
|
|
343
|
+
|
|
344
|
+
// Collect all header names passed to setHeader
|
|
345
|
+
const setHeaderCalls: Array<[unknown, string, unknown]> = (httpAdapter.setHeader as jest.Mock).mock.calls as any;
|
|
346
|
+
const passedHeaderNames = setHeaderCalls.map(([, name]) => name.toLowerCase());
|
|
347
|
+
|
|
348
|
+
// Only 'content-type' should be forwarded
|
|
349
|
+
expect(passedHeaderNames).toContain('content-type');
|
|
350
|
+
|
|
351
|
+
// 'content-length' and 'x-custom' must NOT be set on the adapter response
|
|
352
|
+
expect(passedHeaderNames).not.toContain('content-length');
|
|
353
|
+
expect(passedHeaderNames).not.toContain('x-custom');
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
// ── AC-7 (integration-check) ─────────────────────────────────────────────────
|
|
357
|
+
describe('AC-7: requireKey=true returns HTTP 400 with IDEMPOTENCY_KEY_REQUIRED error when Idempotency-Key header is absent', () => {
|
|
358
|
+
let app: INestApplication;
|
|
359
|
+
|
|
360
|
+
beforeAll(async () => {
|
|
361
|
+
_requireKeyHandlerCount = 0;
|
|
362
|
+
const moduleRef = await Test.createTestingModule({
|
|
363
|
+
imports: [IdempotencyModule.register({ requireKey: true })],
|
|
364
|
+
controllers: [RequireKeyTestController],
|
|
365
|
+
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
366
|
+
}).compile();
|
|
367
|
+
app = moduleRef.createNestApplication();
|
|
368
|
+
await app.init();
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
afterAll(async () => { await app?.close(); });
|
|
372
|
+
|
|
373
|
+
it('returns HTTP 400 and error body with MISSING_REQUIRED_KEY code when key header is absent', async () => {
|
|
374
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
375
|
+
const supertest = require('supertest');
|
|
376
|
+
|
|
377
|
+
const res = await supertest(app.getHttpServer())
|
|
378
|
+
.post('/test')
|
|
379
|
+
.send({ a: 1 });
|
|
380
|
+
|
|
381
|
+
expect(res.statusCode).toBe(HttpStatus.BAD_REQUEST);
|
|
382
|
+
|
|
383
|
+
// AppException response body shape: { code, args, prefix }
|
|
384
|
+
const body = typeof res.body === 'string' ? JSON.parse(res.body) : res.body;
|
|
385
|
+
expect(body).toBeDefined();
|
|
386
|
+
expect(body.code).toBe(IdempotencyExceptionCode.MISSING_REQUIRED_KEY);
|
|
387
|
+
|
|
388
|
+
// Handler must NOT have been invoked
|
|
389
|
+
expect(_requireKeyHandlerCount).toBe(0);
|
|
390
|
+
});
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
// ── AC-8 (integration-check) ─────────────────────────────────────────────────
|
|
394
|
+
describe('AC-8: replay response contains only replayHeaders entries; location and x-custom are excluded', () => {
|
|
395
|
+
let app: INestApplication;
|
|
396
|
+
|
|
397
|
+
beforeAll(async () => {
|
|
398
|
+
_replayHeaderHandlerCount = 0;
|
|
399
|
+
const moduleRef = await Test.createTestingModule({
|
|
400
|
+
imports: [IdempotencyModule.register({ replayHeaders: ['content-type'] })],
|
|
401
|
+
controllers: [ReplayHeaderTestController],
|
|
402
|
+
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
403
|
+
}).compile();
|
|
404
|
+
app = moduleRef.createNestApplication();
|
|
405
|
+
await app.init();
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
afterAll(async () => { await app?.close(); });
|
|
409
|
+
|
|
410
|
+
it('replay response has content-type but not location or x-custom', async () => {
|
|
411
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
412
|
+
const supertest = require('supertest');
|
|
413
|
+
const idempotencyKey = 'AC8-replay-' + Date.now();
|
|
414
|
+
|
|
415
|
+
// First request — handler runs, response cached
|
|
416
|
+
const first = await supertest(app.getHttpServer())
|
|
417
|
+
.post('/test')
|
|
418
|
+
.set('Idempotency-Key', idempotencyKey)
|
|
419
|
+
.send({ data: 'ac8' });
|
|
420
|
+
expect(first.statusCode).toBe(200);
|
|
421
|
+
expect(_replayHeaderHandlerCount).toBe(1);
|
|
422
|
+
|
|
423
|
+
// Second request — must be a replay (handler not called again)
|
|
424
|
+
const second = await supertest(app.getHttpServer())
|
|
425
|
+
.post('/test')
|
|
426
|
+
.set('Idempotency-Key', idempotencyKey)
|
|
427
|
+
.send({ data: 'ac8' });
|
|
428
|
+
expect(second.statusCode).toBe(200);
|
|
429
|
+
expect(_replayHeaderHandlerCount).toBe(1);
|
|
430
|
+
|
|
431
|
+
// 'content-type' is in replayHeaders — must be present
|
|
432
|
+
expect(second.headers['content-type']).toBeDefined();
|
|
433
|
+
|
|
434
|
+
// 'location' and 'x-custom' are NOT in replayHeaders — must be absent
|
|
435
|
+
expect(second.headers['location']).toBeUndefined();
|
|
436
|
+
expect(second.headers['x-custom']).toBeUndefined();
|
|
437
|
+
});
|
|
438
|
+
});
|
|
439
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Test the controller instantiation
|
|
2
|
+
import 'reflect-metadata';
|
|
3
|
+
import { Controller, Post, Body } from '@nestjs/common';
|
|
4
|
+
import { Idempotent } from '../../../lib/decorator/idempotent.decorator';
|
|
5
|
+
|
|
6
|
+
@Controller()
|
|
7
|
+
class TestController {
|
|
8
|
+
@Post('test')
|
|
9
|
+
@Idempotent()
|
|
10
|
+
async handle(@Body() _body: unknown) {
|
|
11
|
+
return { ok: true };
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
describe('Controller instantiation', () => {
|
|
16
|
+
it('should be a constructor', () => {
|
|
17
|
+
console.log('typeof TestController:', typeof TestController);
|
|
18
|
+
console.log('TestController.prototype:', typeof TestController.prototype);
|
|
19
|
+
expect(typeof TestController).toBe('function');
|
|
20
|
+
expect(() => new TestController()).not.toThrow();
|
|
21
|
+
});
|
|
22
|
+
});
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# @nathapp/nestjs-idempotency
|
|
2
|
+
|
|
3
|
+
## 3.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- a27440f: 3.3.0 milestone release. The `@nathapp/nestjs-*` packages now version and publish in lockstep at a unified version.
|
|
8
|
+
|
|
9
|
+
- **nestjs-csrf**: first public release — stateless double-submit-cookie CSRF guard (zero-dep HMAC, Express + Fastify, Bearer coexist skip, `@SkipCsrf()`, auto-binds `APP_GUARD`).
|
|
10
|
+
- **nestjs-health**: first public release — terminus aggregator over cache/prisma/queue with k8s liveness/readiness probes via a dynamic controller factory.
|
|
11
|
+
- **nestjs-idempotency**: first public release — `@Idempotent()` interceptor (zero-dep sha256 fingerprint, Express + Fastify, 409-in-flight, 2xx replay, fingerprint mismatch 422, fail-closed on store error).
|
|
12
|
+
- **nestjs-observability**: first public release — Prometheus RED metrics + OpenTelemetry tracing joined to the logging ALS; `initTracing()` pre-bootstrap hook.
|
|
13
|
+
- **nestjs-outbox**: first public release — transactional outbox relay (at-least-once via `ITransactionManager`, lease-claim + backoff, dead-letter).
|
|
14
|
+
- **nestjs-storage**: migrated from aws-sdk v2 to v3 (zero runtime dep via `import type` + lazy `loadPackage`); NFSStorage stub replaced with an S3-style HTTP file-service client.
|
|
15
|
+
- **nestjs-cache**: `delByPattern` now routes through Redis SCAN instead of an O(n) key sweep, with glob-detection and multi-tier iterator support.
|
package/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @nathapp/nestjs-idempotency
|
|
2
|
+
|
|
3
|
+
HTTP idempotency-key support for NestJS, working on both the Express and Fastify
|
|
4
|
+
adapters, with **zero runtime dependencies** (Node `crypto` only).
|
|
5
|
+
|
|
6
|
+
## Design
|
|
7
|
+
|
|
8
|
+
- **Opt-in per route** — decorate a mutating handler with `@Idempotent()`. Every
|
|
9
|
+
other route is untouched (the interceptor is a no-op without the metadata).
|
|
10
|
+
- **Client-supplied key** — the client sends a stable `Idempotency-Key` header on
|
|
11
|
+
a retryable request. The first successful (2xx) response is stored and replayed
|
|
12
|
+
on any later retry with the same key.
|
|
13
|
+
- **In-flight protection** — a duplicate that arrives while the first request is
|
|
14
|
+
still processing is rejected with **409** (an atomic `putIfAbsent` records a
|
|
15
|
+
`pending` state on first sight).
|
|
16
|
+
- **Payload guard** — the request body is fingerprinted; reusing the same key with
|
|
17
|
+
a different body is rejected with **422**.
|
|
18
|
+
- **Key scope** — the storage key is derived from `method + path + Idempotency-Key`,
|
|
19
|
+
so the same key value on different endpoints is independent.
|
|
20
|
+
- **Pluggable storage** — `IIdempotencyStore` seam with an in-memory default
|
|
21
|
+
(single-process only). Multi-instance deployments supply a shared store
|
|
22
|
+
(e.g. Redis `SET NX`) via the seam.
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { IdempotencyModule, IdempotencyInterceptor, Idempotent } from '@nathapp/nestjs-idempotency';
|
|
28
|
+
import { APP_INTERCEPTOR } from '@nestjs/core';
|
|
29
|
+
|
|
30
|
+
@Module({
|
|
31
|
+
imports: [IdempotencyModule.register()],
|
|
32
|
+
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
33
|
+
})
|
|
34
|
+
export class AppModule {}
|
|
35
|
+
|
|
36
|
+
@Controller('orders')
|
|
37
|
+
export class OrdersController {
|
|
38
|
+
@Post()
|
|
39
|
+
@Idempotent()
|
|
40
|
+
create(@Body() dto: CreateOrderDto) {
|
|
41
|
+
// runs at most once per Idempotency-Key
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
| Option | Default | Meaning |
|
|
49
|
+
|--------|---------|---------|
|
|
50
|
+
| `store` | `InMemoryIdempotencyStore` | Storage backend (`IIdempotencyStore`). |
|
|
51
|
+
| `headerName` | `Idempotency-Key` | Request header carrying the key. |
|
|
52
|
+
| `ttlMs` | `86_400_000` (24h) | How long a stored response is replayable. |
|
|
53
|
+
| `requireKey` | `false` | When `true`, a decorated route without the header returns 400. |
|
|
54
|
+
| `replayHeaders` | `['content-type']` | Response headers stored and replayed. |
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const IDEMPOTENCY_STORE: unique symbol;
|
|
2
|
+
export declare const IDEMPOTENCY_MODULE_OPTIONS = "IDEMPOTENCY_MODULE_OPTIONS";
|
|
3
|
+
export declare const IDEMPOTENCY_INTERCEPTOR_OPTIONS = "IDEMPOTENCY_INTERCEPTOR_OPTIONS";
|
|
4
|
+
export declare const IDEMPOTENT_METADATA_KEY = "idempotent";
|
|
5
|
+
export declare const DEFAULT_HEADER_NAME = "Idempotency-Key";
|
|
6
|
+
export declare const DEFAULT_TTL_MS = 86400000;
|
|
7
|
+
export declare const DEFAULT_REQUIRE_KEY = false;
|
|
8
|
+
export declare const DEFAULT_REPLAY_HEADERS: string[];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_REPLAY_HEADERS = exports.DEFAULT_REQUIRE_KEY = exports.DEFAULT_TTL_MS = exports.DEFAULT_HEADER_NAME = exports.IDEMPOTENT_METADATA_KEY = exports.IDEMPOTENCY_INTERCEPTOR_OPTIONS = exports.IDEMPOTENCY_MODULE_OPTIONS = exports.IDEMPOTENCY_STORE = void 0;
|
|
4
|
+
exports.IDEMPOTENCY_STORE = Symbol.for('IDEMPOTENCY_STORE');
|
|
5
|
+
exports.IDEMPOTENCY_MODULE_OPTIONS = 'IDEMPOTENCY_MODULE_OPTIONS';
|
|
6
|
+
exports.IDEMPOTENCY_INTERCEPTOR_OPTIONS = 'IDEMPOTENCY_INTERCEPTOR_OPTIONS';
|
|
7
|
+
exports.IDEMPOTENT_METADATA_KEY = 'idempotent';
|
|
8
|
+
exports.DEFAULT_HEADER_NAME = 'Idempotency-Key';
|
|
9
|
+
exports.DEFAULT_TTL_MS = 86400000;
|
|
10
|
+
exports.DEFAULT_REQUIRE_KEY = false;
|
|
11
|
+
exports.DEFAULT_REPLAY_HEADERS = ['content-type'];
|
|
12
|
+
//# sourceMappingURL=idempotency.constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency.constants.js","sourceRoot":"","sources":["../../lib/constant/idempotency.constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;AACpD,QAAA,0BAA0B,GAAG,4BAA4B,CAAC;AAC1D,QAAA,+BAA+B,GAAG,iCAAiC,CAAC;AACpE,QAAA,uBAAuB,GAAG,YAAY,CAAC;AACvC,QAAA,mBAAmB,GAAG,iBAAiB,CAAC;AACxC,QAAA,cAAc,GAAG,QAAU,CAAC;AAC5B,QAAA,mBAAmB,GAAG,KAAK,CAAC;AAC5B,QAAA,sBAAsB,GAAG,CAAC,cAAc,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './idempotency.constants';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./idempotency.constants"), exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/constant/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0DAAwC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const Idempotent: () => import("@nestjs/common").CustomDecorator<string>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Idempotent = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const idempotency_constants_1 = require("../constant/idempotency.constants");
|
|
6
|
+
const Idempotent = () => (0, common_1.SetMetadata)(idempotency_constants_1.IDEMPOTENT_METADATA_KEY, true);
|
|
7
|
+
exports.Idempotent = Idempotent;
|
|
8
|
+
//# sourceMappingURL=idempotent.decorator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotent.decorator.js","sourceRoot":"","sources":["../../lib/decorator/idempotent.decorator.ts"],"names":[],"mappings":";;;AAAA,2CAA6C;AAC7C,6EAA4E;AAErE,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,IAAA,oBAAW,EAAC,+CAAuB,EAAE,IAAI,CAAC,CAAC;AAA9D,QAAA,UAAU,cAAoD"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.IdempotencyExceptionCode = void 0;
|
|
4
|
+
var IdempotencyExceptionCode;
|
|
5
|
+
(function (IdempotencyExceptionCode) {
|
|
6
|
+
IdempotencyExceptionCode[IdempotencyExceptionCode["MISSING_REQUIRED_KEY"] = 40002] = "MISSING_REQUIRED_KEY";
|
|
7
|
+
IdempotencyExceptionCode[IdempotencyExceptionCode["CONFLICT_IN_FLIGHT"] = 40900] = "CONFLICT_IN_FLIGHT";
|
|
8
|
+
IdempotencyExceptionCode[IdempotencyExceptionCode["KEY_REUSE_MISMATCH"] = 40901] = "KEY_REUSE_MISMATCH";
|
|
9
|
+
})(IdempotencyExceptionCode || (exports.IdempotencyExceptionCode = IdempotencyExceptionCode = {}));
|
|
10
|
+
//# sourceMappingURL=idempotency-exception-code.enum.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency-exception-code.enum.js","sourceRoot":"","sources":["../../lib/exception/idempotency-exception-code.enum.ts"],"names":[],"mappings":";;;AAAA,IAAY,wBAIX;AAJD,WAAY,wBAAwB;IAClC,2GAA4B,CAAA;IAC5B,uGAA0B,CAAA;IAC1B,uGAA0B,CAAA;AAC5B,CAAC,EAJW,wBAAwB,wCAAxB,wBAAwB,QAInC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.IdempotencyKeyReuseException = exports.IdempotencyConflictException = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const nestjs_common_1 = require("@nathapp/nestjs-common");
|
|
6
|
+
const idempotency_exception_code_enum_1 = require("./idempotency-exception-code.enum");
|
|
7
|
+
class IdempotencyConflictException extends nestjs_common_1.AppException {
|
|
8
|
+
constructor() {
|
|
9
|
+
super(idempotency_exception_code_enum_1.IdempotencyExceptionCode.CONFLICT_IN_FLIGHT, undefined, undefined, common_1.HttpStatus.CONFLICT);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.IdempotencyConflictException = IdempotencyConflictException;
|
|
13
|
+
class IdempotencyKeyReuseException extends nestjs_common_1.AppException {
|
|
14
|
+
constructor() {
|
|
15
|
+
super(idempotency_exception_code_enum_1.IdempotencyExceptionCode.KEY_REUSE_MISMATCH, undefined, undefined, common_1.HttpStatus.UNPROCESSABLE_ENTITY);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.IdempotencyKeyReuseException = IdempotencyKeyReuseException;
|
|
19
|
+
//# sourceMappingURL=idempotency.exceptions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency.exceptions.js","sourceRoot":"","sources":["../../lib/exception/idempotency.exceptions.ts"],"names":[],"mappings":";;;AAAA,2CAA4C;AAC5C,0DAAsD;AACtD,uFAA6E;AAE7E,MAAa,4BAA6B,SAAQ,4BAAY;IAC5D;QACE,KAAK,CAAC,0DAAwB,CAAC,kBAAkB,EAAE,SAAS,EAAE,SAAS,EAAE,mBAAU,CAAC,QAAQ,CAAC,CAAC;IAChG,CAAC;CACF;AAJD,oEAIC;AAED,MAAa,4BAA6B,SAAQ,4BAAY;IAC5D;QACE,KAAK,CAAC,0DAAwB,CAAC,kBAAkB,EAAE,SAAS,EAAE,SAAS,EAAE,mBAAU,CAAC,oBAAoB,CAAC,CAAC;IAC5G,CAAC;CACF;AAJD,oEAIC"}
|