feat: Add support for scheduled workflows (#7651)

We still need to:
But wanted to open the PR for early feedback on the approach
This commit is contained in:
Stevche Radevski
2024-06-10 16:49:52 +02:00
committed by GitHub
parent 7f53fe06b6
commit 69410162f6
20 changed files with 465 additions and 44 deletions

View File

@@ -0,0 +1,23 @@
import { SchedulerOptions } from "@medusajs/orchestration"
import {
createStep,
createWorkflow,
StepResponse,
} from "@medusajs/workflows-sdk"
export const createScheduled = (name: string, schedule?: SchedulerOptions) => {
const workflowScheduledStepInvoke = jest.fn((input, context) => {
return new StepResponse({})
})
const step = createStep("step_1", workflowScheduledStepInvoke)
createWorkflow(
{ name, schedule: schedule ?? "* * * * * *" },
function (input) {
return step(input)
}
)
return workflowScheduledStepInvoke
}

View File

@@ -10,6 +10,7 @@ import { knex } from "knex"
import { setTimeout } from "timers/promises"
import "../__fixtures__"
import { DB_URL, TestDatabase } from "../utils"
import { createScheduled } from "../__fixtures__/workflow_scheduled"
const sharedPgConnection = knex<any, any>({
client: "pg",
@@ -297,4 +298,23 @@ describe("Workflow Orchestrator module", function () {
expect(onFinish).toHaveBeenCalledTimes(0)
})
})
// Note: These tests depend on actual Redis instance and waiting for the scheduled jobs to run, which isn't great.
// Mocking bullmq, however, would make the tests close to useless, so we can keep them very minimal and serve as smoke tests.
describe("Scheduled workflows", () => {
it("should execute a scheduled workflow", async () => {
const spy = createScheduled("standard")
await setTimeout(3100)
expect(spy).toHaveBeenCalledTimes(3)
})
it("should stop executions after the set number of executions", async () => {
const spy = await createScheduled("num-executions", {
cron: "* * * * * *",
numberOfExecutions: 2,
})
await setTimeout(3100)
expect(spy).toHaveBeenCalledTimes(2)
})
})
})