1 import {
2 Context,
3 DAL,
4 FilterableWorkflowExecutionProps,
5 FindConfig,
6 IdempotencyKeyParts,
7 InferEntityType,
8 InternalModuleDeclaration,
9 ModulesSdkTypes,
10 WorkflowExecutionDTO,
11 WorkflowsSdkTypes,
12 } from "@medusajs/framework/types"
13 import {
14 InjectManager,
15 InjectSharedContext,
16 isDefined,
17 MedusaContext,
18 ModulesSdkUtils,
19 } from "@medusajs/framework/utils"
20 import type {
21 ReturnWorkflow,
22 UnwrapWorkflowInputDataType,
23 } from "@medusajs/framework/workflows-sdk"
24 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
25 import { WorkflowExecution } from "@models"
26 import { WorkflowOrchestratorService } from "@services"
27 import { WorkflowOrchestratorCancelOptions } from "@types"
28
29 type InjectedDependencies = {
30 manager: SqlEntityManager
31 baseRepository: DAL.RepositoryService
32 workflowExecutionService: ModulesSdkTypes.IMedusaInternalService<any>
33 workflowOrchestratorService: WorkflowOrchestratorService
34 }
35
36 export class WorkflowsModuleService<
37 TWorkflowExecution extends InferEntityType<
38 typeof WorkflowExecution
39 > = InferEntityType<typeof WorkflowExecution>
40 > extends ModulesSdkUtils.MedusaService<{
41 WorkflowExecution: { dto: InferEntityType<typeof WorkflowExecution> }
42 }>({ WorkflowExecution }) {
43 protected baseRepository_: DAL.RepositoryService
44 protected workflowExecutionService_: ModulesSdkTypes.IMedusaInternalService<TWorkflowExecution>
45 protected workflowOrchestratorService_: WorkflowOrchestratorService
46 protected manager_: SqlEntityManager
47
48 constructor(
49 {
50 manager,
51 baseRepository,
52 workflowExecutionService,
53 workflowOrchestratorService,
54 }: InjectedDependencies,
55 protected readonly moduleDeclaration: InternalModuleDeclaration
56 ) {
57 // @ts-ignore
58 super(...arguments)
59
60 this.manager_ = manager
61 this.baseRepository_ = baseRepository
62 this.workflowExecutionService_ = workflowExecutionService
63 this.workflowOrchestratorService_ = workflowOrchestratorService
64 }
65
66 __hooks = {
67 onApplicationStart: async () => {
68 await this.workflowOrchestratorService_.onApplicationStart()
69 },
70 onApplicationShutdown: async () => {
71 await this.workflowOrchestratorService_.onApplicationShutdown()
72 },
73 }
74
75 static prepareFilters<T>(filters: T & { q?: string }) {
76 const filters_ = { ...filters } // shallow copy
77 if (filters_?.q) {
78 const q = filters_.q
79 delete filters_.q
80
81 const textSearch = { $ilike: `%${q}%` }
82 const textSearchFilters = {
83 $or: [
84 {
85 transaction_id: textSearch,
86 },
87 {
88 workflow_id: textSearch,
89 },
90 {
91 state: textSearch,
92 },
93 {
94 execution: {
95 runId: textSearch,
96 },
97 },
98 ],
99 }
100
101 if (!Object.keys(filters_).length) {
102 return textSearchFilters
103 } else {
104 return { $and: [filters, textSearchFilters] }
105 }
106 }
107
108 return filters
109 }
110
111 @InjectManager()
112 // @ts-expect-error
113 async listWorkflowExecutions(
114 filters: FilterableWorkflowExecutionProps = {},
115 config?: FindConfig<WorkflowExecutionDTO>,
116 @MedusaContext() sharedContext?: Context
117 ) {
118 const filters_ = WorkflowsModuleService.prepareFilters(filters)
119 return await super.listWorkflowExecutions(filters_, config, sharedContext)
120 }
121
122 @InjectManager()
123 // @ts-expect-error
124 async listAndCountWorkflowExecutions(
125 filters: FilterableWorkflowExecutionProps = {},
126 config?: FindConfig<WorkflowExecutionDTO>,
127 @MedusaContext() sharedContext?: Context
128 ) {
129 const filters_ = WorkflowsModuleService.prepareFilters(filters)
130 return await super.listAndCountWorkflowExecutions(
131 filters_,
132 config,
133 sharedContext
134 )
135 }
136
137 @InjectSharedContext()
138 async run<TWorkflow extends string | ReturnWorkflow<any, any, any>>(
139 workflowIdOrWorkflow: TWorkflow,
140 options: WorkflowsSdkTypes.WorkflowOrchestratorRunDTO<
141 TWorkflow extends ReturnWorkflow<any, any, any>
142 ? UnwrapWorkflowInputDataType<TWorkflow>
143 : unknown
144 > = {},
145 @MedusaContext() context: Context = {}
146 ) {
147 const options_ = JSON.parse(JSON.stringify(options ?? {}))
148
149 const {
150 manager,
151 transactionManager,
152 preventReleaseEvents,
153 transactionId,
154 parentStepIdempotencyKey,
155 ...restContext
156 } = context
157
158 let localPreventReleaseEvents = false
159
160 if (isDefined(options_.context?.preventReleaseEvents)) {
161 localPreventReleaseEvents = options_.context!.preventReleaseEvents!
162 } else {
163 if (
164 isDefined(context.eventGroupId) &&
165 isDefined(options_.context?.eventGroupId) &&
166 context.eventGroupId === options_.context?.eventGroupId
167 ) {
168 localPreventReleaseEvents = true
169 }
170 }
171
172 let eventGroupId
173
174 if (options_.context?.eventGroupId) {
175 eventGroupId = options_.context.eventGroupId
176 } else if (localPreventReleaseEvents && context.eventGroupId) {
177 eventGroupId = context.eventGroupId
178 }
179
180 options_.context = {
181 ...(restContext ?? {}),
182 ...(options_.context ?? {}),
183 eventGroupId,
184 runId: options_.runId,
185 preventReleaseEvents: localPreventReleaseEvents,
186 }
187
188 const ret = await this.workflowOrchestratorService_.run<
189 TWorkflow extends ReturnWorkflow<any, any, any>
190 ? UnwrapWorkflowInputDataType<TWorkflow>
191 : unknown
192 >(workflowIdOrWorkflow, options_)
193
194 return ret as any
195 }
196
197 @InjectSharedContext()
198 async getRunningTransaction(
199 workflowId: string,
200 transactionId: string,
201 @MedusaContext() context: Context = {}
202 ) {
203 return await this.workflowOrchestratorService_.getRunningTransaction(
204 workflowId,
205 transactionId,
206 context
207 )
208 }
209
210 @InjectSharedContext()
211 async retryStep(
212 {
213 idempotencyKey,
214 options,
215 }: {
216 idempotencyKey: string | IdempotencyKeyParts
217 options?: Record<string, any>
218 },
219 @MedusaContext() context: Context = {}
220 ) {
221 const options_ = JSON.parse(JSON.stringify(options ?? {}))
222
223 const { manager, transactionManager, ...restContext } = context
224
225 options_.context ??= restContext
226
227 return await this.workflowOrchestratorService_.retryStep({
228 idempotencyKey,
229 options: options_,
230 })
231 }
232
233 @InjectSharedContext()
234 async setStepSuccess(
235 {
236 idempotencyKey,
237 stepResponse,
238 options,
239 }: {
240 idempotencyKey: string | object
241 stepResponse: unknown
242 options?: Record<string, any>
243 },
244 @MedusaContext() context: Context = {}
245 ) {
246 const options_ = JSON.parse(JSON.stringify(options ?? {}))
247
248 const { manager, transactionManager, ...restContext } = context
249
250 options_.context ??= restContext
251
252 return await this.workflowOrchestratorService_.setStepSuccess({
253 idempotencyKey,
254 stepResponse,
255 options,
256 } as any)
257 }
258
259 @InjectSharedContext()
260 async setStepFailure(
261 {
262 idempotencyKey,
263 stepResponse,
264 options,
265 }: {
266 idempotencyKey: string | object
267 stepResponse: unknown
268 options?: Record<string, any> & {
269 forcePermanentFailure?: boolean
270 }
271 },
272 @MedusaContext() context: Context = {}
273 ) {
274 const options_ = JSON.parse(JSON.stringify(options ?? {}))
275
276 const { manager, transactionManager, ...restContext } = context
277
278 options_.context ??= restContext
279
280 return await this.workflowOrchestratorService_.setStepFailure({
281 idempotencyKey,
282 stepResponse,
283 options,
284 } as any)
285 }
286
287 async subscribe(args: {
288 workflowId: string
289 transactionId?: string
290 subscriber: Function
291 subscriberId?: string
292 }) {
293 return this.workflowOrchestratorService_.subscribe(args as any)
294 }
295
296 async unsubscribe(args: {
297 workflowId: string
298 transactionId?: string
299 subscriberOrId: string | Function
300 }) {
301 return this.workflowOrchestratorService_.unsubscribe(args as any)
302 }
303
304 async cancel<TWorkflow extends string | ReturnWorkflow<any, any, any>>(
305 workflowIdOrWorkflow: TWorkflow,
306 options: WorkflowOrchestratorCancelOptions
307 ) {
308 return await this.workflowOrchestratorService_.cancel(
309 workflowIdOrWorkflow,
310 options
311 )
312 }
313 }