1 import { Modules } from "@medusajs/framework/utils"
2 import { MedusaContainer } from "@medusajs/framework/types"
3
4 /**
5 * Waits for all workflow executions to finish. When relying on workflows but not necessarily
6 * waiting for them to finish, this can be used to ensure that a test is not considered done while background executions are still running and can interfere with the other tests.
7 * @param container - The container instance.
8 * @returns A promise that resolves when all workflow executions have finished.
9 */
10 export async function waitWorkflowExecutions(container: MedusaContainer) {
11 const wfe = container.resolve(Modules.WORKFLOW_ENGINE, {
12 allowUnregistered: true,
13 })
14 if (!wfe) {
15 return
16 }
17
18 const timeout = setTimeout(() => {
19 throw new Error("Timeout waiting for workflow executions to finish")
20 }, 60000).unref()
21
22 let waitWorkflowsToFinish = true
23 while (waitWorkflowsToFinish) {
24 const executions = await wfe.listWorkflowExecutions({
25 state: { $nin: ["not_started", "done", "reverted", "failed"] },
26 })
27
28 if (executions.length === 0) {
29 waitWorkflowsToFinish = false
30 clearTimeout(timeout)
31 break
32 }
33 await new Promise((resolve) => setTimeout(resolve, 50))
34 }
35 }