@acmekit/orchestration 2.13.1

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 (74) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +20 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/joiner/helpers.d.ts +3 -0
  6. package/dist/joiner/helpers.d.ts.map +1 -0
  7. package/dist/joiner/helpers.js +69 -0
  8. package/dist/joiner/helpers.js.map +1 -0
  9. package/dist/joiner/index.d.ts +3 -0
  10. package/dist/joiner/index.d.ts.map +1 -0
  11. package/dist/joiner/index.js +19 -0
  12. package/dist/joiner/index.js.map +1 -0
  13. package/dist/joiner/remote-joiner.d.ts +43 -0
  14. package/dist/joiner/remote-joiner.d.ts.map +1 -0
  15. package/dist/joiner/remote-joiner.js +1279 -0
  16. package/dist/joiner/remote-joiner.js.map +1 -0
  17. package/dist/transaction/datastore/abstract-storage.d.ts +44 -0
  18. package/dist/transaction/datastore/abstract-storage.d.ts.map +1 -0
  19. package/dist/transaction/datastore/abstract-storage.js +52 -0
  20. package/dist/transaction/datastore/abstract-storage.js.map +1 -0
  21. package/dist/transaction/datastore/base-in-memory-storage.d.ts +12 -0
  22. package/dist/transaction/datastore/base-in-memory-storage.d.ts.map +1 -0
  23. package/dist/transaction/datastore/base-in-memory-storage.js +35 -0
  24. package/dist/transaction/datastore/base-in-memory-storage.js.map +1 -0
  25. package/dist/transaction/distributed-transaction.d.ts +116 -0
  26. package/dist/transaction/distributed-transaction.d.ts.map +1 -0
  27. package/dist/transaction/distributed-transaction.js +488 -0
  28. package/dist/transaction/distributed-transaction.js.map +1 -0
  29. package/dist/transaction/errors.d.ts +41 -0
  30. package/dist/transaction/errors.d.ts.map +1 -0
  31. package/dist/transaction/errors.js +117 -0
  32. package/dist/transaction/errors.js.map +1 -0
  33. package/dist/transaction/index.d.ts +8 -0
  34. package/dist/transaction/index.d.ts.map +1 -0
  35. package/dist/transaction/index.js +24 -0
  36. package/dist/transaction/index.js.map +1 -0
  37. package/dist/transaction/orchestrator-builder.d.ts +36 -0
  38. package/dist/transaction/orchestrator-builder.d.ts.map +1 -0
  39. package/dist/transaction/orchestrator-builder.js +300 -0
  40. package/dist/transaction/orchestrator-builder.js.map +1 -0
  41. package/dist/transaction/transaction-orchestrator.d.ts +207 -0
  42. package/dist/transaction/transaction-orchestrator.d.ts.map +1 -0
  43. package/dist/transaction/transaction-orchestrator.js +1292 -0
  44. package/dist/transaction/transaction-orchestrator.js.map +1 -0
  45. package/dist/transaction/transaction-step.d.ts +69 -0
  46. package/dist/transaction/transaction-step.d.ts.map +1 -0
  47. package/dist/transaction/transaction-step.js +153 -0
  48. package/dist/transaction/transaction-step.js.map +1 -0
  49. package/dist/transaction/types.d.ts +264 -0
  50. package/dist/transaction/types.d.ts.map +1 -0
  51. package/dist/transaction/types.js +23 -0
  52. package/dist/transaction/types.js.map +1 -0
  53. package/dist/tsconfig.tsbuildinfo +1 -0
  54. package/dist/workflow/global-workflow.d.ts +14 -0
  55. package/dist/workflow/global-workflow.d.ts.map +1 -0
  56. package/dist/workflow/global-workflow.js +105 -0
  57. package/dist/workflow/global-workflow.js.map +1 -0
  58. package/dist/workflow/index.d.ts +5 -0
  59. package/dist/workflow/index.d.ts.map +1 -0
  60. package/dist/workflow/index.js +21 -0
  61. package/dist/workflow/index.js.map +1 -0
  62. package/dist/workflow/local-workflow.d.ts +47 -0
  63. package/dist/workflow/local-workflow.d.ts.map +1 -0
  64. package/dist/workflow/local-workflow.js +390 -0
  65. package/dist/workflow/local-workflow.js.map +1 -0
  66. package/dist/workflow/scheduler.d.ts +12 -0
  67. package/dist/workflow/scheduler.d.ts.map +1 -0
  68. package/dist/workflow/scheduler.js +35 -0
  69. package/dist/workflow/scheduler.js.map +1 -0
  70. package/dist/workflow/workflow-manager.d.ts +38 -0
  71. package/dist/workflow/workflow-manager.d.ts.map +1 -0
  72. package/dist/workflow/workflow-manager.js +124 -0
  73. package/dist/workflow/workflow-manager.js.map +1 -0
  74. package/package.json +41 -0
@@ -0,0 +1,1292 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionOrchestrator = void 0;
4
+ const ulid_1 = require("ulid");
5
+ const distributed_transaction_1 = require("./distributed-transaction");
6
+ const transaction_step_1 = require("./transaction-step");
7
+ const types_1 = require("./types");
8
+ const utils_1 = require("@acmekit/utils");
9
+ const events_1 = require("events");
10
+ const errors_1 = require("./errors");
11
+ const canMoveForwardStates = new Set([
12
+ utils_1.TransactionStepState.DONE,
13
+ utils_1.TransactionStepState.FAILED,
14
+ utils_1.TransactionStepState.TIMEOUT,
15
+ utils_1.TransactionStepState.SKIPPED,
16
+ utils_1.TransactionStepState.SKIPPED_FAILURE,
17
+ ]);
18
+ const canMoveBackwardStates = new Set([
19
+ utils_1.TransactionStepState.DONE,
20
+ utils_1.TransactionStepState.REVERTED,
21
+ utils_1.TransactionStepState.FAILED,
22
+ utils_1.TransactionStepState.DORMANT,
23
+ utils_1.TransactionStepState.SKIPPED,
24
+ ]);
25
+ const flagStepsToRevertStates = new Set([
26
+ utils_1.TransactionStepState.DONE,
27
+ utils_1.TransactionStepState.TIMEOUT,
28
+ ]);
29
+ const setStepTimeoutSkipStates = new Set([
30
+ utils_1.TransactionStepState.TIMEOUT,
31
+ utils_1.TransactionStepState.DONE,
32
+ utils_1.TransactionStepState.REVERTED,
33
+ ]);
34
+ /**
35
+ * @class TransactionOrchestrator is responsible for managing and executing distributed transactions.
36
+ * It is based on a single transaction definition, which is used to execute all the transaction steps
37
+ */
38
+ class TransactionOrchestrator extends events_1.EventEmitter {
39
+ static getWorkflowOptions(modelId) {
40
+ return TransactionOrchestrator.workflowOptions[modelId];
41
+ }
42
+ constructor({ id, definition, options, isClone, }) {
43
+ super();
44
+ this.invokeSteps = [];
45
+ this.compensateSteps = [];
46
+ this.id = id;
47
+ this.definition = definition;
48
+ this.options = options;
49
+ if (!isClone) {
50
+ this.parseFlowOptions();
51
+ }
52
+ }
53
+ static isExpectedError(error) {
54
+ return (errors_1.SkipCancelledExecutionError.isSkipCancelledExecutionError(error) ||
55
+ errors_1.SkipExecutionError.isSkipExecutionError(error) ||
56
+ errors_1.SkipStepAlreadyFinishedError.isSkipStepAlreadyFinishedError(error));
57
+ }
58
+ static clone(orchestrator) {
59
+ return new TransactionOrchestrator({
60
+ id: orchestrator.id,
61
+ definition: orchestrator.definition,
62
+ options: orchestrator.options,
63
+ isClone: true,
64
+ });
65
+ }
66
+ static getKeyName(...params) {
67
+ return params.join(this.SEPARATOR);
68
+ }
69
+ static getPreviousStep(flow, step) {
70
+ const id = step.id.split(".");
71
+ id.pop();
72
+ const parentId = id.join(".");
73
+ return flow.steps[parentId];
74
+ }
75
+ getOptions() {
76
+ return this.options ?? {};
77
+ }
78
+ getInvokeSteps(flow) {
79
+ if (this.invokeSteps.length) {
80
+ return this.invokeSteps;
81
+ }
82
+ const steps = Object.keys(flow.steps);
83
+ steps.sort((a, b) => flow.steps[a].depth - flow.steps[b].depth);
84
+ this.invokeSteps = steps;
85
+ return steps;
86
+ }
87
+ getCompensationSteps(flow) {
88
+ if (this.compensateSteps.length) {
89
+ return this.compensateSteps;
90
+ }
91
+ const steps = Object.keys(flow.steps);
92
+ steps.sort((a, b) => (flow.steps[b].depth || 0) - (flow.steps[a].depth || 0));
93
+ this.compensateSteps = steps;
94
+ return steps;
95
+ }
96
+ static countSiblings(flow, step) {
97
+ const previous = TransactionOrchestrator.getPreviousStep(flow, step);
98
+ return previous.next.length;
99
+ }
100
+ canMoveForward(flow, previousStep) {
101
+ const siblings = TransactionOrchestrator.getPreviousStep(flow, previousStep).next.map((sib) => flow.steps[sib]);
102
+ return (!!previousStep.definition.noWait ||
103
+ siblings.every((sib) => canMoveForwardStates.has(sib.invoke.state)));
104
+ }
105
+ canMoveBackward(flow, step) {
106
+ const siblings = step.next.map((sib) => flow.steps[sib]);
107
+ return (siblings.length === 0 ||
108
+ siblings.every((sib) => canMoveBackwardStates.has(sib.compensate.state)));
109
+ }
110
+ canContinue(flow, step) {
111
+ if (flow.state == types_1.TransactionState.COMPENSATING) {
112
+ return this.canMoveBackward(flow, step);
113
+ }
114
+ else {
115
+ const previous = TransactionOrchestrator.getPreviousStep(flow, step);
116
+ if (previous.id === TransactionOrchestrator.ROOT_STEP) {
117
+ return true;
118
+ }
119
+ return this.canMoveForward(flow, previous);
120
+ }
121
+ }
122
+ hasExpired({ transaction, step, }, dateNow) {
123
+ const hasStepTimedOut = step &&
124
+ step.hasTimeout() &&
125
+ !step.isCompensating() &&
126
+ dateNow > step.startedAt + step.getTimeout() * 1e3;
127
+ const hasTransactionTimedOut = transaction &&
128
+ transaction.hasTimeout() &&
129
+ transaction.getFlow().state !== types_1.TransactionState.COMPENSATING &&
130
+ dateNow >
131
+ transaction.getFlow().startedAt + transaction.getTimeout() * 1e3;
132
+ return !!hasStepTimedOut || !!hasTransactionTimedOut;
133
+ }
134
+ async checkTransactionTimeout(transaction, currentSteps) {
135
+ const flow = transaction.getFlow();
136
+ let hasTimedOut = false;
137
+ if (!flow.timedOutAt && this.hasExpired({ transaction }, Date.now())) {
138
+ flow.timedOutAt = Date.now();
139
+ void transaction.clearTransactionTimeout();
140
+ for (const step of currentSteps) {
141
+ await TransactionOrchestrator.setStepTimeout(transaction, step, new errors_1.TransactionTimeoutError());
142
+ }
143
+ this.emit(types_1.DistributedTransactionEvent.TIMEOUT, { transaction });
144
+ hasTimedOut = true;
145
+ }
146
+ return hasTimedOut;
147
+ }
148
+ async checkStepTimeout(transaction, step) {
149
+ let hasTimedOut = false;
150
+ if (!step.timedOutAt &&
151
+ step.canCancel() &&
152
+ this.hasExpired({ step }, Date.now())) {
153
+ step.timedOutAt = Date.now();
154
+ await TransactionOrchestrator.setStepTimeout(transaction, step, new errors_1.TransactionStepTimeoutError());
155
+ hasTimedOut = true;
156
+ this.emit(types_1.DistributedTransactionEvent.TIMEOUT, { transaction });
157
+ }
158
+ return hasTimedOut;
159
+ }
160
+ async checkAllSteps(transaction) {
161
+ const flow = transaction.getFlow();
162
+ const result = await this.computeCurrentTransactionState(transaction);
163
+ // Handle state transitions and emit events
164
+ if (flow.state === types_1.TransactionState.WAITING_TO_COMPENSATE &&
165
+ result.next.length === 0 &&
166
+ !flow.hasWaitingSteps) {
167
+ flow.state = types_1.TransactionState.COMPENSATING;
168
+ this.flagStepsToRevert(flow);
169
+ this.emit(types_1.DistributedTransactionEvent.COMPENSATE_BEGIN, { transaction });
170
+ const result = await this.checkAllSteps(transaction);
171
+ return result;
172
+ }
173
+ else if (result.completed === result.total) {
174
+ if (result.hasSkippedOnFailure) {
175
+ flow.hasSkippedOnFailureSteps = true;
176
+ }
177
+ if (result.hasSkipped) {
178
+ flow.hasSkippedSteps = true;
179
+ }
180
+ if (result.hasIgnoredFailure) {
181
+ flow.hasFailedSteps = true;
182
+ }
183
+ if (result.hasFailed) {
184
+ flow.state = types_1.TransactionState.FAILED;
185
+ }
186
+ else {
187
+ flow.state = result.hasReverted
188
+ ? types_1.TransactionState.REVERTED
189
+ : types_1.TransactionState.DONE;
190
+ }
191
+ }
192
+ return {
193
+ current: result.current,
194
+ next: result.next,
195
+ total: result.total,
196
+ remaining: result.total - result.completed,
197
+ completed: result.completed,
198
+ };
199
+ }
200
+ async computeCurrentTransactionState(transaction) {
201
+ let hasSkipped = false;
202
+ let hasSkippedOnFailure = false;
203
+ let hasIgnoredFailure = false;
204
+ let hasFailed = false;
205
+ let hasWaiting = false;
206
+ let hasReverted = false;
207
+ let completedSteps = 0;
208
+ const flow = transaction.getFlow();
209
+ const nextSteps = [];
210
+ const currentSteps = [];
211
+ const allSteps = flow.state === types_1.TransactionState.COMPENSATING
212
+ ? this.getCompensationSteps(flow)
213
+ : this.getInvokeSteps(flow);
214
+ for (const step of allSteps) {
215
+ if (step === TransactionOrchestrator.ROOT_STEP ||
216
+ !this.canContinue(flow, flow.steps[step])) {
217
+ continue;
218
+ }
219
+ const stepDef = flow.steps[step];
220
+ const curState = stepDef.getStates();
221
+ const hasTimedOut = await this.checkStepTimeout(transaction, stepDef);
222
+ if (hasTimedOut) {
223
+ continue;
224
+ }
225
+ if (curState.status === types_1.TransactionStepStatus.WAITING) {
226
+ currentSteps.push(stepDef);
227
+ hasWaiting = true;
228
+ if (stepDef.hasAwaitingRetry()) {
229
+ if (stepDef.canRetryAwaiting()) {
230
+ stepDef.retryRescheduledAt = null;
231
+ nextSteps.push(stepDef);
232
+ }
233
+ else if (!stepDef.retryRescheduledAt) {
234
+ stepDef.hasScheduledRetry = true;
235
+ stepDef.retryRescheduledAt = Date.now();
236
+ await transaction.scheduleRetry(stepDef, stepDef.definition.retryIntervalAwaiting);
237
+ }
238
+ }
239
+ else if (stepDef.retryRescheduledAt) {
240
+ // The step is not configured for awaiting retry but is manually force to retry
241
+ stepDef.retryRescheduledAt = null;
242
+ nextSteps.push(stepDef);
243
+ }
244
+ continue;
245
+ }
246
+ else if (curState.status === types_1.TransactionStepStatus.TEMPORARY_FAILURE) {
247
+ if (!stepDef.temporaryFailedAt &&
248
+ stepDef.definition.autoRetry === false) {
249
+ stepDef.temporaryFailedAt = Date.now();
250
+ continue;
251
+ }
252
+ stepDef.temporaryFailedAt = null;
253
+ currentSteps.push(stepDef);
254
+ if (!stepDef.canRetry()) {
255
+ if (stepDef.hasRetryInterval() && !stepDef.retryRescheduledAt) {
256
+ stepDef.hasScheduledRetry = true;
257
+ stepDef.retryRescheduledAt = Date.now();
258
+ await transaction.scheduleRetry(stepDef, stepDef.definition.retryInterval);
259
+ }
260
+ continue;
261
+ }
262
+ stepDef.retryRescheduledAt = null;
263
+ }
264
+ if (stepDef.canInvoke(flow.state) || stepDef.canCompensate(flow.state)) {
265
+ nextSteps.push(stepDef);
266
+ }
267
+ else {
268
+ completedSteps++;
269
+ if (curState.state === utils_1.TransactionStepState.SKIPPED_FAILURE) {
270
+ hasSkippedOnFailure = true;
271
+ }
272
+ else if (curState.state === utils_1.TransactionStepState.SKIPPED) {
273
+ hasSkipped = true;
274
+ }
275
+ else if (curState.state === utils_1.TransactionStepState.REVERTED) {
276
+ hasReverted = true;
277
+ }
278
+ else if (curState.state === utils_1.TransactionStepState.FAILED) {
279
+ if (stepDef.definition.continueOnPermanentFailure ||
280
+ stepDef.definition.skipOnPermanentFailure) {
281
+ hasIgnoredFailure = true;
282
+ }
283
+ else {
284
+ hasFailed = true;
285
+ }
286
+ }
287
+ }
288
+ }
289
+ flow.hasWaitingSteps = hasWaiting;
290
+ flow.hasRevertedSteps = hasReverted;
291
+ return {
292
+ current: currentSteps,
293
+ next: nextSteps,
294
+ total: allSteps.length - 1,
295
+ completed: completedSteps,
296
+ hasSkipped,
297
+ hasSkippedOnFailure,
298
+ hasIgnoredFailure,
299
+ hasFailed,
300
+ hasWaiting,
301
+ hasReverted,
302
+ };
303
+ }
304
+ flagStepsToRevert(flow) {
305
+ for (const step in flow.steps) {
306
+ if (step === TransactionOrchestrator.ROOT_STEP) {
307
+ continue;
308
+ }
309
+ const stepDef = flow.steps[step];
310
+ const curState = stepDef.getStates();
311
+ if (stepDef._v) {
312
+ flow._v = 0;
313
+ stepDef._v = 0;
314
+ }
315
+ if (flagStepsToRevertStates.has(curState.state) ||
316
+ curState.status === types_1.TransactionStepStatus.PERMANENT_FAILURE) {
317
+ stepDef.beginCompensation();
318
+ stepDef.changeState(utils_1.TransactionStepState.NOT_STARTED);
319
+ }
320
+ }
321
+ }
322
+ static async setStepSuccess(transaction, step, response) {
323
+ const hasStepTimedOut = step.getStates().state === utils_1.TransactionStepState.TIMEOUT;
324
+ if (step.saveResponse) {
325
+ transaction.addResponse(step.definition.action, step.isCompensating()
326
+ ? types_1.TransactionHandlerType.COMPENSATE
327
+ : types_1.TransactionHandlerType.INVOKE, response);
328
+ }
329
+ if (!hasStepTimedOut) {
330
+ step.changeStatus(types_1.TransactionStepStatus.OK);
331
+ }
332
+ if (step.isCompensating()) {
333
+ step.changeState(utils_1.TransactionStepState.REVERTED);
334
+ }
335
+ else if (!hasStepTimedOut) {
336
+ step.changeState(utils_1.TransactionStepState.DONE);
337
+ }
338
+ let shouldEmit = true;
339
+ let transactionIsCancelling = false;
340
+ try {
341
+ await transaction.saveCheckpoint({
342
+ _v: step._v,
343
+ parallelSteps: TransactionOrchestrator.countSiblings(transaction.getFlow(), step),
344
+ stepId: step.id,
345
+ });
346
+ }
347
+ catch (error) {
348
+ if (!TransactionOrchestrator.isExpectedError(error)) {
349
+ throw error;
350
+ }
351
+ transactionIsCancelling =
352
+ errors_1.SkipCancelledExecutionError.isSkipCancelledExecutionError(error);
353
+ shouldEmit = !errors_1.SkipExecutionError.isSkipExecutionError(error);
354
+ }
355
+ const cleaningUp = [];
356
+ if (step.hasRetryScheduled()) {
357
+ cleaningUp.push(transaction.clearRetry(step));
358
+ }
359
+ if (step.hasTimeout()) {
360
+ cleaningUp.push(transaction.clearStepTimeout(step));
361
+ }
362
+ if (cleaningUp.length) {
363
+ await (0, utils_1.promiseAll)(cleaningUp);
364
+ }
365
+ if (shouldEmit) {
366
+ const eventName = step.isCompensating()
367
+ ? types_1.DistributedTransactionEvent.COMPENSATE_STEP_SUCCESS
368
+ : types_1.DistributedTransactionEvent.STEP_SUCCESS;
369
+ transaction.emit(eventName, { step, transaction });
370
+ }
371
+ return {
372
+ stopExecution: !shouldEmit,
373
+ transactionIsCancelling,
374
+ };
375
+ }
376
+ static async retryStep(transaction, step) {
377
+ if (!step.retryRescheduledAt) {
378
+ step.hasScheduledRetry = true;
379
+ step.retryRescheduledAt = Date.now();
380
+ }
381
+ transaction.getFlow().hasWaitingSteps = true;
382
+ try {
383
+ await transaction.saveCheckpoint({
384
+ _v: step._v,
385
+ parallelSteps: TransactionOrchestrator.countSiblings(transaction.getFlow(), step),
386
+ stepId: step.id,
387
+ });
388
+ await transaction.scheduleRetry(step, 0);
389
+ }
390
+ catch (error) {
391
+ if (!TransactionOrchestrator.isExpectedError(error)) {
392
+ throw error;
393
+ }
394
+ }
395
+ }
396
+ static async skipStep({ transaction, step, }) {
397
+ const hasStepTimedOut = step.getStates().state === utils_1.TransactionStepState.TIMEOUT;
398
+ if (!hasStepTimedOut) {
399
+ step.changeStatus(types_1.TransactionStepStatus.OK);
400
+ step.changeState(utils_1.TransactionStepState.SKIPPED);
401
+ }
402
+ let shouldEmit = true;
403
+ let transactionIsCancelling = false;
404
+ try {
405
+ await transaction.saveCheckpoint({
406
+ _v: step._v,
407
+ parallelSteps: TransactionOrchestrator.countSiblings(transaction.getFlow(), step),
408
+ stepId: step.id,
409
+ });
410
+ }
411
+ catch (error) {
412
+ if (!TransactionOrchestrator.isExpectedError(error)) {
413
+ throw error;
414
+ }
415
+ transactionIsCancelling =
416
+ errors_1.SkipCancelledExecutionError.isSkipCancelledExecutionError(error);
417
+ if (errors_1.SkipExecutionError.isSkipExecutionError(error)) {
418
+ shouldEmit = false;
419
+ }
420
+ }
421
+ const cleaningUp = [];
422
+ if (step.hasRetryScheduled()) {
423
+ cleaningUp.push(transaction.clearRetry(step));
424
+ }
425
+ if (step.hasTimeout()) {
426
+ cleaningUp.push(transaction.clearStepTimeout(step));
427
+ }
428
+ if (cleaningUp.length) {
429
+ await (0, utils_1.promiseAll)(cleaningUp);
430
+ }
431
+ if (shouldEmit) {
432
+ const eventName = types_1.DistributedTransactionEvent.STEP_SKIPPED;
433
+ transaction.emit(eventName, { step, transaction });
434
+ }
435
+ return {
436
+ stopExecution: !shouldEmit,
437
+ transactionIsCancelling,
438
+ };
439
+ }
440
+ static async setStepTimeout(transaction, step, error) {
441
+ if (setStepTimeoutSkipStates.has(step.getStates().state)) {
442
+ return;
443
+ }
444
+ step.changeState(utils_1.TransactionStepState.TIMEOUT);
445
+ if (error?.stack) {
446
+ const workflowId = transaction.modelId;
447
+ const stepAction = step.definition.action;
448
+ const sourcePath = transaction.getFlow().metadata?.sourcePath;
449
+ const sourceStack = sourcePath
450
+ ? `\n⮑ \sat ${sourcePath}: [${workflowId} -> ${stepAction} (${types_1.TransactionHandlerType.INVOKE})]`
451
+ : `\n⮑ \sat [${workflowId} -> ${stepAction} (${types_1.TransactionHandlerType.INVOKE})]`;
452
+ error.stack += sourceStack;
453
+ }
454
+ transaction.addError(step.definition.action, types_1.TransactionHandlerType.INVOKE, error);
455
+ await TransactionOrchestrator.setStepFailure(transaction, step, undefined, 0, true, error);
456
+ await transaction.clearStepTimeout(step);
457
+ }
458
+ static async setStepFailure(transaction, step, error, maxRetries = TransactionOrchestrator.DEFAULT_RETRIES, isTimeout = false, timeoutError) {
459
+ const result = {
460
+ stopExecution: false,
461
+ transactionIsCancelling: false,
462
+ };
463
+ if (errors_1.SkipExecutionError.isSkipExecutionError(error)) {
464
+ return result;
465
+ }
466
+ step.failures++;
467
+ if ((0, utils_1.isErrorLike)(error)) {
468
+ error = (0, utils_1.serializeError)(error);
469
+ }
470
+ else {
471
+ try {
472
+ const serialized = JSON.stringify(error);
473
+ error = error?.message
474
+ ? JSON.parse(serialized)
475
+ : { message: serialized };
476
+ }
477
+ catch (e) {
478
+ error = {
479
+ message: "Unknown non-serializable error",
480
+ };
481
+ }
482
+ }
483
+ if (!isTimeout &&
484
+ step.getStates().status !== types_1.TransactionStepStatus.PERMANENT_FAILURE) {
485
+ step.changeStatus(types_1.TransactionStepStatus.TEMPORARY_FAILURE);
486
+ }
487
+ const flow = transaction.getFlow();
488
+ const cleaningUp = [];
489
+ const hasTimedOut = step.getStates().state === utils_1.TransactionStepState.TIMEOUT;
490
+ if (step.failures > maxRetries || hasTimedOut) {
491
+ if (!hasTimedOut) {
492
+ step.changeState(utils_1.TransactionStepState.FAILED);
493
+ }
494
+ step.changeStatus(types_1.TransactionStepStatus.PERMANENT_FAILURE);
495
+ if (!isTimeout) {
496
+ const handlerType = step.isCompensating()
497
+ ? types_1.TransactionHandlerType.COMPENSATE
498
+ : types_1.TransactionHandlerType.INVOKE;
499
+ error.stack ??= "";
500
+ const workflowId = transaction.modelId;
501
+ const stepAction = step.definition.action;
502
+ const sourcePath = transaction.getFlow().metadata?.sourcePath;
503
+ const sourceStack = sourcePath
504
+ ? `\n⮑ \sat ${sourcePath}: [${workflowId} -> ${stepAction} (${types_1.TransactionHandlerType.INVOKE})]`
505
+ : `\n⮑ \sat [${workflowId} -> ${stepAction} (${types_1.TransactionHandlerType.INVOKE})]`;
506
+ error.stack += sourceStack;
507
+ transaction.addError(step.definition.action, handlerType, error);
508
+ }
509
+ if (!step.isCompensating()) {
510
+ if ((step.definition.continueOnPermanentFailure ||
511
+ step.definition.skipOnPermanentFailure) &&
512
+ !errors_1.TransactionTimeoutError.isTransactionTimeoutError(timeoutError)) {
513
+ if (step.definition.skipOnPermanentFailure) {
514
+ const until = (0, utils_1.isString)(step.definition.skipOnPermanentFailure)
515
+ ? step.definition.skipOnPermanentFailure
516
+ : undefined;
517
+ let stepsToSkip = [...step.next];
518
+ while (stepsToSkip.length > 0) {
519
+ const currentStep = flow.steps[stepsToSkip.shift()];
520
+ if (until && currentStep.definition.action === until) {
521
+ break;
522
+ }
523
+ currentStep.changeState(utils_1.TransactionStepState.SKIPPED_FAILURE);
524
+ if (currentStep.next?.length > 0) {
525
+ stepsToSkip = stepsToSkip.concat(currentStep.next);
526
+ }
527
+ }
528
+ }
529
+ }
530
+ else {
531
+ flow.state = types_1.TransactionState.WAITING_TO_COMPENSATE;
532
+ }
533
+ }
534
+ if (step.hasTimeout()) {
535
+ cleaningUp.push(transaction.clearStepTimeout(step));
536
+ }
537
+ }
538
+ else {
539
+ const isAsync = step.isCompensating()
540
+ ? step.definition.compensateAsync
541
+ : step.definition.async;
542
+ if (step.getStates().status === types_1.TransactionStepStatus.TEMPORARY_FAILURE &&
543
+ step.definition.autoRetry === false &&
544
+ isAsync) {
545
+ step.temporaryFailedAt = Date.now();
546
+ result.stopExecution = true;
547
+ }
548
+ }
549
+ try {
550
+ await transaction.saveCheckpoint({
551
+ _v: step._v,
552
+ parallelSteps: TransactionOrchestrator.countSiblings(transaction.getFlow(), step),
553
+ stepId: step.id,
554
+ });
555
+ }
556
+ catch (error) {
557
+ if (!TransactionOrchestrator.isExpectedError(error)) {
558
+ throw error;
559
+ }
560
+ result.transactionIsCancelling =
561
+ errors_1.SkipCancelledExecutionError.isSkipCancelledExecutionError(error);
562
+ if (errors_1.SkipExecutionError.isSkipExecutionError(error)) {
563
+ result.stopExecution = true;
564
+ }
565
+ }
566
+ if (step.hasRetryScheduled()) {
567
+ cleaningUp.push(transaction.clearRetry(step));
568
+ }
569
+ if (cleaningUp.length) {
570
+ await (0, utils_1.promiseAll)(cleaningUp);
571
+ }
572
+ if (!result.stopExecution) {
573
+ const eventName = step.isCompensating()
574
+ ? types_1.DistributedTransactionEvent.COMPENSATE_STEP_FAILURE
575
+ : types_1.DistributedTransactionEvent.STEP_FAILURE;
576
+ transaction.emit(eventName, { step, transaction });
577
+ }
578
+ return {
579
+ stopExecution: result.stopExecution,
580
+ transactionIsCancelling: result.transactionIsCancelling,
581
+ };
582
+ }
583
+ async executeNext(transaction) {
584
+ let continueExecution = true;
585
+ while (continueExecution) {
586
+ if (transaction.hasFinished()) {
587
+ return;
588
+ }
589
+ const flow = transaction.getFlow();
590
+ let nextSteps = await this.checkAllSteps(transaction);
591
+ const hasTimedOut = await this.checkTransactionTimeout(transaction, nextSteps.current);
592
+ if (hasTimedOut) {
593
+ continue;
594
+ }
595
+ if (nextSteps.remaining === 0) {
596
+ await this.finalizeTransaction(transaction);
597
+ return;
598
+ }
599
+ const stepsShouldContinueExecution = nextSteps.next.map((step) => {
600
+ const { shouldContinueExecution } = this.prepareStepForExecution(step, flow);
601
+ return shouldContinueExecution;
602
+ });
603
+ let asyncStepCount = 0;
604
+ for (const s of nextSteps.next) {
605
+ const stepIsAsync = s.isCompensating()
606
+ ? s.definition.compensateAsync
607
+ : s.definition.async;
608
+ if (stepIsAsync)
609
+ asyncStepCount++;
610
+ }
611
+ const hasMultipleAsyncSteps = asyncStepCount > 1;
612
+ const hasAsyncSteps = !!asyncStepCount;
613
+ // If there is any async step, we don't need to save the checkpoint here as it will be saved
614
+ // later down there
615
+ await transaction.saveCheckpoint().catch((error) => {
616
+ if (TransactionOrchestrator.isExpectedError(error)) {
617
+ continueExecution = false;
618
+ return;
619
+ }
620
+ throw error;
621
+ });
622
+ if (!continueExecution) {
623
+ break;
624
+ }
625
+ const execution = [];
626
+ const executionAsync = [];
627
+ let i = 0;
628
+ for (const step of nextSteps.next) {
629
+ const stepIndex = i++;
630
+ if (!stepsShouldContinueExecution[stepIndex]) {
631
+ continue;
632
+ }
633
+ if (step.hasTimeout() && !step.timedOutAt && step.attempts === 1) {
634
+ await transaction.scheduleStepTimeout(step, step.definition.timeout);
635
+ }
636
+ transaction.emit(types_1.DistributedTransactionEvent.STEP_BEGIN, {
637
+ step,
638
+ transaction,
639
+ });
640
+ const isAsync = step.isCompensating()
641
+ ? step.definition.compensateAsync
642
+ : step.definition.async;
643
+ // Compute current transaction state
644
+ await this.computeCurrentTransactionState(transaction);
645
+ const promise = this.createStepExecutionPromise(transaction, step);
646
+ const hasVersionControl = hasMultipleAsyncSteps || step.hasAwaitingRetry();
647
+ if (hasVersionControl && !step._v) {
648
+ transaction.getFlow()._v += 1;
649
+ step._v = transaction.getFlow()._v;
650
+ }
651
+ if (!isAsync) {
652
+ execution.push(this.executeSyncStep(promise, transaction, step, nextSteps));
653
+ }
654
+ else {
655
+ // Execute async step in background as part of the next event loop cycle and continue the execution of the transaction
656
+ executionAsync.push(() => this.executeAsyncStep(promise, transaction, step, nextSteps));
657
+ }
658
+ }
659
+ await (0, utils_1.promiseAll)(execution);
660
+ if (!nextSteps.next.length || (hasAsyncSteps && !execution.length)) {
661
+ continueExecution = false;
662
+ }
663
+ if (hasAsyncSteps) {
664
+ await transaction.saveCheckpoint().catch((error) => {
665
+ if (TransactionOrchestrator.isExpectedError(error)) {
666
+ continueExecution = false;
667
+ }
668
+ throw error;
669
+ });
670
+ for (const exec of executionAsync) {
671
+ void exec();
672
+ }
673
+ }
674
+ }
675
+ }
676
+ /**
677
+ * Finalize the transaction when all steps are complete
678
+ */
679
+ async finalizeTransaction(transaction) {
680
+ if (transaction.hasTimeout()) {
681
+ void transaction.clearTransactionTimeout();
682
+ }
683
+ await transaction.saveCheckpoint().catch((error) => {
684
+ if (!TransactionOrchestrator.isExpectedError(error)) {
685
+ throw error;
686
+ }
687
+ });
688
+ this.emit(types_1.DistributedTransactionEvent.FINISH, { transaction });
689
+ }
690
+ /**
691
+ * Prepare a step for execution by setting state and incrementing attempts
692
+ */
693
+ prepareStepForExecution(step, flow) {
694
+ const curState = step.getStates();
695
+ step.lastAttempt = Date.now();
696
+ step.attempts++;
697
+ if (curState.state === utils_1.TransactionStepState.NOT_STARTED) {
698
+ if (!step.startedAt) {
699
+ step.startedAt = Date.now();
700
+ }
701
+ if (step.isCompensating()) {
702
+ step.changeState(utils_1.TransactionStepState.COMPENSATING);
703
+ if (step.definition.noCompensation) {
704
+ step.changeState(utils_1.TransactionStepState.REVERTED);
705
+ return { shouldContinueExecution: false };
706
+ }
707
+ }
708
+ else if (flow.state === types_1.TransactionState.INVOKING) {
709
+ step.changeState(utils_1.TransactionStepState.INVOKING);
710
+ }
711
+ }
712
+ step.changeStatus(types_1.TransactionStepStatus.WAITING);
713
+ return { shouldContinueExecution: true };
714
+ }
715
+ /**
716
+ * Create the payload for a step execution
717
+ */
718
+ createStepPayload(transaction, step, flow, type) {
719
+ return new distributed_transaction_1.TransactionPayload({
720
+ model_id: flow.modelId,
721
+ idempotency_key: TransactionOrchestrator.getKeyName(flow.modelId, flow.transactionId, step.definition.action, type),
722
+ action: step.definition.action + "",
723
+ action_type: type,
724
+ attempt: step.attempts,
725
+ timestamp: Date.now(),
726
+ }, transaction.payload, transaction.getContext());
727
+ }
728
+ /**
729
+ * Prepare handler arguments for step execution
730
+ */
731
+ prepareHandlerArgs(transaction, step, payload, type) {
732
+ return [
733
+ step.definition.action + "",
734
+ type,
735
+ payload,
736
+ transaction,
737
+ step,
738
+ this,
739
+ ];
740
+ }
741
+ /**
742
+ * Create the step execution promise with optional tracing
743
+ */
744
+ createStepExecutionPromise(transaction, step) {
745
+ const type = step.isCompensating()
746
+ ? types_1.TransactionHandlerType.COMPENSATE
747
+ : types_1.TransactionHandlerType.INVOKE;
748
+ const flow = transaction.getFlow();
749
+ const payload = this.createStepPayload(transaction, step, flow, type);
750
+ const handlerArgs = this.prepareHandlerArgs(transaction, step, payload, type);
751
+ const traceData = {
752
+ action: step.definition.action + "",
753
+ type,
754
+ step_id: step.id,
755
+ step_uuid: step.uuid + "",
756
+ attempts: step.attempts,
757
+ failures: step.failures,
758
+ async: !!(type === "invoke"
759
+ ? step.definition.async
760
+ : step.definition.compensateAsync),
761
+ idempotency_key: handlerArgs[2].metadata.idempotency_key,
762
+ };
763
+ const stepHandler = async () => {
764
+ return await transaction.handler(...handlerArgs);
765
+ };
766
+ // Return the appropriate promise based on tracing configuration
767
+ if (TransactionOrchestrator.traceStep) {
768
+ return () => TransactionOrchestrator.traceStep(stepHandler, traceData);
769
+ }
770
+ else {
771
+ return stepHandler;
772
+ }
773
+ }
774
+ /**
775
+ * Execute a synchronous step and handle its result
776
+ */
777
+ executeSyncStep(promiseFn, transaction, step, nextSteps) {
778
+ return promiseFn()
779
+ .then(async (response) => {
780
+ await this.handleStepExpiration(transaction, step, nextSteps);
781
+ const output = response?.__type || response?.output?.__type
782
+ ? response.output
783
+ : response;
784
+ if (errors_1.SkipStepResponse.isSkipStepResponse(output)) {
785
+ await TransactionOrchestrator.skipStep({
786
+ transaction,
787
+ step,
788
+ });
789
+ return;
790
+ }
791
+ await this.handleStepSuccess(transaction, step, response);
792
+ })
793
+ .catch(async (error) => {
794
+ if (TransactionOrchestrator.isExpectedError(error)) {
795
+ return;
796
+ }
797
+ const response = error?.getStepResponse?.();
798
+ await this.handleStepExpiration(transaction, step, nextSteps);
799
+ if (errors_1.PermanentStepFailureError.isPermanentStepFailureError(error)) {
800
+ await this.handleStepFailure(transaction, step, error, true, response);
801
+ return;
802
+ }
803
+ await this.handleStepFailure(transaction, step, error, false, response);
804
+ });
805
+ }
806
+ /**
807
+ * Execute an asynchronous step and handle its result
808
+ */
809
+ executeAsyncStep(promiseFn, transaction, step, nextSteps) {
810
+ return promiseFn()
811
+ .then(async (response) => {
812
+ const output = response?.__type || response?.output?.__type
813
+ ? response.output
814
+ : response;
815
+ if (errors_1.SkipStepResponse.isSkipStepResponse(output)) {
816
+ await TransactionOrchestrator.skipStep({
817
+ transaction,
818
+ step,
819
+ });
820
+ // Schedule to continue the execution of async steps because they are not awaited on purpose and can be handled by another machine
821
+ await transaction.scheduleRetry(step, 0);
822
+ return;
823
+ }
824
+ else {
825
+ if (!step.definition.backgroundExecution || step.definition.nested) {
826
+ const eventName = types_1.DistributedTransactionEvent.STEP_AWAITING;
827
+ transaction.emit(eventName, { step, transaction });
828
+ return;
829
+ }
830
+ await this.handleStepExpiration(transaction, step, nextSteps);
831
+ await this.handleStepSuccess(transaction, step, response);
832
+ }
833
+ })
834
+ .catch(async (error) => {
835
+ if (TransactionOrchestrator.isExpectedError(error)) {
836
+ return;
837
+ }
838
+ const response = error?.getStepResponse?.();
839
+ if (errors_1.PermanentStepFailureError.isPermanentStepFailureError(error)) {
840
+ await this.handleStepFailure(transaction, step, error, true, response);
841
+ return;
842
+ }
843
+ await this.handleStepFailure(transaction, step, error, false, response);
844
+ });
845
+ }
846
+ /**
847
+ * Check if step or transaction has expired and handle timeouts
848
+ */
849
+ async handleStepExpiration(transaction, step, nextSteps) {
850
+ if (this.hasExpired({ transaction, step }, Date.now())) {
851
+ await this.checkStepTimeout(transaction, step);
852
+ await this.checkTransactionTimeout(transaction, nextSteps.next.includes(step) ? nextSteps.next : [step]);
853
+ }
854
+ }
855
+ /**
856
+ * Handle successful step completion
857
+ */
858
+ async handleStepSuccess(transaction, step, response) {
859
+ const isAsync = step.isCompensating()
860
+ ? step.definition.compensateAsync
861
+ : step.definition.async;
862
+ if ((0, utils_1.isDefined)(response) && step.saveResponse && !isAsync) {
863
+ transaction.addResponse(step.definition.action, step.isCompensating()
864
+ ? types_1.TransactionHandlerType.COMPENSATE
865
+ : types_1.TransactionHandlerType.INVOKE, response);
866
+ }
867
+ const ret = await TransactionOrchestrator.setStepSuccess(transaction, step, response);
868
+ if (ret.transactionIsCancelling) {
869
+ await this.cancelTransaction(transaction, {
870
+ preventExecuteNext: true,
871
+ });
872
+ }
873
+ if (isAsync && !ret.stopExecution) {
874
+ // Schedule to continue the execution of async steps because they are not awaited on purpose and can be handled by another machine
875
+ await transaction.scheduleRetry(step, 0);
876
+ }
877
+ }
878
+ /**
879
+ * Handle step failure
880
+ */
881
+ async handleStepFailure(transaction, step, error, isPermanent, response) {
882
+ const isAsync = step.isCompensating()
883
+ ? step.definition.compensateAsync
884
+ : step.definition.async;
885
+ if ((0, utils_1.isDefined)(response) && step.saveResponse) {
886
+ transaction.addResponse(step.definition.action, step.isCompensating()
887
+ ? types_1.TransactionHandlerType.COMPENSATE
888
+ : types_1.TransactionHandlerType.INVOKE, response);
889
+ }
890
+ const ret = await TransactionOrchestrator.setStepFailure(transaction, step, error, isPermanent ? 0 : step.definition.maxRetries);
891
+ if (ret.transactionIsCancelling) {
892
+ await this.cancelTransaction(transaction, {
893
+ preventExecuteNext: true,
894
+ });
895
+ }
896
+ if (isAsync && !ret.stopExecution) {
897
+ // Schedule to continue the execution of async steps because they are not awaited on purpose and can be handled by another machine
898
+ await transaction.scheduleRetry(step, 0);
899
+ }
900
+ }
901
+ /**
902
+ * Start a new transaction or resume a transaction that has been previously started
903
+ * @param transaction - The transaction to resume
904
+ */
905
+ async resume(transaction) {
906
+ if (transaction.modelId !== this.id) {
907
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `TransactionModel "${transaction.modelId}" cannot be orchestrated by "${this.id}" model.`);
908
+ }
909
+ if (transaction.hasFinished()) {
910
+ return;
911
+ }
912
+ const executeNext = async () => {
913
+ const flow = transaction.getFlow();
914
+ if (flow.state === types_1.TransactionState.NOT_STARTED) {
915
+ flow.state = types_1.TransactionState.INVOKING;
916
+ flow.startedAt = Date.now();
917
+ await transaction.saveCheckpoint({
918
+ ttl: flow.hasAsyncSteps ? 0 : TransactionOrchestrator.DEFAULT_TTL,
919
+ });
920
+ if (transaction.hasTimeout()) {
921
+ await transaction.scheduleTransactionTimeout(transaction.getTimeout());
922
+ }
923
+ this.emit(types_1.DistributedTransactionEvent.BEGIN, { transaction });
924
+ }
925
+ else {
926
+ this.emit(types_1.DistributedTransactionEvent.RESUME, { transaction });
927
+ }
928
+ return await this.executeNext(transaction);
929
+ };
930
+ if (TransactionOrchestrator.traceTransaction &&
931
+ !transaction.getFlow().hasAsyncSteps) {
932
+ await TransactionOrchestrator.traceTransaction(executeNext, {
933
+ model_id: transaction.modelId,
934
+ transaction_id: transaction.transactionId,
935
+ flow_metadata: transaction.getFlow().metadata,
936
+ });
937
+ return;
938
+ }
939
+ await executeNext();
940
+ }
941
+ /**
942
+ * Cancel and revert a transaction compensating all its executed steps. It can be an ongoing transaction or a completed one
943
+ * @param transaction - The transaction to be reverted
944
+ */
945
+ async cancelTransaction(transaction, options) {
946
+ if (transaction.modelId !== this.id) {
947
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `TransactionModel "${transaction.modelId}" cannot be orchestrated by "${this.id}" model.`);
948
+ }
949
+ const flow = transaction.getFlow();
950
+ if (flow.state === types_1.TransactionState.FAILED) {
951
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot revert a permanent failed transaction.`);
952
+ }
953
+ if (flow.state === types_1.TransactionState.COMPENSATING ||
954
+ flow.state === types_1.TransactionState.WAITING_TO_COMPENSATE) {
955
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot revert a transaction that is already compensating.`);
956
+ }
957
+ flow.state = types_1.TransactionState.WAITING_TO_COMPENSATE;
958
+ flow.cancelledAt = Date.now();
959
+ await transaction.saveCheckpoint();
960
+ if (options?.preventExecuteNext) {
961
+ return;
962
+ }
963
+ await this.executeNext(transaction);
964
+ }
965
+ parseFlowOptions() {
966
+ const [steps, features] = TransactionOrchestrator.buildSteps(this.definition);
967
+ this.options ??= {};
968
+ const hasAsyncSteps = features.hasAsyncSteps;
969
+ const hasStepTimeouts = features.hasStepTimeouts;
970
+ const hasRetriesTimeout = features.hasRetriesTimeout;
971
+ const hasTransactionTimeout = !!this.options.timeout;
972
+ const isIdempotent = !!this.options.idempotent;
973
+ if (hasStepTimeouts ||
974
+ hasRetriesTimeout ||
975
+ hasTransactionTimeout ||
976
+ isIdempotent ||
977
+ this.options.retentionTime ||
978
+ hasAsyncSteps) {
979
+ this.options.store = true;
980
+ }
981
+ const parsedOptions = {
982
+ ...this.options,
983
+ hasAsyncSteps,
984
+ hasStepTimeouts,
985
+ hasRetriesTimeout,
986
+ };
987
+ TransactionOrchestrator.workflowOptions[this.id] = parsedOptions;
988
+ return [steps, features];
989
+ }
990
+ createTransactionFlow(transactionId, flowMetadata, context) {
991
+ const [steps, features] = TransactionOrchestrator.buildSteps(this.definition);
992
+ const flow = {
993
+ modelId: this.id,
994
+ options: this.options,
995
+ transactionId: transactionId,
996
+ runId: context?.runId ?? (0, ulid_1.ulid)(),
997
+ metadata: flowMetadata,
998
+ hasAsyncSteps: features.hasAsyncSteps,
999
+ hasFailedSteps: false,
1000
+ hasSkippedOnFailureSteps: false,
1001
+ hasSkippedSteps: false,
1002
+ hasWaitingSteps: false,
1003
+ hasRevertedSteps: false,
1004
+ timedOutAt: null,
1005
+ state: types_1.TransactionState.NOT_STARTED,
1006
+ definition: this.definition,
1007
+ steps,
1008
+ _v: 0, // Initialize version to 0
1009
+ };
1010
+ return flow;
1011
+ }
1012
+ static async loadTransactionById(modelId, transactionId, options) {
1013
+ const transaction = await distributed_transaction_1.DistributedTransaction.loadTransaction(modelId, transactionId, options);
1014
+ if (transaction !== null) {
1015
+ const flow = transaction.flow;
1016
+ const [steps] = TransactionOrchestrator.buildSteps(flow.definition, flow.steps);
1017
+ transaction.flow.steps = steps;
1018
+ return transaction;
1019
+ }
1020
+ return null;
1021
+ }
1022
+ static buildSteps(flow, existingSteps) {
1023
+ const states = {
1024
+ [TransactionOrchestrator.ROOT_STEP]: {
1025
+ id: TransactionOrchestrator.ROOT_STEP,
1026
+ next: [],
1027
+ },
1028
+ };
1029
+ const actionNames = new Set();
1030
+ const queue = [
1031
+ { obj: flow, level: [TransactionOrchestrator.ROOT_STEP] },
1032
+ ];
1033
+ const features = {
1034
+ hasAsyncSteps: false,
1035
+ hasStepTimeouts: false,
1036
+ hasRetriesTimeout: false,
1037
+ hasNestedTransactions: false,
1038
+ };
1039
+ while (queue.length > 0) {
1040
+ const { obj, level } = queue.shift();
1041
+ if (obj.action) {
1042
+ if (actionNames.has(obj.action)) {
1043
+ throw new Error(`Step ${obj.action} is already defined in workflow.`);
1044
+ }
1045
+ actionNames.add(obj.action);
1046
+ level.push(obj.action);
1047
+ const id = level.join(".");
1048
+ const parent = level.slice(0, level.length - 1).join(".");
1049
+ if (!existingSteps || parent === TransactionOrchestrator.ROOT_STEP) {
1050
+ states[parent].next?.push(id);
1051
+ }
1052
+ const definitionCopy = { ...obj };
1053
+ delete definitionCopy.next;
1054
+ const isAsync = !!definitionCopy.async;
1055
+ const hasRetryInterval = !!(definitionCopy.retryInterval || definitionCopy.retryIntervalAwaiting);
1056
+ const hasTimeout = !!definitionCopy.timeout;
1057
+ if (definitionCopy.async) {
1058
+ features.hasAsyncSteps = true;
1059
+ }
1060
+ if (definitionCopy.timeout) {
1061
+ features.hasStepTimeouts = true;
1062
+ }
1063
+ if (definitionCopy.retryInterval ||
1064
+ definitionCopy.retryIntervalAwaiting) {
1065
+ features.hasRetriesTimeout = true;
1066
+ }
1067
+ if (definitionCopy.nested) {
1068
+ features.hasNestedTransactions = true;
1069
+ }
1070
+ /**
1071
+ * Force the checkpoint to save even for sync step when they have specific configurations.
1072
+ */
1073
+ definitionCopy.store = !!(definitionCopy.store ||
1074
+ isAsync ||
1075
+ hasRetryInterval ||
1076
+ hasTimeout);
1077
+ if (existingSteps?.[id]) {
1078
+ existingSteps[id].definition.store = definitionCopy.store;
1079
+ }
1080
+ states[id] = Object.assign(new transaction_step_1.TransactionStep(), existingSteps?.[id] || {
1081
+ id,
1082
+ uuid: definitionCopy.uuid,
1083
+ depth: level.length - 1,
1084
+ definition: definitionCopy,
1085
+ saveResponse: definitionCopy.saveResponse ?? true,
1086
+ invoke: {
1087
+ state: utils_1.TransactionStepState.NOT_STARTED,
1088
+ status: types_1.TransactionStepStatus.IDLE,
1089
+ },
1090
+ compensate: {
1091
+ state: utils_1.TransactionStepState.DORMANT,
1092
+ status: types_1.TransactionStepStatus.IDLE,
1093
+ },
1094
+ attempts: 0,
1095
+ failures: 0,
1096
+ lastAttempt: null,
1097
+ next: [],
1098
+ _v: 0, // Initialize step version to 0
1099
+ });
1100
+ }
1101
+ if (Array.isArray(obj.next)) {
1102
+ for (const next of obj.next) {
1103
+ queue.push({ obj: next, level: [...level] });
1104
+ }
1105
+ }
1106
+ else if ((0, utils_1.isObject)(obj.next)) {
1107
+ queue.push({ obj: obj.next, level: [...level] });
1108
+ }
1109
+ }
1110
+ return [states, features];
1111
+ }
1112
+ /** Create a new transaction
1113
+ * @param transactionId - unique identifier of the transaction
1114
+ * @param handler - function to handle action of the transaction
1115
+ * @param payload - payload to be passed to all the transaction steps
1116
+ * @param flowMetadata - flow metadata which can include event group id for example
1117
+ */
1118
+ async beginTransaction({ transactionId, handler, payload, flowMetadata, context, onLoad, }) {
1119
+ const existingTransaction = await TransactionOrchestrator.loadTransactionById(this.id, transactionId);
1120
+ let newTransaction = false;
1121
+ let modelFlow;
1122
+ if (!existingTransaction) {
1123
+ modelFlow = this.createTransactionFlow(transactionId, flowMetadata, context);
1124
+ newTransaction = true;
1125
+ }
1126
+ else {
1127
+ modelFlow = existingTransaction.flow;
1128
+ }
1129
+ const transaction = new distributed_transaction_1.DistributedTransaction(modelFlow, handler, payload, existingTransaction?.errors, existingTransaction?.context);
1130
+ if (newTransaction && this.getOptions().store) {
1131
+ await transaction.saveCheckpoint({
1132
+ ttl: modelFlow.hasAsyncSteps ? 0 : TransactionOrchestrator.DEFAULT_TTL,
1133
+ });
1134
+ }
1135
+ if (onLoad) {
1136
+ await onLoad(transaction);
1137
+ }
1138
+ return transaction;
1139
+ }
1140
+ /** Returns an existing transaction
1141
+ * @param transactionId - unique identifier of the transaction
1142
+ * @param handler - function to handle action of the transaction
1143
+ */
1144
+ async retrieveExistingTransaction(transactionId, handler, options) {
1145
+ const existingTransaction = await TransactionOrchestrator.loadTransactionById(this.id, transactionId, { isCancelling: options?.isCancelling });
1146
+ if (!existingTransaction) {
1147
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_FOUND, `Transaction ${transactionId} could not be found.`);
1148
+ }
1149
+ const transaction = new distributed_transaction_1.DistributedTransaction(existingTransaction.flow, handler, undefined, existingTransaction?.errors, existingTransaction?.context);
1150
+ return transaction;
1151
+ }
1152
+ static getStepByAction(flow, action) {
1153
+ for (const key in flow.steps) {
1154
+ if (action === flow.steps[key]?.definition?.action) {
1155
+ return flow.steps[key];
1156
+ }
1157
+ }
1158
+ return null;
1159
+ }
1160
+ static async getTransactionAndStepFromIdempotencyKey(responseIdempotencyKey, handler, transaction) {
1161
+ const [modelId, transactionId, action, actionType] = responseIdempotencyKey.split(TransactionOrchestrator.SEPARATOR);
1162
+ if (!transaction && !handler) {
1163
+ throw new Error("If a transaction is not provided, the handler is required");
1164
+ }
1165
+ if (!transaction) {
1166
+ const existingTransaction = await TransactionOrchestrator.loadTransactionById(modelId, transactionId);
1167
+ if (existingTransaction === null) {
1168
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_FOUND, `Transaction ${transactionId} could not be found.`);
1169
+ }
1170
+ transaction = new distributed_transaction_1.DistributedTransaction(existingTransaction.flow, handler, undefined, existingTransaction.errors, existingTransaction.context);
1171
+ }
1172
+ const step = TransactionOrchestrator.getStepByAction(transaction.getFlow(), action);
1173
+ if (step === null) {
1174
+ throw new Error("Action not found.");
1175
+ }
1176
+ else if (step.isCompensating()
1177
+ ? actionType !== types_1.TransactionHandlerType.COMPENSATE
1178
+ : actionType !== types_1.TransactionHandlerType.INVOKE) {
1179
+ throw new Error("Incorrect action type.");
1180
+ }
1181
+ return [transaction, step];
1182
+ }
1183
+ /** Skip the execution of a specific transaction and step
1184
+ * @param responseIdempotencyKey - The idempotency key for the step
1185
+ * @param handler - The handler function to execute the step
1186
+ * @param transaction - The current transaction. If not provided it will be loaded based on the responseIdempotencyKey
1187
+ */
1188
+ async skipStep({ responseIdempotencyKey, handler, transaction, }) {
1189
+ const [curTransaction, step] = await TransactionOrchestrator.getTransactionAndStepFromIdempotencyKey(responseIdempotencyKey, handler, transaction);
1190
+ if (step.getStates().status === types_1.TransactionStepStatus.WAITING) {
1191
+ this.emit(types_1.DistributedTransactionEvent.RESUME, {
1192
+ transaction: curTransaction,
1193
+ });
1194
+ await TransactionOrchestrator.skipStep({
1195
+ transaction: curTransaction,
1196
+ step,
1197
+ });
1198
+ await this.executeNext(curTransaction);
1199
+ }
1200
+ else {
1201
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot skip a step when status is ${step.getStates().status}`);
1202
+ }
1203
+ return curTransaction;
1204
+ }
1205
+ /**
1206
+ * Manually force a step to retry even if it is still in awaiting status
1207
+ * @param responseIdempotencyKey - The idempotency key for the step
1208
+ * @param handler - The handler function to execute the step
1209
+ * @param transaction - The current transaction. If not provided it will be loaded based on the responseIdempotencyKey
1210
+ */
1211
+ async retryStep({ responseIdempotencyKey, handler, transaction, onLoad, }) {
1212
+ const [curTransaction, step] = await TransactionOrchestrator.getTransactionAndStepFromIdempotencyKey(responseIdempotencyKey, handler, transaction);
1213
+ if (onLoad) {
1214
+ await onLoad(curTransaction);
1215
+ }
1216
+ if (step.getStates().status === types_1.TransactionStepStatus.WAITING) {
1217
+ this.emit(types_1.DistributedTransactionEvent.RESUME, {
1218
+ transaction: curTransaction,
1219
+ });
1220
+ await TransactionOrchestrator.retryStep(curTransaction, step);
1221
+ }
1222
+ else {
1223
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot retry step when status is ${step.getStates().status}`);
1224
+ }
1225
+ return curTransaction;
1226
+ }
1227
+ /** Register a step success for a specific transaction and step
1228
+ * @param responseIdempotencyKey - The idempotency key for the step
1229
+ * @param handler - The handler function to execute the step
1230
+ * @param transaction - The current transaction. If not provided it will be loaded based on the responseIdempotencyKey
1231
+ * @param response - The response of the step
1232
+ */
1233
+ async registerStepSuccess({ responseIdempotencyKey, handler, transaction, response, onLoad, }) {
1234
+ const [curTransaction, step] = await TransactionOrchestrator.getTransactionAndStepFromIdempotencyKey(responseIdempotencyKey, handler, transaction);
1235
+ if (onLoad) {
1236
+ await onLoad(curTransaction);
1237
+ }
1238
+ if (step.getStates().status === types_1.TransactionStepStatus.WAITING) {
1239
+ this.emit(types_1.DistributedTransactionEvent.RESUME, {
1240
+ transaction: curTransaction,
1241
+ });
1242
+ const ret = await TransactionOrchestrator.setStepSuccess(curTransaction, step, response);
1243
+ if (ret.transactionIsCancelling) {
1244
+ await this.cancelTransaction(curTransaction);
1245
+ return curTransaction;
1246
+ }
1247
+ await this.executeNext(curTransaction);
1248
+ }
1249
+ else {
1250
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot set step success when status is ${step.getStates().status}`);
1251
+ }
1252
+ return curTransaction;
1253
+ }
1254
+ /**
1255
+ * Register a step failure for a specific transaction and step
1256
+ * @param responseIdempotencyKey - The idempotency key for the step
1257
+ * @param error - The error that caused the failure
1258
+ * @param handler - The handler function to execute the step
1259
+ * @param transaction - The current transaction
1260
+ * @param response - The response of the step
1261
+ */
1262
+ async registerStepFailure({ responseIdempotencyKey, error, handler, transaction, onLoad, forcePermanentFailure, }) {
1263
+ const [curTransaction, step] = await TransactionOrchestrator.getTransactionAndStepFromIdempotencyKey(responseIdempotencyKey, handler, transaction);
1264
+ if (onLoad) {
1265
+ await onLoad(curTransaction);
1266
+ }
1267
+ if (step.getStates().status === types_1.TransactionStepStatus.WAITING) {
1268
+ this.emit(types_1.DistributedTransactionEvent.RESUME, {
1269
+ transaction: curTransaction,
1270
+ });
1271
+ const ret = await TransactionOrchestrator.setStepFailure(curTransaction, step, error,
1272
+ // On permanent failure, the step should not consider any retries
1273
+ forcePermanentFailure ? 0 : step.definition.maxRetries);
1274
+ if (ret.transactionIsCancelling) {
1275
+ await this.cancelTransaction(curTransaction);
1276
+ return curTransaction;
1277
+ }
1278
+ await this.executeNext(curTransaction);
1279
+ }
1280
+ else {
1281
+ throw new utils_1.AcmeKitError(utils_1.AcmeKitError.Types.NOT_ALLOWED, `Cannot set step failure when status is ${step.getStates().status}`);
1282
+ }
1283
+ return curTransaction;
1284
+ }
1285
+ }
1286
+ exports.TransactionOrchestrator = TransactionOrchestrator;
1287
+ TransactionOrchestrator.ROOT_STEP = "_root";
1288
+ TransactionOrchestrator.DEFAULT_TTL = 30;
1289
+ TransactionOrchestrator.DEFAULT_RETRIES = 0;
1290
+ TransactionOrchestrator.workflowOptions = {};
1291
+ TransactionOrchestrator.SEPARATOR = ":";
1292
+ //# sourceMappingURL=transaction-orchestrator.js.map