1 import type { SchedulerOptions } from "@medusajs/orchestration"
2 import { MedusaContainer } from "@medusajs/types"
3 import {
4 dynamicImport,
5 isFileSkipped,
6 isObject,
7 MedusaError,
8 registerDevServerResource,
9 } from "@medusajs/utils"
10 import {
11 createStep,
12 createWorkflow,
13 StepResponse,
14 WorkflowData,
15 WorkflowResponse,
16 } from "@medusajs/workflows-sdk"
17 import { ResourceLoader } from "../utils/resource-loader"
18 import {
19 ScheduledJobContext,
20 ScheduledJobHandler,
21 ScheduledJobWorkflowInput,
22 } from "./types"
23
24 type CronJobConfig = {
25 name: string
26 schedule: string | SchedulerOptions
27 numberOfExecutions?: SchedulerOptions["numberOfExecutions"]
28 }
29
30 type CronJobHandler = ScheduledJobHandler
31
32 export class JobLoader extends ResourceLoader {
33 protected resourceName = "job"
34
35 constructor(sourceDir: string | string[], container: MedusaContainer) {
36 super(sourceDir, container)
37 }
38
39 async loadFile(path: string) {
40 const exports = await dynamicImport(path)
41 await this.onFileLoaded(path, exports)
42 }
43
44 protected async onFileLoaded(
45 path: string,
46 fileExports: {
47 default: CronJobHandler
48 config: CronJobConfig
49 }
50 ) {
51 if (isFileSkipped(fileExports)) {
52 return
53 }
54
55 this.validateConfig(fileExports.config)
56 this.logger.debug(`Registering job from ${path}.`)
57 this.register({
58 path,
59 config: fileExports.config,
60 handler: fileExports.default,
61 })
62 }
63
64 /**
65 * Validate cron job configuration
66 * @param config
67 * @protected
68 */
69 protected validateConfig(config: {
70 schedule: string | SchedulerOptions
71 name: string
72 }) {
73 if (!config) {
74 throw new MedusaError(
75 MedusaError.Types.INVALID_ARGUMENT,
76 "Config is required for scheduled jobs."
77 )
78 }
79
80 if (!config.schedule) {
81 throw new MedusaError(
82 MedusaError.Types.INVALID_ARGUMENT,
83 "Cron schedule definition is required for scheduled jobs."
84 )
85 }
86
87 if (!config.name) {
88 throw new MedusaError(
89 MedusaError.Types.INVALID_ARGUMENT,
90 "Job name is required for scheduled jobs."
91 )
92 }
93 }
94
95 /**
96 * Create a workflow to register a new cron job
97 * @param config
98 * @param handler
99 * @protected
100 */
101 protected register({
102 path,
103 config,
104 handler,
105 }: {
106 path: string
107 config: CronJobConfig
108 handler: CronJobHandler
109 }) {
110 const workflowName = `job-${config.name}`
111 const step = createStep(
112 `${config.name}-as-step`,
113 async (input: ScheduledJobWorkflowInput | undefined, stepContext) => {
114 const { container } = stepContext
115 const context: ScheduledJobContext = {
116 scheduledFor: input?.scheduledFor
117 ? new Date(input.scheduledFor)
118 : new Date(),
119 }
120
121 try {
122 const res = await handler(container, context)
123 return new StepResponse(res, res)
124 } catch (error) {
125 this.logger.error(
126 `Scheduled job ${config.name} failed with error: ${error.message}`
127 )
128 throw error
129 }
130 }
131 )
132
133 const workflowConfig = {
134 name: workflowName,
135 schedule: isObject(config.schedule)
136 ? config.schedule
137 : {
138 cron: config.schedule,
139 numberOfExecutions: config.numberOfExecutions,
140 },
141 }
142
143 createWorkflow(
144 workflowConfig,
145 (input: WorkflowData<ScheduledJobWorkflowInput>) => {
146 return new WorkflowResponse(step(input))
147 }
148 )
149
150 registerDevServerResource({
151 sourcePath: path,
152 id: workflowName,
153 type: "job",
154 config: config,
155 })
156 }
157
158 /**
159 * Load cron jobs from one or multiple source paths
160 */
161 async load() {
162 await super.discoverResources()
163
164 this.logger.debug(`Jobs registered.`)
165 }
166 }