-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbatchJobWorker.spec.ts
More file actions
417 lines (383 loc) · 14.5 KB
/
Copy pathbatchJobWorker.spec.ts
File metadata and controls
417 lines (383 loc) · 14.5 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import { describe, expect, it, jest } from '@jest/globals'
type ProcessorFn = (job: { data: { jobId: string } }) => Promise<unknown>
function makeModule(opts: {
sharedRedis?: object | null
bullmqRedisCtor?: jest.Mock | null
bullmqRedisFails?: boolean
dbJob?: object | null
executorExecute?: jest.Mock
executorMissing?: boolean
executorRegistrationThrows?: boolean
workerCtorThrows?: boolean
checkpointThrows?: boolean
}) {
const {
sharedRedis = { setex: jest.fn().mockResolvedValue('OK') },
bullmqRedisCtor = undefined,
bullmqRedisFails = false,
dbJob = null,
executorExecute,
executorMissing = false,
executorRegistrationThrows = false,
workerCtorThrows = false,
checkpointThrows = false,
} = opts
const infoLog = jest.fn()
const errorLog = jest.fn()
const debugLog = jest.fn()
const mockCheckpoint = checkpointThrows
? jest.fn().mockRejectedValue(new Error('DB error'))
: jest.fn().mockResolvedValue(undefined)
const mockMarkInProgress = jest.fn().mockResolvedValue(undefined)
const mockMarkCompleted = jest.fn().mockResolvedValue(undefined)
const mockMarkFailed = jest.fn().mockResolvedValue(undefined)
const mockSetSummary = jest.fn().mockResolvedValue(undefined)
const mockGetById = jest.fn().mockResolvedValue(dbJob)
const mockExecute =
executorExecute ?? jest.fn().mockResolvedValue({ moved: 5 })
const mockExecutor = executorMissing
? null
: { jobType: 'bulk_move_messages', execute: mockExecute }
const mockGetExecutor = jest.fn().mockReturnValue(mockExecutor)
const mockRegisterExecutor = executorRegistrationThrows
? jest.fn().mockImplementation(() => {
throw new Error('registration failed')
})
: jest.fn()
const mockWorkerOn = jest.fn()
const mockWorkerClose = jest.fn().mockResolvedValue(undefined)
// BullMQ redis instance mock (with disconnect method)
const mockBullmqRedisDisconnect = jest.fn().mockResolvedValue(undefined)
const mockBullmqRedis = bullmqRedisFails
? null
: {
disconnect: mockBullmqRedisDisconnect,
}
const MockRedis =
bullmqRedisCtor ?? jest.fn().mockReturnValue(mockBullmqRedis)
let capturedProcessor: ProcessorFn | null = null
const MockWorker = workerCtorThrows
? jest.fn(() => {
throw new Error('Worker failed')
})
: jest
.fn()
.mockImplementation((_name: string, processor: ProcessorFn) => {
capturedProcessor = processor
return { on: mockWorkerOn, close: mockWorkerClose }
})
const MockChannelMoveBatchExecutor = jest.fn().mockImplementation(() => ({
jobType: 'bulk_move_messages',
execute: mockExecute,
}))
let mod: {
startBatchJobWorker: () => Promise<void>
stopBatchJobWorker: () => Promise<void>
}
jest.isolateModules(() => {
jest.doMock('ioredis', () => MockRedis)
jest.doMock('@lucky/shared/services', () => ({
redisClient: { getClient: () => sharedRedis },
}))
jest.doMock('@lucky/shared/services/batch', () => ({
batchJobService: {
getById: mockGetById,
markInProgress: mockMarkInProgress,
markCompleted: mockMarkCompleted,
markFailed: mockMarkFailed,
setSummary: mockSetSummary,
checkpoint: mockCheckpoint,
},
}))
jest.doMock('@lucky/shared/utils', () => ({
infoLog,
errorLog,
debugLog,
}))
jest.doMock('@lucky/shared/config', () => ({
ENVIRONMENT_CONFIG: {
REDIS: {
HOST: 'localhost',
PORT: 6379,
PASSWORD: undefined,
DB: 0,
},
},
}))
jest.doMock('./executorRegistry', () => ({
getExecutor: mockGetExecutor,
registerExecutor: mockRegisterExecutor,
}))
jest.doMock('bullmq', () => ({ Worker: MockWorker }))
jest.doMock(
'../functions/moderation/batch/channelMoveExecutor',
() => ({
ChannelMoveBatchExecutor: MockChannelMoveBatchExecutor,
}),
)
// eslint-disable-next-line @typescript-eslint/no-require-imports
mod = require('./batchJobWorker')
})
return {
mod: mod!,
capturedProcessor: () => capturedProcessor,
MockWorker,
MockRedis,
mockBullmqRedis,
mockBullmqRedisDisconnect,
mockWorkerClose,
mockWorkerOn,
mockGetById,
mockMarkInProgress,
mockMarkCompleted,
mockMarkFailed,
mockSetSummary,
mockCheckpoint,
mockGetExecutor,
mockRegisterExecutor,
errorLog,
infoLog,
}
}
function makeJob(jobId = 'job-abc') {
return { data: { jobId }, id: jobId }
}
describe('batchJobWorker', () => {
describe('startBatchJobWorker', () => {
it('returns early and logs error when redis is unavailable', async () => {
const { mod, MockWorker, errorLog } = makeModule({
sharedRedis: null,
})
await mod.startBatchJobWorker()
expect(MockWorker).not.toHaveBeenCalled()
expect(errorLog).toHaveBeenCalled()
})
it('creates BullMQ redis connection with maxRetriesPerRequest: null', async () => {
const { mod, MockRedis } = makeModule({})
await mod.startBatchJobWorker()
expect(MockRedis).toHaveBeenCalledWith(
expect.objectContaining({
maxRetriesPerRequest: null,
}),
)
})
it('registers executor and creates Worker when redis is available', async () => {
const { mod, MockWorker, mockBullmqRedis, mockRegisterExecutor } =
makeModule({})
await mod.startBatchJobWorker()
expect(mockRegisterExecutor).toHaveBeenCalled()
expect(MockWorker).toHaveBeenCalledWith(
'batch-jobs',
expect.any(Function),
{ connection: mockBullmqRedis, concurrency: 1 },
)
})
it('returns early and logs error when executor registration throws', async () => {
const { mod, MockWorker, errorLog } = makeModule({
executorRegistrationThrows: true,
})
await mod.startBatchJobWorker()
expect(MockWorker).not.toHaveBeenCalled()
expect(errorLog).toHaveBeenCalled()
})
it('logs error when Worker constructor throws', async () => {
const { mod, errorLog } = makeModule({ workerCtorThrows: true })
await mod.startBatchJobWorker()
expect(errorLog).toHaveBeenCalled()
})
it('wires up completed and failed event handlers', async () => {
const { mod, mockWorkerOn } = makeModule({})
await mod.startBatchJobWorker()
const events = mockWorkerOn.mock.calls.map((c: unknown[]) => c[0])
expect(events).toContain('completed')
expect(events).toContain('failed')
})
})
describe('stopBatchJobWorker', () => {
it('does nothing when no worker is active', async () => {
const { mod, mockWorkerClose } = makeModule({ sharedRedis: null })
await mod.stopBatchJobWorker()
expect(mockWorkerClose).not.toHaveBeenCalled()
})
it('closes the worker when active', async () => {
const { mod, mockWorkerClose } = makeModule({})
await mod.startBatchJobWorker()
await mod.stopBatchJobWorker()
expect(mockWorkerClose).toHaveBeenCalled()
})
it('logs error when close throws', async () => {
const { mod, mockWorkerClose, errorLog } = makeModule({})
mockWorkerClose.mockRejectedValue(new Error('close error'))
await mod.startBatchJobWorker()
await mod.stopBatchJobWorker()
expect(errorLog).toHaveBeenCalled()
})
it('disconnects the BullMQ redis connection', async () => {
const { mod, mockBullmqRedisDisconnect } = makeModule({})
await mod.startBatchJobWorker()
await mod.stopBatchJobWorker()
expect(mockBullmqRedisDisconnect).toHaveBeenCalled()
})
})
describe('processBatchJob (via worker processor)', () => {
it('throws when job not found in DB', async () => {
const { mod, capturedProcessor, mockMarkFailed } = makeModule({
dbJob: null,
})
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await expect(processor(makeJob())).rejects.toThrow(
'Batch job not found',
)
expect(mockMarkFailed).toHaveBeenCalled()
})
it('throws when no executor registered for job type', async () => {
const dbJob = {
id: 'job-abc',
guildId: 'g1',
jobType: 'unknown_type',
totalItems: 10,
options: {},
}
const { mod, capturedProcessor, mockMarkFailed } = makeModule({
dbJob,
executorMissing: true,
})
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await expect(processor(makeJob())).rejects.toThrow(
'No executor registered',
)
expect(mockMarkFailed).toHaveBeenCalled()
})
it('marks job completed and sets summary on success', async () => {
const dbJob = {
id: 'job-abc',
guildId: 'g1',
jobType: 'bulk_move_messages',
totalItems: 5,
options: {},
}
const {
mod,
capturedProcessor,
mockMarkCompleted,
mockMarkInProgress,
mockSetSummary,
} = makeModule({ dbJob })
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await processor(makeJob())
expect(mockMarkInProgress).toHaveBeenCalledWith('job-abc')
expect(mockMarkCompleted).toHaveBeenCalledWith('job-abc')
expect(mockSetSummary).toHaveBeenCalledWith(
'job-abc',
expect.any(Object),
)
})
it('marks job failed when executor throws', async () => {
const dbJob = {
id: 'job-abc',
guildId: 'g1',
jobType: 'bulk_move_messages',
totalItems: 5,
options: {},
}
const failingExecute = jest
.fn()
.mockRejectedValue(new Error('executor crashed'))
const { mod, capturedProcessor, mockMarkFailed } = makeModule({
dbJob,
executorExecute: failingExecute,
})
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await expect(processor(makeJob())).rejects.toThrow(
'executor crashed',
)
expect(mockMarkFailed).toHaveBeenCalledWith(
'job-abc',
'executor crashed',
)
})
})
describe('onProgress (via executor boundOnProgress callback)', () => {
it('checkpoints to DB and does not throw when redis is available', async () => {
const fakeRedis = { setex: jest.fn().mockResolvedValue('OK') }
const progressCapture = {
fn: null as ((p: unknown) => Promise<void>) | null,
}
const captureExecute = jest
.fn()
.mockImplementation(
async (
_ctx: unknown,
onProgress: (p: unknown) => Promise<void>,
) => {
progressCapture.fn = onProgress
await onProgress({
processed: 10,
failed: 0,
skipped: 0,
nextCursor: 'c1',
})
return { moved: 10 }
},
)
const dbJob = {
id: 'job-abc',
guildId: 'g1',
jobType: 'bulk_move_messages',
totalItems: 10,
options: {},
}
const { mod, capturedProcessor, mockCheckpoint } = makeModule({
dbJob,
executorExecute: captureExecute,
redis: fakeRedis as never,
})
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await processor(makeJob())
expect(mockCheckpoint).toHaveBeenCalledWith(
'job-abc',
expect.objectContaining({ processedItems: 10 }),
)
})
it('re-throws when checkpoint fails', async () => {
const progressCapture = {
fn: null as ((p: unknown) => Promise<void>) | null,
}
const captureExecute = jest
.fn()
.mockImplementation(
async (
_ctx: unknown,
onProgress: (p: unknown) => Promise<void>,
) => {
await onProgress({
processed: 10,
failed: 0,
skipped: 0,
})
return {}
},
)
const dbJob = {
id: 'job-abc',
guildId: 'g1',
jobType: 'bulk_move_messages',
totalItems: 10,
options: {},
}
const { mod, capturedProcessor } = makeModule({
dbJob,
executorExecute: captureExecute,
checkpointThrows: true,
})
await mod.startBatchJobWorker()
const processor = capturedProcessor()!
await expect(processor(makeJob())).rejects.toThrow('DB error')
})
})
})