|
1
|
import { setTimeout } from "node:timers/promises" |
|
2
|
import { RedisLockingProvider } from "../redis-lock" |
|
3
|
|
|
4
|
jest.mock("node:timers/promises", () => ({ |
|
5
|
setTimeout: jest.fn().mockResolvedValue(undefined), |
|
6
|
})) |
|
7
|
|
|
8
|
describe("RedisLockingProvider Jitter", () => { |
|
9
|
let provider: RedisLockingProvider |
|
10
|
const redisClientMock = { |
|
11
|
defineCommand: jest.fn(), |
|
12
|
acquireLock: jest.fn(), |
|
13
|
} |
|
14
|
|
|
15
|
beforeEach(() => { |
|
16
|
provider = new RedisLockingProvider( |
|
17
|
{ |
|
18
|
redisClient: redisClientMock as any, |
|
19
|
prefix: "test:", |
|
20
|
}, |
|
21
|
{ |
|
22
|
defaultRetryInterval: 100, |
|
23
|
backoffFactor: 2, |
|
24
|
} as any |
|
25
|
) |
|
26
|
jest.clearAllMocks() |
|
27
|
}) |
|
28
|
|
|
29
|
it("should apply jitter between 50% and 100% of the retryDelay", async () => { |
|
30
|
// Mock acquireLock to fail once then succeed |
|
31
|
redisClientMock.acquireLock |
|
32
|
.mockResolvedValueOnce(0) |
|
33
|
.mockResolvedValueOnce(1) |
|
34
|
|
|
35
|
await provider.acquire("test-key", { awaitQueue: true }) |
|
36
|
|
|
37
|
// The first retryDelay should be the defaultRetryInterval (100) |
|
38
|
const expectedBaseDelay = 100 |
|
39
|
|
|
40
|
expect(setTimeout).toHaveBeenCalledTimes(1) |
|
41
|
const actualDelay = (setTimeout as jest.Mock).mock.calls[0][0] |
|
42
|
|
|
43
|
expect(actualDelay).toBeGreaterThanOrEqual(expectedBaseDelay * 0.5) |
|
44
|
expect(actualDelay).toBeLessThanOrEqual(expectedBaseDelay) |
|
45
|
}) |
|
46
|
|
|
47
|
it("should apply jitter to subsequent exponential backoff steps", async () => { |
|
48
|
// Mock acquireLock to fail twice then succeed |
|
49
|
redisClientMock.acquireLock |
|
50
|
.mockResolvedValueOnce(0) |
|
51
|
.mockResolvedValueOnce(0) |
|
52
|
.mockResolvedValueOnce(1) |
|
53
|
|
|
54
|
await provider.acquire("test-key", { awaitQueue: true }) |
|
55
|
|
|
56
|
expect(setTimeout).toHaveBeenCalledTimes(2) |
|
57
|
|
|
58
|
// First delay (base 100) |
|
59
|
const firstDelay = (setTimeout as jest.Mock).mock.calls[0][0] |
|
60
|
expect(firstDelay).toBeGreaterThanOrEqual(100 * 0.5) |
|
61
|
expect(firstDelay).toBeLessThanOrEqual(100) |
|
62
|
|
|
63
|
// Second delay (base 200, due to backoffFactor 2) |
|
64
|
const secondDelay = (setTimeout as jest.Mock).mock.calls[1][0] |
|
65
|
expect(secondDelay).toBeGreaterThanOrEqual(200 * 0.5) |
|
66
|
expect(secondDelay).toBeLessThanOrEqual(200) |
|
67
|
}) |
|
68
|
}) |