/
RedisJobsTests.swift
328 lines (296 loc) · 13.8 KB
/
RedisJobsTests.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Atomics
import Hummingbird
import HummingbirdJobs
@testable import HummingbirdJobsRedis
import HummingbirdRedis
import HummingbirdTesting
import Logging
import NIOConcurrencyHelpers
import RediStack
import ServiceLifecycle
import XCTest
extension XCTestExpectation {
convenience init(description: String, expectedFulfillmentCount: Int) {
self.init(description: description)
self.expectedFulfillmentCount = expectedFulfillmentCount
}
}
final class HummingbirdRedisJobsTests: XCTestCase {
func wait(for expectations: [XCTestExpectation], timeout: TimeInterval) async {
#if (os(Linux) && swift(<5.9)) || swift(<5.8)
super.wait(for: expectations, timeout: timeout)
#else
await fulfillment(of: expectations, timeout: timeout)
#endif
}
static let env = Environment()
static let redisHostname = env.get("REDIS_HOSTNAME") ?? "localhost"
/// Helper function for test a server
///
/// Creates test client, runs test function abd ensures everything is
/// shutdown correctly
@discardableResult public func testJobQueue<T>(
numWorkers: Int,
failedJobsInitialization: RedisQueue.JobInitialization = .remove,
test: (JobQueue<RedisQueue>) async throws -> T
) async throws -> T {
var logger = Logger(label: "RedisJobsTests")
logger.logLevel = .debug
let redisService = try RedisConnectionPoolService(
.init(hostname: Self.redisHostname, port: 6379),
logger: logger
)
let jobQueue = JobQueue(
.redis(
redisService,
configuration: .init(
pendingJobInitialization: .remove,
processingJobsInitialization: .remove,
failedJobsInitialization: failedJobsInitialization
)
),
numWorkers: numWorkers,
logger: logger
)
return try await withThrowingTaskGroup(of: Void.self) { group in
let serviceGroup = ServiceGroup(
configuration: .init(
services: [redisService, jobQueue],
gracefulShutdownSignals: [.sigterm, .sigint],
logger: Logger(label: "JobQueueService")
)
)
group.addTask {
try await serviceGroup.run()
}
let value = try await test(jobQueue)
await serviceGroup.triggerGracefulShutdown()
return value
}
}
func testBasic() async throws {
let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 10)
let jobIdentifer = JobIdentifier<Int>(#function)
try await self.testJobQueue(numWorkers: 1) { jobQueue in
jobQueue.registerJob(jobIdentifer) { parameters, context in
context.logger.info("Parameters=\(parameters)")
try await Task.sleep(for: .milliseconds(Int.random(in: 10..<50)))
expectation.fulfill()
}
try await jobQueue.push(id: jobIdentifer, parameters: 1)
try await jobQueue.push(id: jobIdentifer, parameters: 2)
try await jobQueue.push(id: jobIdentifer, parameters: 3)
try await jobQueue.push(id: jobIdentifer, parameters: 4)
try await jobQueue.push(id: jobIdentifer, parameters: 5)
try await jobQueue.push(id: jobIdentifer, parameters: 6)
try await jobQueue.push(id: jobIdentifer, parameters: 7)
try await jobQueue.push(id: jobIdentifer, parameters: 8)
try await jobQueue.push(id: jobIdentifer, parameters: 9)
try await jobQueue.push(id: jobIdentifer, parameters: 10)
await self.wait(for: [expectation], timeout: 5)
}
}
func testMultipleWorkers() async throws {
let jobIdentifer = JobIdentifier<Int>(#function)
let runningJobCounter = ManagedAtomic(0)
let maxRunningJobCounter = ManagedAtomic(0)
let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 10)
try await self.testJobQueue(numWorkers: 4) { jobQueue in
jobQueue.registerJob(jobIdentifer) { parameters, context in
let runningJobs = runningJobCounter.wrappingIncrementThenLoad(by: 1, ordering: .relaxed)
if runningJobs > maxRunningJobCounter.load(ordering: .relaxed) {
maxRunningJobCounter.store(runningJobs, ordering: .relaxed)
}
try await Task.sleep(for: .milliseconds(Int.random(in: 10..<50)))
context.logger.info("Parameters=\(parameters)")
expectation.fulfill()
runningJobCounter.wrappingDecrement(by: 1, ordering: .relaxed)
}
try await jobQueue.push(id: jobIdentifer, parameters: 1)
try await jobQueue.push(id: jobIdentifer, parameters: 2)
try await jobQueue.push(id: jobIdentifer, parameters: 3)
try await jobQueue.push(id: jobIdentifer, parameters: 4)
try await jobQueue.push(id: jobIdentifer, parameters: 5)
try await jobQueue.push(id: jobIdentifer, parameters: 6)
try await jobQueue.push(id: jobIdentifer, parameters: 7)
try await jobQueue.push(id: jobIdentifer, parameters: 8)
try await jobQueue.push(id: jobIdentifer, parameters: 9)
try await jobQueue.push(id: jobIdentifer, parameters: 10)
await self.wait(for: [expectation], timeout: 5)
XCTAssertGreaterThan(maxRunningJobCounter.load(ordering: .relaxed), 1)
XCTAssertLessThanOrEqual(maxRunningJobCounter.load(ordering: .relaxed), 4)
}
}
func testErrorRetryCount() async throws {
let jobIdentifer = JobIdentifier<Int>(#function)
let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 4)
struct FailedError: Error {}
try await self.testJobQueue(numWorkers: 1) { jobQueue in
jobQueue.registerJob(jobIdentifer, maxRetryCount: 3) { _, _ in
expectation.fulfill()
throw FailedError()
}
try await jobQueue.push(id: jobIdentifer, parameters: 0)
await self.wait(for: [expectation], timeout: 5)
try await Task.sleep(for: .milliseconds(200))
let failedJobs = try await jobQueue.queue.redisConnectionPool.llen(of: jobQueue.queue.configuration.failedQueueKey).get()
XCTAssertEqual(failedJobs, 1)
let pendingJobs = try await jobQueue.queue.redisConnectionPool.llen(of: jobQueue.queue.configuration.queueKey).get()
XCTAssertEqual(pendingJobs, 0)
}
}
func testJobSerialization() async throws {
struct TestJobParameters: Codable {
let id: Int
let message: String
}
let expectation = XCTestExpectation(description: "TestJob.execute was called")
let jobIdentifer = JobIdentifier<TestJobParameters>(#function)
try await self.testJobQueue(numWorkers: 1) { jobQueue in
jobQueue.registerJob(jobIdentifer) { parameters, _ in
XCTAssertEqual(parameters.id, 23)
XCTAssertEqual(parameters.message, "Hello!")
expectation.fulfill()
}
try await jobQueue.push(id: jobIdentifer, parameters: .init(id: 23, message: "Hello!"))
await self.wait(for: [expectation], timeout: 5)
}
}
/// Test job is cancelled on shutdown
func testShutdownJob() async throws {
let jobIdentifer = JobIdentifier<Int>(#function)
let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 1)
var logger = Logger(label: "HummingbirdJobsTests")
logger.logLevel = .trace
try await self.testJobQueue(numWorkers: 4) { jobQueue in
jobQueue.registerJob(jobIdentifer) { _, _ in
expectation.fulfill()
try await Task.sleep(for: .milliseconds(1000))
}
try await jobQueue.push(id: jobIdentifer, parameters: 0)
await self.wait(for: [expectation], timeout: 5)
let pendingJobs = try await jobQueue.queue.redisConnectionPool.llen(of: jobQueue.queue.configuration.queueKey).get()
XCTAssertEqual(pendingJobs, 0)
let failedJobs = try await jobQueue.queue.redisConnectionPool.llen(of: jobQueue.queue.configuration.failedQueueKey).get()
let processingJobs = try await jobQueue.queue.redisConnectionPool.llen(of: jobQueue.queue.configuration.processingQueueKey).get()
XCTAssertEqual(failedJobs + processingJobs, 1)
}
}
/// test job fails to decode but queue continues to process
func testFailToDecode() async throws {
let string: NIOLockedValueBox<String> = .init("")
let jobIdentifer1 = JobIdentifier<Int>(#function)
let jobIdentifer2 = JobIdentifier<String>(#function)
let expectation = XCTestExpectation(description: "job was called", expectedFulfillmentCount: 1)
try await self.testJobQueue(numWorkers: 4) { jobQueue in
jobQueue.registerJob(jobIdentifer2) { parameters, _ in
string.withLockedValue { $0 = parameters }
expectation.fulfill()
}
try await jobQueue.push(id: jobIdentifer1, parameters: 2)
try await jobQueue.push(id: jobIdentifer2, parameters: "test")
await self.wait(for: [expectation], timeout: 5)
}
string.withLockedValue {
XCTAssertEqual($0, "test")
}
}
/// creates job that errors on first attempt, and is left on processing queue and
/// is then rerun on startup of new server
func testRerunAtStartup() async throws {
struct RetryError: Error {}
let jobIdentifer = JobIdentifier<Int>(#function)
let firstTime = ManagedAtomic(true)
let finished = ManagedAtomic(false)
let failedExpectation = XCTestExpectation(description: "TestJob failed", expectedFulfillmentCount: 1)
let succeededExpectation = XCTestExpectation(description: "TestJob2 succeeded", expectedFulfillmentCount: 1)
let job = JobDefinition(id: jobIdentifer) { _, _ in
if firstTime.compareExchange(expected: true, desired: false, ordering: .relaxed).original {
failedExpectation.fulfill()
throw RetryError()
}
succeededExpectation.fulfill()
finished.store(true, ordering: .relaxed)
}
try await self.testJobQueue(numWorkers: 4) { jobQueue in
jobQueue.registerJob(job)
try await jobQueue.push(id: jobIdentifer, parameters: 0)
await self.wait(for: [failedExpectation], timeout: 10)
// stall to give job chance to start running
try await Task.sleep(for: .milliseconds(50))
XCTAssertFalse(firstTime.load(ordering: .relaxed))
XCTAssertFalse(finished.load(ordering: .relaxed))
}
try await self.testJobQueue(numWorkers: 4, failedJobsInitialization: .rerun) { jobQueue in
jobQueue.registerJob(job)
await self.wait(for: [succeededExpectation], timeout: 10)
XCTAssertTrue(finished.load(ordering: .relaxed))
}
}
func testMultipleJobQueueHandlers() async throws {
let jobIdentifer = JobIdentifier<Int>(#function)
let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 200)
let logger = {
var logger = Logger(label: "HummingbirdJobsTests")
logger.logLevel = .debug
return logger
}()
let job = JobDefinition(id: jobIdentifer) { parameters, context in
context.logger.info("Parameters=\(parameters)")
try await Task.sleep(for: .milliseconds(Int.random(in: 10..<50)))
expectation.fulfill()
}
let redisService = try RedisConnectionPoolService(
.init(hostname: Self.redisHostname, port: 6379),
logger: Logger(label: "Redis")
)
let jobQueue = JobQueue(
RedisQueue(redisService),
numWorkers: 2,
logger: logger
)
jobQueue.registerJob(job)
let jobQueue2 = JobQueue(
RedisQueue(redisService),
numWorkers: 2,
logger: logger
)
jobQueue2.registerJob(job)
try await withThrowingTaskGroup(of: Void.self) { group in
let serviceGroup = ServiceGroup(
configuration: .init(
services: [jobQueue, jobQueue2],
gracefulShutdownSignals: [.sigterm, .sigint],
logger: logger
)
)
group.addTask {
try await serviceGroup.run()
}
do {
for i in 0..<200 {
try await jobQueue.push(id: jobIdentifer, parameters: i)
}
await self.wait(for: [expectation], timeout: 5)
await serviceGroup.triggerGracefulShutdown()
} catch {
XCTFail("\(String(reflecting: error))")
await serviceGroup.triggerGracefulShutdown()
throw error
}
}
}
}