-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathoutbox.spec.ts
256 lines (220 loc) · 7.14 KB
/
outbox.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { randomUUID } from 'node:crypto'
import {
CommonMetadataFiller,
DomainEventEmitter,
EventRegistry,
} from '@message-queue-toolkit/core'
import {
type CommonEventDefinition,
type CommonEventDefinitionPublisherSchemaType,
enrichMessageSchemaWithBase,
} from '@message-queue-toolkit/schemas'
import pino, { type Logger } from 'pino'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { InMemoryOutboxAccumulator } from '../lib/accumulators'
import { type OutboxDependencies, OutboxEventEmitter, OutboxProcessor } from '../lib/outbox'
import { InMemoryOutboxStorage } from './InMemoryOutboxStorage'
const TestEvents = {
created: {
...enrichMessageSchemaWithBase(
'entity.created',
z.object({
message: z.string(),
}),
),
},
updated: {
...enrichMessageSchemaWithBase(
'entity.updated',
z.object({
message: z.string(),
}),
),
},
} as const satisfies Record<string, CommonEventDefinition>
type TestEventsType = (typeof TestEvents)[keyof typeof TestEvents][]
const createdEventPayload: CommonEventDefinitionPublisherSchemaType<typeof TestEvents.created> = {
payload: {
message: 'msg',
},
type: 'entity.created',
metadata: {
originatedFrom: 'service',
producedBy: 'producer',
schemaVersion: '1',
correlationId: randomUUID(),
},
}
const TestLogger: Logger = pino()
const MAX_RETRY_COUNT = 2
describe('outbox', () => {
let outboxProcessor: OutboxProcessor<TestEventsType>
let eventEmitter: DomainEventEmitter<TestEventsType>
let outboxEventEmitter: OutboxEventEmitter<TestEventsType>
let outboxStorage: InMemoryOutboxStorage<TestEventsType>
let inMemoryOutboxAccumulator: InMemoryOutboxAccumulator<TestEventsType>
beforeEach(() => {
eventEmitter = new DomainEventEmitter({
logger: TestLogger,
errorReporter: { report: () => {} },
eventRegistry: new EventRegistry(Object.values(TestEvents)),
metadataFiller: new CommonMetadataFiller({
serviceId: 'test',
}),
})
outboxStorage = new InMemoryOutboxStorage<TestEventsType>()
outboxEventEmitter = new OutboxEventEmitter<TestEventsType>(outboxStorage)
inMemoryOutboxAccumulator = new InMemoryOutboxAccumulator()
outboxProcessor = new OutboxProcessor<TestEventsType>(
{
outboxStorage,
//@ts-ignore
outboxAccumulator: inMemoryOutboxAccumulator,
eventEmitter,
} satisfies OutboxDependencies<TestEventsType>,
{ maxRetryCount: MAX_RETRY_COUNT, emitBatchSize: 1 },
)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('saves outbox entry to storage', async () => {
await outboxEventEmitter.emit(createdEventPayload, {
correlationId: randomUUID(),
})
const entries = await outboxStorage.getEntries(MAX_RETRY_COUNT)
expect(entries).toHaveLength(1)
})
it('saves outbox entry and process it', async () => {
await outboxEventEmitter.emit(createdEventPayload, {
correlationId: randomUUID(),
})
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
const entries = await outboxStorage.getEntries(MAX_RETRY_COUNT)
expect(entries).toHaveLength(0)
expect(outboxStorage.entries).toMatchObject([
{
status: 'SUCCESS',
},
])
})
it('saves outbox entry and process it with error and retries', async () => {
const mockedEventEmitter = vi.spyOn(eventEmitter, 'emit')
mockedEventEmitter.mockImplementationOnce(() => {
throw new Error('Could not emit event.')
})
mockedEventEmitter.mockImplementationOnce(() =>
Promise.resolve({
...createdEventPayload,
id: randomUUID(),
timestamp: new Date().toISOString(),
metadata: {
schemaVersion: '1',
producedBy: 'test',
originatedFrom: 'service',
correlationId: randomUUID(),
},
}),
)
await outboxEventEmitter.emit(createdEventPayload, {
correlationId: randomUUID(),
})
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
let entries = await outboxStorage.getEntries(MAX_RETRY_COUNT)
expect(entries).toHaveLength(1)
expect(outboxStorage.entries).toMatchObject([
{
status: 'FAILED',
retryCount: 1,
},
])
//Now let's process again successfully
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
entries = await outboxStorage.getEntries(MAX_RETRY_COUNT)
expect(entries).toHaveLength(0) //Nothing to process anymore
expect(outboxStorage.entries).toMatchObject([
{
status: 'SUCCESS',
retryCount: 1,
},
])
})
it('no longer processes the event if exceeded retry count', async () => {
//Let's always fail the event
const mockedEventEmitter = vi.spyOn(eventEmitter, 'emit')
mockedEventEmitter.mockImplementation(() => {
throw new Error('Could not emit event.')
})
//Persist the event
await outboxEventEmitter.emit(createdEventPayload, {
correlationId: randomUUID(),
})
//Initially event is present in outbox storage.
expect(await outboxStorage.getEntries(MAX_RETRY_COUNT)).toHaveLength(1)
//Retry +1
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
//Still present
expect(await outboxStorage.getEntries(MAX_RETRY_COUNT)).toHaveLength(1)
//Retry +2
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
//Stil present
expect(await outboxStorage.getEntries(MAX_RETRY_COUNT)).toHaveLength(1)
//Retry +3
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
//Now it's gone, we no longer try to process it
expect(await outboxStorage.getEntries(MAX_RETRY_COUNT)).toHaveLength(0)
expect(outboxStorage.entries).toMatchObject([
{
status: 'FAILED',
retryCount: 3,
},
])
})
it("doesn't emit event again if it's already present in accumulator", async () => {
const mockedEventEmitter = vi.spyOn(eventEmitter, 'emit')
await outboxEventEmitter.emit(createdEventPayload, {
correlationId: randomUUID(),
})
await inMemoryOutboxAccumulator.add(outboxStorage.entries[0])
await outboxProcessor.processOutboxEntries({
logger: TestLogger,
reqId: randomUUID(),
executorId: randomUUID(),
})
//We pretended that event was emitted in previous run by adding state to accumulator
expect(mockedEventEmitter).toHaveBeenCalledTimes(0)
//But after the loop, if successful, it should be marked as success anyway
expect(outboxStorage.entries).toMatchObject([
{
status: 'SUCCESS',
},
])
//And accumulator should be cleared
expect(await inMemoryOutboxAccumulator.getEntries()).toHaveLength(0)
})
})