@nathapp/nestjs-outbox 4.0.0 → 4.0.2
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/interface/outbox-module-options.interface.d.ts +1 -0
- package/dist/provider/outbox-relay.js +17 -5
- package/dist/provider/outbox-relay.js.map +1 -1
- package/dist/provider/outbox.service.d.ts +4 -1
- package/dist/provider/outbox.service.js +9 -2
- package/dist/provider/outbox.service.js.map +1 -1
- package/dist/provider/resolve-outbox-options.d.ts +2 -0
- package/dist/provider/resolve-outbox-options.js +3 -1
- package/dist/provider/resolve-outbox-options.js.map +1 -1
- package/dist/util/compute-backoff.js +2 -1
- package/dist/util/compute-backoff.js.map +1 -1
- package/package.json +6 -6
- package/.eslintrc.js +0 -8
- package/.nax/features/nestjs-outbox/.nax-acceptance.test.ts +0 -878
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -43
- package/lib/constant/index.ts +0 -1
- package/lib/constant/outbox.constants.ts +0 -3
- package/lib/exception/index.ts +0 -3
- package/lib/exception/outbox-exception-code.enum.ts +0 -4
- package/lib/exception/outbox-invalid-event.exception.ts +0 -9
- package/lib/exception/outbox-misconfigured.exception.ts +0 -9
- package/lib/index.ts +0 -6
- package/lib/interface/index.ts +0 -18
- package/lib/interface/outbox-module-options.interface.ts +0 -18
- package/lib/interface/outbox-publisher.interface.ts +0 -5
- package/lib/interface/outbox-record.interface.ts +0 -23
- package/lib/interface/outbox-status.enum.ts +0 -6
- package/lib/interface/outbox-store.interface.ts +0 -23
- package/lib/module/index.ts +0 -1
- package/lib/module/outbox.module.ts +0 -64
- package/lib/provider/in-memory-outbox-store.ts +0 -114
- package/lib/provider/index.ts +0 -4
- package/lib/provider/outbox-relay.ts +0 -147
- package/lib/provider/outbox.service.ts +0 -70
- package/lib/provider/resolve-outbox-options.ts +0 -51
- package/lib/util/compute-backoff.ts +0 -4
- package/lib/util/index.ts +0 -1
- package/test/barrel/index.spec.ts +0 -45
- package/test/constant/outbox.constants.spec.ts +0 -20
- package/test/e2e/outbox.module.spec.ts +0 -371
- package/test/exception/outbox.exceptions.spec.ts +0 -38
- package/test/interface/outbox-status.enum.spec.ts +0 -19
- package/test/jest-nax-setup.js +0 -31
- package/test/jest-nax.json +0 -30
- package/test/jest-test.json +0 -28
- package/test/module/outbox.module.spec.ts +0 -139
- package/test/provider/in-memory-outbox-store.spec.ts +0 -216
- package/test/provider/outbox-relay.spec.ts +0 -565
- package/test/provider/outbox-service.spec.ts +0 -229
- package/test/provider/resolve-outbox-options.spec.ts +0 -50
- package/test/util/compute-backoff.spec.ts +0 -25
- package/tsconfig.json +0 -9
|
@@ -1,878 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, beforeEach, afterEach, jest } from '@jest/globals';
|
|
2
|
-
import { Test } from '@nestjs/testing';
|
|
3
|
-
import { AppException } from '@nathapp/nestjs-common';
|
|
4
|
-
import { CLOCK, SystemClock } from '@nathapp/nestjs-common';
|
|
5
|
-
import { ID_GENERATOR, UuidIdGenerator } from '@nathapp/nestjs-common';
|
|
6
|
-
import { TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
|
|
7
|
-
|
|
8
|
-
import {
|
|
9
|
-
OutboxModule,
|
|
10
|
-
OutboxService,
|
|
11
|
-
OutboxRelay,
|
|
12
|
-
InMemoryOutboxStore,
|
|
13
|
-
OutboxInvalidEventException,
|
|
14
|
-
OutboxMisconfiguredException,
|
|
15
|
-
OUTBOX_STORE,
|
|
16
|
-
} from '../../../lib';
|
|
17
|
-
|
|
18
|
-
import { OutboxStatus } from '../../../lib/interface';
|
|
19
|
-
import { resolveOutboxOptions } from '../../../lib/provider/resolve-outbox-options';
|
|
20
|
-
import { computeBackoff } from '../../../lib/util/compute-backoff';
|
|
21
|
-
import { OutboxExceptionCode } from '../../../lib/exception/outbox-exception-code.enum';
|
|
22
|
-
import { OUTBOX_PUBLISHER, OUTBOX_MODULE_OPTIONS } from '../../../lib/constant';
|
|
23
|
-
|
|
24
|
-
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
25
|
-
|
|
26
|
-
const makeRecord = (overrides: Partial<{
|
|
27
|
-
id: string;
|
|
28
|
-
type: string;
|
|
29
|
-
payload: unknown;
|
|
30
|
-
status: string;
|
|
31
|
-
attempts: number;
|
|
32
|
-
createdAt: Date;
|
|
33
|
-
nextAttemptAt: Date;
|
|
34
|
-
leaseUntil?: Date;
|
|
35
|
-
owner?: string;
|
|
36
|
-
publishedAt?: Date;
|
|
37
|
-
headers?: Record<string, string>;
|
|
38
|
-
metadata?: Record<string, unknown>;
|
|
39
|
-
}> = {}) => ({
|
|
40
|
-
id: overrides.id ?? 'r1',
|
|
41
|
-
type: overrides.type ?? 'test.event',
|
|
42
|
-
payload: overrides.payload ?? { val: 1 },
|
|
43
|
-
status: overrides.status ?? OutboxStatus.PENDING,
|
|
44
|
-
attempts: overrides.attempts ?? 0,
|
|
45
|
-
createdAt: overrides.createdAt ?? new Date(),
|
|
46
|
-
nextAttemptAt: overrides.nextAttemptAt ?? new Date(Date.now() - 1000),
|
|
47
|
-
leaseUntil: overrides.leaseUntil,
|
|
48
|
-
owner: overrides.owner,
|
|
49
|
-
publishedAt: overrides.publishedAt,
|
|
50
|
-
headers: overrides.headers,
|
|
51
|
-
metadata: overrides.metadata,
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
const makeStoreMock = () => ({
|
|
55
|
-
save: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
56
|
-
claimBatch: jest.fn<() => Promise<any[]>>().mockResolvedValue([]),
|
|
57
|
-
markPublished: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
58
|
-
markRetry: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
59
|
-
markDead: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
const makePublisherMock = () => ({
|
|
63
|
-
publish: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
const makeTxManagerMock = () => {
|
|
67
|
-
const client = {};
|
|
68
|
-
return {
|
|
69
|
-
getClient: jest.fn<() => unknown>().mockReturnValue(client),
|
|
70
|
-
run: jest.fn(),
|
|
71
|
-
isInTransaction: jest.fn().mockReturnValue(false),
|
|
72
|
-
_client: client,
|
|
73
|
-
};
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const makeClockMock = (fixedDate?: Date) => {
|
|
77
|
-
const date = fixedDate ?? new Date('2024-06-01T00:00:00.000Z');
|
|
78
|
-
return {
|
|
79
|
-
now: jest.fn<() => Date>().mockReturnValue(date),
|
|
80
|
-
_date: date,
|
|
81
|
-
};
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
const makeIdGenMock = (id = 'test-uuid-1234') => ({
|
|
85
|
-
generate: jest.fn<() => string>().mockReturnValue(id),
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
89
|
-
// US-001: Outbox primitives
|
|
90
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
91
|
-
|
|
92
|
-
describe('US-001: Outbox primitives', () => {
|
|
93
|
-
it('AC-1: OutboxStatus enum values equal the correct strings', () => {
|
|
94
|
-
expect(OutboxStatus.PENDING).toBe('pending');
|
|
95
|
-
expect(OutboxStatus.PROCESSING).toBe('processing');
|
|
96
|
-
expect(OutboxStatus.PUBLISHED).toBe('published');
|
|
97
|
-
expect(OutboxStatus.DEAD).toBe('dead');
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
it('AC-2: resolveOutboxOptions(undefined) returns all relay defaults', () => {
|
|
101
|
-
const result = resolveOutboxOptions(undefined);
|
|
102
|
-
expect(result.relay.enabled).toBe(true);
|
|
103
|
-
expect(result.relay.pollIntervalMs).toBe(5000);
|
|
104
|
-
expect(result.relay.batchSize).toBe(10);
|
|
105
|
-
expect(result.relay.leaseMs).toBe(30000);
|
|
106
|
-
expect(result.relay.maxAttempts).toBe(10);
|
|
107
|
-
expect(result.relay.backoffBaseMs).toBe(1000);
|
|
108
|
-
expect(result.relay.backoffCapMs).toBe(300000);
|
|
109
|
-
});
|
|
110
|
-
|
|
111
|
-
it('AC-3: resolveOutboxOptions({}) returns InMemoryOutboxStore and undefined publisher', () => {
|
|
112
|
-
const result = resolveOutboxOptions({});
|
|
113
|
-
expect(result.store).toBeInstanceOf(InMemoryOutboxStore);
|
|
114
|
-
expect(result.publisher).toBeUndefined();
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
it('AC-4: resolveOutboxOptions with partial relay overrides merges with defaults', () => {
|
|
118
|
-
const result = resolveOutboxOptions({ relay: { pollIntervalMs: 100, batchSize: 3, maxAttempts: 2 } });
|
|
119
|
-
expect(result.relay.pollIntervalMs).toBe(100);
|
|
120
|
-
expect(result.relay.batchSize).toBe(3);
|
|
121
|
-
expect(result.relay.maxAttempts).toBe(2);
|
|
122
|
-
expect(result.relay.leaseMs).toBe(30000);
|
|
123
|
-
expect(result.relay.backoffBaseMs).toBe(1000);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
it('AC-5: resolveOutboxOptions with custom store and publisher returns same instances', () => {
|
|
127
|
-
const store = new InMemoryOutboxStore();
|
|
128
|
-
const publisher = makePublisherMock();
|
|
129
|
-
const result = resolveOutboxOptions({ store, publisher });
|
|
130
|
-
expect(result.store).toBe(store);
|
|
131
|
-
expect(result.publisher).toBe(publisher);
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
it('AC-6: computeBackoff returns correct exponential values for attempts 1, 2, 3', () => {
|
|
135
|
-
expect(computeBackoff(1, 1000, 300000)).toBe(1000);
|
|
136
|
-
expect(computeBackoff(2, 1000, 300000)).toBe(2000);
|
|
137
|
-
expect(computeBackoff(3, 1000, 300000)).toBe(4000);
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
it('AC-7: computeBackoff(50) is capped at capMs and does not exceed it', () => {
|
|
141
|
-
const result = computeBackoff(50, 1000, 300000);
|
|
142
|
-
expect(result).toBe(300000);
|
|
143
|
-
expect(result).toBeLessThanOrEqual(300000);
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
it('AC-8: OutboxInvalidEventException is AppException with httpStatus 400 and correct code', () => {
|
|
147
|
-
const ex = new OutboxInvalidEventException();
|
|
148
|
-
expect(ex).toBeInstanceOf(AppException);
|
|
149
|
-
expect(ex.httpStatus).toBe(400);
|
|
150
|
-
expect(ex.code).toBe(OutboxExceptionCode.INVALID_EVENT_TYPE);
|
|
151
|
-
expect(OutboxExceptionCode.INVALID_EVENT_TYPE).toBe(40010);
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
it('AC-9: OutboxMisconfiguredException is AppException with httpStatus 500 and correct code', () => {
|
|
155
|
-
const ex = new OutboxMisconfiguredException();
|
|
156
|
-
expect(ex).toBeInstanceOf(AppException);
|
|
157
|
-
expect(ex.httpStatus).toBe(500);
|
|
158
|
-
expect(ex.code).toBe(OutboxExceptionCode.PUBLISHER_NOT_CONFIGURED);
|
|
159
|
-
expect(OutboxExceptionCode.PUBLISHER_NOT_CONFIGURED).toBe(50010);
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it('AC-10: OUTBOX_STORE and OUTBOX_PUBLISHER are symbols equal to their Symbol.for equivalents', () => {
|
|
163
|
-
expect(OUTBOX_STORE).toBe(Symbol.for('OUTBOX_STORE'));
|
|
164
|
-
expect(OUTBOX_PUBLISHER).toBe(Symbol.for('OUTBOX_PUBLISHER'));
|
|
165
|
-
});
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
169
|
-
// US-002: InMemoryOutboxStore
|
|
170
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
171
|
-
|
|
172
|
-
describe('US-002: InMemoryOutboxStore', () => {
|
|
173
|
-
let store: InMemoryOutboxStore;
|
|
174
|
-
const now = new Date('2024-06-01T00:00:00.000Z');
|
|
175
|
-
|
|
176
|
-
beforeEach(() => {
|
|
177
|
-
store = new InMemoryOutboxStore();
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
it('AC-11: save + claimBatch returns the saved record when nextAttemptAt <= now', async () => {
|
|
181
|
-
const record = makeRecord({ id: 'r1', status: OutboxStatus.PENDING, nextAttemptAt: new Date(now.getTime() - 1) });
|
|
182
|
-
await store.save(record as any, {});
|
|
183
|
-
const result = await store.claimBatch(10, 30000, now, 'owner-1');
|
|
184
|
-
expect(Array.isArray(result)).toBe(true);
|
|
185
|
-
expect(result.length).toBe(1);
|
|
186
|
-
expect(result[0].id).toBe('r1');
|
|
187
|
-
expect(result[0].status).toBe(OutboxStatus.PROCESSING);
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
it('AC-12: claimed records have correct status, owner, and leaseUntil', async () => {
|
|
191
|
-
for (let i = 0; i < 3; i++) {
|
|
192
|
-
const record = makeRecord({ id: `r${i}`, nextAttemptAt: new Date(now.getTime() - 1) });
|
|
193
|
-
await store.save(record as any, {});
|
|
194
|
-
}
|
|
195
|
-
const result = await store.claimBatch(10, 30000, now, 'owner-1');
|
|
196
|
-
expect(result.length).toBe(3);
|
|
197
|
-
for (const r of result) {
|
|
198
|
-
expect(r.status).toBe(OutboxStatus.PROCESSING);
|
|
199
|
-
expect(r.owner).toBe('owner-1');
|
|
200
|
-
expect(r.leaseUntil).toBeInstanceOf(Date);
|
|
201
|
-
expect(r.leaseUntil!.getTime()).toBe(now.getTime() + 30000);
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
it('AC-13: claimBatch respects the limit parameter', async () => {
|
|
206
|
-
for (let i = 0; i < 5; i++) {
|
|
207
|
-
const record = makeRecord({ id: `r${i}`, nextAttemptAt: new Date(now.getTime() - 1) });
|
|
208
|
-
await store.save(record as any, {});
|
|
209
|
-
}
|
|
210
|
-
const result = await store.claimBatch(2, 30000, now, 'o');
|
|
211
|
-
expect(result.length).toBe(2);
|
|
212
|
-
});
|
|
213
|
-
|
|
214
|
-
it('AC-14: record with nextAttemptAt strictly after now is not claimed', async () => {
|
|
215
|
-
const record = makeRecord({ id: 'r1', status: OutboxStatus.PENDING, nextAttemptAt: new Date(now.getTime() + 1000) });
|
|
216
|
-
await store.save(record as any, {});
|
|
217
|
-
const result = await store.claimBatch(10, 30000, now, 'o');
|
|
218
|
-
expect(result.find(r => r.id === 'r1')).toBeUndefined();
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
it('AC-15: record claimed by o1 is not returned by a second claimBatch by o2 (exclusivity)', async () => {
|
|
222
|
-
const record = makeRecord({ id: 'r1', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
223
|
-
await store.save(record as any, {});
|
|
224
|
-
const result1 = await store.claimBatch(10, 30000, now, 'o1');
|
|
225
|
-
expect(result1.find(r => r.id === 'r1')).toBeDefined();
|
|
226
|
-
const result2 = await store.claimBatch(10, 30000, now, 'o2');
|
|
227
|
-
expect(result2.find(r => r.id === 'r1')).toBeUndefined();
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
it('AC-16: expired lease allows record to be reclaimed', async () => {
|
|
231
|
-
const record = makeRecord({ id: 'r1', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
232
|
-
await store.save(record as any, {});
|
|
233
|
-
const now1 = now;
|
|
234
|
-
await store.claimBatch(10, 30000, now1, 'o1');
|
|
235
|
-
const now2 = new Date(now1.getTime() + 30000);
|
|
236
|
-
const result = await store.claimBatch(10, 30000, now2, 'o3');
|
|
237
|
-
expect(result.some(r => r.id === 'r1')).toBe(true);
|
|
238
|
-
});
|
|
239
|
-
|
|
240
|
-
it('AC-17: markPublished sets status PUBLISHED and prevents future claims', async () => {
|
|
241
|
-
const record = makeRecord({ id: 'r1', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
242
|
-
await store.save(record as any, {});
|
|
243
|
-
await store.claimBatch(10, 30000, now, 'o');
|
|
244
|
-
const publishedAt = new Date(now.getTime() + 100);
|
|
245
|
-
await store.markPublished('r1', publishedAt, 'o');
|
|
246
|
-
const laterNow = new Date(now.getTime() + 60000);
|
|
247
|
-
const result = await store.claimBatch(10, 30000, laterNow, 'o');
|
|
248
|
-
expect(result.find(r => r.id === 'r1')).toBeUndefined();
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
it('AC-18: markRetry sets PENDING + attempts + futureDate, claimBatch respects the future date', async () => {
|
|
252
|
-
const record = makeRecord({ id: 'r1', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
253
|
-
await store.save(record as any, {});
|
|
254
|
-
await store.claimBatch(10, 30000, now, 'o');
|
|
255
|
-
const futureDate = new Date(now.getTime() + 5000);
|
|
256
|
-
await store.markRetry('r1', 3, futureDate, 'o');
|
|
257
|
-
const beforeFuture = new Date(futureDate.getTime() - 1);
|
|
258
|
-
const resultBefore = await store.claimBatch(10, 30000, beforeFuture, 'o');
|
|
259
|
-
expect(resultBefore.find(r => r.id === 'r1')).toBeUndefined();
|
|
260
|
-
const afterFuture = new Date(futureDate.getTime() + 1);
|
|
261
|
-
const resultAfter = await store.claimBatch(10, 30000, afterFuture, 'o');
|
|
262
|
-
const reClaimed = resultAfter.find(r => r.id === 'r1');
|
|
263
|
-
expect(reClaimed).toBeDefined();
|
|
264
|
-
expect(reClaimed!.status).toBe(OutboxStatus.PROCESSING);
|
|
265
|
-
expect(reClaimed!.attempts).toBe(3);
|
|
266
|
-
});
|
|
267
|
-
|
|
268
|
-
it('AC-19: markDead sets DEAD and record is never returned by claimBatch again', async () => {
|
|
269
|
-
const record = makeRecord({ id: 'r1', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
270
|
-
await store.save(record as any, {});
|
|
271
|
-
await store.claimBatch(10, 30000, now, 'o');
|
|
272
|
-
await store.markDead('r1', 10, 'o');
|
|
273
|
-
const laterNow = new Date(now.getTime() + 60000);
|
|
274
|
-
const result = await store.claimBatch(10, 30000, laterNow, 'o');
|
|
275
|
-
expect(result.find(r => r.id === 'r1')).toBeUndefined();
|
|
276
|
-
// verify store still functional
|
|
277
|
-
const r2 = makeRecord({ id: 'r2', nextAttemptAt: new Date(laterNow.getTime() - 1) });
|
|
278
|
-
await store.save(r2 as any, {});
|
|
279
|
-
const result2 = await store.claimBatch(10, 30000, laterNow, 'o');
|
|
280
|
-
expect(result2.length).toBeGreaterThanOrEqual(1);
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
it('AC-20: payload with Date is preserved as live object reference (not re-serialized)', async () => {
|
|
284
|
-
const payload = { createdAt: new Date('2024-01-01'), value: 42 };
|
|
285
|
-
const record = makeRecord({ id: 'r1', payload, nextAttemptAt: new Date(now.getTime() - 1) });
|
|
286
|
-
await store.save(record as any, {});
|
|
287
|
-
const result = await store.claimBatch(10, 30000, now, 'o');
|
|
288
|
-
expect(result[0].payload).toBeDefined();
|
|
289
|
-
const p = result[0].payload as typeof payload;
|
|
290
|
-
expect(p.createdAt).toBeInstanceOf(Date);
|
|
291
|
-
expect(p.createdAt.getTime()).toBe(new Date('2024-01-01').getTime());
|
|
292
|
-
expect(p.value).toBe(42);
|
|
293
|
-
});
|
|
294
|
-
});
|
|
295
|
-
|
|
296
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
297
|
-
// US-003: OutboxService
|
|
298
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
299
|
-
|
|
300
|
-
describe('US-003: OutboxService', () => {
|
|
301
|
-
const buildService = async (opts: {
|
|
302
|
-
clock?: ReturnType<typeof makeClockMock>;
|
|
303
|
-
idGen?: ReturnType<typeof makeIdGenMock>;
|
|
304
|
-
store?: ReturnType<typeof makeStoreMock>;
|
|
305
|
-
txManager?: ReturnType<typeof makeTxManagerMock>;
|
|
306
|
-
omitClock?: boolean;
|
|
307
|
-
omitIdGen?: boolean;
|
|
308
|
-
} = {}) => {
|
|
309
|
-
const store = opts.store ?? makeStoreMock();
|
|
310
|
-
const txManager = opts.txManager ?? makeTxManagerMock();
|
|
311
|
-
const clock = opts.clock ?? makeClockMock();
|
|
312
|
-
const idGen = opts.idGen ?? makeIdGenMock();
|
|
313
|
-
const providers: any[] = [
|
|
314
|
-
OutboxService,
|
|
315
|
-
{ provide: TRANSACTION_MANAGER, useValue: txManager },
|
|
316
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
317
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolveOutboxOptions({}) },
|
|
318
|
-
];
|
|
319
|
-
if (!opts.omitClock) providers.push({ provide: CLOCK, useValue: clock });
|
|
320
|
-
if (!opts.omitIdGen) providers.push({ provide: ID_GENERATOR, useValue: idGen });
|
|
321
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
322
|
-
return { service: moduleRef.get(OutboxService), store, txManager, clock, idGen };
|
|
323
|
-
};
|
|
324
|
-
|
|
325
|
-
it('AC-21: record({ type: "" }) rejects with OutboxInvalidEventException (400) and save never called', async () => {
|
|
326
|
-
const store = makeStoreMock();
|
|
327
|
-
const { service } = await buildService({ store });
|
|
328
|
-
await expect(service.record({ type: '', payload: {} })).rejects.toBeInstanceOf(OutboxInvalidEventException);
|
|
329
|
-
try {
|
|
330
|
-
await service.record({ type: '', payload: {} });
|
|
331
|
-
} catch (ex: any) {
|
|
332
|
-
expect(ex.httpStatus).toBe(400);
|
|
333
|
-
}
|
|
334
|
-
expect((store.save as jest.Mock).mock.calls.length).toBe(0);
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
it('AC-22: record({ type: " " }) rejects with OutboxInvalidEventException and save never called', async () => {
|
|
338
|
-
const store = makeStoreMock();
|
|
339
|
-
const { service } = await buildService({ store });
|
|
340
|
-
await expect(service.record({ type: ' ', payload: {} })).rejects.toBeInstanceOf(OutboxInvalidEventException);
|
|
341
|
-
expect((store.save as jest.Mock).mock.calls.length).toBe(0);
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
it('AC-23: getClient called once, save called once with the exact client object', async () => {
|
|
345
|
-
const txManager = makeTxManagerMock();
|
|
346
|
-
const store = makeStoreMock();
|
|
347
|
-
const { service } = await buildService({ txManager, store });
|
|
348
|
-
await service.record({ type: 'user.created', payload: { x: 1 } });
|
|
349
|
-
expect((txManager.getClient as jest.Mock).mock.calls.length).toBe(1);
|
|
350
|
-
expect((store.save as jest.Mock).mock.calls.length).toBe(1);
|
|
351
|
-
const txClient = (txManager.getClient as jest.Mock).mock.results[0].value;
|
|
352
|
-
const savedClient = (store.save as jest.Mock).mock.calls[0][1];
|
|
353
|
-
expect(savedClient).toBe(txClient);
|
|
354
|
-
});
|
|
355
|
-
|
|
356
|
-
it('AC-24: saved record has correct status, attempts, id, type, and payload', async () => {
|
|
357
|
-
const idGen = makeIdGenMock('my-uuid-42');
|
|
358
|
-
const store = makeStoreMock();
|
|
359
|
-
const { service } = await buildService({ idGen, store });
|
|
360
|
-
await service.record({ type: 'user.created', payload: { x: 1 } });
|
|
361
|
-
const savedRecord = (store.save as jest.Mock).mock.calls[0][0] as any;
|
|
362
|
-
expect(savedRecord.status).toBe(OutboxStatus.PENDING);
|
|
363
|
-
expect(savedRecord.attempts).toBe(0);
|
|
364
|
-
expect(savedRecord.id).toBe('my-uuid-42');
|
|
365
|
-
expect(savedRecord.type).toBe('user.created');
|
|
366
|
-
expect(savedRecord.payload).toEqual({ x: 1 });
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
it('AC-25: createdAt equals clock.now(), nextAttemptAt <= createdAt, and record() resolves to the saved record', async () => {
|
|
370
|
-
const fixedDate = new Date('2024-06-01T12:00:00.000Z');
|
|
371
|
-
const clock = makeClockMock(fixedDate);
|
|
372
|
-
const store = makeStoreMock();
|
|
373
|
-
const { service } = await buildService({ clock, store });
|
|
374
|
-
const result = await service.record({ type: 'user.created', payload: { x: 1 } });
|
|
375
|
-
const savedRecord = (store.save as jest.Mock).mock.calls[0][0] as any;
|
|
376
|
-
expect(savedRecord.createdAt.getTime()).toBe(fixedDate.getTime());
|
|
377
|
-
expect(savedRecord.nextAttemptAt.getTime()).toBeLessThanOrEqual(savedRecord.createdAt.getTime());
|
|
378
|
-
expect(result).toEqual(savedRecord);
|
|
379
|
-
});
|
|
380
|
-
|
|
381
|
-
it('AC-26: headers and metadata pass through to the saved record', async () => {
|
|
382
|
-
const store = makeStoreMock();
|
|
383
|
-
const { service } = await buildService({ store });
|
|
384
|
-
await service.record({ type: 't', payload: {}, headers: { 'x-h': '1' }, metadata: { a: 2 } });
|
|
385
|
-
const savedRecord = (store.save as jest.Mock).mock.calls[0][0] as any;
|
|
386
|
-
expect(savedRecord.headers).toEqual({ 'x-h': '1' });
|
|
387
|
-
expect(savedRecord.metadata).toEqual({ a: 2 });
|
|
388
|
-
});
|
|
389
|
-
|
|
390
|
-
it('AC-27: without CLOCK or ID_GENERATOR, record() still produces a non-empty string id and Date createdAt', async () => {
|
|
391
|
-
const store = makeStoreMock();
|
|
392
|
-
const txManager = makeTxManagerMock();
|
|
393
|
-
const providers: any[] = [
|
|
394
|
-
OutboxService,
|
|
395
|
-
{ provide: TRANSACTION_MANAGER, useValue: txManager },
|
|
396
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
397
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolveOutboxOptions({}) },
|
|
398
|
-
];
|
|
399
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
400
|
-
const service = moduleRef.get(OutboxService);
|
|
401
|
-
const result = await service.record({ type: 't', payload: {} });
|
|
402
|
-
expect(typeof result.id).toBe('string');
|
|
403
|
-
expect(result.id.length).toBeGreaterThan(0);
|
|
404
|
-
expect(result.createdAt).toBeInstanceOf(Date);
|
|
405
|
-
});
|
|
406
|
-
|
|
407
|
-
it('AC-28: store.save rejection propagates unchanged from record()', async () => {
|
|
408
|
-
const store = makeStoreMock();
|
|
409
|
-
const err = new Error('db-fail');
|
|
410
|
-
(store.save as jest.Mock).mockRejectedValue(err);
|
|
411
|
-
const { service } = await buildService({ store });
|
|
412
|
-
const recordPromise = service.record({ type: 'user.created', payload: { x: 1 } });
|
|
413
|
-
await expect(recordPromise).rejects.toBe(err);
|
|
414
|
-
});
|
|
415
|
-
});
|
|
416
|
-
|
|
417
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
418
|
-
// US-004: OutboxRelay
|
|
419
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
420
|
-
|
|
421
|
-
describe('US-004: OutboxRelay', () => {
|
|
422
|
-
const buildRelay = async (opts: {
|
|
423
|
-
store?: ReturnType<typeof makeStoreMock>;
|
|
424
|
-
publisher?: ReturnType<typeof makePublisherMock> | null;
|
|
425
|
-
clock?: ReturnType<typeof makeClockMock>;
|
|
426
|
-
relayOptions?: Partial<{
|
|
427
|
-
enabled: boolean;
|
|
428
|
-
pollIntervalMs: number;
|
|
429
|
-
batchSize: number;
|
|
430
|
-
leaseMs: number;
|
|
431
|
-
maxAttempts: number;
|
|
432
|
-
backoffBaseMs: number;
|
|
433
|
-
backoffCapMs: number;
|
|
434
|
-
}>;
|
|
435
|
-
} = {}) => {
|
|
436
|
-
const store = opts.store ?? makeStoreMock();
|
|
437
|
-
const clock = opts.clock ?? makeClockMock();
|
|
438
|
-
const relayOpts = {
|
|
439
|
-
enabled: false,
|
|
440
|
-
pollIntervalMs: 5000,
|
|
441
|
-
batchSize: 10,
|
|
442
|
-
leaseMs: 30000,
|
|
443
|
-
maxAttempts: 10,
|
|
444
|
-
backoffBaseMs: 1000,
|
|
445
|
-
backoffCapMs: 300000,
|
|
446
|
-
...opts.relayOptions,
|
|
447
|
-
};
|
|
448
|
-
const resolved = { store, publisher: opts.publisher === null ? undefined : (opts.publisher ?? makePublisherMock()), relay: relayOpts };
|
|
449
|
-
const providers: any[] = [
|
|
450
|
-
OutboxRelay,
|
|
451
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
452
|
-
{ provide: CLOCK, useValue: clock },
|
|
453
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
454
|
-
];
|
|
455
|
-
if (opts.publisher !== null) {
|
|
456
|
-
providers.push({ provide: OUTBOX_PUBLISHER, useValue: resolved.publisher });
|
|
457
|
-
}
|
|
458
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
459
|
-
return { relay: moduleRef.get(OutboxRelay), store, publisher: resolved.publisher, clock };
|
|
460
|
-
};
|
|
461
|
-
|
|
462
|
-
it('AC-29: dispatchPendingBatch() with no publisher rejects with OutboxMisconfiguredException (500) and claimBatch never called', async () => {
|
|
463
|
-
const store = makeStoreMock();
|
|
464
|
-
const providers: any[] = [
|
|
465
|
-
OutboxRelay,
|
|
466
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
467
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
468
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: { store, publisher: undefined, relay: { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 } } },
|
|
469
|
-
];
|
|
470
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
471
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
472
|
-
await expect(relay.dispatchPendingBatch()).rejects.toBeInstanceOf(OutboxMisconfiguredException);
|
|
473
|
-
try { await relay.dispatchPendingBatch(); } catch (ex: any) { expect(ex.httpStatus).toBe(500); }
|
|
474
|
-
expect((store.claimBatch as jest.Mock).mock.calls.length).toBe(0);
|
|
475
|
-
});
|
|
476
|
-
|
|
477
|
-
it('AC-30: empty claimBatch result — claimBatch called once with correct args, publish and markPublished never called', async () => {
|
|
478
|
-
const store = makeStoreMock();
|
|
479
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([]);
|
|
480
|
-
const publisher = makePublisherMock();
|
|
481
|
-
const now = new Date('2024-06-01T00:00:00.000Z');
|
|
482
|
-
const clock = makeClockMock(now);
|
|
483
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
484
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
485
|
-
const providers: any[] = [
|
|
486
|
-
OutboxRelay,
|
|
487
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
488
|
-
{ provide: CLOCK, useValue: clock },
|
|
489
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
490
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
491
|
-
];
|
|
492
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
493
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
494
|
-
await relay.dispatchPendingBatch();
|
|
495
|
-
expect((store.claimBatch as jest.Mock).mock.calls.length).toBe(1);
|
|
496
|
-
const [batchSize, leaseMs, nowArg, owner] = (store.claimBatch as jest.Mock).mock.calls[0] as any[];
|
|
497
|
-
expect(batchSize).toBe(10);
|
|
498
|
-
expect(leaseMs).toBe(30000);
|
|
499
|
-
expect(nowArg).toBeInstanceOf(Date);
|
|
500
|
-
expect(typeof owner).toBe('string');
|
|
501
|
-
expect((publisher.publish as jest.Mock).mock.calls.length).toBe(0);
|
|
502
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(0);
|
|
503
|
-
});
|
|
504
|
-
|
|
505
|
-
it('AC-31: success path — publish called once with record, markPublished called once with record.id, no markRetry/markDead', async () => {
|
|
506
|
-
const store = makeStoreMock();
|
|
507
|
-
const record = makeRecord({ id: 'r1' });
|
|
508
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([record]);
|
|
509
|
-
const publisher = makePublisherMock();
|
|
510
|
-
(publisher.publish as jest.Mock).mockResolvedValue(undefined);
|
|
511
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
512
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
513
|
-
const providers: any[] = [
|
|
514
|
-
OutboxRelay,
|
|
515
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
516
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
517
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
518
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
519
|
-
];
|
|
520
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
521
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
522
|
-
await relay.dispatchPendingBatch();
|
|
523
|
-
expect((publisher.publish as jest.Mock).mock.calls.length).toBe(1);
|
|
524
|
-
expect((publisher.publish as jest.Mock).mock.calls[0][0]).toBe(record);
|
|
525
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(1);
|
|
526
|
-
expect((store.markPublished as jest.Mock).mock.calls[0][0]).toBe('r1');
|
|
527
|
-
expect((store.markRetry as jest.Mock).mock.calls.length).toBe(0);
|
|
528
|
-
expect((store.markDead as jest.Mock).mock.calls.length).toBe(0);
|
|
529
|
-
});
|
|
530
|
-
|
|
531
|
-
it('AC-32: publish rejects with attempts=0, maxAttempts=10 → markRetry once with attempts=1 and correct nextAttemptAt', async () => {
|
|
532
|
-
const store = makeStoreMock();
|
|
533
|
-
const now = new Date('2024-06-01T00:00:00.000Z');
|
|
534
|
-
const clock = makeClockMock(now);
|
|
535
|
-
const record = makeRecord({ id: 'r1', attempts: 0 });
|
|
536
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([record]);
|
|
537
|
-
const publisher = makePublisherMock();
|
|
538
|
-
(publisher.publish as jest.Mock).mockRejectedValue(new Error('publish failed'));
|
|
539
|
-
const backoffBaseMs = 1000;
|
|
540
|
-
const backoffCapMs = 300000;
|
|
541
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs, backoffCapMs };
|
|
542
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
543
|
-
const providers: any[] = [
|
|
544
|
-
OutboxRelay,
|
|
545
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
546
|
-
{ provide: CLOCK, useValue: clock },
|
|
547
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
548
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
549
|
-
];
|
|
550
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
551
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
552
|
-
await relay.dispatchPendingBatch();
|
|
553
|
-
expect((store.markRetry as jest.Mock).mock.calls.length).toBe(1);
|
|
554
|
-
const [id, attempts, nextAttemptAt] = (store.markRetry as jest.Mock).mock.calls[0] as any[];
|
|
555
|
-
expect(id).toBe('r1');
|
|
556
|
-
expect(attempts).toBe(1);
|
|
557
|
-
const expectedBackoff = computeBackoff(1, backoffBaseMs, backoffCapMs);
|
|
558
|
-
expect(nextAttemptAt.getTime()).toBe(now.getTime() + expectedBackoff);
|
|
559
|
-
expect((store.markDead as jest.Mock).mock.calls.length).toBe(0);
|
|
560
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(0);
|
|
561
|
-
});
|
|
562
|
-
|
|
563
|
-
it('AC-33: publish rejects with attempts=9, maxAttempts=10 → markDead once with attempts=10, no markRetry/markPublished', async () => {
|
|
564
|
-
const store = makeStoreMock();
|
|
565
|
-
const record = makeRecord({ id: 'r1', attempts: 9 });
|
|
566
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([record]);
|
|
567
|
-
const publisher = makePublisherMock();
|
|
568
|
-
(publisher.publish as jest.Mock).mockRejectedValue(new Error('publish failed'));
|
|
569
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
570
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
571
|
-
const providers: any[] = [
|
|
572
|
-
OutboxRelay,
|
|
573
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
574
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
575
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
576
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
577
|
-
];
|
|
578
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
579
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
580
|
-
await relay.dispatchPendingBatch();
|
|
581
|
-
expect((store.markDead as jest.Mock).mock.calls.length).toBe(1);
|
|
582
|
-
const [id, attempts] = (store.markDead as jest.Mock).mock.calls[0] as any[];
|
|
583
|
-
expect(id).toBe('r1');
|
|
584
|
-
expect(attempts).toBe(10);
|
|
585
|
-
expect((store.markRetry as jest.Mock).mock.calls.length).toBe(0);
|
|
586
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(0);
|
|
587
|
-
});
|
|
588
|
-
|
|
589
|
-
it('AC-34: first record fails, second succeeds — markPublished called for second.id only', async () => {
|
|
590
|
-
const store = makeStoreMock();
|
|
591
|
-
const firstRecord = makeRecord({ id: 'r1', attempts: 0 });
|
|
592
|
-
const secondRecord = makeRecord({ id: 'r2', attempts: 0 });
|
|
593
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([firstRecord, secondRecord]);
|
|
594
|
-
const publisher = makePublisherMock();
|
|
595
|
-
(publisher.publish as jest.Mock)
|
|
596
|
-
.mockRejectedValueOnce(new Error('first failed'))
|
|
597
|
-
.mockResolvedValueOnce(undefined);
|
|
598
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
599
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
600
|
-
const providers: any[] = [
|
|
601
|
-
OutboxRelay,
|
|
602
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
603
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
604
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
605
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
606
|
-
];
|
|
607
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
608
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
609
|
-
await relay.dispatchPendingBatch();
|
|
610
|
-
const markPublishedCalls = (store.markPublished as jest.Mock).mock.calls;
|
|
611
|
-
expect(markPublishedCalls.length).toBe(1);
|
|
612
|
-
expect(markPublishedCalls[0][0]).toBe('r2');
|
|
613
|
-
const allMarkPublishedIds = markPublishedCalls.map((c: any[]) => c[0]);
|
|
614
|
-
expect(allMarkPublishedIds).not.toContain('r1');
|
|
615
|
-
});
|
|
616
|
-
|
|
617
|
-
it('AC-35: second dispatchPendingBatch while first is in-flight resolves without calling claimBatch again', async () => {
|
|
618
|
-
const store = makeStoreMock();
|
|
619
|
-
let resolvePublish!: () => void;
|
|
620
|
-
const publishPromise = new Promise<void>(resolve => { resolvePublish = resolve; });
|
|
621
|
-
const record = makeRecord({ id: 'r1' });
|
|
622
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([record]);
|
|
623
|
-
const publisher = makePublisherMock();
|
|
624
|
-
(publisher.publish as jest.Mock).mockReturnValue(publishPromise);
|
|
625
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
626
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
627
|
-
const providers: any[] = [
|
|
628
|
-
OutboxRelay,
|
|
629
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
630
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
631
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
632
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
633
|
-
];
|
|
634
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
635
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
636
|
-
const first = relay.dispatchPendingBatch();
|
|
637
|
-
await relay.dispatchPendingBatch();
|
|
638
|
-
expect((store.claimBatch as jest.Mock).mock.calls.length).toBe(1);
|
|
639
|
-
resolvePublish();
|
|
640
|
-
await first;
|
|
641
|
-
});
|
|
642
|
-
|
|
643
|
-
it('AC-36: empty batch resolves without calling publish, markPublished, markRetry, or markDead', async () => {
|
|
644
|
-
const store = makeStoreMock();
|
|
645
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([]);
|
|
646
|
-
const publisher = makePublisherMock();
|
|
647
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
648
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
649
|
-
const providers: any[] = [
|
|
650
|
-
OutboxRelay,
|
|
651
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
652
|
-
{ provide: CLOCK, useValue: makeClockMock() },
|
|
653
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
654
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
655
|
-
];
|
|
656
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
657
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
658
|
-
await expect(relay.dispatchPendingBatch()).resolves.not.toThrow();
|
|
659
|
-
expect((publisher.publish as jest.Mock).mock.calls.length).toBe(0);
|
|
660
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(0);
|
|
661
|
-
expect((store.markRetry as jest.Mock).mock.calls.length).toBe(0);
|
|
662
|
-
expect((store.markDead as jest.Mock).mock.calls.length).toBe(0);
|
|
663
|
-
});
|
|
664
|
-
|
|
665
|
-
it('AC-37: only claimable records published; future-dated record excluded from publish', async () => {
|
|
666
|
-
const store = makeStoreMock();
|
|
667
|
-
const now = new Date('2024-06-01T00:00:00.000Z');
|
|
668
|
-
const claimableRecord = makeRecord({ id: 'r-claimable', nextAttemptAt: new Date(now.getTime() - 1) });
|
|
669
|
-
// claimBatch already filters by nextAttemptAt, so it returns only claimable records
|
|
670
|
-
(store.claimBatch as jest.Mock).mockResolvedValue([claimableRecord]);
|
|
671
|
-
const publisher = makePublisherMock();
|
|
672
|
-
const relayOpts = { enabled: false, pollIntervalMs: 5000, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 };
|
|
673
|
-
const resolved = { store, publisher, relay: relayOpts };
|
|
674
|
-
const providers: any[] = [
|
|
675
|
-
OutboxRelay,
|
|
676
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
677
|
-
{ provide: CLOCK, useValue: makeClockMock(now) },
|
|
678
|
-
{ provide: OUTBOX_PUBLISHER, useValue: publisher },
|
|
679
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: resolved },
|
|
680
|
-
];
|
|
681
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
682
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
683
|
-
await relay.dispatchPendingBatch();
|
|
684
|
-
expect((publisher.publish as jest.Mock).mock.calls.length).toBe(1);
|
|
685
|
-
expect((publisher.publish as jest.Mock).mock.calls[0][0]).toBe(claimableRecord);
|
|
686
|
-
expect((store.markPublished as jest.Mock).mock.calls.length).toBe(1);
|
|
687
|
-
expect((store.markPublished as jest.Mock).mock.calls[0][0]).toBe('r-claimable');
|
|
688
|
-
});
|
|
689
|
-
});
|
|
690
|
-
|
|
691
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
692
|
-
// US-005: Module assembly, barrel, lifecycle, integration
|
|
693
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
694
|
-
|
|
695
|
-
describe('US-005: Module assembly, barrel, lifecycle, integration', () => {
|
|
696
|
-
const fakePublisher = { publish: jest.fn<() => Promise<void>>().mockResolvedValue(undefined) };
|
|
697
|
-
|
|
698
|
-
beforeEach(() => {
|
|
699
|
-
(fakePublisher.publish as jest.Mock).mockClear();
|
|
700
|
-
});
|
|
701
|
-
|
|
702
|
-
it('AC-38: OutboxModule.register() returns DynamicModule with global=true and module===OutboxModule', () => {
|
|
703
|
-
const mod = OutboxModule.register() as any;
|
|
704
|
-
expect(mod.global).toBe(true);
|
|
705
|
-
expect(mod.module).toBe(OutboxModule);
|
|
706
|
-
});
|
|
707
|
-
|
|
708
|
-
it('AC-39: TestModule with register({ publisher }) resolves OUTBOX_STORE to InMemoryOutboxStore', async () => {
|
|
709
|
-
const moduleRef = await Test.createTestingModule({
|
|
710
|
-
imports: [OutboxModule.register({ publisher: fakePublisher })],
|
|
711
|
-
}).compile();
|
|
712
|
-
const store = moduleRef.get(OUTBOX_STORE);
|
|
713
|
-
expect(store).toBeInstanceOf(InMemoryOutboxStore);
|
|
714
|
-
await moduleRef.close();
|
|
715
|
-
});
|
|
716
|
-
|
|
717
|
-
it('AC-40: TestModule with register({ store: myStore }) resolves OUTBOX_STORE to exact myStore instance', async () => {
|
|
718
|
-
const myStore = new InMemoryOutboxStore();
|
|
719
|
-
const moduleRef = await Test.createTestingModule({
|
|
720
|
-
imports: [OutboxModule.register({ store: myStore, publisher: fakePublisher })],
|
|
721
|
-
}).compile();
|
|
722
|
-
const resolved = moduleRef.get(OUTBOX_STORE);
|
|
723
|
-
expect(resolved).toBe(myStore);
|
|
724
|
-
await moduleRef.close();
|
|
725
|
-
});
|
|
726
|
-
|
|
727
|
-
it('AC-41: registerAsync with useFactory exposes pollIntervalMs=111 via OUTBOX_MODULE_OPTIONS', async () => {
|
|
728
|
-
const moduleRef = await Test.createTestingModule({
|
|
729
|
-
imports: [
|
|
730
|
-
OutboxModule.registerAsync({
|
|
731
|
-
useFactory: () => ({ publisher: fakePublisher, relay: { pollIntervalMs: 111 } }),
|
|
732
|
-
}),
|
|
733
|
-
],
|
|
734
|
-
}).compile();
|
|
735
|
-
const options = moduleRef.get(OUTBOX_MODULE_OPTIONS) as any;
|
|
736
|
-
expect(options.relay.pollIntervalMs).toBe(111);
|
|
737
|
-
await moduleRef.close();
|
|
738
|
-
});
|
|
739
|
-
|
|
740
|
-
it('AC-42: all seven barrel exports are importable and of the correct kind', () => {
|
|
741
|
-
expect(OutboxModule).toBeInstanceOf(Function);
|
|
742
|
-
expect(OutboxService).toBeInstanceOf(Function);
|
|
743
|
-
expect(OutboxRelay).toBeInstanceOf(Function);
|
|
744
|
-
expect(InMemoryOutboxStore).toBeInstanceOf(Function);
|
|
745
|
-
expect(OutboxInvalidEventException).toBeInstanceOf(Function);
|
|
746
|
-
expect(OutboxMisconfiguredException).toBeInstanceOf(Function);
|
|
747
|
-
expect(typeof OUTBOX_STORE).toBe('symbol');
|
|
748
|
-
});
|
|
749
|
-
|
|
750
|
-
it('AC-43: record 3 events with relay disabled, dispatchPendingBatch publishes all 3 as PUBLISHED', async () => {
|
|
751
|
-
const store = new InMemoryOutboxStore();
|
|
752
|
-
const publisher = { publish: jest.fn<() => Promise<void>>().mockResolvedValue(undefined) };
|
|
753
|
-
const moduleRef = await Test.createTestingModule({
|
|
754
|
-
imports: [OutboxModule.register({ store, publisher, relay: { enabled: false } })],
|
|
755
|
-
}).compile();
|
|
756
|
-
const outboxService = moduleRef.get(OutboxService);
|
|
757
|
-
const outboxRelay = moduleRef.get(OutboxRelay);
|
|
758
|
-
await outboxService.record({ type: 'e1', payload: { n: 1 } });
|
|
759
|
-
await outboxService.record({ type: 'e2', payload: { n: 2 } });
|
|
760
|
-
await outboxService.record({ type: 'e3', payload: { n: 3 } });
|
|
761
|
-
await outboxRelay.dispatchPendingBatch();
|
|
762
|
-
expect((publisher.publish as jest.Mock).mock.calls.length).toBe(3);
|
|
763
|
-
const now = new Date();
|
|
764
|
-
const remaining = await store.claimBatch(100, 30000, now, 'check');
|
|
765
|
-
expect(remaining.length).toBe(0);
|
|
766
|
-
await moduleRef.close();
|
|
767
|
-
});
|
|
768
|
-
|
|
769
|
-
it('AC-44: publisher always rejects with maxAttempts=3 → record becomes DEAD after 3 dispatches', async () => {
|
|
770
|
-
const store = new InMemoryOutboxStore();
|
|
771
|
-
const failPublisher = { publish: jest.fn<() => Promise<void>>().mockRejectedValue(new Error('fail')) };
|
|
772
|
-
const now = new Date('2024-06-01T00:00:00.000Z');
|
|
773
|
-
let clockTime = now.getTime();
|
|
774
|
-
const fakeClock: SystemClock = { now: () => new Date(clockTime) } as any;
|
|
775
|
-
const moduleRef = await Test.createTestingModule({
|
|
776
|
-
imports: [OutboxModule.register({
|
|
777
|
-
store,
|
|
778
|
-
publisher: failPublisher,
|
|
779
|
-
relay: { enabled: false, maxAttempts: 3, backoffBaseMs: 0, backoffCapMs: 0 },
|
|
780
|
-
})],
|
|
781
|
-
providers: [{ provide: CLOCK, useValue: fakeClock }],
|
|
782
|
-
}).compile();
|
|
783
|
-
const outboxService = moduleRef.get(OutboxService);
|
|
784
|
-
const outboxRelay = moduleRef.get(OutboxRelay);
|
|
785
|
-
await outboxService.record({ type: 'test.event', payload: {} });
|
|
786
|
-
// Dispatch 1: attempts 0 → markRetry with attempts=1
|
|
787
|
-
await outboxRelay.dispatchPendingBatch();
|
|
788
|
-
// Advance clock past backoff (0ms so any advance works)
|
|
789
|
-
clockTime += 100;
|
|
790
|
-
// Dispatch 2: attempts 1 → markRetry with attempts=2
|
|
791
|
-
await outboxRelay.dispatchPendingBatch();
|
|
792
|
-
clockTime += 100;
|
|
793
|
-
// Dispatch 3: attempts 2 → markDead with attempts=3
|
|
794
|
-
await outboxRelay.dispatchPendingBatch();
|
|
795
|
-
// Verify record is DEAD and not claimable
|
|
796
|
-
const laterNow = new Date(clockTime + 60000);
|
|
797
|
-
const remaining = await store.claimBatch(100, 30000, laterNow, 'check');
|
|
798
|
-
expect(remaining.length).toBe(0);
|
|
799
|
-
await moduleRef.close();
|
|
800
|
-
});
|
|
801
|
-
|
|
802
|
-
it('AC-45: relay disabled — store.claimBatch never called after advancing timers', async () => {
|
|
803
|
-
const store = new InMemoryOutboxStore();
|
|
804
|
-
const claimSpy = jest.spyOn(store, 'claimBatch');
|
|
805
|
-
jest.useFakeTimers();
|
|
806
|
-
try {
|
|
807
|
-
const moduleRef = await Test.createTestingModule({
|
|
808
|
-
imports: [OutboxModule.register({ store, publisher: fakePublisher, relay: { enabled: false } })],
|
|
809
|
-
}).compile();
|
|
810
|
-
const app = moduleRef.createNestApplication();
|
|
811
|
-
await app.init();
|
|
812
|
-
jest.advanceTimersByTime(10000);
|
|
813
|
-
await Promise.resolve();
|
|
814
|
-
expect(claimSpy).not.toHaveBeenCalled();
|
|
815
|
-
await app.close();
|
|
816
|
-
} finally {
|
|
817
|
-
jest.useRealTimers();
|
|
818
|
-
}
|
|
819
|
-
});
|
|
820
|
-
|
|
821
|
-
it('AC-46: relay enabled but no publisher — onApplicationBootstrap throws OutboxMisconfiguredException, no setInterval', async () => {
|
|
822
|
-
const store = new InMemoryOutboxStore();
|
|
823
|
-
jest.useFakeTimers();
|
|
824
|
-
const setIntervalSpy = jest.spyOn(global, 'setInterval');
|
|
825
|
-
try {
|
|
826
|
-
const providers: any[] = [
|
|
827
|
-
OutboxRelay,
|
|
828
|
-
{ provide: OUTBOX_STORE, useValue: store },
|
|
829
|
-
{ provide: CLOCK, useValue: new SystemClock() },
|
|
830
|
-
{ provide: OUTBOX_MODULE_OPTIONS, useValue: {
|
|
831
|
-
store,
|
|
832
|
-
publisher: undefined,
|
|
833
|
-
relay: { enabled: true, pollIntervalMs: 100, batchSize: 10, leaseMs: 30000, maxAttempts: 10, backoffBaseMs: 1000, backoffCapMs: 300000 },
|
|
834
|
-
}},
|
|
835
|
-
];
|
|
836
|
-
const moduleRef = await Test.createTestingModule({ providers }).compile();
|
|
837
|
-
const relay = moduleRef.get(OutboxRelay);
|
|
838
|
-
await expect(relay.onApplicationBootstrap()).rejects.toBeInstanceOf(OutboxMisconfiguredException);
|
|
839
|
-
expect(setIntervalSpy).not.toHaveBeenCalled();
|
|
840
|
-
} finally {
|
|
841
|
-
jest.useRealTimers();
|
|
842
|
-
setIntervalSpy.mockRestore();
|
|
843
|
-
}
|
|
844
|
-
});
|
|
845
|
-
|
|
846
|
-
it('AC-47: claimBatch rejects → app does not crash, logger called with an Error', async () => {
|
|
847
|
-
jest.useFakeTimers();
|
|
848
|
-
const store = new InMemoryOutboxStore();
|
|
849
|
-
jest.spyOn(store, 'claimBatch').mockRejectedValue(new Error('db down'));
|
|
850
|
-
const publisher = { publish: jest.fn<() => Promise<void>>().mockResolvedValue(undefined) };
|
|
851
|
-
try {
|
|
852
|
-
const moduleRef = await Test.createTestingModule({
|
|
853
|
-
imports: [OutboxModule.register({
|
|
854
|
-
store,
|
|
855
|
-
publisher,
|
|
856
|
-
relay: { enabled: true, pollIntervalMs: 100 },
|
|
857
|
-
})],
|
|
858
|
-
}).compile();
|
|
859
|
-
const app = moduleRef.createNestApplication();
|
|
860
|
-
await app.init();
|
|
861
|
-
const originalHandler = process.listeners('unhandledRejection').slice();
|
|
862
|
-
let unhandledRejection: any = null;
|
|
863
|
-
const captureUnhandled = (reason: any) => { unhandledRejection = reason; };
|
|
864
|
-
process.on('unhandledRejection', captureUnhandled);
|
|
865
|
-
try {
|
|
866
|
-
jest.advanceTimersByTime(200);
|
|
867
|
-
await Promise.resolve();
|
|
868
|
-
await Promise.resolve();
|
|
869
|
-
expect(unhandledRejection).toBeNull();
|
|
870
|
-
} finally {
|
|
871
|
-
process.removeListener('unhandledRejection', captureUnhandled);
|
|
872
|
-
}
|
|
873
|
-
await app.close();
|
|
874
|
-
} finally {
|
|
875
|
-
jest.useRealTimers();
|
|
876
|
-
}
|
|
877
|
-
});
|
|
878
|
-
});
|