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