1 import { IWorkflowEngineService } from "@medusajs/framework/types"
2 import { Modules, TransactionHandlerType } from "@medusajs/framework/utils"
3 import {
4 createStep,
5 createWorkflow,
6 parallelize,
7 StepResponse,
8 transform,
9 WorkflowResponse,
10 } from "@medusajs/framework/workflows-sdk"
11 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
12 import { setTimeout } from "timers/promises"
13 import { ulid } from "ulid"
14 import "../__fixtures__"
15
16 jest.setTimeout(30000)
17
18 moduleIntegrationTestRunner<IWorkflowEngineService>({
19 moduleName: Modules.WORKFLOW_ENGINE,
20 resolve: __dirname + "/../..",
21 testSuite: ({ service: workflowOrcModule }) => {
22 describe("Testing race condition of the workflow during retry", () => {
23 it("should manage saving multiple async steps in concurrency", async () => {
24 const step0 = createStep(
25 { name: "step0", async: true, backgroundExecution: true },
26 async () => {
27 return new StepResponse("result from step 0")
28 }
29 )
30
31 const step1 = createStep(
32 { name: "step1", async: true, backgroundExecution: true },
33 async () => {
34 return new StepResponse("result from step 1")
35 }
36 )
37
38 const step2 = createStep(
39 { name: "step2", async: true, backgroundExecution: true },
40 async () => {
41 return new StepResponse("result from step 2")
42 }
43 )
44 const step3 = createStep(
45 { name: "step3", async: true, backgroundExecution: true },
46 async () => {
47 return new StepResponse("result from step 3")
48 }
49 )
50
51 const step4 = createStep(
52 { name: "step4", async: true, backgroundExecution: true },
53 async () => {
54 return new StepResponse("result from step 4")
55 }
56 )
57 const step5 = createStep({ name: "step5" }, async (all: string[]) => {
58 const ret = [...all, "result from step 5"]
59 return new StepResponse(ret)
60 })
61
62 const workflowId = "workflow-1" + ulid()
63 createWorkflow(
64 {
65 name: workflowId,
66 idempotent: true,
67 retentionTime: 5,
68 },
69 function () {
70 const all = parallelize(step0(), step1(), step2(), step3(), step4())
71 const res = step5(all)
72 return new WorkflowResponse(res)
73 }
74 )
75
76 const transactionId = ulid()
77 const done = new Promise<void>((resolve, reject) => {
78 void workflowOrcModule.subscribe({
79 workflowId: workflowId,
80 transactionId,
81 subscriber: async (event) => {
82 if (event.eventType === "onFinish") {
83 resolve(event.result)
84 }
85 },
86 })
87 })
88
89 await workflowOrcModule.run(workflowId, {
90 throwOnError: false,
91 logOnError: true,
92 transactionId,
93 })
94
95 const result = await done
96
97 expect(result).toEqual([
98 "result from step 0",
99 "result from step 1",
100 "result from step 2",
101 "result from step 3",
102 "result from step 4",
103 "result from step 5",
104 ])
105 })
106
107 it("should manage saving multiple async steps in concurrency without background execution while setting steps as success manually concurrently", async () => {
108 const step0 = createStep({ name: "step0", async: true }, async () => {})
109
110 const step1 = createStep({ name: "step1", async: true }, async () => {})
111
112 const step2 = createStep({ name: "step2", async: true }, async () => {})
113 const step3 = createStep({ name: "step3", async: true }, async () => {})
114
115 const step4 = createStep({ name: "step4", async: true }, async () => {})
116 const step5 = createStep({ name: "step5" }, async (all: any[]) => {
117 const ret = [...all, "result from step 5"]
118 return new StepResponse(ret)
119 })
120
121 const workflowId = "workflow-1" + ulid()
122 createWorkflow(
123 {
124 name: workflowId,
125 idempotent: true,
126 retentionTime: 1,
127 },
128 function () {
129 const all = parallelize(step0(), step1(), step2(), step3(), step4())
130 const res = step5(all)
131 return new WorkflowResponse(res)
132 }
133 )
134
135 const transactionId = ulid()
136 const done = new Promise<void>((resolve, reject) => {
137 void workflowOrcModule.subscribe({
138 workflowId: workflowId,
139 transactionId,
140 subscriber: async (event) => {
141 if (event.eventType === "onFinish") {
142 resolve(event.result)
143 }
144 },
145 })
146 })
147
148 await workflowOrcModule.run(workflowId, {
149 throwOnError: false,
150 logOnError: true,
151 transactionId,
152 })
153
154 await setTimeout(100) // Just to wait a bit before firering everything
155
156 for (let i = 0; i <= 4; i++) {
157 void workflowOrcModule.setStepSuccess({
158 idempotencyKey: {
159 workflowId: workflowId,
160 transactionId: transactionId,
161 stepId: `step${i}`,
162 action: TransactionHandlerType.INVOKE,
163 },
164 stepResponse: new StepResponse("result from step " + i),
165 })
166 }
167
168 const res = await done
169
170 expect(res).toEqual([
171 "result from step 0",
172 "result from step 1",
173 "result from step 2",
174 "result from step 3",
175 "result from step 4",
176 "result from step 5",
177 ])
178 })
179
180 it("should prevent race continuation of the workflow during retryIntervalAwaiting in background execution", async () => {
181 const transactionId = "transaction_id" + ulid()
182 const workflowId = "RACE_workflow-1" + ulid()
183
184 const step0InvokeMock = jest.fn()
185 const step1InvokeMock = jest.fn()
186 const step2InvokeMock = jest.fn()
187 const transformMock = jest.fn()
188
189 const step0 = createStep("step0", async (_) => {
190 step0InvokeMock()
191 return new StepResponse("result from step 0")
192 })
193
194 const step1 = createStep("step1", async (_) => {
195 step1InvokeMock()
196 await setTimeout(200)
197 return new StepResponse({ isSuccess: true })
198 })
199
200 const step2 = createStep("step2", async (input: any) => {
201 step2InvokeMock()
202 return new StepResponse({ result: input })
203 })
204
205 const subWorkflow = createWorkflow("sub-workflow-1", function () {
206 const status = step1()
207 return new WorkflowResponse(status)
208 })
209
210 createWorkflow(
211 {
212 name: workflowId,
213 idempotent: true,
214 retentionTime: 5,
215 },
216 function () {
217 const build = step0()
218
219 const status = subWorkflow.runAsStep({} as any).config({
220 async: true,
221 compensateAsync: true,
222 backgroundExecution: true,
223 retryIntervalAwaiting: 0.1,
224 })
225
226 const transformedResult = transform({ status }, (data) => {
227 transformMock()
228 return {
229 status: data.status,
230 }
231 })
232
233 step2(transformedResult)
234 return new WorkflowResponse(build)
235 }
236 )
237
238 const onFinish = new Promise<void>((resolve) => {
239 void workflowOrcModule.subscribe({
240 workflowId,
241 transactionId,
242 subscriber: (event) => {
243 if (event.eventType === "onFinish") {
244 resolve()
245 }
246 },
247 })
248 })
249
250 workflowOrcModule
251 .run(workflowId, {
252 transactionId,
253 throwOnError: false,
254 logOnError: true,
255 })
256 .then(({ result }) => {
257 expect(result).toBe("result from step 0")
258 })
259
260 await onFinish
261
262 expect(step0InvokeMock).toHaveBeenCalledTimes(1)
263 expect(step1InvokeMock.mock.calls.length).toBeGreaterThan(1)
264 expect(step2InvokeMock).toHaveBeenCalledTimes(1)
265 expect(transformMock).toHaveBeenCalledTimes(1)
266 })
267
268 it("should prevent race continuation of the workflow compensation during retryIntervalAwaiting in background execution", async () => {
269 const transactionId = "transaction_id" + ulid()
270 const workflowId = "RACE_workflow-1" + ulid()
271
272 const step0InvokeMock = jest.fn()
273 const step0CompensateMock = jest.fn()
274 const step1InvokeMock = jest.fn()
275 const step1CompensateMock = jest.fn()
276 const step2InvokeMock = jest.fn()
277 const transformMock = jest.fn()
278
279 const step0 = createStep(
280 "RACE_step0",
281 async (_) => {
282 step0InvokeMock()
283 return new StepResponse("result from step 0")
284 },
285 () => {
286 step0CompensateMock()
287 }
288 )
289
290 const step1 = createStep(
291 "RACE_step1",
292 async (_) => {
293 step1InvokeMock()
294 await setTimeout(1000)
295 throw new Error("error from step 1")
296 },
297 () => {
298 step1CompensateMock()
299 }
300 )
301
302 const step2 = createStep("RACE_step2", async (input: any) => {
303 step2InvokeMock()
304 return new StepResponse({ result: input })
305 })
306
307 const subWorkflow = createWorkflow("RACE_sub-workflow-1", function () {
308 const status = step1()
309 return new WorkflowResponse(status)
310 })
311
312 createWorkflow(
313 {
314 name: workflowId,
315 },
316 function () {
317 const build = step0()
318
319 const status = subWorkflow.runAsStep({} as any).config({
320 async: true,
321 compensateAsync: true,
322 backgroundExecution: true,
323 retryIntervalAwaiting: 0.1,
324 maxAwaitingRetries: 3,
325 })
326
327 const transformedResult = transform({ status }, (data) => {
328 transformMock()
329 return {
330 status: data.status,
331 }
332 })
333
334 step2(transformedResult)
335 return new WorkflowResponse(build)
336 }
337 )
338
339 const onFinish = new Promise<void>((resolve) => {
340 void workflowOrcModule.subscribe({
341 workflowId,
342 transactionId,
343 subscriber: async (event) => {
344 if (event.eventType === "onFinish") {
345 resolve()
346 }
347 },
348 })
349 })
350
351 await workflowOrcModule
352 .run(workflowId, {
353 transactionId,
354 throwOnError: false,
355 logOnError: true,
356 })
357 .then(({ result }) => {
358 expect(result).toBe("result from step 0")
359 })
360
361 await onFinish
362
363 expect(step0InvokeMock).toHaveBeenCalledTimes(1)
364 expect(step0CompensateMock).toHaveBeenCalledTimes(1)
365 expect(step1InvokeMock).toHaveBeenCalledTimes(3)
366 expect(step1CompensateMock.mock.calls.length).toBeGreaterThan(0)
367 expect(step2InvokeMock).toHaveBeenCalledTimes(0)
368 expect(transformMock).toHaveBeenCalledTimes(0)
369 })
370 })
371 },
372 })