@etohq/workflow-engine-inmemory 1.3.0 → 1.5.0

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 (33) hide show
  1. package/LICENSE +21 -0
  2. package/dist/migrations/Migration20250128174331.d.ts +6 -0
  3. package/dist/migrations/Migration20250128174331.d.ts.map +1 -0
  4. package/dist/migrations/Migration20250128174331.js +24 -0
  5. package/dist/migrations/Migration20250128174331.js.map +1 -0
  6. package/dist/migrations/Migration20250505092459.d.ts +6 -0
  7. package/dist/migrations/Migration20250505092459.d.ts.map +1 -0
  8. package/dist/migrations/Migration20250505092459.js +40 -0
  9. package/dist/migrations/Migration20250505092459.js.map +1 -0
  10. package/dist/models/workflow-execution.d.ts +2 -0
  11. package/dist/models/workflow-execution.d.ts.map +1 -1
  12. package/dist/models/workflow-execution.js +7 -0
  13. package/dist/models/workflow-execution.js.map +1 -1
  14. package/dist/schema/index.d.ts +1 -1
  15. package/dist/schema/index.d.ts.map +1 -1
  16. package/dist/schema/index.js +1 -0
  17. package/dist/schema/index.js.map +1 -1
  18. package/dist/services/workflow-orchestrator.d.ts +14 -6
  19. package/dist/services/workflow-orchestrator.d.ts.map +1 -1
  20. package/dist/services/workflow-orchestrator.js +136 -77
  21. package/dist/services/workflow-orchestrator.js.map +1 -1
  22. package/dist/services/workflows-module.d.ts +112 -3
  23. package/dist/services/workflows-module.d.ts.map +1 -1
  24. package/dist/services/workflows-module.js +119 -7
  25. package/dist/services/workflows-module.js.map +1 -1
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/dist/types/index.d.ts +6 -0
  28. package/dist/types/index.d.ts.map +1 -1
  29. package/dist/utils/workflow-orchestrator-storage.d.ts +8 -2
  30. package/dist/utils/workflow-orchestrator-storage.d.ts.map +1 -1
  31. package/dist/utils/workflow-orchestrator-storage.js +255 -37
  32. package/dist/utils/workflow-orchestrator-storage.js.map +1 -1
  33. package/package.json +30 -30
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Etohq
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ import { Migration } from "@mikro-orm/migrations";
2
+ export declare class Migration20250128174331 extends Migration {
3
+ up(): Promise<void>;
4
+ down(): Promise<void>;
5
+ }
6
+ //# sourceMappingURL=Migration20250128174331.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Migration20250128174331.d.ts","sourceRoot":"","sources":["../../src/migrations/Migration20250128174331.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AAEjD,qBAAa,uBAAwB,SAAQ,SAAS;IACrC,EAAE,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBnB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAKrC"}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Migration20250128174331 = void 0;
4
+ const migrations_1 = require("@mikro-orm/migrations");
5
+ class Migration20250128174331 extends migrations_1.Migration {
6
+ async up() {
7
+ this.addSql(`alter table if exists "workflow_execution" add column if not exists "retention_time" integer null;`);
8
+ this.addSql(`
9
+ UPDATE workflow_execution
10
+ SET retention_time = (
11
+ SELECT COALESCE(
12
+ (execution->'options'->>'retentionTime')::integer,
13
+ 0
14
+ )
15
+ )
16
+ WHERE execution->'options' ? 'retentionTime';
17
+ `);
18
+ }
19
+ async down() {
20
+ this.addSql(`alter table if exists "workflow_execution" drop column if exists "retention_time";`);
21
+ }
22
+ }
23
+ exports.Migration20250128174331 = Migration20250128174331;
24
+ //# sourceMappingURL=Migration20250128174331.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Migration20250128174331.js","sourceRoot":"","sources":["../../src/migrations/Migration20250128174331.ts"],"names":[],"mappings":";;;AAAA,sDAAiD;AAEjD,MAAa,uBAAwB,SAAQ,sBAAS;IAC3C,KAAK,CAAC,EAAE;QACf,IAAI,CAAC,MAAM,CACT,oGAAoG,CACrG,CAAA;QACD,IAAI,CAAC,MAAM,CAAC;;;;;;;;;KASX,CAAC,CAAA;IACJ,CAAC;IAEQ,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,MAAM,CACT,oFAAoF,CACrF,CAAA;IACH,CAAC;CACF;AAtBD,0DAsBC"}
@@ -0,0 +1,6 @@
1
+ import { Migration } from "@mikro-orm/migrations";
2
+ export declare class Migration20250505092459 extends Migration {
3
+ up(): Promise<void>;
4
+ down(): Promise<void>;
5
+ }
6
+ //# sourceMappingURL=Migration20250505092459.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Migration20250505092459.d.ts","sourceRoot":"","sources":["../../src/migrations/Migration20250505092459.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AAGjD,qBAAa,uBAAwB,SAAQ,SAAS;IACrC,EAAE,IAAI,OAAO,CAAC,IAAI,CAAC;IAwCnB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAkBrC"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Migration20250505092459 = void 0;
4
+ const migrations_1 = require("@mikro-orm/migrations");
5
+ const ulid_1 = require("ulid");
6
+ class Migration20250505092459 extends migrations_1.Migration {
7
+ async up() {
8
+ this.addSql(`alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_workflow_id_transaction_id_run_id_unique";`);
9
+ this.addSql(`drop index if exists "IDX_workflow_execution_workflow_id_transaction_id_unique";`);
10
+ this.addSql(`alter table if exists "workflow_execution" drop constraint if exists "PK_workflow_execution_workflow_id_transaction_id";`);
11
+ this.addSql(`alter table if exists "workflow_execution" add column if not exists "run_id" text not null default '${(0, ulid_1.ulid)()}';`);
12
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_workflow_execution_workflow_id_transaction_id_run_id_unique" ON "workflow_execution" (workflow_id, transaction_id, run_id) WHERE deleted_at IS NULL;`);
13
+ /*
14
+ * We mistakenly named this migration differently in the workflow engines; this has caused issues with the migrations. Switching between engines will fail because the primary key is attempted to be set twice.
15
+ * The issue happens in the following scenario:
16
+ * 1. In memory engine is used
17
+ * 2. Migration is run
18
+ * 3. Primary is key added
19
+ * 3. Redis engine is used
20
+ * 4. Migration is run
21
+ * 5. Same primary key is attempted to be set again
22
+ * 6. Migration fails
23
+ *
24
+ * The same scenario can happen if you go from Redis to In memory.
25
+ *
26
+ * With this fix, we ensure the primary key is only ever set once.
27
+ */
28
+ this.addSql(`alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_pkey";`);
29
+ this.addSql(`alter table if exists "workflow_execution" add constraint "workflow_execution_pkey" primary key ("workflow_id", "transaction_id", "run_id");`);
30
+ }
31
+ async down() {
32
+ this.addSql(`drop index if exists "IDX_workflow_execution_workflow_id_transaction_id_run_id_unique";`);
33
+ this.addSql(`alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_pkey";`);
34
+ this.addSql(`alter table if exists "workflow_execution" drop column if exists "run_id";`);
35
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_workflow_execution_workflow_id_transaction_id_unique" ON "workflow_execution" (workflow_id, transaction_id) WHERE deleted_at IS NULL;`);
36
+ this.addSql(`alter table if exists "workflow_execution" add constraint "workflow_execution_pkey" primary key ("workflow_id", "transaction_id");`);
37
+ }
38
+ }
39
+ exports.Migration20250505092459 = Migration20250505092459;
40
+ //# sourceMappingURL=Migration20250505092459.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Migration20250505092459.js","sourceRoot":"","sources":["../../src/migrations/Migration20250505092459.ts"],"names":[],"mappings":";;;AAAA,sDAAiD;AACjD,+BAA2B;AAE3B,MAAa,uBAAwB,SAAQ,sBAAS;IAC3C,KAAK,CAAC,EAAE;QACf,IAAI,CAAC,MAAM,CACT,qIAAqI,CACtI,CAAA;QACD,IAAI,CAAC,MAAM,CACT,kFAAkF,CACnF,CAAA;QACD,IAAI,CAAC,MAAM,CACT,0HAA0H,CAC3H,CAAA;QAED,IAAI,CAAC,MAAM,CACT,uGAAuG,IAAA,WAAI,GAAE,IAAI,CAClH,CAAA;QACD,IAAI,CAAC,MAAM,CACT,6LAA6L,CAC9L,CAAA;QACD;;;;;;;;;;;;;;WAcG;QACH,IAAI,CAAC,MAAM,CACT,iGAAiG,CAClG,CAAA;QACD,IAAI,CAAC,MAAM,CACT,8IAA8I,CAC/I,CAAA;IACH,CAAC;IAEQ,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,MAAM,CACT,yFAAyF,CAC1F,CAAA;QACD,IAAI,CAAC,MAAM,CACT,iGAAiG,CAClG,CAAA;QACD,IAAI,CAAC,MAAM,CACT,4EAA4E,CAC7E,CAAA;QAED,IAAI,CAAC,MAAM,CACT,8KAA8K,CAC/K,CAAA;QACD,IAAI,CAAC,MAAM,CACT,oIAAoI,CACrI,CAAA;IACH,CAAC;CACF;AA3DD,0DA2DC"}
@@ -3,8 +3,10 @@ export declare const WorkflowExecution: import("@etohq/framework/utils").DmlEnti
3
3
  id: import("@etohq/framework/utils").IdProperty;
4
4
  workflow_id: import("@etohq/framework/utils").PrimaryKeyModifier<string, import("@etohq/framework/utils").TextProperty>;
5
5
  transaction_id: import("@etohq/framework/utils").PrimaryKeyModifier<string, import("@etohq/framework/utils").TextProperty>;
6
+ run_id: import("@etohq/framework/utils").PrimaryKeyModifier<string, import("@etohq/framework/utils").TextProperty>;
6
7
  execution: import("@etohq/framework/utils").NullableModifier<Record<string, unknown>, import("@etohq/framework/utils").JSONProperty>;
7
8
  context: import("@etohq/framework/utils").NullableModifier<Record<string, unknown>, import("@etohq/framework/utils").JSONProperty>;
8
9
  state: import("@etohq/framework/utils").EnumProperty<typeof TransactionState>;
10
+ retention_time: import("@etohq/framework/utils").NullableModifier<number, import("@etohq/framework/utils").NumberProperty>;
9
11
  }>, "workflow_execution">;
10
12
  //# sourceMappingURL=workflow-execution.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-execution.d.ts","sourceRoot":"","sources":["../../src/models/workflow-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AAGjE,eAAO,MAAM,iBAAiB;;;;;;;yBA0B1B,CAAA"}
1
+ {"version":3,"file":"workflow-execution.d.ts","sourceRoot":"","sources":["../../src/models/workflow-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AAGjE,eAAO,MAAM,iBAAiB;;;;;;;;;yBAiC1B,CAAA"}
@@ -8,9 +8,11 @@ exports.WorkflowExecution = utils_1.model
8
8
  id: utils_1.model.id({ prefix: "wf_exec" }),
9
9
  workflow_id: utils_1.model.text().primaryKey(),
10
10
  transaction_id: utils_1.model.text().primaryKey(),
11
+ run_id: utils_1.model.text().primaryKey(),
11
12
  execution: utils_1.model.json().nullable(),
12
13
  context: utils_1.model.json().nullable(),
13
14
  state: utils_1.model.enum(orchestration_1.TransactionState),
15
+ retention_time: utils_1.model.number().nullable(),
14
16
  })
15
17
  .indexes([
16
18
  {
@@ -25,6 +27,11 @@ exports.WorkflowExecution = utils_1.model
25
27
  on: ["transaction_id"],
26
28
  where: "deleted_at IS NULL",
27
29
  },
30
+ {
31
+ on: ["workflow_id", "transaction_id", "run_id"],
32
+ unique: true,
33
+ where: "deleted_at IS NULL",
34
+ },
28
35
  {
29
36
  on: ["state"],
30
37
  where: "deleted_at IS NULL",
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-execution.js","sourceRoot":"","sources":["../../src/models/workflow-execution.ts"],"names":[],"mappings":";;;AAAA,kEAAiE;AACjE,kDAA8C;AAEjC,QAAA,iBAAiB,GAAG,aAAK;KACnC,MAAM,CAAC,oBAAoB,EAAE;IAC5B,EAAE,EAAE,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IACnC,WAAW,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE;IACtC,cAAc,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE;IACzC,SAAS,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;IAClC,OAAO,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;IAChC,KAAK,EAAE,aAAK,CAAC,IAAI,CAAC,gCAAgB,CAAC;CACpC,CAAC;KACD,OAAO,CAAC;IACP;QACE,EAAE,EAAE,CAAC,IAAI,CAAC;QACV,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,aAAa,CAAC;QACnB,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,gBAAgB,CAAC;QACtB,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,OAAO,CAAC;QACb,KAAK,EAAE,oBAAoB;KAC5B;CACF,CAAC,CAAA"}
1
+ {"version":3,"file":"workflow-execution.js","sourceRoot":"","sources":["../../src/models/workflow-execution.ts"],"names":[],"mappings":";;;AAAA,kEAAiE;AACjE,kDAA8C;AAEjC,QAAA,iBAAiB,GAAG,aAAK;KACnC,MAAM,CAAC,oBAAoB,EAAE;IAC5B,EAAE,EAAE,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IACnC,WAAW,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE;IACtC,cAAc,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE;IACzC,MAAM,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE;IACjC,SAAS,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;IAClC,OAAO,EAAE,aAAK,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;IAChC,KAAK,EAAE,aAAK,CAAC,IAAI,CAAC,gCAAgB,CAAC;IACnC,cAAc,EAAE,aAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC1C,CAAC;KACD,OAAO,CAAC;IACP;QACE,EAAE,EAAE,CAAC,IAAI,CAAC;QACV,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,aAAa,CAAC;QACnB,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,gBAAgB,CAAC;QACtB,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,aAAa,EAAE,gBAAgB,EAAE,QAAQ,CAAC;QAC/C,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,oBAAoB;KAC5B;IACD;QACE,EAAE,EAAE,CAAC,OAAO,CAAC;QACb,KAAK,EAAE,oBAAoB;KAC5B;CACF,CAAC,CAAA"}
@@ -1,3 +1,3 @@
1
- declare const _default: "\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";
1
+ declare const _default: "\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 run_id: string\n execution: JSON\n context: JSON\n state: TransactionState\n}\n";
2
2
  export default _default;
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":";AAAA,wBAsBC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":";AAAA,wBAuBC"}
@@ -18,6 +18,7 @@ type WorkflowExecution {
18
18
  deleted_at: DateTime
19
19
  workflow_id: string
20
20
  transaction_id: string
21
+ run_id: string
21
22
  execution: JSON
22
23
  context: JSON
23
24
  state: TransactionState
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":";;AAAA,kBAAe;;;;;;;;;;;;;;;;;;;;;;CAsBd,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":";;AAAA,kBAAe;;;;;;;;;;;;;;;;;;;;;;;CAuBd,CAAA"}
@@ -1,9 +1,12 @@
1
1
  import { DistributedTransactionEvents, DistributedTransactionType, TransactionStep } from "@etohq/framework/orchestration";
2
2
  import { ContainerLike, Context, EtoContainer } from "@etohq/framework/types";
3
+ import { TransactionState } from "@etohq/framework/utils";
3
4
  import { type FlowRunOptions, ReturnWorkflow } from "@etohq/framework/workflows-sdk";
5
+ import { WorkflowOrchestratorCancelOptions } from "../types";
4
6
  import { InMemoryDistributedTransactionStorage } from "../utils";
5
7
  export type WorkflowOrchestratorRunOptions<T> = Omit<FlowRunOptions<T>, "container"> & {
6
8
  transactionId?: string;
9
+ runId?: string;
7
10
  container?: ContainerLike;
8
11
  };
9
12
  type RegisterStepSuccessOptions<T> = Omit<WorkflowOrchestratorRunOptions<T>, "transactionId" | "input">;
@@ -17,6 +20,7 @@ type NotifyOptions = {
17
20
  eventType: keyof DistributedTransactionEvents;
18
21
  workflowId: string;
19
22
  transactionId?: string;
23
+ state?: TransactionState;
20
24
  step?: TransactionStep;
21
25
  response?: unknown;
22
26
  result?: unknown;
@@ -41,26 +45,30 @@ type UnsubscribeOptions = {
41
45
  export declare class WorkflowOrchestratorService {
42
46
  private subscribers;
43
47
  private container_;
48
+ private inMemoryDistributedTransactionStorage_;
44
49
  constructor({ inMemoryDistributedTransactionStorage, sharedContainer, }: {
45
50
  inMemoryDistributedTransactionStorage: InMemoryDistributedTransactionStorage;
46
51
  workflowOrchestratorService: WorkflowOrchestratorService;
47
52
  sharedContainer: EtoContainer;
48
53
  });
54
+ onApplicationStart(): Promise<void>;
55
+ onApplicationShutdown(): Promise<void>;
49
56
  private triggerParentStep;
50
- run<T = unknown>(workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, options?: WorkflowOrchestratorRunOptions<T>, sharedContext?: Context): Promise<any>;
51
- getRunningTransaction(workflowId: string, transactionId: string, options?: WorkflowOrchestratorRunOptions<undefined>, sharedContext?: Context): Promise<DistributedTransactionType>;
57
+ run<T = unknown>(workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, options?: WorkflowOrchestratorRunOptions<T>): Promise<any>;
58
+ cancel(workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, options?: WorkflowOrchestratorCancelOptions): Promise<any>;
59
+ getRunningTransaction(workflowId: string, transactionId: string, context?: Context): Promise<DistributedTransactionType>;
52
60
  setStepSuccess<T = unknown>({ idempotencyKey, stepResponse, options, }: {
53
61
  idempotencyKey: string | IdempotencyKeyParts;
54
62
  stepResponse: unknown;
55
63
  options?: RegisterStepSuccessOptions<T>;
56
- }, sharedContext?: Context): Promise<any>;
64
+ }): Promise<any>;
57
65
  setStepFailure<T = unknown>({ idempotencyKey, stepResponse, options, }: {
58
66
  idempotencyKey: string | IdempotencyKeyParts;
59
67
  stepResponse: unknown;
60
68
  options?: RegisterStepSuccessOptions<T>;
61
- }, sharedContext?: Context): Promise<any>;
62
- subscribe({ workflowId, transactionId, subscriber, subscriberId }: SubscribeOptions, sharedContext?: Context): void;
63
- unsubscribe({ workflowId, transactionId, subscriberOrId }: UnsubscribeOptions, sharedContext?: Context): void;
69
+ }): Promise<any>;
70
+ subscribe({ workflowId, transactionId, subscriber, subscriberId, }: SubscribeOptions): void;
71
+ unsubscribe({ workflowId, transactionId, subscriberOrId, }: UnsubscribeOptions): void;
64
72
  private notify;
65
73
  private buildWorkflowEvents;
66
74
  private buildIdempotencyKeyAndParts;
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-orchestrator.d.ts","sourceRoot":"","sources":["../../src/services/workflow-orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,EAC5B,0BAA0B,EAE1B,eAAe,EAEhB,MAAM,gCAAgC,CAAA;AACvC,OAAO,EACL,aAAa,EACb,OAAO,EACP,YAAY,EACb,MAAM,wBAAwB,CAAA;AAQ/B,OAAO,EACL,KAAK,cAAc,EAGnB,cAAc,EACf,MAAM,gCAAgC,CAAA;AAEvC,OAAO,EAAE,qCAAqC,EAAE,MAAM,UAAU,CAAA;AAEhE,MAAM,MAAM,8BAA8B,CAAC,CAAC,IAAI,IAAI,CAClD,cAAc,CAAC,CAAC,CAAC,EACjB,WAAW,CACZ,GAAG;IACF,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,aAAa,CAAA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+BpC"}
1
+ {"version":3,"file":"workflow-orchestrator.d.ts","sourceRoot":"","sources":["../../src/services/workflow-orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,EAC5B,0BAA0B,EAE1B,eAAe,EAEhB,MAAM,gCAAgC,CAAA;AACvC,OAAO,EACL,aAAa,EACb,OAAO,EACP,YAAY,EACb,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAGL,gBAAgB,EACjB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,KAAK,cAAc,EAGnB,cAAc,EACf,MAAM,gCAAgC,CAAA;AACvC,OAAO,EAAE,iCAAiC,EAAE,MAAM,QAAQ,CAAA;AAE1D,OAAO,EAAE,qCAAqC,EAAE,MAAM,UAAU,CAAA;AAEhE,MAAM,MAAM,8BAA8B,CAAC,CAAC,IAAI,IAAI,CAClD,cAAc,CAAC,CAAC,CAAC,EACjB,WAAW,CACZ,GAAG;IACF,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,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,MAAM,CAAA;IAClB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,KAAK,CAAC,EAAE,gBAAgB,CAAA;IACxB,IAAI,CAAC,EAAE,eAAe,CAAA;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,MA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,EAAE,OAAO,GAChB,OAAO,CAAC,0BAA0B,CAAC;IAwBhC,cAAc,CAAC,CAAC,GAAG,OAAO,EAAE,EAChC,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;IA+DK,cAAc,CAAC,CAAC,GAAG,OAAO,EAAE,EAChC,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;IA+DD,SAAS,CAAC,EACR,UAAU,EACV,aAAa,EACb,UAAU,EACV,YAAY,GACb,EAAE,gBAAgB;IAkCnB,WAAW,CAAC,EACV,UAAU,EACV,aAAa,EACb,cAAc,GACf,EAAE,kBAAkB;IAmCrB,OAAO,CAAC,MAAM;IA2Cd,OAAO,CAAC,mBAAmB;IA6G3B,OAAO,CAAC,2BAA2B;CA+BpC"}
@@ -1,16 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.WorkflowOrchestratorService = void 0;
16
4
  const orchestration_1 = require("@etohq/framework/orchestration");
@@ -22,10 +10,18 @@ class WorkflowOrchestratorService {
22
10
  constructor({ inMemoryDistributedTransactionStorage, sharedContainer, }) {
23
11
  this.subscribers = new Map();
24
12
  this.container_ = sharedContainer;
13
+ this.inMemoryDistributedTransactionStorage_ =
14
+ inMemoryDistributedTransactionStorage;
25
15
  inMemoryDistributedTransactionStorage.setWorkflowOrchestratorService(this);
26
16
  orchestration_1.DistributedTransaction.setStorage(inMemoryDistributedTransactionStorage);
27
17
  orchestration_1.WorkflowScheduler.setStorage(inMemoryDistributedTransactionStorage);
28
18
  }
19
+ async onApplicationStart() {
20
+ await this.inMemoryDistributedTransactionStorage_.onApplicationStart();
21
+ }
22
+ async onApplicationShutdown() {
23
+ await this.inMemoryDistributedTransactionStorage_.onApplicationShutdown();
24
+ }
29
25
  async triggerParentStep(transaction, result) {
30
26
  const metadata = transaction.flow.metadata;
31
27
  const { parentStepIdempotencyKey } = metadata ?? {};
@@ -48,12 +44,12 @@ class WorkflowOrchestratorService {
48
44
  }
49
45
  }
50
46
  }
51
- async run(workflowIdOrWorkflow, options, sharedContext = {}) {
47
+ async run(workflowIdOrWorkflow, options) {
52
48
  const { input, transactionId, resultFrom, logOnError, events: eventHandlers, container, } = options ?? {};
53
49
  let { throwOnError, context } = options ?? {};
54
50
  throwOnError ??= true;
55
51
  context ??= {};
56
- context.transactionId ??= transactionId ?? (0, ulid_1.ulid)();
52
+ context.transactionId = transactionId ?? "auto-" + (0, ulid_1.ulid)();
57
53
  const workflowId = (0, utils_1.isString)(workflowIdOrWorkflow)
58
54
  ? workflowIdOrWorkflow
59
55
  : workflowIdOrWorkflow.getName();
@@ -98,18 +94,101 @@ class WorkflowOrchestratorService {
98
94
  eventType: "onFinish",
99
95
  workflowId,
100
96
  transactionId: context.transactionId,
97
+ state: ret.transaction.getFlow().state,
98
+ result,
99
+ errors,
100
+ });
101
+ await this.triggerParentStep(ret.transaction, result);
102
+ }
103
+ if (throwOnError && (ret.thrownError || ret.errors?.length)) {
104
+ if (ret.thrownError) {
105
+ throw ret.thrownError;
106
+ }
107
+ throw ret.errors[0].error;
108
+ }
109
+ return { acknowledgement, ...ret };
110
+ }
111
+ async cancel(workflowIdOrWorkflow, options) {
112
+ const { transactionId, logOnError, events: eventHandlers, container, } = options ?? {};
113
+ let { throwOnError, context } = options ?? {};
114
+ throwOnError ??= true;
115
+ context ??= {};
116
+ const workflowId = (0, utils_1.isString)(workflowIdOrWorkflow)
117
+ ? workflowIdOrWorkflow
118
+ : workflowIdOrWorkflow.getName();
119
+ if (!workflowId) {
120
+ throw new Error("Workflow ID is required");
121
+ }
122
+ if (!transactionId) {
123
+ throw new Error("Transaction ID is required");
124
+ }
125
+ const events = this.buildWorkflowEvents({
126
+ customEventHandlers: eventHandlers,
127
+ workflowId,
128
+ transactionId: transactionId,
129
+ });
130
+ const exportedWorkflow = workflows_sdk_1.EtoWorkflow.getWorkflow(workflowId);
131
+ if (!exportedWorkflow) {
132
+ throw new Error(`Workflow with id "${workflowId}" not found.`);
133
+ }
134
+ const transaction = await this.getRunningTransaction(workflowId, transactionId, {
135
+ ...options,
136
+ isCancelling: true,
137
+ });
138
+ if (!transaction) {
139
+ if (!throwOnError) {
140
+ return {
141
+ acknowledgement: {
142
+ transactionId,
143
+ workflowId,
144
+ exists: false,
145
+ },
146
+ };
147
+ }
148
+ throw new Error("Transaction not found");
149
+ }
150
+ const ret = await exportedWorkflow.cancel({
151
+ transaction,
152
+ throwOnError: false,
153
+ logOnError,
154
+ context,
155
+ events,
156
+ container: container ?? this.container_,
157
+ });
158
+ const hasFinished = ret.transaction.hasFinished();
159
+ const metadata = ret.transaction.getFlow().metadata;
160
+ const { parentStepIdempotencyKey } = metadata ?? {};
161
+ const transactionState = ret.transaction.getFlow().state;
162
+ const hasFailed = [utils_1.TransactionState.FAILED].includes(transactionState);
163
+ const acknowledgement = {
164
+ transactionId: transaction.transactionId,
165
+ workflowId: workflowId,
166
+ parentStepIdempotencyKey,
167
+ hasFinished,
168
+ hasFailed,
169
+ exists: true,
170
+ };
171
+ if (hasFinished) {
172
+ const { result, errors } = ret;
173
+ this.notify({
174
+ eventType: "onFinish",
175
+ workflowId,
176
+ transactionId: transaction.transactionId,
177
+ state: transactionState,
101
178
  result,
102
179
  errors,
103
180
  });
104
181
  await this.triggerParentStep(ret.transaction, result);
105
182
  }
106
- if (throwOnError && ret.thrownError) {
107
- throw ret.thrownError;
183
+ if (throwOnError && (ret.thrownError || ret.errors?.length)) {
184
+ if (ret.thrownError) {
185
+ throw ret.thrownError;
186
+ }
187
+ throw ret.errors[0].error;
108
188
  }
109
189
  return { acknowledgement, ...ret };
110
190
  }
111
- async getRunningTransaction(workflowId, transactionId, options, sharedContext = {}) {
112
- let { context, container } = options ?? {};
191
+ async getRunningTransaction(workflowId, transactionId, context) {
113
192
  if (!workflowId) {
114
193
  throw new Error("Workflow ID is required");
115
194
  }
@@ -122,11 +201,11 @@ class WorkflowOrchestratorService {
122
201
  if (!exportedWorkflow) {
123
202
  throw new Error(`Workflow with id "${workflowId}" not found.`);
124
203
  }
125
- const flow = exportedWorkflow(container ?? this.container_);
204
+ const flow = exportedWorkflow();
126
205
  const transaction = await flow.getRunningTransaction(transactionId, context);
127
206
  return transaction;
128
207
  }
129
- async setStepSuccess({ idempotencyKey, stepResponse, options, }, sharedContext = {}) {
208
+ async setStepSuccess({ idempotencyKey, stepResponse, options, }) {
130
209
  const { context, logOnError, resultFrom, container, events: eventHandlers, } = options ?? {};
131
210
  let { throwOnError } = options ?? {};
132
211
  throwOnError ??= true;
@@ -156,17 +235,21 @@ class WorkflowOrchestratorService {
156
235
  eventType: "onFinish",
157
236
  workflowId,
158
237
  transactionId,
238
+ state: ret.transaction.getFlow().state,
159
239
  result,
160
240
  errors,
161
241
  });
162
242
  await this.triggerParentStep(ret.transaction, result);
163
243
  }
164
- if (throwOnError && ret.thrownError) {
165
- throw ret.thrownError;
244
+ if (throwOnError && (ret.thrownError || ret.errors?.length)) {
245
+ if (ret.thrownError) {
246
+ throw ret.thrownError;
247
+ }
248
+ throw ret.errors[0].error;
166
249
  }
167
250
  return ret;
168
251
  }
169
- async setStepFailure({ idempotencyKey, stepResponse, options, }, sharedContext = {}) {
252
+ async setStepFailure({ idempotencyKey, stepResponse, options, }) {
170
253
  const { context, logOnError, resultFrom, container, events: eventHandlers, } = options ?? {};
171
254
  let { throwOnError } = options ?? {};
172
255
  throwOnError ??= true;
@@ -196,27 +279,31 @@ class WorkflowOrchestratorService {
196
279
  eventType: "onFinish",
197
280
  workflowId,
198
281
  transactionId,
282
+ state: ret.transaction.getFlow().state,
199
283
  result,
200
284
  errors,
201
285
  });
202
286
  await this.triggerParentStep(ret.transaction, result);
203
287
  }
204
- if (throwOnError && ret.thrownError) {
205
- throw ret.thrownError;
288
+ if (throwOnError && (ret.thrownError || ret.errors?.length)) {
289
+ if (ret.thrownError) {
290
+ throw ret.thrownError;
291
+ }
292
+ throw ret.errors[0].error;
206
293
  }
207
294
  return ret;
208
295
  }
209
- subscribe({ workflowId, transactionId, subscriber, subscriberId }, sharedContext = {}) {
296
+ subscribe({ workflowId, transactionId, subscriber, subscriberId, }) {
210
297
  subscriber._id = subscriberId;
211
298
  const subscribers = this.subscribers.get(workflowId) ?? new Map();
212
299
  const handlerIndex = (handlers) => {
213
- return handlers.indexOf((s) => s === subscriber || s._id === subscriberId);
300
+ return handlers.findIndex((s) => s === subscriber || s._id === subscriberId);
214
301
  };
215
302
  if (transactionId) {
216
303
  const transactionSubscribers = subscribers.get(transactionId) ?? [];
217
304
  const subscriberIndex = handlerIndex(transactionSubscribers);
218
305
  if (subscriberIndex !== -1) {
219
- transactionSubscribers.slice(subscriberIndex, 1);
306
+ transactionSubscribers.splice(subscriberIndex, 1);
220
307
  }
221
308
  transactionSubscribers.push(subscriber);
222
309
  subscribers.set(transactionId, transactionSubscribers);
@@ -226,13 +313,13 @@ class WorkflowOrchestratorService {
226
313
  const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
227
314
  const subscriberIndex = handlerIndex(workflowSubscribers);
228
315
  if (subscriberIndex !== -1) {
229
- workflowSubscribers.slice(subscriberIndex, 1);
316
+ workflowSubscribers.splice(subscriberIndex, 1);
230
317
  }
231
318
  workflowSubscribers.push(subscriber);
232
319
  subscribers.set(AnySubscriber, workflowSubscribers);
233
320
  this.subscribers.set(workflowId, subscribers);
234
321
  }
235
- unsubscribe({ workflowId, transactionId, subscriberOrId }, sharedContext = {}) {
322
+ unsubscribe({ workflowId, transactionId, subscriberOrId, }) {
236
323
  const subscribers = this.subscribers.get(workflowId) ?? new Map();
237
324
  const filterSubscribers = (handlers) => {
238
325
  return handlers.filter((handler) => {
@@ -244,17 +331,27 @@ class WorkflowOrchestratorService {
244
331
  if (transactionId) {
245
332
  const transactionSubscribers = subscribers.get(transactionId) ?? [];
246
333
  const newTransactionSubscribers = filterSubscribers(transactionSubscribers);
247
- subscribers.set(transactionId, newTransactionSubscribers);
334
+ if (newTransactionSubscribers.length) {
335
+ subscribers.set(transactionId, newTransactionSubscribers);
336
+ }
337
+ else {
338
+ subscribers.delete(transactionId);
339
+ }
248
340
  this.subscribers.set(workflowId, subscribers);
249
341
  return;
250
342
  }
251
343
  const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
252
344
  const newWorkflowSubscribers = filterSubscribers(workflowSubscribers);
253
- subscribers.set(AnySubscriber, newWorkflowSubscribers);
345
+ if (newWorkflowSubscribers.length) {
346
+ subscribers.set(AnySubscriber, newWorkflowSubscribers);
347
+ }
348
+ else {
349
+ subscribers.delete(AnySubscriber);
350
+ }
254
351
  this.subscribers.set(workflowId, subscribers);
255
352
  }
256
353
  notify(options) {
257
- const { eventType, workflowId, transactionId, errors, result, step, response, } = options;
354
+ const { eventType, workflowId, transactionId, errors, result, step, response, state, } = options;
258
355
  const subscribers = this.subscribers.get(workflowId) ?? new Map();
259
356
  const notifySubscribers = (handlers) => {
260
357
  handlers.forEach((handler) => {
@@ -266,18 +363,22 @@ class WorkflowOrchestratorService {
266
363
  response,
267
364
  result,
268
365
  errors,
366
+ state,
269
367
  });
270
368
  });
271
369
  };
272
370
  if (transactionId) {
273
371
  const transactionSubscribers = subscribers.get(transactionId) ?? [];
274
372
  notifySubscribers(transactionSubscribers);
373
+ if (options.eventType === "onFinish") {
374
+ subscribers.delete(transactionId);
375
+ }
275
376
  }
276
377
  const workflowSubscribers = subscribers.get(AnySubscriber) ?? [];
277
378
  notifySubscribers(workflowSubscribers);
278
379
  }
279
380
  buildWorkflowEvents({ customEventHandlers, workflowId, transactionId, }) {
280
- const notify = ({ eventType, step, result, response, errors, }) => {
381
+ const notify = ({ eventType, step, result, response, errors, state, }) => {
281
382
  this.notify({
282
383
  workflowId,
283
384
  transactionId,
@@ -286,6 +387,7 @@ class WorkflowOrchestratorService {
286
387
  step,
287
388
  result,
288
389
  errors,
390
+ state,
289
391
  });
290
392
  };
291
393
  return {
@@ -306,7 +408,6 @@ class WorkflowOrchestratorService {
306
408
  notify({ eventType: "onCompensateBegin" });
307
409
  },
308
410
  onFinish: ({ transaction, result, errors }) => {
309
- // TODO: unsubscribe transaction handlers on finish
310
411
  customEventHandlers?.onFinish?.({ transaction, result, errors });
311
412
  },
312
413
  onStepBegin: ({ step, transaction }) => {
@@ -378,46 +479,4 @@ class WorkflowOrchestratorService {
378
479
  }
379
480
  }
380
481
  exports.WorkflowOrchestratorService = WorkflowOrchestratorService;
381
- __decorate([
382
- (0, utils_1.InjectSharedContext)(),
383
- __param(2, (0, utils_1.EtoContext)()),
384
- __metadata("design:type", Function),
385
- __metadata("design:paramtypes", [Object, Object, Object]),
386
- __metadata("design:returntype", Promise)
387
- ], WorkflowOrchestratorService.prototype, "run", null);
388
- __decorate([
389
- (0, utils_1.InjectSharedContext)(),
390
- __param(3, (0, utils_1.EtoContext)()),
391
- __metadata("design:type", Function),
392
- __metadata("design:paramtypes", [String, String, Object, Object]),
393
- __metadata("design:returntype", Promise)
394
- ], WorkflowOrchestratorService.prototype, "getRunningTransaction", null);
395
- __decorate([
396
- (0, utils_1.InjectSharedContext)(),
397
- __param(1, (0, utils_1.EtoContext)()),
398
- __metadata("design:type", Function),
399
- __metadata("design:paramtypes", [Object, Object]),
400
- __metadata("design:returntype", Promise)
401
- ], WorkflowOrchestratorService.prototype, "setStepSuccess", null);
402
- __decorate([
403
- (0, utils_1.InjectSharedContext)(),
404
- __param(1, (0, utils_1.EtoContext)()),
405
- __metadata("design:type", Function),
406
- __metadata("design:paramtypes", [Object, Object]),
407
- __metadata("design:returntype", Promise)
408
- ], WorkflowOrchestratorService.prototype, "setStepFailure", null);
409
- __decorate([
410
- (0, utils_1.InjectSharedContext)(),
411
- __param(1, (0, utils_1.EtoContext)()),
412
- __metadata("design:type", Function),
413
- __metadata("design:paramtypes", [Object, Object]),
414
- __metadata("design:returntype", void 0)
415
- ], WorkflowOrchestratorService.prototype, "subscribe", null);
416
- __decorate([
417
- (0, utils_1.InjectSharedContext)(),
418
- __param(1, (0, utils_1.EtoContext)()),
419
- __metadata("design:type", Function),
420
- __metadata("design:paramtypes", [Object, Object]),
421
- __metadata("design:returntype", void 0)
422
- ], WorkflowOrchestratorService.prototype, "unsubscribe", null);
423
482
  //# sourceMappingURL=workflow-orchestrator.js.map