@medusajs/workflow-engine-redis 0.0.2-next-20240124093206

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +1 -0
  2. package/dist/index.d.ts +7 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +43 -0
  5. package/dist/initialize/index.d.ts +6 -0
  6. package/dist/initialize/index.d.ts.map +1 -0
  7. package/dist/initialize/index.js +18 -0
  8. package/dist/joiner-config.d.ts +8 -0
  9. package/dist/joiner-config.d.ts.map +1 -0
  10. package/dist/joiner-config.js +34 -0
  11. package/dist/loaders/connection.d.ts +5 -0
  12. package/dist/loaders/connection.d.ts.map +1 -0
  13. package/dist/loaders/connection.js +41 -0
  14. package/dist/loaders/container.d.ts +3 -0
  15. package/dist/loaders/container.d.ts.map +1 -0
  16. package/dist/loaders/container.js +33 -0
  17. package/dist/loaders/index.d.ts +5 -0
  18. package/dist/loaders/index.d.ts.map +1 -0
  19. package/dist/loaders/index.js +20 -0
  20. package/dist/loaders/redis.d.ts +4 -0
  21. package/dist/loaders/redis.d.ts.map +1 -0
  22. package/dist/loaders/redis.js +54 -0
  23. package/dist/loaders/utils.d.ts +5 -0
  24. package/dist/loaders/utils.d.ts.map +1 -0
  25. package/dist/loaders/utils.js +9 -0
  26. package/dist/migrations/Migration20231228143900.d.ts +6 -0
  27. package/dist/migrations/Migration20231228143900.d.ts.map +1 -0
  28. package/dist/migrations/Migration20231228143900.js +39 -0
  29. package/dist/models/index.d.ts +2 -0
  30. package/dist/models/index.d.ts.map +1 -0
  31. package/dist/models/index.js +8 -0
  32. package/dist/models/workflow-execution.d.ts +19 -0
  33. package/dist/models/workflow-execution.d.ts.map +1 -0
  34. package/dist/models/workflow-execution.js +97 -0
  35. package/dist/module-definition.d.ts +3 -0
  36. package/dist/module-definition.d.ts.map +1 -0
  37. package/dist/module-definition.js +22 -0
  38. package/dist/repositories/index.d.ts +3 -0
  39. package/dist/repositories/index.d.ts.map +1 -0
  40. package/dist/repositories/index.js +7 -0
  41. package/dist/repositories/workflow-execution.d.ts +35 -0
  42. package/dist/repositories/workflow-execution.d.ts.map +1 -0
  43. package/dist/repositories/workflow-execution.js +9 -0
  44. package/dist/schema/index.d.ts +3 -0
  45. package/dist/schema/index.d.ts.map +1 -0
  46. package/dist/schema/index.js +28 -0
  47. package/dist/services/index.d.ts +4 -0
  48. package/dist/services/index.d.ts.map +1 -0
  49. package/dist/services/index.js +19 -0
  50. package/dist/services/workflow-execution.d.ts +16 -0
  51. package/dist/services/workflow-execution.d.ts.map +1 -0
  52. package/dist/services/workflow-execution.js +13 -0
  53. package/dist/services/workflow-orchestrator.d.ts +73 -0
  54. package/dist/services/workflow-orchestrator.d.ts.map +1 -0
  55. package/dist/services/workflow-orchestrator.js +381 -0
  56. package/dist/services/workflows-module.d.ts +43 -0
  57. package/dist/services/workflows-module.d.ts.map +1 -0
  58. package/dist/services/workflows-module.js +128 -0
  59. package/dist/types/index.d.ts +30 -0
  60. package/dist/types/index.d.ts.map +1 -0
  61. package/dist/types/index.js +2 -0
  62. package/dist/utils/index.d.ts +2 -0
  63. package/dist/utils/index.d.ts.map +1 -0
  64. package/dist/utils/index.js +17 -0
  65. package/dist/utils/workflow-orchestrator-storage.d.ts +35 -0
  66. package/dist/utils/workflow-orchestrator-storage.d.ts.map +1 -0
  67. package/dist/utils/workflow-orchestrator-storage.js +182 -0
  68. package/package.json +61 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-execution.d.ts","sourceRoot":"","sources":["../../src/repositories/workflow-execution.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAG3C,qBAAa,2BAA4B,SAAQ,gCAEhD;CAAG"}
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WorkflowExecutionRepository = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ const _models_1 = require("../models");
6
+ // eslint-disable-next-line max-len
7
+ class WorkflowExecutionRepository extends utils_1.DALUtils.mikroOrmBaseRepositoryFactory(_models_1.WorkflowExecution) {
8
+ }
9
+ exports.WorkflowExecutionRepository = WorkflowExecutionRepository;
@@ -0,0 +1,3 @@
1
+ declare const _default: "\nscalar DateTime\nscalar JSON\n\nenum TransactionState {\n NOT_STARTED\n INVOKING\n WAITING_TO_COMPENSATE\n COMPENSATING\n DONE\n REVERTED\n FAILED\n}\n\ntype WorkflowExecution {\n id: ID!\n created_at: DateTime!\n updated_at: DateTime!\n deleted_at: DateTime\n workflow_id: string\n transaction_id: string\n execution: JSON\n context: JSON\n state: TransactionState\n}\n";
2
+ export default _default;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":";AAAA,wBAyBC"}
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = `
4
+ scalar DateTime
5
+ scalar JSON
6
+
7
+ enum TransactionState {
8
+ NOT_STARTED
9
+ INVOKING
10
+ WAITING_TO_COMPENSATE
11
+ COMPENSATING
12
+ DONE
13
+ REVERTED
14
+ FAILED
15
+ }
16
+
17
+ type WorkflowExecution {
18
+ id: ID!
19
+ created_at: DateTime!
20
+ updated_at: DateTime!
21
+ deleted_at: DateTime
22
+ workflow_id: string
23
+ transaction_id: string
24
+ execution: JSON
25
+ context: JSON
26
+ state: TransactionState
27
+ }
28
+ `;
@@ -0,0 +1,4 @@
1
+ export * from "./workflow-execution";
2
+ export * from "./workflow-orchestrator";
3
+ export * from "./workflows-module";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAA;AACpC,cAAc,yBAAyB,CAAA;AACvC,cAAc,oBAAoB,CAAA"}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./workflow-execution"), exports);
18
+ __exportStar(require("./workflow-orchestrator"), exports);
19
+ __exportStar(require("./workflows-module"), exports);
@@ -0,0 +1,16 @@
1
+ import { DAL } from "@medusajs/types";
2
+ import { ModulesSdkUtils } from "@medusajs/utils";
3
+ import { WorkflowExecution } from "../models";
4
+ type InjectedDependencies = {
5
+ workflowExecutionRepository: DAL.RepositoryService;
6
+ };
7
+ declare const WorkflowExecutionService_base: new <TEntity_1 extends object = any>(container: InjectedDependencies) => ModulesSdkUtils.AbstractService<TEntity_1, InjectedDependencies, {}, {
8
+ list?: any;
9
+ listAndCount?: any;
10
+ }>;
11
+ export declare class WorkflowExecutionService<TEntity extends WorkflowExecution = WorkflowExecution> extends WorkflowExecutionService_base<TEntity> {
12
+ protected workflowExecutionRepository_: DAL.RepositoryService<TEntity>;
13
+ constructor({ workflowExecutionRepository }: InjectedDependencies);
14
+ }
15
+ export {};
16
+ //# sourceMappingURL=workflow-execution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-execution.d.ts","sourceRoot":"","sources":["../../src/services/workflow-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAA;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAE3C,KAAK,oBAAoB,GAAG;IAC1B,2BAA2B,EAAE,GAAG,CAAC,iBAAiB,CAAA;CACnD,CAAA;;;;;AAED,qBAAa,wBAAwB,CACnC,OAAO,SAAS,iBAAiB,GAAG,iBAAiB,CACrD,SAAQ,8BAER,OAAO,CAAC;IACR,SAAS,CAAC,4BAA4B,EAAE,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAA;gBAE1D,EAAE,2BAA2B,EAAE,EAAE,oBAAoB;CAKlE"}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WorkflowExecutionService = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ const _models_1 = require("../models");
6
+ class WorkflowExecutionService extends utils_1.ModulesSdkUtils.abstractServiceFactory(_models_1.WorkflowExecution) {
7
+ constructor({ workflowExecutionRepository }) {
8
+ // @ts-ignore
9
+ super(...arguments);
10
+ this.workflowExecutionRepository_ = workflowExecutionRepository;
11
+ }
12
+ }
13
+ exports.WorkflowExecutionService = WorkflowExecutionService;
@@ -0,0 +1,73 @@
1
+ import { DistributedTransaction, DistributedTransactionEvents, TransactionStep } from "@medusajs/orchestration";
2
+ import { ContainerLike, Context } from "@medusajs/types";
3
+ import { FlowRunOptions, ReturnWorkflow } from "@medusajs/workflows-sdk";
4
+ import Redis from "ioredis";
5
+ import type { RedisDistributedTransactionStorage } from "../utils";
6
+ export type WorkflowOrchestratorRunOptions<T> = FlowRunOptions<T> & {
7
+ transactionId?: string;
8
+ container?: ContainerLike;
9
+ };
10
+ type RegisterStepSuccessOptions<T> = Omit<WorkflowOrchestratorRunOptions<T>, "transactionId" | "input">;
11
+ type IdempotencyKeyParts = {
12
+ workflowId: string;
13
+ transactionId: string;
14
+ stepId: string;
15
+ action: "invoke" | "compensate";
16
+ };
17
+ type NotifyOptions = {
18
+ eventType: keyof DistributedTransactionEvents;
19
+ workflowId: string;
20
+ transactionId?: string;
21
+ step?: TransactionStep;
22
+ response?: unknown;
23
+ result?: unknown;
24
+ errors?: unknown[];
25
+ };
26
+ type SubscriberHandler = {
27
+ (input: NotifyOptions): void;
28
+ } & {
29
+ _id?: string;
30
+ };
31
+ type SubscribeOptions = {
32
+ workflowId: string;
33
+ transactionId?: string;
34
+ subscriber: SubscriberHandler;
35
+ subscriberId?: string;
36
+ };
37
+ type UnsubscribeOptions = {
38
+ workflowId: string;
39
+ transactionId?: string;
40
+ subscriberOrId: string | SubscriberHandler;
41
+ };
42
+ export declare class WorkflowOrchestratorService {
43
+ private instanceId;
44
+ protected redisPublisher: Redis;
45
+ protected redisSubscriber: Redis;
46
+ private subscribers;
47
+ constructor({ redisDistributedTransactionStorage, redisPublisher, redisSubscriber, }: {
48
+ redisDistributedTransactionStorage: RedisDistributedTransactionStorage;
49
+ workflowOrchestratorService: WorkflowOrchestratorService;
50
+ redisPublisher: Redis;
51
+ redisSubscriber: Redis;
52
+ });
53
+ run<T = unknown>(workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, options?: WorkflowOrchestratorRunOptions<T>, sharedContext?: Context): Promise<any>;
54
+ getRunningTransaction(workflowId: string, transactionId: string, options?: WorkflowOrchestratorRunOptions<undefined>, sharedContext?: Context): Promise<DistributedTransaction>;
55
+ setStepSuccess<T = unknown>({ idempotencyKey, stepResponse, options, }: {
56
+ idempotencyKey: string | IdempotencyKeyParts;
57
+ stepResponse: unknown;
58
+ options?: RegisterStepSuccessOptions<T>;
59
+ }, sharedContext?: Context): Promise<any>;
60
+ setStepFailure<T = unknown>({ idempotencyKey, stepResponse, options, }: {
61
+ idempotencyKey: string | IdempotencyKeyParts;
62
+ stepResponse: unknown;
63
+ options?: RegisterStepSuccessOptions<T>;
64
+ }, sharedContext?: Context): Promise<any>;
65
+ subscribe({ workflowId, transactionId, subscriber, subscriberId }: SubscribeOptions, sharedContext?: Context): void;
66
+ unsubscribe({ workflowId, transactionId, subscriberOrId }: UnsubscribeOptions, sharedContext?: Context): void;
67
+ private notify;
68
+ private getChannelName;
69
+ private buildWorkflowEvents;
70
+ private buildIdempotencyKeyAndParts;
71
+ }
72
+ export {};
73
+ //# sourceMappingURL=workflow-orchestrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-orchestrator.d.ts","sourceRoot":"","sources":["../../src/services/workflow-orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAE5B,eAAe,EAChB,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAmB,MAAM,iBAAiB,CAAA;AAEzE,OAAO,EACL,cAAc,EAEd,cAAc,EACf,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,MAAM,SAAS,CAAA;AAE3B,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,UAAU,CAAA;AAElE,MAAM,MAAM,8BAA8B,CAAC,CAAC,IAAI,cAAc,CAAC,CAAC,CAAC,GAAG;IAClE,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,aAAa,CAAA;CAC1B,CAAA;AAED,KAAK,0BAA0B,CAAC,CAAC,IAAI,IAAI,CACvC,8BAA8B,CAAC,CAAC,CAAC,EACjC,eAAe,GAAG,OAAO,CAC1B,CAAA;AAED,KAAK,mBAAmB,GAAG;IACzB,UAAU,EAAE,MAAM,CAAA;IAClB,aAAa,EAAE,MAAM,CAAA;IACrB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,QAAQ,GAAG,YAAY,CAAA;CAChC,CAAA;AAED,KAAK,aAAa,GAAG;IACnB,SAAS,EAAE,MAAM,4BAA4B,CAAA;IAC7C,UAAU,EAAE,MAA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B,CACzB,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,8BAA8B,CAAC,SAAS,CAAC,EAClC,aAAa,GAAE,OAAY,GAC3C,OAAO,CAAC,sBAAsB,CAAC;IA2B5B,cAAc,CAAC,CAAC,GAAG,OAAO,EAC9B,EACE,cAAc,EACd,YAAY,EACZ,OAAO,GACR,EAAE;QACD,cAAc,EAAE,MAAM,GAAG,mBAAmB,CAAA;QAC5C,YAAY,EAAE,OAAO,CAAA;QACrB,OAAO,CAAC,EAAE,0BAA0B,CAAC,CAAC,CAAC,CAAA;KACxC,EACgB,aAAa,GAAE,OAAY;IAkDxC,cAAc,CAAC,CAAC,GAAG,OAAO,EAC9B,EACE,cAAc,EACd,YAAY,EACZ,OAAO,GACR,EAAE;QACD,cAAc,EAAE,MAAM,GAAG,mBAAmB,CAAA;QAC5C,YAAY,EAAE,OAAO,CAAA;QACrB,OAAO,CAAC,EAAE,0BAA0B,CAAC,CAAC,CAAC,CAAA;KACxC,EACgB,aAAa,GAAE,OAAY;IAkD9C,SAAS,CACP,EAAE,UAAU,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,gBAAgB,EACxD,aAAa,GAAE,OAAY;IAuC9C,WAAW,CACT,EAAE,UAAU,EAAE,aAAa,EAAE,cAAc,EAAE,EAAE,kBAAkB,EAChD,aAAa,GAAE,OAAY;YAiChC,MAAM;IAuDpB,OAAO,CAAC,cAAc;IAItB,OAAO,CAAC,mBAAmB;IAyF3B,OAAO,CAAC,2BAA2B;CA+BpC"}
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.WorkflowOrchestratorService = void 0;
16
+ const orchestration_1 = require("@medusajs/orchestration");
17
+ const utils_1 = require("@medusajs/utils");
18
+ const workflows_sdk_1 = require("@medusajs/workflows-sdk");
19
+ const ulid_1 = require("ulid");
20
+ const AnySubscriber = "any";
21
+ class WorkflowOrchestratorService {
22
+ constructor({ redisDistributedTransactionStorage, redisPublisher, redisSubscriber, }) {
23
+ this.instanceId = (0, ulid_1.ulid)();
24
+ this.subscribers = new Map();
25
+ this.redisPublisher = redisPublisher;
26
+ this.redisSubscriber = redisSubscriber;
27
+ redisDistributedTransactionStorage.setWorkflowOrchestratorService(this);
28
+ orchestration_1.DistributedTransaction.setStorage(redisDistributedTransactionStorage);
29
+ this.redisSubscriber.on("message", async (_, message) => {
30
+ const { instanceId, data } = JSON.parse(message);
31
+ await this.notify(data, false, instanceId);
32
+ });
33
+ }
34
+ async run(workflowIdOrWorkflow, options, sharedContext = {}) {
35
+ let { input, context, transactionId, resultFrom, throwOnError, events: eventHandlers, container, } = options ?? {};
36
+ const workflowId = (0, utils_1.isString)(workflowIdOrWorkflow)
37
+ ? workflowIdOrWorkflow
38
+ : workflowIdOrWorkflow.getName();
39
+ if (!workflowId) {
40
+ throw new Error("Workflow ID is required");
41
+ }
42
+ context ?? (context = {});
43
+ context.transactionId ?? (context.transactionId = transactionId ?? (0, ulid_1.ulid)());
44
+ const events = this.buildWorkflowEvents({
45
+ customEventHandlers: eventHandlers,
46
+ workflowId,
47
+ transactionId: context.transactionId,
48
+ });
49
+ const exportedWorkflow = workflows_sdk_1.MedusaWorkflow.getWorkflow(workflowId);
50
+ if (!exportedWorkflow) {
51
+ throw new Error(`Workflow with id "${workflowId}" not found.`);
52
+ }
53
+ const flow = exportedWorkflow(container);
54
+ const ret = await flow.run({
55
+ input,
56
+ throwOnError,
57
+ resultFrom,
58
+ context,
59
+ events,
60
+ });
61
+ // TODO: temporary
62
+ const acknowledgement = {
63
+ transactionId: context.transactionId,
64
+ workflowId: workflowId,
65
+ };
66
+ if (ret.transaction.hasFinished()) {
67
+ const { result, errors } = ret;
68
+ await this.notify({
69
+ eventType: "onFinish",
70
+ workflowId,
71
+ transactionId: context.transactionId,
72
+ result,
73
+ errors,
74
+ });
75
+ }
76
+ return { acknowledgement, ...ret };
77
+ }
78
+ async getRunningTransaction(workflowId, transactionId, options, sharedContext = {}) {
79
+ let { context, container } = options ?? {};
80
+ if (!workflowId) {
81
+ throw new Error("Workflow ID is required");
82
+ }
83
+ if (!transactionId) {
84
+ throw new Error("TransactionId ID is required");
85
+ }
86
+ context ?? (context = {});
87
+ context.transactionId ?? (context.transactionId = transactionId);
88
+ const exportedWorkflow = workflows_sdk_1.MedusaWorkflow.getWorkflow(workflowId);
89
+ if (!exportedWorkflow) {
90
+ throw new Error(`Workflow with id "${workflowId}" not found.`);
91
+ }
92
+ const flow = exportedWorkflow(container);
93
+ const transaction = await flow.getRunningTransaction(transactionId, context);
94
+ return transaction;
95
+ }
96
+ async setStepSuccess({ idempotencyKey, stepResponse, options, }, sharedContext = {}) {
97
+ const { context, throwOnError, resultFrom, container, events: eventHandlers, } = options ?? {};
98
+ const [idempotencyKey_, { workflowId, transactionId }] = this.buildIdempotencyKeyAndParts(idempotencyKey);
99
+ const exportedWorkflow = workflows_sdk_1.MedusaWorkflow.getWorkflow(workflowId);
100
+ if (!exportedWorkflow) {
101
+ throw new Error(`Workflow with id "${workflowId}" not found.`);
102
+ }
103
+ const flow = exportedWorkflow(container);
104
+ const events = this.buildWorkflowEvents({
105
+ customEventHandlers: eventHandlers,
106
+ transactionId,
107
+ workflowId,
108
+ });
109
+ const ret = await flow.registerStepSuccess({
110
+ idempotencyKey: idempotencyKey_,
111
+ context,
112
+ resultFrom,
113
+ throwOnError,
114
+ events,
115
+ response: stepResponse,
116
+ });
117
+ if (ret.transaction.hasFinished()) {
118
+ const { result, errors } = ret;
119
+ await this.notify({
120
+ eventType: "onFinish",
121
+ workflowId,
122
+ transactionId,
123
+ result,
124
+ errors,
125
+ });
126
+ }
127
+ return ret;
128
+ }
129
+ async setStepFailure({ idempotencyKey, stepResponse, options, }, sharedContext = {}) {
130
+ const { context, throwOnError, resultFrom, container, events: eventHandlers, } = options ?? {};
131
+ const [idempotencyKey_, { workflowId, transactionId }] = this.buildIdempotencyKeyAndParts(idempotencyKey);
132
+ const exportedWorkflow = workflows_sdk_1.MedusaWorkflow.getWorkflow(workflowId);
133
+ if (!exportedWorkflow) {
134
+ throw new Error(`Workflow with id "${workflowId}" not found.`);
135
+ }
136
+ const flow = exportedWorkflow(container);
137
+ const events = this.buildWorkflowEvents({
138
+ customEventHandlers: eventHandlers,
139
+ transactionId,
140
+ workflowId,
141
+ });
142
+ const ret = await flow.registerStepFailure({
143
+ idempotencyKey: idempotencyKey_,
144
+ context,
145
+ resultFrom,
146
+ throwOnError,
147
+ events,
148
+ response: stepResponse,
149
+ });
150
+ if (ret.transaction.hasFinished()) {
151
+ const { result, errors } = ret;
152
+ await this.notify({
153
+ eventType: "onFinish",
154
+ workflowId,
155
+ transactionId,
156
+ result,
157
+ errors,
158
+ });
159
+ }
160
+ return ret;
161
+ }
162
+ subscribe({ workflowId, transactionId, subscriber, subscriberId }, sharedContext = {}) {
163
+ subscriber._id = subscriberId;
164
+ const subscribers = this.subscribers.get(workflowId) ?? new Map();
165
+ // Subscribe instance to redis
166
+ if (!this.subscribers.has(workflowId)) {
167
+ void this.redisSubscriber.subscribe(this.getChannelName(workflowId));
168
+ }
169
+ const handlerIndex = (handlers) => {
170
+ return handlers.indexOf((s) => s === subscriber || s._id === subscriberId);
171
+ };
172
+ if (transactionId) {
173
+ const transactionSubscribers = subscribers.get(transactionId) ?? [];
174
+ const subscriberIndex = handlerIndex(transactionSubscribers);
175
+ if (subscriberIndex !== -1) {
176
+ transactionSubscribers.slice(subscriberIndex, 1);
177
+ }
178
+ transactionSubscribers.push(subscriber);
179
+ subscribers.set(transactionId, transactionSubscribers);
180
+ this.subscribers.set(workflowId, subscribers);
181
+ return;
182
+ }
183
+ const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
184
+ const subscriberIndex = handlerIndex(workflowSubscribers);
185
+ if (subscriberIndex !== -1) {
186
+ workflowSubscribers.slice(subscriberIndex, 1);
187
+ }
188
+ workflowSubscribers.push(subscriber);
189
+ subscribers.set(AnySubscriber, workflowSubscribers);
190
+ this.subscribers.set(workflowId, subscribers);
191
+ }
192
+ unsubscribe({ workflowId, transactionId, subscriberOrId }, sharedContext = {}) {
193
+ const subscribers = this.subscribers.get(workflowId) ?? new Map();
194
+ const filterSubscribers = (handlers) => {
195
+ return handlers.filter((handler) => {
196
+ return handler._id
197
+ ? handler._id !== subscriberOrId
198
+ : handler !== subscriberOrId;
199
+ });
200
+ };
201
+ // Unsubscribe instance
202
+ if (!this.subscribers.has(workflowId)) {
203
+ void this.redisSubscriber.unsubscribe(this.getChannelName(workflowId));
204
+ }
205
+ if (transactionId) {
206
+ const transactionSubscribers = subscribers.get(transactionId) ?? [];
207
+ const newTransactionSubscribers = filterSubscribers(transactionSubscribers);
208
+ subscribers.set(transactionId, newTransactionSubscribers);
209
+ this.subscribers.set(workflowId, subscribers);
210
+ return;
211
+ }
212
+ const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
213
+ const newWorkflowSubscribers = filterSubscribers(workflowSubscribers);
214
+ subscribers.set(AnySubscriber, newWorkflowSubscribers);
215
+ this.subscribers.set(workflowId, subscribers);
216
+ }
217
+ async notify(options, publish = true, instanceId = this.instanceId) {
218
+ if (!publish && instanceId === this.instanceId) {
219
+ return;
220
+ }
221
+ if (publish) {
222
+ const channel = this.getChannelName(options.workflowId);
223
+ const message = JSON.stringify({
224
+ instanceId: this.instanceId,
225
+ data: options,
226
+ });
227
+ await this.redisPublisher.publish(channel, message);
228
+ }
229
+ const { eventType, workflowId, transactionId, errors, result, step, response, } = options;
230
+ const subscribers = this.subscribers.get(workflowId) ?? new Map();
231
+ const notifySubscribers = (handlers) => {
232
+ handlers.forEach((handler) => {
233
+ handler({
234
+ eventType,
235
+ workflowId,
236
+ transactionId,
237
+ step,
238
+ response,
239
+ result,
240
+ errors,
241
+ });
242
+ });
243
+ };
244
+ if (transactionId) {
245
+ const transactionSubscribers = subscribers.get(transactionId) ?? [];
246
+ notifySubscribers(transactionSubscribers);
247
+ }
248
+ const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
249
+ notifySubscribers(workflowSubscribers);
250
+ }
251
+ getChannelName(workflowId) {
252
+ return `orchestrator:${workflowId}`;
253
+ }
254
+ buildWorkflowEvents({ customEventHandlers, workflowId, transactionId, }) {
255
+ const notify = async ({ eventType, step, result, response, errors, }) => {
256
+ await this.notify({
257
+ workflowId,
258
+ transactionId,
259
+ eventType,
260
+ response,
261
+ step,
262
+ result,
263
+ errors,
264
+ });
265
+ };
266
+ return {
267
+ onTimeout: async ({ transaction }) => {
268
+ customEventHandlers?.onTimeout?.({ transaction });
269
+ await notify({ eventType: "onTimeout" });
270
+ },
271
+ onBegin: async ({ transaction }) => {
272
+ customEventHandlers?.onBegin?.({ transaction });
273
+ await notify({ eventType: "onBegin" });
274
+ },
275
+ onResume: async ({ transaction }) => {
276
+ customEventHandlers?.onResume?.({ transaction });
277
+ await notify({ eventType: "onResume" });
278
+ },
279
+ onCompensateBegin: async ({ transaction }) => {
280
+ customEventHandlers?.onCompensateBegin?.({ transaction });
281
+ await notify({ eventType: "onCompensateBegin" });
282
+ },
283
+ onFinish: async ({ transaction, result, errors }) => {
284
+ // TODO: unsubscribe transaction handlers on finish
285
+ customEventHandlers?.onFinish?.({ transaction, result, errors });
286
+ },
287
+ onStepBegin: async ({ step, transaction }) => {
288
+ customEventHandlers?.onStepBegin?.({ step, transaction });
289
+ await notify({ eventType: "onStepBegin", step });
290
+ },
291
+ onStepSuccess: async ({ step, transaction }) => {
292
+ const response = transaction.getContext().invoke[step.id];
293
+ customEventHandlers?.onStepSuccess?.({ step, transaction, response });
294
+ await notify({ eventType: "onStepSuccess", step, response });
295
+ },
296
+ onStepFailure: async ({ step, transaction }) => {
297
+ const errors = transaction.getErrors(orchestration_1.TransactionHandlerType.INVOKE)[step.id];
298
+ customEventHandlers?.onStepFailure?.({ step, transaction, errors });
299
+ await notify({ eventType: "onStepFailure", step, errors });
300
+ },
301
+ onCompensateStepSuccess: async ({ step, transaction }) => {
302
+ const response = transaction.getContext().compensate[step.id];
303
+ customEventHandlers?.onStepSuccess?.({ step, transaction, response });
304
+ await notify({ eventType: "onCompensateStepSuccess", step, response });
305
+ },
306
+ onCompensateStepFailure: async ({ step, transaction }) => {
307
+ const errors = transaction.getErrors(orchestration_1.TransactionHandlerType.COMPENSATE)[step.id];
308
+ customEventHandlers?.onStepFailure?.({ step, transaction, errors });
309
+ await notify({ eventType: "onCompensateStepFailure", step, errors });
310
+ },
311
+ };
312
+ }
313
+ buildIdempotencyKeyAndParts(idempotencyKey) {
314
+ const parts = {
315
+ workflowId: "",
316
+ transactionId: "",
317
+ stepId: "",
318
+ action: "invoke",
319
+ };
320
+ let idempotencyKey_ = idempotencyKey;
321
+ const setParts = (workflowId, transactionId, stepId, action) => {
322
+ parts.workflowId = workflowId;
323
+ parts.transactionId = transactionId;
324
+ parts.stepId = stepId;
325
+ parts.action = action;
326
+ };
327
+ if (!(0, utils_1.isString)(idempotencyKey)) {
328
+ const { workflowId, transactionId, stepId, action } = idempotencyKey;
329
+ idempotencyKey_ = [workflowId, transactionId, stepId, action].join(":");
330
+ setParts(workflowId, transactionId, stepId, action);
331
+ }
332
+ else {
333
+ const [workflowId, transactionId, stepId, action] = idempotencyKey_.split(":");
334
+ setParts(workflowId, transactionId, stepId, action);
335
+ }
336
+ return [idempotencyKey_, parts];
337
+ }
338
+ }
339
+ exports.WorkflowOrchestratorService = WorkflowOrchestratorService;
340
+ __decorate([
341
+ (0, utils_1.InjectSharedContext)(),
342
+ __param(2, (0, utils_1.MedusaContext)()),
343
+ __metadata("design:type", Function),
344
+ __metadata("design:paramtypes", [Object, Object, Object]),
345
+ __metadata("design:returntype", Promise)
346
+ ], WorkflowOrchestratorService.prototype, "run", null);
347
+ __decorate([
348
+ (0, utils_1.InjectSharedContext)(),
349
+ __param(3, (0, utils_1.MedusaContext)()),
350
+ __metadata("design:type", Function),
351
+ __metadata("design:paramtypes", [String, String, Object, Object]),
352
+ __metadata("design:returntype", Promise)
353
+ ], WorkflowOrchestratorService.prototype, "getRunningTransaction", null);
354
+ __decorate([
355
+ (0, utils_1.InjectSharedContext)(),
356
+ __param(1, (0, utils_1.MedusaContext)()),
357
+ __metadata("design:type", Function),
358
+ __metadata("design:paramtypes", [Object, Object]),
359
+ __metadata("design:returntype", Promise)
360
+ ], WorkflowOrchestratorService.prototype, "setStepSuccess", null);
361
+ __decorate([
362
+ (0, utils_1.InjectSharedContext)(),
363
+ __param(1, (0, utils_1.MedusaContext)()),
364
+ __metadata("design:type", Function),
365
+ __metadata("design:paramtypes", [Object, Object]),
366
+ __metadata("design:returntype", Promise)
367
+ ], WorkflowOrchestratorService.prototype, "setStepFailure", null);
368
+ __decorate([
369
+ (0, utils_1.InjectSharedContext)(),
370
+ __param(1, (0, utils_1.MedusaContext)()),
371
+ __metadata("design:type", Function),
372
+ __metadata("design:paramtypes", [Object, Object]),
373
+ __metadata("design:returntype", void 0)
374
+ ], WorkflowOrchestratorService.prototype, "subscribe", null);
375
+ __decorate([
376
+ (0, utils_1.InjectSharedContext)(),
377
+ __param(1, (0, utils_1.MedusaContext)()),
378
+ __metadata("design:type", Function),
379
+ __metadata("design:paramtypes", [Object, Object]),
380
+ __metadata("design:returntype", void 0)
381
+ ], WorkflowOrchestratorService.prototype, "unsubscribe", null);
@@ -0,0 +1,43 @@
1
+ import { Context, DAL, FindConfig, InternalModuleDeclaration, ModuleJoinerConfig } from "@medusajs/types";
2
+ import type { ReturnWorkflow, UnwrapWorkflowInputDataType, WorkflowOrchestratorTypes } from "@medusajs/workflows-sdk";
3
+ import { WorkflowExecutionService, WorkflowOrchestratorService } from ".";
4
+ type InjectedDependencies = {
5
+ baseRepository: DAL.RepositoryService;
6
+ workflowExecutionService: WorkflowExecutionService;
7
+ workflowOrchestratorService: WorkflowOrchestratorService;
8
+ };
9
+ export declare class WorkflowsModuleService implements WorkflowOrchestratorTypes.IWorkflowsModuleService {
10
+ protected readonly moduleDeclaration: InternalModuleDeclaration;
11
+ protected baseRepository_: DAL.RepositoryService;
12
+ protected workflowExecutionService_: WorkflowExecutionService;
13
+ protected workflowOrchestratorService_: WorkflowOrchestratorService;
14
+ constructor({ baseRepository, workflowExecutionService, workflowOrchestratorService, }: InjectedDependencies, moduleDeclaration: InternalModuleDeclaration);
15
+ __joinerConfig(): ModuleJoinerConfig;
16
+ listWorkflowExecution(filters?: WorkflowOrchestratorTypes.FilterableWorkflowExecutionProps, config?: FindConfig<WorkflowOrchestratorTypes.WorkflowExecutionDTO>, sharedContext?: Context): Promise<WorkflowOrchestratorTypes.WorkflowExecutionDTO[]>;
17
+ listAndCountWorkflowExecution(filters?: WorkflowOrchestratorTypes.FilterableWorkflowExecutionProps, config?: FindConfig<WorkflowOrchestratorTypes.WorkflowExecutionDTO>, sharedContext?: Context): Promise<[WorkflowOrchestratorTypes.WorkflowExecutionDTO[], number]>;
18
+ run<TWorkflow extends string | ReturnWorkflow<any, any, any>>(workflowIdOrWorkflow: TWorkflow, options?: WorkflowOrchestratorTypes.WorkflowOrchestratorRunDTO<TWorkflow extends ReturnWorkflow<any, any, any> ? UnwrapWorkflowInputDataType<TWorkflow> : unknown>, context?: Context): Promise<any>;
19
+ getRunningTransaction(workflowId: string, transactionId: string, context?: Context): Promise<import("@medusajs/orchestration").DistributedTransaction>;
20
+ setStepSuccess({ idempotencyKey, stepResponse, options, }: {
21
+ idempotencyKey: string | object;
22
+ stepResponse: unknown;
23
+ options?: Record<string, any>;
24
+ }, context?: Context): Promise<any>;
25
+ setStepFailure({ idempotencyKey, stepResponse, options, }: {
26
+ idempotencyKey: string | object;
27
+ stepResponse: unknown;
28
+ options?: Record<string, any>;
29
+ }, context?: Context): Promise<any>;
30
+ subscribe(args: {
31
+ workflowId: string;
32
+ transactionId?: string;
33
+ subscriber: Function;
34
+ subscriberId?: string;
35
+ }, context?: Context): Promise<void>;
36
+ unsubscribe(args: {
37
+ workflowId: string;
38
+ transactionId?: string;
39
+ subscriberOrId: string | Function;
40
+ }, context?: Context): Promise<void>;
41
+ }
42
+ export {};
43
+ //# sourceMappingURL=workflows-module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflows-module.d.ts","sourceRoot":"","sources":["../../src/services/workflows-module.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,GAAG,EACH,UAAU,EACV,yBAAyB,EACzB,kBAAkB,EACnB,MAAM,iBAAiB,CAAA;AAOxB,OAAO,KAAK,EACV,cAAc,EACd,2BAA2B,EAC3B,yBAAyB,EAC1B,MAAM,yBAAyB,CAAA;AAChC,OAAO,EACL,wBAAwB,EACxB,2BAA2B,EAC5B,MAAM,WAAW,CAAA;AAGlB,KAAK,oBAAoB,GAAG;IAC1B,cAAc,EAAE,GAAG,CAAC,iBAAiB,CAAA;IACrC,wBAAwB,EAAE,wBAAwB,CAAA;IAClD,2BAA2B,EAAE,2BAA2B,CAAA;CACzD,CAAA;AAED,qBAAa,sBACX,YAAW,yBAAyB,CAAC,uBAAuB;IAY1D,SAAS,CAAC,QAAQ,CAAC,iBAAiB,EAAE,yBAAyB;IAVjE,SAAS,CAAC,eAAe,EAAE,GAAG,CAAC,iBAAiB,CAAA;IAChD,SAAS,CAAC,yBAAyB,EAAE,wBA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