Raw
1 import { asValue } from "@medusajs/framework/awilix"
2 import {
3 DistributedTransactionType,
4 TransactionState,
5 TransactionStep,
6 TransactionStepTimeoutError,
7 TransactionTimeoutError,
8 WorkflowManager,
9 } from "@medusajs/framework/orchestration"
10 import {
11 IWorkflowEngineService,
12 Logger,
13 MedusaContainer,
14 RemoteQueryFunction,
15 } from "@medusajs/framework/types"
16 import {
17 ContainerRegistrationKeys,
18 Module,
19 Modules,
20 promiseAll,
21 TransactionHandlerType,
22 TransactionStepState,
23 } from "@medusajs/framework/utils"
24 import {
25 createStep,
26 createWorkflow,
27 StepResponse,
28 WorkflowResponse,
29 } from "@medusajs/framework/workflows-sdk"
30 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
31 import { setTimeout as setTimeoutSync } from "timers"
32 import { setTimeout } from "timers/promises"
33 import { ulid } from "ulid"
34 import { WorkflowsModuleService } from "../../src/services"
35 import "../__fixtures__"
36 import {
37 workflowNotIdempotentWithRetentionStep2Invoke,
38 workflowNotIdempotentWithRetentionStep3Invoke,
39 } from "../__fixtures__"
40 import {
41 step1CompensateMock as step1CompensateMockAutoRetries,
42 step1InvokeMock as step1InvokeMockAutoRetries,
43 step2CompensateMock as step2CompensateMockAutoRetries,
44 step2InvokeMock as step2InvokeMockAutoRetries,
45 } from "../__fixtures__/workflow_1_auto_retries"
46 import {
47 step1CompensateMock as step1CompensateMockAutoRetriesFalse,
48 step1InvokeMock as step1InvokeMockAutoRetriesFalse,
49 step2CompensateMock as step2CompensateMockAutoRetriesFalse,
50 step2InvokeMock as step2InvokeMockAutoRetriesFalse,
51 } from "../__fixtures__/workflow_1_auto_retries_false"
52 import { createScheduled } from "../__fixtures__/workflow_scheduled"
53
54 import {
55 step1InvokeMock as step1InvokeMockManualRetry,
56 step2InvokeMock as step2InvokeMockManualRetry,
57 } from "../__fixtures__/workflow_1_manual_retry_step"
58 import { TestDatabase } from "../utils"
59
60 jest.setTimeout(30000)
61
62 function times(num) {
63 let resolver
64 let counter = 0
65 const promise = new Promise((resolve) => {
66 resolver = resolve
67 })
68
69 return {
70 next: () => {
71 counter += 1
72 if (counter === num) {
73 resolver()
74 }
75 },
76 // Force resolution after 10 seconds to prevent infinite awaiting
77 promise: Promise.race([
78 promise,
79 new Promise((_, reject) => {
80 setTimeoutSync(
81 () => reject("times has not been resolved after 10 seconds."),
82 10000
83 )
84 }),
85 ]),
86 }
87 }
88
89 // REF:https://stackoverflow.com/questions/78028715/jest-async-test-with-event-emitter-isnt-ending
90
91 const testRunId = ulid()
92
93 moduleIntegrationTestRunner<IWorkflowEngineService>({
94 moduleName: Modules.WORKFLOW_ENGINE,
95 resolve: __dirname + "/../..",
96 moduleOptions: {
97 redis: {
98 redisUrl: "localhost:6379",
99 queueName: `medusa-workflows-${
100 process.env.JEST_WORKER_ID ?? "1"
101 }-${testRunId}`,
102 jobQueueName: `medusa-workflows-jobs-${
103 process.env.JEST_WORKER_ID ?? "1"
104 }-${testRunId}`,
105 },
106 },
107 testSuite: ({ service: workflowOrcModule, medusaApp }) => {
108 describe("Workflow Orchestrator module", function () {
109 beforeEach(async () => {
110 await TestDatabase.clearTables()
111 jest.clearAllMocks()
112
113 query = medusaApp.query
114 sharedContainer_ = medusaApp.sharedContainer
115 })
116
117 afterEach(async () => {
118 await TestDatabase.clearTables()
119 })
120
121 let query: RemoteQueryFunction
122 let sharedContainer_: MedusaContainer
123
124 it(`should export the appropriate linkable configuration`, () => {
125 const linkable = Module(Modules.WORKFLOW_ENGINE, {
126 service: WorkflowsModuleService,
127 }).linkable
128
129 expect(Object.keys(linkable)).toEqual(["workflowExecution"])
130
131 Object.keys(linkable).forEach((key) => {
132 delete linkable[key].toJSON
133 })
134
135 expect(linkable).toEqual({
136 workflowExecution: {
137 id: {
138 linkable: "workflow_execution_id",
139 entity: "WorkflowExecution",
140 primaryKey: "id",
141 serviceName: "workflows",
142 field: "workflowExecution",
143 },
144 transaction_id: {
145 entity: "WorkflowExecution",
146 field: "workflowExecution",
147 linkable: "workflow_execution_transaction_id",
148 primaryKey: "transaction_id",
149 serviceName: "workflows",
150 },
151 workflow_id: {
152 entity: "WorkflowExecution",
153 field: "workflowExecution",
154 linkable: "workflow_execution_workflow_id",
155 primaryKey: "workflow_id",
156 serviceName: "workflows",
157 },
158 run_id: {
159 entity: "WorkflowExecution",
160 field: "workflowExecution",
161 linkable: "workflow_execution_run_id",
162 primaryKey: "run_id",
163 serviceName: "workflows",
164 },
165 },
166 })
167 })
168
169 describe("Testing basic workflow", function () {
170 describe("Cancel transaction", function () {
171 it("should cancel an ongoing execution with async unfinished yet step", async () => {
172 const transactionId = "transaction-to-cancel-id" + ulid()
173 const step1 = createStep("step1", async () => {
174 return new StepResponse("step1")
175 })
176
177 const step2 = createStep("step2", async () => {
178 await setTimeout(2000)
179 return new StepResponse("step2")
180 })
181
182 const step3 = createStep("step3", async () => {
183 return new StepResponse("step3")
184 })
185
186 const workflowId = "workflow-to-cancel-id" + ulid()
187
188 createWorkflow(
189 { name: workflowId, retentionTime: 60 },
190 function () {
191 step1()
192 step2().config({ async: true })
193 step3()
194
195 return new WorkflowResponse("finished")
196 }
197 )
198
199 const onFinishPromise = new Promise<void>((resolve) => {
200 workflowOrcModule.subscribe({
201 workflowId,
202 transactionId,
203 subscriber: async (event) => {
204 if (event.eventType === "onFinish") {
205 resolve()
206 }
207 },
208 })
209 })
210
211 await workflowOrcModule.run(workflowId, {
212 input: {},
213 transactionId,
214 })
215
216 await setTimeout(100)
217
218 await workflowOrcModule.cancel(workflowId, {
219 transactionId,
220 })
221
222 await onFinishPromise
223
224 const execution = await workflowOrcModule.listWorkflowExecutions({
225 transaction_id: transactionId,
226 })
227
228 expect(execution.length).toEqual(1)
229 expect(execution[0].state).toEqual(TransactionState.REVERTED)
230 })
231
232 it("should cancel a complete execution with a sync workflow running as async", async () => {
233 const workflowId = "workflow-to-cancel-id" + ulid()
234 const transactionId = "transaction-to-cancel-id" + ulid()
235 const step1 = createStep("step1", async () => {
236 return new StepResponse("step1")
237 })
238
239 const step2 = createStep("step2", async () => {
240 return new StepResponse("step2")
241 })
242
243 const step3 = createStep("step3", async () => {
244 return new StepResponse("step3")
245 })
246
247 const subWorkflowId = "sub-workflow-id" + ulid()
248 const subWorkflow = createWorkflow(
249 { name: subWorkflowId, retentionTime: 60 },
250 function () {
251 return new WorkflowResponse(step2())
252 }
253 )
254
255 createWorkflow(
256 { name: workflowId, retentionTime: 60 },
257 function () {
258 step1()
259 subWorkflow.runAsStep({ input: {} }).config({ async: true })
260 step3()
261
262 return new WorkflowResponse("finished")
263 }
264 )
265
266 const onFinishPromise = new Promise<void>((resolve) => {
267 workflowOrcModule.subscribe({
268 workflowId,
269 transactionId,
270 subscriber: (event) => {
271 if (event.eventType === "onFinish") {
272 resolve()
273 }
274 },
275 })
276 })
277
278 await workflowOrcModule.run(workflowId, {
279 input: {},
280 transactionId,
281 })
282
283 await onFinishPromise
284
285 await workflowOrcModule.cancel(workflowId, {
286 transactionId,
287 })
288
289 const execution = await workflowOrcModule.listWorkflowExecutions({
290 transaction_id: transactionId,
291 })
292
293 expect(execution.length).toEqual(1)
294 expect(execution[0].state).toEqual(TransactionState.REVERTED)
295 })
296
297 it("should cancel an ongoing execution with a sync workflow running as async", async () => {
298 const workflowId = "workflow-to-cancel-id" + ulid()
299 const transactionId = "transaction-to-cancel-id" + ulid()
300 const step1 = createStep("step1", async () => {
301 return new StepResponse("step1")
302 })
303
304 const step2 = createStep("step2", async () => {
305 await setTimeout(500)
306 return new StepResponse("step2")
307 })
308
309 const step3 = createStep("step3", async () => {
310 return new StepResponse("step3")
311 })
312
313 const subWorkflowId = "sub-workflow-id" + ulid()
314 const subWorkflow = createWorkflow(
315 { name: subWorkflowId, retentionTime: 60 },
316 function () {
317 return new WorkflowResponse(step2())
318 }
319 )
320
321 createWorkflow(
322 { name: workflowId, retentionTime: 60 },
323 function () {
324 step1()
325 subWorkflow.runAsStep({ input: {} }).config({ async: true })
326 step3()
327
328 return new WorkflowResponse("finished")
329 }
330 )
331
332 await workflowOrcModule.run(workflowId, {
333 input: {},
334 transactionId,
335 })
336
337 await setTimeout(100)
338
339 await workflowOrcModule.cancel(workflowId, {
340 transactionId,
341 })
342
343 await setTimeout(1000)
344
345 const execution = await workflowOrcModule.listWorkflowExecutions({
346 transaction_id: transactionId,
347 })
348
349 expect(execution.length).toEqual(1)
350 expect(execution[0].state).toEqual(TransactionState.REVERTED)
351 })
352
353 it("should cancel an ongoing execution with sync steps only", async () => {
354 const transactionId = "transaction-to-cancel-id" + ulid()
355 const step1 = createStep("step1", async () => {
356 return new StepResponse("step1")
357 })
358
359 const step2 = createStep("step2", async () => {
360 await setTimeout(500)
361 return new StepResponse("step2")
362 })
363
364 const step3 = createStep("step3", async () => {
365 return new StepResponse("step3")
366 })
367
368 const workflowId = "workflow-to-cancel-id" + ulid()
369
370 createWorkflow(
371 { name: workflowId, retentionTime: 60 },
372 function () {
373 step1()
374 step2()
375 step3()
376
377 return new WorkflowResponse("finished")
378 }
379 )
380
381 await workflowOrcModule.run(workflowId, {
382 input: {},
383 transactionId,
384 })
385
386 await setTimeout(100)
387
388 await workflowOrcModule.cancel(workflowId, {
389 transactionId,
390 })
391
392 await setTimeout(1000)
393
394 const execution = await workflowOrcModule.listWorkflowExecutions({
395 transaction_id: transactionId,
396 })
397
398 expect(execution.length).toEqual(1)
399 expect(execution[0].state).toEqual(TransactionState.REVERTED)
400 })
401 })
402
403 it("should manually retry a step that is taking too long to finish", async () => {
404 const transactionId = "transaction-manual-retry" + ulid()
405 const workflowId = "workflow_1_manual_retry_step"
406
407 await workflowOrcModule.run(workflowId, {
408 input: {},
409 transactionId,
410 })
411
412 const onFinishPromise = new Promise<void>((resolve) => {
413 workflowOrcModule.subscribe({
414 workflowId,
415 transactionId,
416 subscriber: async (event) => {
417 if (event.eventType === "onFinish") {
418 expect(step1InvokeMockManualRetry).toHaveBeenCalledTimes(1)
419 expect(step2InvokeMockManualRetry).toHaveBeenCalledTimes(2)
420 resolve()
421 }
422 },
423 })
424 })
425
426 expect(step1InvokeMockManualRetry).toHaveBeenCalledTimes(1)
427 expect(step2InvokeMockManualRetry).toHaveBeenCalledTimes(1)
428
429 await workflowOrcModule.retryStep({
430 idempotencyKey: {
431 workflowId,
432 transactionId,
433 stepId: "step_2",
434 action: "invoke",
435 },
436 })
437
438 await onFinishPromise
439 })
440
441 it("should retry steps X times automatically when maxRetries is set", async () => {
442 const transactionId = "transaction-auto-retries" + ulid()
443 const workflowId = "workflow_1_auto_retries"
444
445 const onFinishPromise = new Promise<void>((resolve) => {
446 workflowOrcModule.subscribe({
447 workflowId,
448 transactionId,
449 subscriber: async (event) => {
450 if (event.eventType === "onFinish") {
451 resolve()
452 }
453 },
454 })
455 })
456
457 void workflowOrcModule.run(workflowId, {
458 input: {},
459 transactionId,
460 })
461
462 await onFinishPromise
463
464 expect(step1InvokeMockAutoRetries).toHaveBeenCalledTimes(1)
465 expect(step2InvokeMockAutoRetries).toHaveBeenCalledTimes(3)
466 expect(step1CompensateMockAutoRetries).toHaveBeenCalledTimes(1)
467 expect(step2CompensateMockAutoRetries).toHaveBeenCalledTimes(1)
468 })
469
470 it("should not retry steps X times automatically when maxRetries is set and autoRetry is false", async () => {
471 const transactionId = "transaction-auto-retries" + ulid()
472 const workflowId = "workflow_1_auto_retries_false"
473
474 const onFinishPromise = new Promise<void>((resolve, reject) => {
475 workflowOrcModule.subscribe({
476 workflowId,
477 transactionId,
478 subscriber: async (event) => {
479 if (event.eventType === "onFinish") {
480 resolve()
481 }
482 },
483 })
484 })
485
486 await workflowOrcModule.run(workflowId, {
487 input: {},
488 transactionId,
489 throwOnError: false,
490 })
491
492 expect(step1InvokeMockAutoRetriesFalse).toHaveBeenCalledTimes(1)
493 expect(step2InvokeMockAutoRetriesFalse).toHaveBeenCalledTimes(1)
494 expect(step1CompensateMockAutoRetriesFalse).toHaveBeenCalledTimes(0)
495 expect(step2CompensateMockAutoRetriesFalse).toHaveBeenCalledTimes(0)
496
497 await setTimeout(3000)
498
499 await workflowOrcModule.run(workflowId, {
500 input: {},
501 transactionId,
502 throwOnError: false,
503 })
504
505 await setTimeout(3000)
506
507 await workflowOrcModule.run(workflowId, {
508 input: {},
509 transactionId,
510 throwOnError: false,
511 })
512
513 await onFinishPromise
514
515 expect(step1InvokeMockAutoRetriesFalse).toHaveBeenCalledTimes(1)
516 expect(step2InvokeMockAutoRetriesFalse).toHaveBeenCalledTimes(3)
517 expect(step1CompensateMockAutoRetriesFalse).toHaveBeenCalledTimes(1)
518 expect(step2CompensateMockAutoRetriesFalse).toHaveBeenCalledTimes(1)
519 })
520
521 it("should prevent executing twice the same workflow in perfect concurrency with the same transactionId and non idempotent and not async but retention time is set", async () => {
522 const transactionId = "concurrency_transaction_id" + ulid()
523 const workflowId = "concurrency_workflow_id" + ulid()
524
525 const step1 = createStep("step1", async () => {
526 await setTimeout(100)
527 return new StepResponse("step1")
528 })
529
530 createWorkflow(
531 {
532 name: workflowId,
533 retentionTime: 1000,
534 },
535 function () {
536 return new WorkflowResponse(step1())
537 }
538 )
539
540 const [result1, result2] = await promiseAll([
541 workflowOrcModule
542 .run(workflowId, {
543 input: {},
544 transactionId,
545 })
546 .catch((e) => e),
547 workflowOrcModule
548 .run(workflowId, {
549 input: {},
550 transactionId,
551 })
552 .catch((e) => e),
553 ])
554
555 expect(result1.result || result2.result).toEqual("step1")
556 expect(result2.message || result1.message).toEqual(
557 "Transaction already started for transactionId: " + transactionId
558 )
559 })
560
561 it("should return a list of workflow executions and remove after completed when there is no retentionTime set", async () => {
562 await workflowOrcModule.run("workflow_1", {
563 input: {
564 value: "123",
565 },
566 throwOnError: true,
567 })
568
569 let { data: executionsList } = await query.graph({
570 entity: "workflow_executions",
571 fields: ["workflow_id", "transaction_id", "state"],
572 })
573
574 expect(executionsList).toHaveLength(1)
575 const { result } = await workflowOrcModule.setStepSuccess({
576 idempotencyKey: {
577 action: TransactionHandlerType.INVOKE,
578 stepId: "new_step_name",
579 workflowId: "workflow_1",
580 transactionId: executionsList[0].transaction_id,
581 },
582 stepResponse: { uhuuuu: "yeaah!" },
583 })
584
585 ;({ data: executionsList } = await query.graph({
586 entity: "workflow_executions",
587 fields: ["id"],
588 }))
589
590 expect(executionsList).toHaveLength(0)
591 expect(result).toEqual({
592 done: {
593 inputFromSyncStep: "oh",
594 },
595 })
596 })
597
598 it("should return a list of workflow executions and keep it saved when there is a retentionTime set", async () => {
599 const transactionId = "transaction_1" + ulid()
600 await workflowOrcModule.run("workflow_2", {
601 input: {
602 value: "123",
603 },
604 throwOnError: true,
605 transactionId,
606 })
607
608 let { data: executionsList } = await query.graph({
609 entity: "workflow_executions",
610 fields: ["id"],
611 })
612
613 expect(executionsList).toHaveLength(1)
614
615 await workflowOrcModule.setStepSuccess({
616 idempotencyKey: {
617 action: TransactionHandlerType.INVOKE,
618 stepId: "new_step_name",
619 workflowId: "workflow_2",
620 transactionId,
621 },
622 stepResponse: { uhuuuu: "yeaah!" },
623 })
624 ;({ data: executionsList } = await query.graph({
625 entity: "workflow_executions",
626 fields: ["id"],
627 }))
628
629 expect(executionsList).toHaveLength(1)
630 })
631
632 it("should return a list of failed workflow executions and keep it saved when there is a retentionTime set", async () => {
633 const transactionId = "transaction_1" + ulid()
634 await workflowOrcModule.run("workflow_2", {
635 input: {
636 value: "123",
637 },
638 transactionId,
639 })
640
641 let { data: executionsList } = await query.graph({
642 entity: "workflow_executions",
643 fields: ["id"],
644 })
645
646 expect(executionsList).toHaveLength(1)
647
648 await workflowOrcModule.setStepFailure({
649 idempotencyKey: {
650 action: TransactionHandlerType.INVOKE,
651 stepId: "new_step_name",
652 workflowId: "workflow_2",
653 transactionId,
654 },
655 stepResponse: { uhuuuu: "yeaah!" },
656 options: {
657 throwOnError: false,
658 },
659 })
660 ;({ data: executionsList } = await query.graph({
661 entity: "workflow_executions",
662 fields: ["id", "state"],
663 }))
664
665 expect(executionsList).toHaveLength(1)
666 expect(executionsList[0].state).toEqual("reverted")
667 })
668
669 it("should throw if setStepFailure fails", async () => {
670 const { acknowledgement } = await workflowOrcModule.run(
671 "workflow_2_revert_fail",
672 {
673 input: {
674 value: "123",
675 },
676 }
677 )
678
679 let done = false
680 void workflowOrcModule.subscribe({
681 workflowId: "workflow_2_revert_fail",
682 transactionId: acknowledgement.transactionId,
683 subscriber: (event) => {
684 if (event.eventType === "onFinish") {
685 done = true
686 }
687 },
688 })
689
690 let { data: executionsList } = await query.graph({
691 entity: "workflow_executions",
692 fields: ["id"],
693 })
694
695 expect(executionsList).toHaveLength(1)
696
697 const setStepError = await workflowOrcModule
698 .setStepFailure({
699 idempotencyKey: {
700 action: TransactionHandlerType.INVOKE,
701 stepId: "broken_step_2",
702 workflowId: "workflow_2_revert_fail",
703 transactionId: acknowledgement.transactionId,
704 },
705 stepResponse: { uhuuuu: "yeaah!" },
706 })
707 .catch((e) => {
708 return e
709 })
710
711 expect(setStepError).toEqual(
712 expect.objectContaining({
713 message: JSON.stringify({
714 uhuuuu: "yeaah!",
715 }),
716 stack: expect.any(String),
717 })
718 )
719 ;({ data: executionsList } = await query.graph({
720 entity: "workflow_executions",
721 fields: ["id", "state", "context"],
722 }))
723
724 expect(executionsList).toHaveLength(1)
725 expect(executionsList[0].state).toEqual("failed")
726 expect(done).toBe(true)
727 })
728
729 it("should return a list of workflow executions and keep it saved when there is a retentionTime set but allow for executing the same workflow multiple times with different run_id if the workflow is considered done", async () => {
730 const transactionId = "transaction_1"
731 await workflowOrcModule.run(
732 "workflow_not_idempotent_with_retention",
733 {
734 input: {
735 value: "123",
736 },
737 transactionId,
738 }
739 )
740
741 let { data: executionsList } = await query.graph({
742 entity: "workflow_executions",
743 fields: ["id", "run_id", "transaction_id"],
744 })
745
746 expect(executionsList).toHaveLength(1)
747
748 expect(
749 workflowNotIdempotentWithRetentionStep2Invoke
750 ).toHaveBeenCalledTimes(2)
751 expect(
752 workflowNotIdempotentWithRetentionStep2Invoke.mock.calls[0][0]
753 ).toEqual({ hey: "oh" })
754 expect(
755 workflowNotIdempotentWithRetentionStep2Invoke.mock.calls[1][0]
756 ).toEqual({
757 hey: "hello",
758 })
759 expect(
760 workflowNotIdempotentWithRetentionStep3Invoke
761 ).toHaveBeenCalledTimes(1)
762 expect(
763 workflowNotIdempotentWithRetentionStep3Invoke.mock.calls[0][0]
764 ).toEqual({
765 notAsyncResponse: "hello",
766 })
767
768 await workflowOrcModule.run(
769 "workflow_not_idempotent_with_retention",
770 {
771 input: {
772 value: "123",
773 },
774 transactionId,
775 }
776 )
777
778 const { data: executionsList2 } = await query.graph({
779 entity: "workflow_executions",
780 filters: {
781 id: { $nin: executionsList.map((e) => e.id) },
782 },
783 fields: ["id", "run_id", "transaction_id"],
784 })
785
786 expect(executionsList2).toHaveLength(1)
787 expect(executionsList2[0].run_id).not.toEqual(
788 executionsList[0].run_id
789 )
790 expect(executionsList2[0].transaction_id).toEqual(
791 executionsList[0].transaction_id
792 )
793 })
794
795 it("should revert the entire transaction when a step timeout expires", async () => {
796 const { transaction, result, errors } = (await workflowOrcModule.run(
797 "workflow_step_timeout",
798 {
799 input: {
800 myInput: "123",
801 },
802 throwOnError: false,
803 logOnError: true,
804 }
805 )) as Awaited<{
806 transaction: DistributedTransactionType
807 result: any
808 errors: any
809 }>
810
811 expect(transaction.getFlow().state).toEqual("reverted")
812 expect(result).toEqual({
813 myInput: "123",
814 })
815 expect(errors).toHaveLength(1)
816 expect(errors[0].action).toEqual("step_1")
817 expect(errors[0].error).toBeInstanceOf(TransactionStepTimeoutError)
818 })
819
820 it("should revert the entire transaction when the transaction timeout expires", async () => {
821 const { transaction, result, errors } = (await workflowOrcModule.run(
822 "workflow_transaction_timeout",
823 {
824 input: {},
825 transactionId: "trx" + ulid(),
826 throwOnError: false,
827 }
828 )) as Awaited<{
829 transaction: DistributedTransactionType
830 result: any
831 errors: any
832 }>
833
834 await setTimeout(500)
835
836 expect(transaction.getFlow().state).toEqual("reverted")
837 expect(result).toEqual({ executed: true })
838 expect(errors).toHaveLength(1)
839 expect(errors[0].action).toEqual("step_1")
840 expect(
841 TransactionTimeoutError.isTransactionTimeoutError(errors[0].error)
842 ).toBe(true)
843 })
844
845 it("should revert the entire transaction when a step timeout expires in a async step", async () => {
846 const transactionId = "transaction_1" + ulid()
847 await workflowOrcModule.run("workflow_step_timeout_async", {
848 input: {
849 myInput: "123",
850 },
851 transactionId,
852 throwOnError: false,
853 })
854
855 await setTimeout(2000)
856
857 const { transaction, result, errors } = (await workflowOrcModule.run(
858 "workflow_step_timeout_async",
859 {
860 input: {
861 myInput: "123",
862 },
863 transactionId,
864 throwOnError: false,
865 }
866 )) as Awaited<{
867 transaction: DistributedTransactionType
868 result: any
869 errors: any
870 }>
871
872 expect(transaction.getFlow().state).toEqual("reverted")
873 expect(result).toEqual(undefined)
874 expect(errors).toHaveLength(1)
875 expect(errors[0].action).toEqual("step_1_async")
876 expect(
877 TransactionStepTimeoutError.isTransactionStepTimeoutError(
878 errors[0].error
879 )
880 ).toBe(true)
881 })
882
883 it("should revert the entire transaction when the transaction timeout expires in a transaction containing an async step", async () => {
884 const transactionId = "transaction_1" + ulid()
885 await workflowOrcModule.run("workflow_transaction_timeout_async", {
886 input: {},
887 transactionId,
888 throwOnError: false,
889 })
890
891 await setTimeout(500)
892
893 const { transaction, result, errors } = (await workflowOrcModule.run(
894 "workflow_transaction_timeout_async",
895 {
896 input: {},
897 transactionId,
898 throwOnError: false,
899 }
900 )) as Awaited<{
901 transaction: DistributedTransactionType
902 result: any
903 errors: any
904 }>
905
906 expect(transaction.getFlow().state).toEqual("reverted")
907 expect(result).toEqual(undefined)
908 expect(errors).toHaveLength(1)
909 expect(errors[0].action).toEqual("step_1_async")
910 expect(
911 TransactionTimeoutError.isTransactionTimeoutError(errors[0].error)
912 ).toBe(true)
913 })
914
915 it("should complete an async workflow that returns a StepResponse", async () => {
916 const transactionId = "transaction_1" + ulid()
917
918 const onFinishPromise = new Promise<void>((resolve) => {
919 void workflowOrcModule.subscribe({
920 workflowId: "workflow_async_background",
921 transactionId,
922 subscriber: (event) => {
923 if (event.eventType === "onFinish") {
924 resolve()
925 }
926 },
927 })
928 })
929
930 const { transaction, result } = await workflowOrcModule.run(
931 "workflow_async_background",
932 {
933 input: {
934 myInput: "123",
935 },
936 transactionId,
937 throwOnError: true,
938 }
939 )
940
941 expect(transaction.flow.state).toEqual(TransactionStepState.INVOKING)
942 expect(result).toEqual(undefined)
943
944 await onFinishPromise
945 })
946
947 it("should subscribe to a async workflow and receive the response when it finishes", async () => {
948 const transactionId = "trx_123" + ulid()
949
950 const onFinishPromise = new Promise<void>((resolve) => {
951 void workflowOrcModule.subscribe({
952 workflowId: "workflow_async_background",
953 transactionId,
954 subscriber: (event) => {
955 if (event.eventType === "onFinish") {
956 resolve()
957 }
958 },
959 })
960 })
961
962 void workflowOrcModule.run("workflow_async_background", {
963 input: {
964 myInput: "123",
965 },
966 transactionId,
967 throwOnError: false,
968 })
969
970 await onFinishPromise
971 })
972
973 it("should not skip step if condition is true", async () => {
974 const transactionId = "trx_123_when" + ulid()
975
976 const onFinishPromise = new Promise<void>((resolve) => {
977 void workflowOrcModule.subscribe({
978 workflowId: "wf-when",
979 transactionId,
980 subscriber: (event) => {
981 if (event.eventType === "onFinish") {
982 resolve()
983 }
984 },
985 })
986 })
987
988 void workflowOrcModule.run("wf-when", {
989 input: {
990 callSubFlow: true,
991 },
992 transactionId,
993 throwOnError: true,
994 logOnError: true,
995 })
996
997 await onFinishPromise
998 })
999
1000 it("should cancel an async sub workflow when compensating", async () => {
1001 const workflowId = "workflow_async_background_fail"
1002 const transactionId = "trx_123_compensate_async_sub_workflow" + ulid()
1003
1004 let onCompensateStepSuccess: { step: TransactionStep } | null = null
1005
1006 const onFinishPromise = new Promise<void>((resolve) => {
1007 void workflowOrcModule.subscribe({
1008 workflowId,
1009 transactionId,
1010 subscriber: (event) => {
1011 if (event.eventType === "onCompensateStepSuccess") {
1012 onCompensateStepSuccess = event
1013 }
1014 if (event.eventType === "onFinish") {
1015 resolve()
1016 }
1017 },
1018 })
1019 })
1020
1021 void workflowOrcModule.run(workflowId, {
1022 input: {
1023 callSubFlow: true,
1024 },
1025 transactionId,
1026 throwOnError: false,
1027 logOnError: false,
1028 })
1029
1030 await onFinishPromise
1031
1032 expect(onCompensateStepSuccess).toBeDefined()
1033 expect(onCompensateStepSuccess!.step.id).toEqual(
1034 "_root.nested_sub_flow_async_fail-as-step" // The workflow as step
1035 )
1036 expect(onCompensateStepSuccess!.step.compensate).toEqual({
1037 state: "reverted",
1038 status: "ok",
1039 })
1040 })
1041
1042 it("should cancel and revert a completed workflow", async () => {
1043 const workflowId = "workflow_sync"
1044
1045 const { acknowledgement, transaction: trx } =
1046 await workflowOrcModule.run(workflowId, {
1047 input: {
1048 value: "123",
1049 },
1050 })
1051
1052 expect(trx.getFlow().state).toEqual("done")
1053 expect(acknowledgement.hasFinished).toBe(true)
1054
1055 const { transaction } = await workflowOrcModule.cancel(workflowId, {
1056 transactionId: acknowledgement.transactionId,
1057 })
1058
1059 expect(transaction.getFlow().state).toEqual("reverted")
1060 })
1061 })
1062
1063 describe("Testing complex workflows", function () {
1064 it("should execute workflow + workflow as step + manual workflow within a step correctly", async () => {
1065 const workflowA_id = "workflow_a"
1066 const workflowB_id = "workflow_b"
1067 const workflowC_id = "workflow_c"
1068
1069 const stepB_1 = createStep("stepB_1", async (input, context) => {
1070 let results: any[] = []
1071 for (let i = 0; i < 2; i++) {
1072 const { result } = await workflowOrcModule.run(workflowC_id, {
1073 input: {},
1074 })
1075
1076 results.push(result)
1077 }
1078
1079 return new StepResponse(results)
1080 })
1081
1082 const stepC_1 = createStep("stepC_1", async (input, context) => {
1083 return new StepResponse({
1084 stepC_1_result: "stepC_1_result",
1085 })
1086 })
1087
1088 createWorkflow(workflowC_id, (input) => {
1089 const result = stepC_1()
1090 return new WorkflowResponse(result)
1091 })
1092
1093 const workflowB = createWorkflow(workflowB_id, (input) => {
1094 const result = stepB_1()
1095 return new WorkflowResponse(result)
1096 })
1097
1098 createWorkflow(workflowA_id, (input) => {
1099 const workflowB_response = workflowB.runAsStep({
1100 input: {},
1101 })
1102
1103 return new WorkflowResponse({ workflowB_response })
1104 })
1105
1106 const { result } = await workflowOrcModule.run(workflowA_id, {
1107 input: {},
1108 throwOnError: false,
1109 })
1110
1111 expect(result).toEqual({
1112 workflowB_response: [
1113 {
1114 stepC_1_result: "stepC_1_result",
1115 },
1116 {
1117 stepC_1_result: "stepC_1_result",
1118 },
1119 ],
1120 })
1121 })
1122
1123 it("should execute workflow + workflow as step + manual workflow within a step that fail but do not fail the step", async () => {
1124 const workflowA_id = "workflow_a"
1125 const workflowB_id = "workflow_b"
1126 const workflowC_id = "workflow_c"
1127
1128 const stepB_1 = createStep("stepB_1", async (input, context) => {
1129 let results: any[] = []
1130 for (let i = 0; i < 2; i++) {
1131 const { errors } = await workflowOrcModule.run(workflowC_id, {
1132 input: {},
1133 throwOnError: false,
1134 })
1135
1136 results.push(errors)
1137 }
1138
1139 return new StepResponse(results)
1140 })
1141
1142 const stepC_1 = createStep("stepC_1", async (input, context) => {
1143 throw new Error("Workflow C failed")
1144 })
1145
1146 createWorkflow(workflowC_id, (input) => {
1147 const result = stepC_1()
1148 return new WorkflowResponse(result)
1149 })
1150
1151 const workflowB = createWorkflow(workflowB_id, (input) => {
1152 const result = stepB_1()
1153 return new WorkflowResponse(result)
1154 })
1155
1156 createWorkflow(workflowA_id, (input) => {
1157 const workflowB_response = workflowB.runAsStep({
1158 input: {},
1159 })
1160
1161 return new WorkflowResponse({ workflowB_response })
1162 })
1163
1164 const { result, transaction } = await workflowOrcModule.run(
1165 workflowA_id,
1166 {
1167 input: {},
1168 throwOnError: false,
1169 }
1170 )
1171
1172 expect(
1173 (transaction as DistributedTransactionType).getFlow().state
1174 ).toEqual(TransactionState.DONE)
1175 expect(result).toEqual({
1176 workflowB_response: [
1177 [
1178 {
1179 action: "stepC_1",
1180 handlerType: TransactionHandlerType.INVOKE,
1181 error: expect.objectContaining({
1182 message: "Workflow C failed",
1183 }),
1184 },
1185 ],
1186 [
1187 {
1188 action: "stepC_1",
1189 handlerType: TransactionHandlerType.INVOKE,
1190 error: expect.objectContaining({
1191 message: "Workflow C failed",
1192 }),
1193 },
1194 ],
1195 ],
1196 })
1197 })
1198 })
1199
1200 // Note: These tests depend on actual Redis instance and waiting for the scheduled jobs to run, which isn't great.
1201 // Mocking bullmq, however, would make the tests close to useless, so we can keep them very minimal and serve as smoke tests.
1202 describe.skip("Scheduled workflows", () => {
1203 beforeEach(() => {
1204 jest.clearAllMocks()
1205 })
1206
1207 it("should execute a scheduled workflow", async () => {
1208 const wait = times(2)
1209 const spy = createScheduled("standard", wait.next)
1210
1211 await wait.promise
1212 expect(spy).toHaveBeenCalledTimes(2)
1213 WorkflowManager.unregister("standard")
1214 })
1215
1216 it("should stop executions after the set number of executions", async () => {
1217 const wait = times(2)
1218 const spy = createScheduled("num-executions", wait.next, {
1219 interval: 1000,
1220 numberOfExecutions: 2,
1221 })
1222
1223 await wait.promise
1224 expect(spy).toHaveBeenCalledTimes(2)
1225
1226 // Make sure that on the next tick it doesn't execute again
1227 await setTimeout(1100)
1228 expect(spy).toHaveBeenCalledTimes(2)
1229
1230 WorkflowManager.unregister("num-execution")
1231 })
1232
1233 it("should remove scheduled workflow if workflow no longer exists", async () => {
1234 const wait = times(1)
1235 const logger = sharedContainer_.resolve<Logger>(
1236 ContainerRegistrationKeys.LOGGER
1237 )
1238
1239 const spy = createScheduled("remove-scheduled", wait.next, {
1240 interval: 1000,
1241 })
1242 const logSpy = jest.spyOn(logger, "warn")
1243
1244 await wait.promise
1245 expect(spy).toHaveBeenCalledTimes(1)
1246 WorkflowManager["workflows"].delete("remove-scheduled")
1247
1248 await setTimeout(1100)
1249 expect(spy).toHaveBeenCalledTimes(1)
1250 expect(logSpy).toHaveBeenCalledWith(
1251 "Tried to execute a scheduled workflow with ID remove-scheduled that does not exist, removing it from the scheduler."
1252 )
1253 })
1254
1255 // TODO: investigate why sometimes flow doesn't have access to the new key registered
1256 describe.skip("Scheduled workflows", () => {
1257 beforeEach(() => {
1258 sharedContainer_.register("test-value", asValue("test"))
1259 })
1260
1261 it("the scheduled workflow should have access to the shared container", async () => {
1262 const wait = times(1)
1263
1264 const spy = await createScheduled(
1265 "shared-container-job",
1266 wait.next,
1267 {
1268 interval: 1000,
1269 }
1270 )
1271 await wait.promise
1272
1273 expect(spy).toHaveBeenCalledTimes(1)
1274
1275 console.log(spy.mock.results)
1276 expect(spy).toHaveReturnedWith(
1277 expect.objectContaining({ output: { testValue: "test" } })
1278 )
1279 WorkflowManager.unregister("shared-container-job")
1280 })
1281 })
1282 })
1283
1284 describe("Cleaner job", function () {
1285 it("should remove expired executions of finished workflows and keep the others", async () => {
1286 const doneWorkflowId = "done-workflow-" + ulid()
1287 createWorkflow({ name: doneWorkflowId, retentionTime: 1 }, () => {
1288 return new WorkflowResponse("done")
1289 })
1290
1291 const failingWorkflowId = "failing-workflow-" + ulid()
1292 const failingStep = createStep("failing-step", () => {
1293 throw new Error("I am failing")
1294 })
1295 createWorkflow({ name: failingWorkflowId, retentionTime: 1 }, () => {
1296 failingStep()
1297 })
1298
1299 const revertingStep = createStep(
1300 "reverting-step",
1301 () => {
1302 throw new Error("I am reverting")
1303 },
1304 () => {
1305 return new StepResponse("reverted")
1306 }
1307 )
1308
1309 const revertingWorkflowId = "reverting-workflow-" + ulid()
1310 createWorkflow(
1311 { name: revertingWorkflowId, retentionTime: 1 },
1312 () => {
1313 revertingStep()
1314 return new WorkflowResponse("reverted")
1315 }
1316 )
1317
1318 const runningWorkflowId = "running-workflow-" + ulid()
1319 const longRunningStep = createStep("long-running-step", async () => {
1320 await setTimeout(10000)
1321 return new StepResponse("long running finished")
1322 })
1323 createWorkflow({ name: runningWorkflowId, retentionTime: 1 }, () => {
1324 longRunningStep().config({ async: true, backgroundExecution: true })
1325 return new WorkflowResponse("running workflow started")
1326 })
1327
1328 const notExpiredWorkflowId = "not-expired-workflow-" + ulid()
1329 createWorkflow(
1330 { name: notExpiredWorkflowId, retentionTime: 10000 },
1331 () => {
1332 return new WorkflowResponse("not expired")
1333 }
1334 )
1335
1336 const trx_done = "trx-done-" + ulid()
1337 const trx_failed = "trx-failed-" + ulid()
1338 const trx_reverting = "trx-reverting-" + ulid()
1339 const trx_running = "trx-running-" + ulid()
1340 const trx_not_expired = "trx-not-expired-" + ulid()
1341
1342 // run workflows
1343 await workflowOrcModule.run(doneWorkflowId, {
1344 transactionId: trx_done,
1345 })
1346
1347 await workflowOrcModule.run(failingWorkflowId, {
1348 transactionId: trx_failed,
1349 throwOnError: false,
1350 })
1351
1352 await workflowOrcModule.run(revertingWorkflowId, {
1353 transactionId: trx_reverting,
1354 throwOnError: false,
1355 })
1356
1357 await workflowOrcModule.run(runningWorkflowId, {
1358 transactionId: trx_running,
1359 })
1360
1361 await workflowOrcModule.run(notExpiredWorkflowId, {
1362 transactionId: trx_not_expired,
1363 })
1364
1365 let executions = await workflowOrcModule.listWorkflowExecutions()
1366 expect(executions).toHaveLength(5)
1367
1368 await setTimeout(2000)
1369
1370 // Manually trigger cleaner
1371 await (workflowOrcModule as any).workflowOrchestratorService_[
1372 "redisDistributedTransactionStorage_"
1373 ]["clearExpiredExecutions"]()
1374
1375 let remainingExecutions =
1376 await workflowOrcModule.listWorkflowExecutions()
1377
1378 expect(remainingExecutions).toHaveLength(2)
1379
1380 const remainingTrxIds = remainingExecutions
1381 .map((e) => e.transaction_id)
1382 .sort()
1383
1384 expect(remainingTrxIds).toEqual([trx_not_expired, trx_running].sort())
1385
1386 const notExpiredExec = remainingExecutions.find(
1387 (e) => e.transaction_id === trx_not_expired
1388 )
1389 expect(notExpiredExec?.state).toBe(TransactionState.DONE)
1390
1391 const runningExec = remainingExecutions.find(
1392 (e) => e.transaction_id === trx_running
1393 )
1394 expect(runningExec?.state).toBe(TransactionState.INVOKING)
1395 })
1396 })
1397 })
1398 },
1399 })