@nathapp/nestjs-idempotency 3.3.0 → 4.0.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/package.json +10 -10
- package/.eslintrc.js +0 -8
- package/.nax/features/nestjs-idempotency/.nax-acceptance.test.ts +0 -766
- package/.nax/features/nestjs-idempotency/.nax-suggested.test.ts +0 -439
- package/.nax/test-debug.ts +0 -22
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -15
- package/lib/constant/idempotency.constants.ts +0 -8
- package/lib/constant/index.ts +0 -1
- package/lib/decorator/idempotent.decorator.ts +0 -4
- package/lib/exception/idempotency-exception-code.enum.ts +0 -5
- package/lib/exception/idempotency.exceptions.ts +0 -15
- package/lib/index.ts +0 -13
- package/lib/interceptor/idempotency.interceptor.ts +0 -187
- package/lib/interface/idempotency-module-options.interface.ts +0 -21
- package/lib/interface/idempotency-record.interface.ts +0 -14
- package/lib/interface/idempotency-store.interface.ts +0 -8
- package/lib/module/idempotency.module.ts +0 -61
- package/lib/provider/default-principal-extractor.ts +0 -17
- package/lib/provider/fingerprint.ts +0 -17
- package/lib/provider/in-memory-idempotency-store.ts +0 -53
- package/lib/provider/resolve-idempotency-options.ts +0 -32
- package/test/barrel/index.spec.ts +0 -40
- package/test/constant/idempotency.constants.spec.ts +0 -10
- package/test/decorator/idempotent.decorator.spec.ts +0 -20
- package/test/e2e/express.e2e.spec.ts +0 -219
- package/test/e2e/fastify.e2e.spec.ts +0 -64
- package/test/exception/idempotency.exceptions.spec.ts +0 -24
- package/test/interceptor/idempotency.interceptor.spec.ts +0 -739
- package/test/jest-nax-setup-test.js +0 -21
- package/test/jest-nax-setup.js +0 -92
- package/test/jest-nax.json +0 -30
- package/test/jest-test.json +0 -28
- package/test/module/idempotency.module.spec.ts +0 -87
- package/test/provider/fingerprint.spec.ts +0 -27
- package/test/provider/in-memory-idempotency-store.spec.ts +0 -212
- package/test/provider/resolve-idempotency-options.spec.ts +0 -42
- package/tsconfig.json +0 -9
|
@@ -1,739 +0,0 @@
|
|
|
1
|
-
import 'reflect-metadata';
|
|
2
|
-
import { describe, expect, it, jest } from '@jest/globals';
|
|
3
|
-
import { ExecutionContext, CallHandler } from '@nestjs/common';
|
|
4
|
-
import { Reflector, HttpAdapterHost } from '@nestjs/core';
|
|
5
|
-
import { of, throwError, lastValueFrom } from 'rxjs';
|
|
6
|
-
import { createHash } from 'crypto';
|
|
7
|
-
import { AppException } from '@nathapp/nestjs-common';
|
|
8
|
-
import { IdempotencyInterceptor } from '../../lib/interceptor/idempotency.interceptor';
|
|
9
|
-
import { IdempotencyRecord } from '../../lib/interface/idempotency-record.interface';
|
|
10
|
-
import { IdempotencyConflictException } from '../../lib/exception/idempotency.exceptions';
|
|
11
|
-
import { IdempotencyKeyReuseException } from '../../lib/exception/idempotency.exceptions';
|
|
12
|
-
import { computeFingerprint } from '../../lib/provider/fingerprint';
|
|
13
|
-
import { InterceptorOptions } from '../../lib/provider/resolve-idempotency-options';
|
|
14
|
-
import { defaultPrincipalExtractor } from '../../lib/provider/default-principal-extractor';
|
|
15
|
-
|
|
16
|
-
// ─── Test helpers ─────────────────────────────────────────────────────────────
|
|
17
|
-
|
|
18
|
-
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex');
|
|
19
|
-
|
|
20
|
-
type AnyAsyncFn = (...args: any[]) => Promise<any>;
|
|
21
|
-
|
|
22
|
-
const mockResolved = <T>(value: T) =>
|
|
23
|
-
(jest.fn() as unknown as jest.Mock<AnyAsyncFn>).mockResolvedValue(value);
|
|
24
|
-
|
|
25
|
-
const makeStoreMock = (putResult: IdempotencyRecord | undefined = undefined) => ({
|
|
26
|
-
putIfAbsent: mockResolved(putResult),
|
|
27
|
-
complete: mockResolved<void>(undefined),
|
|
28
|
-
remove: mockResolved<void>(undefined),
|
|
29
|
-
get: mockResolved<IdempotencyRecord | undefined>(undefined),
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
const makeHttpAdapterComponents = () => {
|
|
33
|
-
const httpAdapter = {
|
|
34
|
-
reply: jest.fn() as jest.Mock,
|
|
35
|
-
setHeader: jest.fn() as jest.Mock,
|
|
36
|
-
};
|
|
37
|
-
const host = { httpAdapter } as unknown as HttpAdapterHost;
|
|
38
|
-
return { httpAdapter, host };
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
const makeIdempotentReflector = (hasMetadata: boolean): Reflector =>
|
|
42
|
-
({ get: jest.fn().mockReturnValue(hasMetadata ? true : undefined) }) as unknown as Reflector;
|
|
43
|
-
|
|
44
|
-
const makeNext = (body: unknown, isError = false): CallHandler => ({
|
|
45
|
-
handle: jest.fn().mockReturnValue(isError ? throwError(() => body) : of(body)) as any,
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
const makeContext = (opts: {
|
|
49
|
-
method?: string;
|
|
50
|
-
path?: string;
|
|
51
|
-
headers?: Record<string, string>;
|
|
52
|
-
body?: unknown;
|
|
53
|
-
statusCode?: number;
|
|
54
|
-
responseHeaders?: Record<string, string>;
|
|
55
|
-
handler?: object;
|
|
56
|
-
user?: unknown;
|
|
57
|
-
type?: string;
|
|
58
|
-
} = {}): ExecutionContext => {
|
|
59
|
-
const request = {
|
|
60
|
-
method: opts.method ?? 'POST',
|
|
61
|
-
path: opts.path ?? '/users',
|
|
62
|
-
url: opts.path ?? '/users',
|
|
63
|
-
headers: opts.headers ?? { 'idempotency-key': 'test-key-123' },
|
|
64
|
-
body: opts.body ?? { a: 1 },
|
|
65
|
-
user: opts.user,
|
|
66
|
-
};
|
|
67
|
-
const response = {
|
|
68
|
-
statusCode: opts.statusCode ?? 200,
|
|
69
|
-
getHeaders: () => opts.responseHeaders ?? { 'content-type': 'application/json' },
|
|
70
|
-
};
|
|
71
|
-
return {
|
|
72
|
-
getHandler: () => opts.handler ?? {},
|
|
73
|
-
getType: () => opts.type ?? 'http',
|
|
74
|
-
switchToHttp: () => ({ getRequest: () => request, getResponse: () => response }),
|
|
75
|
-
} as unknown as ExecutionContext;
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
const defaultOptions: InterceptorOptions = {
|
|
79
|
-
headerName: 'Idempotency-Key',
|
|
80
|
-
ttlMs: 86_400_000,
|
|
81
|
-
requireKey: false,
|
|
82
|
-
replayHeaders: ['content-type'],
|
|
83
|
-
principalExtractor: defaultPrincipalExtractor,
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
const buildInterceptor = (opts: {
|
|
87
|
-
hasMetadata?: boolean;
|
|
88
|
-
store?: ReturnType<typeof makeStoreMock>;
|
|
89
|
-
requireKey?: boolean;
|
|
90
|
-
httpAdapterHost?: HttpAdapterHost;
|
|
91
|
-
principalExtractor?: InterceptorOptions['principalExtractor'];
|
|
92
|
-
} = {}) => {
|
|
93
|
-
const reflector = makeIdempotentReflector(opts.hasMetadata ?? true);
|
|
94
|
-
const store = opts.store ?? makeStoreMock();
|
|
95
|
-
const { host } = makeHttpAdapterComponents();
|
|
96
|
-
const adapterHost = opts.httpAdapterHost ?? host;
|
|
97
|
-
const options: InterceptorOptions = {
|
|
98
|
-
...defaultOptions,
|
|
99
|
-
requireKey: opts.requireKey ?? false,
|
|
100
|
-
principalExtractor: opts.principalExtractor ?? defaultOptions.principalExtractor,
|
|
101
|
-
};
|
|
102
|
-
return {
|
|
103
|
-
interceptor: new IdempotencyInterceptor(reflector, store as any, adapterHost, options),
|
|
104
|
-
reflector,
|
|
105
|
-
store,
|
|
106
|
-
};
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Runs intercept, handling both synchronous throws and observable errors uniformly.
|
|
111
|
-
* Returns the emitted value (or undefined for EMPTY) on success.
|
|
112
|
-
*/
|
|
113
|
-
const runIntercept = async (
|
|
114
|
-
interceptor: IdempotencyInterceptor,
|
|
115
|
-
context: ExecutionContext,
|
|
116
|
-
next: CallHandler,
|
|
117
|
-
): Promise<unknown> => {
|
|
118
|
-
let obs: unknown;
|
|
119
|
-
try {
|
|
120
|
-
obs = interceptor.intercept(context, next);
|
|
121
|
-
} catch (err) {
|
|
122
|
-
throw err;
|
|
123
|
-
}
|
|
124
|
-
if (obs != null && typeof (obs as { subscribe?: unknown }).subscribe === 'function') {
|
|
125
|
-
return lastValueFrom(obs as Parameters<typeof lastValueFrom>[0], { defaultValue: undefined });
|
|
126
|
-
}
|
|
127
|
-
return undefined;
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Captures the first error thrown (sync or via observable) by runIntercept.
|
|
132
|
-
* Throws if the interceptor completes without error.
|
|
133
|
-
*/
|
|
134
|
-
const captureInterceptError = async (
|
|
135
|
-
interceptor: IdempotencyInterceptor,
|
|
136
|
-
context: ExecutionContext,
|
|
137
|
-
next: CallHandler,
|
|
138
|
-
): Promise<unknown> => {
|
|
139
|
-
try {
|
|
140
|
-
await runIntercept(interceptor, context, next);
|
|
141
|
-
} catch (err) {
|
|
142
|
-
return err;
|
|
143
|
-
}
|
|
144
|
-
throw new Error('Expected interceptor to throw but it completed successfully');
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
148
|
-
|
|
149
|
-
describe('IdempotencyInterceptor', () => {
|
|
150
|
-
describe('AC1: handler WITHOUT @Idempotent() metadata', () => {
|
|
151
|
-
it('AC1: calls next.handle() and never calls putIfAbsent (success path)', async () => {
|
|
152
|
-
const store = makeStoreMock();
|
|
153
|
-
const { interceptor } = buildInterceptor({ hasMetadata: false, store });
|
|
154
|
-
const next = makeNext('response');
|
|
155
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
156
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
157
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
158
|
-
});
|
|
159
|
-
|
|
160
|
-
it('AC1: even with a valid idempotency header present, putIfAbsent is skipped when metadata is absent', async () => {
|
|
161
|
-
const store = makeStoreMock();
|
|
162
|
-
const { interceptor } = buildInterceptor({ hasMetadata: false, store });
|
|
163
|
-
const next = makeNext('response');
|
|
164
|
-
await runIntercept(
|
|
165
|
-
interceptor,
|
|
166
|
-
makeContext({ headers: { 'idempotency-key': 'should-be-ignored' } }),
|
|
167
|
-
next,
|
|
168
|
-
);
|
|
169
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
170
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
171
|
-
});
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
describe('AC2: @Idempotent() + requireKey false + no header', () => {
|
|
175
|
-
it('AC2: calls next.handle() and does not call putIfAbsent (success path)', async () => {
|
|
176
|
-
const store = makeStoreMock();
|
|
177
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: false });
|
|
178
|
-
const next = makeNext('response');
|
|
179
|
-
await runIntercept(interceptor, makeContext({ headers: {} }), next);
|
|
180
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
181
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
it('AC2: complete and remove are also not called when header is absent', async () => {
|
|
185
|
-
const store = makeStoreMock();
|
|
186
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: false });
|
|
187
|
-
const next = makeNext('response');
|
|
188
|
-
await runIntercept(interceptor, makeContext({ headers: {} }), next);
|
|
189
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
190
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
191
|
-
});
|
|
192
|
-
});
|
|
193
|
-
|
|
194
|
-
describe('AC3: @Idempotent() + requireKey true + no header', () => {
|
|
195
|
-
it('AC3: throws an AppException with httpStatus 400 (success path)', async () => {
|
|
196
|
-
const store = makeStoreMock();
|
|
197
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: true });
|
|
198
|
-
const next = makeNext('response');
|
|
199
|
-
const err = await captureInterceptError(interceptor, makeContext({ headers: {} }), next);
|
|
200
|
-
expect(err).toBeInstanceOf(AppException);
|
|
201
|
-
expect((err as AppException).httpStatus).toBe(400);
|
|
202
|
-
});
|
|
203
|
-
|
|
204
|
-
it('AC3: does not call next.handle() when the header is missing and requireKey is true (boundary)', async () => {
|
|
205
|
-
const store = makeStoreMock();
|
|
206
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: true });
|
|
207
|
-
const next = makeNext('response');
|
|
208
|
-
await captureInterceptError(interceptor, makeContext({ headers: {} }), next);
|
|
209
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
210
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
211
|
-
});
|
|
212
|
-
});
|
|
213
|
-
|
|
214
|
-
describe('AC4: header present, putIfAbsent resolves undefined', () => {
|
|
215
|
-
it('AC4: calls next.handle() once and calls putIfAbsent once (success path)', async () => {
|
|
216
|
-
const store = makeStoreMock(undefined);
|
|
217
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
218
|
-
const next = makeNext({ a: 1 });
|
|
219
|
-
await runIntercept(
|
|
220
|
-
interceptor,
|
|
221
|
-
makeContext({
|
|
222
|
-
method: 'POST',
|
|
223
|
-
path: '/users',
|
|
224
|
-
headers: { 'idempotency-key': 'test-key-123' },
|
|
225
|
-
body: { a: 1 },
|
|
226
|
-
statusCode: 200,
|
|
227
|
-
}),
|
|
228
|
-
next,
|
|
229
|
-
);
|
|
230
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
231
|
-
expect(store.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
it('AC4: storage key equals sha256(method + LF + path + LF + headerValue)', async () => {
|
|
235
|
-
const store = makeStoreMock(undefined);
|
|
236
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
237
|
-
await runIntercept(
|
|
238
|
-
interceptor,
|
|
239
|
-
makeContext({
|
|
240
|
-
method: 'POST',
|
|
241
|
-
path: '/users',
|
|
242
|
-
headers: { 'idempotency-key': 'test-key-123' },
|
|
243
|
-
statusCode: 200,
|
|
244
|
-
}),
|
|
245
|
-
makeNext({}),
|
|
246
|
-
);
|
|
247
|
-
expect(store.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
248
|
-
const storageKey = (store.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
249
|
-
expect(storageKey).toBe(sha256('POST\n/users\ntest-key-123'));
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
it('AC4: identical method+path+key inputs produce the same storage key (deterministic)', async () => {
|
|
253
|
-
const store1 = makeStoreMock(undefined);
|
|
254
|
-
const { interceptor: i1 } = buildInterceptor({ hasMetadata: true, store: store1 });
|
|
255
|
-
await runIntercept(
|
|
256
|
-
i1,
|
|
257
|
-
makeContext({ method: 'POST', path: '/users', headers: { 'idempotency-key': 'K' }, statusCode: 200 }),
|
|
258
|
-
makeNext({}),
|
|
259
|
-
);
|
|
260
|
-
expect(store1.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
261
|
-
const key1 = (store1.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
262
|
-
|
|
263
|
-
const store2 = makeStoreMock(undefined);
|
|
264
|
-
const { interceptor: i2 } = buildInterceptor({ hasMetadata: true, store: store2 });
|
|
265
|
-
await runIntercept(
|
|
266
|
-
i2,
|
|
267
|
-
makeContext({ method: 'POST', path: '/users', headers: { 'idempotency-key': 'K' }, statusCode: 200 }),
|
|
268
|
-
makeNext({}),
|
|
269
|
-
);
|
|
270
|
-
expect(store2.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
271
|
-
const key2 = (store2.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
272
|
-
|
|
273
|
-
expect(key1).toBe(key2);
|
|
274
|
-
});
|
|
275
|
-
|
|
276
|
-
it('AC4: a different path produces a different storage key (boundary)', async () => {
|
|
277
|
-
const store1 = makeStoreMock(undefined);
|
|
278
|
-
const { interceptor: i1 } = buildInterceptor({ hasMetadata: true, store: store1 });
|
|
279
|
-
await runIntercept(
|
|
280
|
-
i1,
|
|
281
|
-
makeContext({ method: 'POST', path: '/users', headers: { 'idempotency-key': 'K' }, statusCode: 200 }),
|
|
282
|
-
makeNext({}),
|
|
283
|
-
);
|
|
284
|
-
expect(store1.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
285
|
-
const key1 = (store1.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
286
|
-
|
|
287
|
-
const store2 = makeStoreMock(undefined);
|
|
288
|
-
const { interceptor: i2 } = buildInterceptor({ hasMetadata: true, store: store2 });
|
|
289
|
-
await runIntercept(
|
|
290
|
-
i2,
|
|
291
|
-
makeContext({ method: 'POST', path: '/orders', headers: { 'idempotency-key': 'K' }, statusCode: 200 }),
|
|
292
|
-
makeNext({}),
|
|
293
|
-
);
|
|
294
|
-
expect(store2.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
295
|
-
const key2 = (store2.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
296
|
-
|
|
297
|
-
expect(key1).not.toBe(key2);
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
it('AC4: putIfAbsent record has state=pending and fingerprint matching the request body', async () => {
|
|
301
|
-
const body = { amount: 100, currency: 'USD' };
|
|
302
|
-
const store = makeStoreMock(undefined);
|
|
303
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
304
|
-
await runIntercept(
|
|
305
|
-
interceptor,
|
|
306
|
-
makeContext({ headers: { 'idempotency-key': 'K' }, body, statusCode: 200 }),
|
|
307
|
-
makeNext({}),
|
|
308
|
-
);
|
|
309
|
-
expect(store.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
310
|
-
const record = (store.putIfAbsent as jest.Mock).mock.calls[0][1] as IdempotencyRecord;
|
|
311
|
-
expect(record.state).toBe('pending');
|
|
312
|
-
expect(record.fingerprint).toBe(computeFingerprint(body));
|
|
313
|
-
});
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
describe('SEC-1: storage key is scoped to the authenticated principal', () => {
|
|
317
|
-
it('two different principals with the same method+path+Idempotency-Key get different storage keys', async () => {
|
|
318
|
-
const store1 = makeStoreMock(undefined);
|
|
319
|
-
const { interceptor: i1 } = buildInterceptor({ hasMetadata: true, store: store1 });
|
|
320
|
-
await runIntercept(
|
|
321
|
-
i1,
|
|
322
|
-
makeContext({
|
|
323
|
-
method: 'POST',
|
|
324
|
-
path: '/orders',
|
|
325
|
-
headers: { 'idempotency-key': 'SAME-KEY' },
|
|
326
|
-
user: { id: 'user-A' },
|
|
327
|
-
statusCode: 200,
|
|
328
|
-
}),
|
|
329
|
-
makeNext({}),
|
|
330
|
-
);
|
|
331
|
-
const key1 = (store1.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
332
|
-
|
|
333
|
-
const store2 = makeStoreMock(undefined);
|
|
334
|
-
const { interceptor: i2 } = buildInterceptor({ hasMetadata: true, store: store2 });
|
|
335
|
-
await runIntercept(
|
|
336
|
-
i2,
|
|
337
|
-
makeContext({
|
|
338
|
-
method: 'POST',
|
|
339
|
-
path: '/orders',
|
|
340
|
-
headers: { 'idempotency-key': 'SAME-KEY' },
|
|
341
|
-
user: { id: 'user-B' },
|
|
342
|
-
statusCode: 200,
|
|
343
|
-
}),
|
|
344
|
-
makeNext({}),
|
|
345
|
-
);
|
|
346
|
-
const key2 = (store2.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
347
|
-
|
|
348
|
-
expect(key1).not.toBe(key2);
|
|
349
|
-
});
|
|
350
|
-
|
|
351
|
-
it('the same principal with the same method+path+Idempotency-Key produces the same storage key', async () => {
|
|
352
|
-
const store1 = makeStoreMock(undefined);
|
|
353
|
-
const { interceptor: i1 } = buildInterceptor({ hasMetadata: true, store: store1 });
|
|
354
|
-
await runIntercept(
|
|
355
|
-
i1,
|
|
356
|
-
makeContext({
|
|
357
|
-
method: 'POST',
|
|
358
|
-
path: '/orders',
|
|
359
|
-
headers: { 'idempotency-key': 'SAME-KEY' },
|
|
360
|
-
user: { id: 'user-A' },
|
|
361
|
-
statusCode: 200,
|
|
362
|
-
}),
|
|
363
|
-
makeNext({}),
|
|
364
|
-
);
|
|
365
|
-
const key1 = (store1.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
366
|
-
|
|
367
|
-
const store2 = makeStoreMock(undefined);
|
|
368
|
-
const { interceptor: i2 } = buildInterceptor({ hasMetadata: true, store: store2 });
|
|
369
|
-
await runIntercept(
|
|
370
|
-
i2,
|
|
371
|
-
makeContext({
|
|
372
|
-
method: 'POST',
|
|
373
|
-
path: '/orders',
|
|
374
|
-
headers: { 'idempotency-key': 'SAME-KEY' },
|
|
375
|
-
user: { id: 'user-A' },
|
|
376
|
-
statusCode: 200,
|
|
377
|
-
}),
|
|
378
|
-
makeNext({}),
|
|
379
|
-
);
|
|
380
|
-
const key2 = (store2.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
381
|
-
|
|
382
|
-
expect(key1).toBe(key2);
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
it('falls back to the unscoped key (method+path+key) when no principal is resolvable', async () => {
|
|
386
|
-
const store = makeStoreMock(undefined);
|
|
387
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
388
|
-
await runIntercept(
|
|
389
|
-
interceptor,
|
|
390
|
-
makeContext({
|
|
391
|
-
method: 'POST',
|
|
392
|
-
path: '/public',
|
|
393
|
-
headers: { 'idempotency-key': 'K' },
|
|
394
|
-
statusCode: 200,
|
|
395
|
-
}),
|
|
396
|
-
makeNext({}),
|
|
397
|
-
);
|
|
398
|
-
const storageKey = (store.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
399
|
-
expect(storageKey).toBe(sha256('POST\n/public\nK'));
|
|
400
|
-
});
|
|
401
|
-
|
|
402
|
-
it('respects a caller-supplied principalExtractor over the default', async () => {
|
|
403
|
-
const store = makeStoreMock(undefined);
|
|
404
|
-
const principalExtractor = jest.fn().mockReturnValue('tenant-42') as InterceptorOptions['principalExtractor'];
|
|
405
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, principalExtractor });
|
|
406
|
-
await runIntercept(
|
|
407
|
-
interceptor,
|
|
408
|
-
makeContext({
|
|
409
|
-
method: 'POST',
|
|
410
|
-
path: '/orders',
|
|
411
|
-
headers: { 'idempotency-key': 'K' },
|
|
412
|
-
statusCode: 200,
|
|
413
|
-
}),
|
|
414
|
-
makeNext({}),
|
|
415
|
-
);
|
|
416
|
-
expect(principalExtractor).toHaveBeenCalled();
|
|
417
|
-
const storageKey = (store.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
418
|
-
expect(storageKey).toBe(sha256('POST\n/orders\ntenant-42\nK'));
|
|
419
|
-
});
|
|
420
|
-
});
|
|
421
|
-
|
|
422
|
-
describe('multi-transport dispatch: non-http contexts are skipped', () => {
|
|
423
|
-
it('skips idempotency handling entirely for an rpc context (no switchToHttp dispatch)', async () => {
|
|
424
|
-
const store = makeStoreMock();
|
|
425
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
426
|
-
const next = makeNext('rpc-response');
|
|
427
|
-
const context = {
|
|
428
|
-
getHandler: () => ({}),
|
|
429
|
-
getType: () => 'rpc',
|
|
430
|
-
switchToHttp: () => {
|
|
431
|
-
throw new Error('should not be called for a non-http context');
|
|
432
|
-
},
|
|
433
|
-
} as unknown as ExecutionContext;
|
|
434
|
-
|
|
435
|
-
const result = await runIntercept(interceptor, context, next);
|
|
436
|
-
expect(result).toBe('rpc-response');
|
|
437
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
438
|
-
});
|
|
439
|
-
});
|
|
440
|
-
|
|
441
|
-
describe('AC5: handler completes with 2xx status', () => {
|
|
442
|
-
it('AC5: calls store.complete once with 2xx status and the emitted response body (success path)', async () => {
|
|
443
|
-
const store = makeStoreMock(undefined);
|
|
444
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
445
|
-
const responseBody = { id: 42 };
|
|
446
|
-
const next = makeNext(responseBody);
|
|
447
|
-
await runIntercept(
|
|
448
|
-
interceptor,
|
|
449
|
-
makeContext({
|
|
450
|
-
statusCode: 200,
|
|
451
|
-
body: { a: 1 },
|
|
452
|
-
responseHeaders: { 'content-type': 'application/json' },
|
|
453
|
-
}),
|
|
454
|
-
next,
|
|
455
|
-
);
|
|
456
|
-
expect(store.complete).toHaveBeenCalledTimes(1);
|
|
457
|
-
const [, completedResponse] = (store.complete as jest.Mock).mock.calls[0] as [string, { status: number; body: unknown }];
|
|
458
|
-
expect(completedResponse.status).toBeGreaterThanOrEqual(200);
|
|
459
|
-
expect(completedResponse.status).toBeLessThan(300);
|
|
460
|
-
expect(completedResponse.body).toEqual(responseBody);
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
it('AC5: does not call store.remove after a 2xx completion (boundary)', async () => {
|
|
464
|
-
const store = makeStoreMock(undefined);
|
|
465
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
466
|
-
await runIntercept(
|
|
467
|
-
interceptor,
|
|
468
|
-
makeContext({ statusCode: 201 }),
|
|
469
|
-
makeNext({ created: true }),
|
|
470
|
-
);
|
|
471
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
472
|
-
});
|
|
473
|
-
|
|
474
|
-
it('AC5: replayHeaders matching is case-insensitive — Content-Type option captures content-type response header', async () => {
|
|
475
|
-
// Spec: HTTP header names are case-insensitive (RFC 7230). A replayHeaders entry
|
|
476
|
-
// of 'Content-Type' must match the lowercase 'content-type' key returned by
|
|
477
|
-
// Express's getHeaders(), so the header is captured in the complete() call.
|
|
478
|
-
const store = makeStoreMock(undefined);
|
|
479
|
-
const options: InterceptorOptions = {
|
|
480
|
-
...defaultOptions,
|
|
481
|
-
replayHeaders: ['Content-Type'],
|
|
482
|
-
};
|
|
483
|
-
const reflector = makeIdempotentReflector(true);
|
|
484
|
-
const { host } = makeHttpAdapterComponents();
|
|
485
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, options);
|
|
486
|
-
await runIntercept(
|
|
487
|
-
interceptor,
|
|
488
|
-
makeContext({
|
|
489
|
-
statusCode: 200,
|
|
490
|
-
responseHeaders: { 'content-type': 'application/json' },
|
|
491
|
-
}),
|
|
492
|
-
makeNext({ id: 1 }),
|
|
493
|
-
);
|
|
494
|
-
expect(store.complete).toHaveBeenCalledTimes(1);
|
|
495
|
-
const [, storedResp] = (store.complete as jest.Mock).mock.calls[0] as [
|
|
496
|
-
string,
|
|
497
|
-
{ headers: Record<string, string> },
|
|
498
|
-
];
|
|
499
|
-
expect(storedResp.headers['content-type']).toBe('application/json');
|
|
500
|
-
});
|
|
501
|
-
});
|
|
502
|
-
|
|
503
|
-
describe('AC6: handler throws', () => {
|
|
504
|
-
it('AC6: calls store.remove once and the original error propagates unchanged (success path)', async () => {
|
|
505
|
-
const store = makeStoreMock(undefined);
|
|
506
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
507
|
-
const handlerError = new Error('handler failure');
|
|
508
|
-
const next = makeNext(handlerError, true);
|
|
509
|
-
let caughtError: unknown;
|
|
510
|
-
try {
|
|
511
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
512
|
-
} catch (err) {
|
|
513
|
-
caughtError = err;
|
|
514
|
-
}
|
|
515
|
-
expect(store.remove).toHaveBeenCalledTimes(1);
|
|
516
|
-
expect(caughtError).toBe(handlerError);
|
|
517
|
-
});
|
|
518
|
-
|
|
519
|
-
it('AC6: does not call store.complete when handler throws (boundary)', async () => {
|
|
520
|
-
const store = makeStoreMock(undefined);
|
|
521
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
522
|
-
const next = makeNext(new Error('boom'), true);
|
|
523
|
-
try {
|
|
524
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
525
|
-
} catch {
|
|
526
|
-
// expected
|
|
527
|
-
}
|
|
528
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
529
|
-
});
|
|
530
|
-
});
|
|
531
|
-
|
|
532
|
-
describe('AC7: putIfAbsent resolves an existing record with state=pending (matching fingerprint)', () => {
|
|
533
|
-
it('AC7: throws IdempotencyConflictException with httpStatus 409 (success path)', async () => {
|
|
534
|
-
const body = { a: 1 };
|
|
535
|
-
const existingRecord: IdempotencyRecord = {
|
|
536
|
-
state: 'pending',
|
|
537
|
-
fingerprint: computeFingerprint(body),
|
|
538
|
-
createdAt: Date.now(),
|
|
539
|
-
};
|
|
540
|
-
const store = makeStoreMock(existingRecord);
|
|
541
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
542
|
-
const err = await captureInterceptError(interceptor, makeContext({ body }), makeNext('ignored'));
|
|
543
|
-
expect(err).toBeInstanceOf(IdempotencyConflictException);
|
|
544
|
-
expect((err as IdempotencyConflictException).httpStatus).toBe(409);
|
|
545
|
-
});
|
|
546
|
-
|
|
547
|
-
it('AC7: does not call next.handle() when putIfAbsent returns a pending record (boundary)', async () => {
|
|
548
|
-
const body = { a: 1 };
|
|
549
|
-
const existingRecord: IdempotencyRecord = {
|
|
550
|
-
state: 'pending',
|
|
551
|
-
fingerprint: computeFingerprint(body),
|
|
552
|
-
createdAt: Date.now(),
|
|
553
|
-
};
|
|
554
|
-
const store = makeStoreMock(existingRecord);
|
|
555
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
556
|
-
const next = makeNext('ignored');
|
|
557
|
-
await captureInterceptError(interceptor, makeContext({ body }), next);
|
|
558
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
559
|
-
});
|
|
560
|
-
});
|
|
561
|
-
|
|
562
|
-
describe('AC8: putIfAbsent resolves a record whose fingerprint differs from current request', () => {
|
|
563
|
-
it('AC8: throws IdempotencyKeyReuseException with httpStatus 422 (success path)', async () => {
|
|
564
|
-
const currentBody = { a: 1 };
|
|
565
|
-
const existingRecord: IdempotencyRecord = {
|
|
566
|
-
state: 'pending',
|
|
567
|
-
fingerprint: computeFingerprint({ a: 2 }),
|
|
568
|
-
createdAt: Date.now(),
|
|
569
|
-
};
|
|
570
|
-
const store = makeStoreMock(existingRecord);
|
|
571
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
572
|
-
const err = await captureInterceptError(interceptor, makeContext({ body: currentBody }), makeNext('ignored'));
|
|
573
|
-
expect(err).toBeInstanceOf(IdempotencyKeyReuseException);
|
|
574
|
-
expect((err as IdempotencyKeyReuseException).httpStatus).toBe(422);
|
|
575
|
-
});
|
|
576
|
-
|
|
577
|
-
it('AC8: does not call next.handle() when fingerprint differs (boundary)', async () => {
|
|
578
|
-
const currentBody = { a: 1 };
|
|
579
|
-
const existingRecord: IdempotencyRecord = {
|
|
580
|
-
state: 'pending',
|
|
581
|
-
fingerprint: computeFingerprint({ b: 99 }),
|
|
582
|
-
createdAt: Date.now(),
|
|
583
|
-
};
|
|
584
|
-
const store = makeStoreMock(existingRecord);
|
|
585
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
586
|
-
const next = makeNext('ignored');
|
|
587
|
-
await captureInterceptError(interceptor, makeContext({ body: currentBody }), next);
|
|
588
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
589
|
-
});
|
|
590
|
-
});
|
|
591
|
-
|
|
592
|
-
describe('AC9: putIfAbsent resolves an existing completed record (replay path)', () => {
|
|
593
|
-
it('AC9: calls httpAdapter.reply with stored body and status (success path)', async () => {
|
|
594
|
-
const storedResponse = {
|
|
595
|
-
status: 201,
|
|
596
|
-
body: { id: 7 },
|
|
597
|
-
headers: { 'content-type': 'application/json' },
|
|
598
|
-
};
|
|
599
|
-
const completedRecord: IdempotencyRecord = {
|
|
600
|
-
state: 'completed',
|
|
601
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
602
|
-
createdAt: Date.now(),
|
|
603
|
-
response: storedResponse,
|
|
604
|
-
};
|
|
605
|
-
const store = makeStoreMock(completedRecord);
|
|
606
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
607
|
-
const reflector = makeIdempotentReflector(true);
|
|
608
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
609
|
-
|
|
610
|
-
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
611
|
-
|
|
612
|
-
expect(httpAdapter.reply).toHaveBeenCalledTimes(1);
|
|
613
|
-
const replyArgs = (httpAdapter.reply as jest.Mock).mock.calls[0] as [unknown, unknown, number];
|
|
614
|
-
expect(replyArgs[1]).toEqual(storedResponse.body);
|
|
615
|
-
expect(replyArgs[2]).toBe(storedResponse.status);
|
|
616
|
-
});
|
|
617
|
-
|
|
618
|
-
it('AC9: calls httpAdapter.setHeader for each allowlisted stored response header (success path)', async () => {
|
|
619
|
-
const storedResponse = {
|
|
620
|
-
status: 200,
|
|
621
|
-
body: { ok: true },
|
|
622
|
-
headers: {
|
|
623
|
-
'content-type': 'application/json',
|
|
624
|
-
'x-secret': 'should-not-appear',
|
|
625
|
-
},
|
|
626
|
-
};
|
|
627
|
-
const completedRecord: IdempotencyRecord = {
|
|
628
|
-
state: 'completed',
|
|
629
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
630
|
-
createdAt: Date.now(),
|
|
631
|
-
response: storedResponse,
|
|
632
|
-
};
|
|
633
|
-
const store = makeStoreMock(completedRecord);
|
|
634
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
635
|
-
const reflector = makeIdempotentReflector(true);
|
|
636
|
-
// replayHeaders = ['content-type'] — only this one is allowlisted
|
|
637
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
638
|
-
|
|
639
|
-
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
640
|
-
|
|
641
|
-
expect(httpAdapter.setHeader).toHaveBeenCalledWith(
|
|
642
|
-
expect.anything(),
|
|
643
|
-
'content-type',
|
|
644
|
-
'application/json',
|
|
645
|
-
);
|
|
646
|
-
const setHeaderCalls = (httpAdapter.setHeader as jest.Mock).mock.calls.map(
|
|
647
|
-
(c) => (c as [unknown, string, string])[1],
|
|
648
|
-
);
|
|
649
|
-
expect(setHeaderCalls).not.toContain('x-secret');
|
|
650
|
-
});
|
|
651
|
-
|
|
652
|
-
it('AC9: does not call next.handle() when replaying a completed record (boundary)', async () => {
|
|
653
|
-
const completedRecord: IdempotencyRecord = {
|
|
654
|
-
state: 'completed',
|
|
655
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
656
|
-
createdAt: Date.now(),
|
|
657
|
-
response: { status: 200, body: { ok: true }, headers: { 'content-type': 'application/json' } },
|
|
658
|
-
};
|
|
659
|
-
const store = makeStoreMock(completedRecord);
|
|
660
|
-
const { host } = makeHttpAdapterComponents();
|
|
661
|
-
const reflector = makeIdempotentReflector(true);
|
|
662
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
663
|
-
const next = makeNext('ignored');
|
|
664
|
-
|
|
665
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
666
|
-
|
|
667
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
668
|
-
});
|
|
669
|
-
|
|
670
|
-
it('AC9: replayHeaders matching is case-insensitive — Content-Type option triggers setHeader for content-type stored header', async () => {
|
|
671
|
-
// Spec: during replay the stored header key is lowercase (captured from getHeaders()).
|
|
672
|
-
// A replayHeaders entry of 'Content-Type' must still match it case-insensitively.
|
|
673
|
-
const storedResponse = {
|
|
674
|
-
status: 200,
|
|
675
|
-
body: { ok: true },
|
|
676
|
-
headers: { 'content-type': 'application/json' },
|
|
677
|
-
};
|
|
678
|
-
const completedRecord: IdempotencyRecord = {
|
|
679
|
-
state: 'completed',
|
|
680
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
681
|
-
createdAt: Date.now(),
|
|
682
|
-
response: storedResponse,
|
|
683
|
-
};
|
|
684
|
-
const store = makeStoreMock(completedRecord);
|
|
685
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
686
|
-
const reflector = makeIdempotentReflector(true);
|
|
687
|
-
const options: InterceptorOptions = {
|
|
688
|
-
...defaultOptions,
|
|
689
|
-
replayHeaders: ['Content-Type'],
|
|
690
|
-
};
|
|
691
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, options);
|
|
692
|
-
|
|
693
|
-
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
694
|
-
|
|
695
|
-
expect(httpAdapter.setHeader).toHaveBeenCalledWith(
|
|
696
|
-
expect.anything(),
|
|
697
|
-
'content-type',
|
|
698
|
-
'application/json',
|
|
699
|
-
);
|
|
700
|
-
});
|
|
701
|
-
|
|
702
|
-
it('AC9: does not call store.complete or store.remove during replay (boundary)', async () => {
|
|
703
|
-
const completedRecord: IdempotencyRecord = {
|
|
704
|
-
state: 'completed',
|
|
705
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
706
|
-
createdAt: Date.now(),
|
|
707
|
-
response: { status: 200, body: {}, headers: { 'content-type': 'application/json' } },
|
|
708
|
-
};
|
|
709
|
-
const store = makeStoreMock(completedRecord);
|
|
710
|
-
const { host } = makeHttpAdapterComponents();
|
|
711
|
-
const reflector = makeIdempotentReflector(true);
|
|
712
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
713
|
-
|
|
714
|
-
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
715
|
-
|
|
716
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
717
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
718
|
-
});
|
|
719
|
-
|
|
720
|
-
it('AC8/AC9: throws IdempotencyKeyReuseException (422) when an existing completed record has a mismatched fingerprint, instead of replaying', async () => {
|
|
721
|
-
const completedRecord: IdempotencyRecord = {
|
|
722
|
-
state: 'completed',
|
|
723
|
-
fingerprint: computeFingerprint({ a: 2 }),
|
|
724
|
-
createdAt: Date.now(),
|
|
725
|
-
response: { status: 200, body: { ok: true }, headers: { 'content-type': 'application/json' } },
|
|
726
|
-
};
|
|
727
|
-
const store = makeStoreMock(completedRecord);
|
|
728
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
729
|
-
const reflector = makeIdempotentReflector(true);
|
|
730
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
731
|
-
|
|
732
|
-
const err = await captureInterceptError(interceptor, makeContext({ body: { a: 1 } }), makeNext('ignored'));
|
|
733
|
-
|
|
734
|
-
expect(err).toBeInstanceOf(IdempotencyKeyReuseException);
|
|
735
|
-
expect((err as IdempotencyKeyReuseException).httpStatus).toBe(422);
|
|
736
|
-
expect(httpAdapter.reply).not.toHaveBeenCalled();
|
|
737
|
-
});
|
|
738
|
-
});
|
|
739
|
-
});
|