1 import { MedusaError } from "@medusajs/framework/utils"
2 import { setTimeout as delay } from "node:timers/promises"
3 import { RedisLockingProvider } from "../redis-lock"
4
5 // The promisified timer is only used to wait — for the acquisition timeout, and
6 // between acquisition retries. Neither should fire on its own here, so it hangs
7 // by default and each test resolves it when it wants that wait to end.
8 jest.mock("node:timers/promises", () => ({
9 setTimeout: jest.fn(),
10 }))
11
12 const delayMock = delay as unknown as jest.Mock
13
14 describe("RedisLockingProvider - execute", () => {
15 let provider: RedisLockingProvider
16
17 const redisClientMock = {
18 defineCommand: jest.fn(),
19 acquireLock: jest.fn(),
20 releaseLock: jest.fn(),
21 extendLock: jest.fn(),
22 }
23
24 // Lets the pending microtasks run without moving the clock, so `execute` gets
25 // past acquiring the lock and into the job.
26 const settle = async () => {
27 await jest.advanceTimersByTimeAsync(0)
28 }
29
30 beforeEach(() => {
31 jest.clearAllMocks()
32 jest.useFakeTimers()
33
34 delayMock.mockImplementation(() => new Promise(() => {}))
35 redisClientMock.acquireLock.mockResolvedValue(1)
36 redisClientMock.releaseLock.mockResolvedValue(1)
37 redisClientMock.extendLock.mockResolvedValue(1)
38
39 provider = new RedisLockingProvider(
40 {
41 redisClient: redisClientMock as any,
42 prefix: "test:",
43 },
44 {} as any
45 )
46 })
47
48 afterEach(() => {
49 jest.useRealTimers()
50 })
51
52 it("should release the lock under the same owner it acquired it with", async () => {
53 const job = jest.fn(async () => "done")
54
55 await expect(provider.execute("key", job)).resolves.toBe("done")
56
57 expect(redisClientMock.acquireLock).toHaveBeenCalledTimes(1)
58
59 const [key, ownerId] = redisClientMock.acquireLock.mock.calls[0]
60
61 expect(key).toBe("test:key")
62 expect(ownerId).not.toEqual("*")
63 expect(redisClientMock.releaseLock).toHaveBeenCalledWith(
64 "test:key",
65 ownerId
66 )
67 })
68
69 it("should give every call its own owner", async () => {
70 await provider.execute("key", async () => {})
71 await provider.execute("key", async () => {})
72
73 const [firstOwner, secondOwner] =
74 redisClientMock.acquireLock.mock.calls.map((call) => call[1])
75
76 expect(firstOwner).not.toEqual(secondOwner)
77 })
78
79 it("should keep the lease independent of the acquisition timeout", async () => {
80 await provider.execute("key", async () => {}, { timeout: 2 })
81
82 expect(redisClientMock.acquireLock).toHaveBeenCalledWith(
83 "test:key",
84 expect.any(String),
85 60,
86 true
87 )
88 })
89
90 it("should acquire the lease for the requested expiration", async () => {
91 await provider.execute("key", async () => {}, { expire: 900 })
92
93 expect(redisClientMock.acquireLock).toHaveBeenCalledWith(
94 "test:key",
95 expect.any(String),
96 900,
97 true
98 )
99 })
100
101 it("should renew the lease while the job is still running", async () => {
102 let finishJob: () => void
103 const job = jest.fn(
104 () =>
105 new Promise<void>((resolve) => {
106 finishJob = resolve
107 })
108 )
109
110 const executing = provider.execute("key", job, { expire: 30 })
111 await settle()
112
113 await jest.advanceTimersByTimeAsync(10_000)
114 expect(redisClientMock.extendLock).toHaveBeenCalledTimes(1)
115
116 await jest.advanceTimersByTimeAsync(10_000)
117 expect(redisClientMock.extendLock).toHaveBeenCalledTimes(2)
118 expect(redisClientMock.extendLock).toHaveBeenLastCalledWith(
119 "test:key",
120 expect.any(String),
121 30
122 )
123
124 finishJob!()
125 await executing
126
127 // Nothing keeps renewing a lock that has already been released.
128 await jest.advanceTimersByTimeAsync(60_000)
129 expect(redisClientMock.extendLock).toHaveBeenCalledTimes(2)
130 })
131
132 it("should renew every key it locked", async () => {
133 let finishJob: () => void
134 const job = jest.fn(
135 () =>
136 new Promise<void>((resolve) => {
137 finishJob = resolve
138 })
139 )
140
141 const executing = provider.execute(["key_1", "key_2"], job, { expire: 30 })
142 await settle()
143
144 await jest.advanceTimersByTimeAsync(10_000)
145
146 expect(redisClientMock.extendLock).toHaveBeenCalledWith(
147 "test:key_1",
148 expect.any(String),
149 30
150 )
151 expect(redisClientMock.extendLock).toHaveBeenCalledWith(
152 "test:key_2",
153 expect.any(String),
154 30
155 )
156
157 finishJob!()
158 await executing
159 })
160
161 it("should abort the job's signal and throw when the lease is lost", async () => {
162 redisClientMock.extendLock.mockResolvedValue(0)
163
164 let observedSignal: AbortSignal | undefined
165 const job = jest.fn(async (signal?: AbortSignal) => {
166 observedSignal = signal
167
168 await new Promise<void>((resolve) => {
169 signal?.addEventListener("abort", () => resolve())
170 })
171
172 return "finished anyway"
173 })
174
175 const executing = provider
176 .execute("key", job, { expire: 3 })
177 .catch((error) => error)
178
179 await settle()
180 await jest.advanceTimersByTimeAsync(1_000)
181
182 const error = await executing
183
184 expect(observedSignal?.aborted).toBe(true)
185 expect(error.type).toEqual(MedusaError.Types.CONFLICT)
186 expect(error.message).toContain("Lost the lock")
187 })
188
189 it("should keep the job running when a renewal cannot reach redis", async () => {
190 redisClientMock.extendLock
191 .mockRejectedValueOnce(new Error("Connection is closed."))
192 .mockResolvedValue(1)
193
194 let finishJob: () => void
195 const job = jest.fn(
196 () =>
197 new Promise<string>((resolve) => {
198 finishJob = () => resolve("done")
199 })
200 )
201
202 const executing = provider.execute("key", job, { expire: 3 })
203 await settle()
204
205 await jest.advanceTimersByTimeAsync(1_000)
206 await jest.advanceTimersByTimeAsync(1_000)
207
208 expect(redisClientMock.extendLock).toHaveBeenCalledTimes(2)
209
210 finishJob!()
211 await expect(executing).resolves.toBe("done")
212 })
213
214 it("should release a lock that was acquired after the acquisition timed out", async () => {
215 let landAcquisition: (result: number) => void
216 redisClientMock.acquireLock.mockReturnValue(
217 new Promise((resolve) => {
218 landAcquisition = resolve
219 })
220 )
221
222 // The first wait is the acquisition timeout, which this test fires by hand.
223 let fireTimeout: () => void
224 delayMock.mockReturnValueOnce(
225 new Promise((resolve) => {
226 fireTimeout = () => resolve(undefined)
227 })
228 )
229
230 const job = jest.fn(async () => "unreachable")
231 const executing = provider
232 .execute("key", job, { timeout: 1 })
233 .catch((error) => error)
234
235 await settle()
236 fireTimeout!()
237
238 const error = await executing
239
240 expect(error.message).toEqual("Timed-out acquiring lock.")
241 expect(job).not.toHaveBeenCalled()
242
243 // The `SET` was already in flight when the timeout fired, so the keys end
244 // up locked with nobody to use them. They have to be handed back.
245 landAcquisition!(1)
246 await settle()
247
248 expect(redisClientMock.releaseLock).toHaveBeenCalledWith(
249 "test:key",
250 expect.any(String)
251 )
252 })
253 })