1 import { isDefined, TransactionStepState } from "@medusajs/utils"
2 import { EventEmitter } from "events"
3 import { setTimeout as setTimeoutPromise } from "node:timers/promises"
4 import { IDistributedTransactionStorage } from "./datastore/abstract-storage"
5 import { BaseInMemoryDistributedTransactionStorage } from "./datastore/base-in-memory-storage"
6 import { NonSerializableCheckPointError, SkipExecutionError } from "./errors"
7 import { TransactionOrchestrator } from "./transaction-orchestrator"
8 import { TransactionStep, TransactionStepHandler } from "./transaction-step"
9 import {
10 TransactionFlow,
11 TransactionHandlerType,
12 TransactionState,
13 TransactionStepStatus,
14 } from "./types"
15
16 const flowMergeableProperties = [
17 "state",
18 "hasFailedSteps",
19 "hasSkippedOnFailureSteps",
20 "hasSkippedSteps",
21 "hasRevertedSteps",
22 "cancelledAt",
23 "startedAt",
24 "hasAsyncSteps",
25 "_v",
26 "timedOutAt",
27 ]
28
29 const mergeStep = (
30 currentStep: TransactionStep,
31 storedStep: TransactionStep
32 ) => {
33 const mergeProperties = [
34 "attempts",
35 "failures",
36 "temporaryFailedAt",
37 "retryRescheduledAt",
38 "hasScheduledRetry",
39 "lastAttempt",
40 "_v",
41 "stepFailed",
42 "startedAt",
43 ]
44
45 for (const prop of mergeProperties) {
46 if (prop === "hasScheduledRetry" || prop === "stepFailed") {
47 currentStep[prop] = storedStep[prop] ?? currentStep[prop]
48 continue
49 }
50
51 currentStep[prop] =
52 storedStep[prop] || currentStep[prop]
53 ? Math.max(storedStep[prop] ?? 0, currentStep[prop] ?? 0)
54 : currentStep[prop] ?? storedStep[prop]
55 }
56 }
57
58 const getErrorSignature = (err: TransactionStepError) =>
59 `${err.action}:${err.handlerType}:${err.error?.message}`
60
61 /**
62 * @typedef TransactionMetadata
63 * @property model_id - The id of the model_id that created the transaction (modelId).
64 * @property idempotency_key - The idempotency key of the transaction.
65 * @property action - The action of the transaction.
66 * @property action_type - The type of the transaction.
67 * @property attempt - The number of attempts for the transaction.
68 * @property timestamp - The timestamp of the transaction.
69 */
70 export type TransactionMetadata = {
71 model_id: string
72 idempotency_key: string
73 action: string
74 action_type: TransactionHandlerType
75 attempt: number
76 timestamp: number
77 }
78
79 /**
80 * @typedef TransactionContext
81 * @property payload - Object containing the initial payload.
82 * @property invoke - Object containing responses of Invoke handlers on steps flagged with saveResponse.
83 * @property compensate - Object containing responses of Compensate handlers on steps flagged with saveResponse.
84 */
85 export class TransactionContext {
86 constructor(
87 public payload: unknown = undefined,
88 public invoke: Record<string, unknown> = {},
89 public compensate: Record<string, unknown> = {}
90 ) {}
91 }
92
93 export class TransactionStepError {
94 constructor(
95 public action: string,
96 public handlerType: TransactionHandlerType,
97 public error: Error | any
98 ) {}
99 }
100
101 const stateFlowOrder = [
102 TransactionState.NOT_STARTED,
103 TransactionState.INVOKING,
104 TransactionState.DONE,
105 TransactionState.WAITING_TO_COMPENSATE,
106 TransactionState.COMPENSATING,
107 TransactionState.REVERTED,
108 TransactionState.FAILED,
109 ]
110
111 const stateFlowOrderMap = new Map<TransactionState, number>(
112 stateFlowOrder.map((state, index) => [state, index])
113 )
114
115 const finishedStatesSet = new Set([
116 TransactionState.DONE,
117 TransactionState.REVERTED,
118 TransactionState.FAILED,
119 ])
120
121 export class TransactionCheckpoint {
122 static readonly #ALLOWED_STATE_TRANSITIONS = {
123 [TransactionStepState.DORMANT]: [TransactionStepState.NOT_STARTED],
124 [TransactionStepState.NOT_STARTED]: [
125 TransactionStepState.INVOKING,
126 TransactionStepState.COMPENSATING,
127 TransactionStepState.FAILED,
128 TransactionStepState.SKIPPED,
129 TransactionStepState.SKIPPED_FAILURE,
130 ],
131 [TransactionStepState.INVOKING]: [
132 TransactionStepState.FAILED,
133 TransactionStepState.DONE,
134 TransactionStepState.TIMEOUT,
135 TransactionStepState.SKIPPED,
136 ],
137 [TransactionStepState.COMPENSATING]: [
138 TransactionStepState.REVERTED,
139 TransactionStepState.FAILED,
140 ],
141 [TransactionStepState.DONE]: [TransactionStepState.COMPENSATING],
142 } as const
143
144 static readonly #ALLOWED_STATUS_TRANSITIONS = {
145 [TransactionStepStatus.WAITING]: [
146 TransactionStepStatus.OK,
147 TransactionStepStatus.TEMPORARY_FAILURE,
148 TransactionStepStatus.PERMANENT_FAILURE,
149 ],
150 [TransactionStepStatus.TEMPORARY_FAILURE]: [
151 TransactionStepStatus.IDLE,
152 TransactionStepStatus.PERMANENT_FAILURE,
153 ],
154 [TransactionStepStatus.PERMANENT_FAILURE]: [TransactionStepStatus.IDLE],
155 } as const
156
157 constructor(
158 public flow: TransactionFlow,
159 public context: TransactionContext,
160 public errors: TransactionStepError[] = []
161 ) {}
162
163 /**
164 * Merge the current checkpoint with incoming data from a concurrent save operation.
165 * This handles race conditions when multiple steps complete simultaneously.
166 *
167 * @param storedData - The checkpoint data being saved
168 * @param savingStepId - Optional step ID if this is a step-specific save
169 */
170 static mergeCheckpoints(
171 currentTransactionData: TransactionCheckpoint,
172 storedData?: TransactionCheckpoint
173 ): TransactionCheckpoint {
174 if (!currentTransactionData || !storedData) {
175 return currentTransactionData
176 }
177
178 TransactionCheckpoint.#mergeFlow(currentTransactionData, storedData)
179 TransactionCheckpoint.#mergeErrors(
180 currentTransactionData.errors ?? [],
181 storedData.errors
182 )
183
184 return currentTransactionData
185 }
186
187 static #mergeFlow(
188 currentTransactionData: TransactionCheckpoint,
189 storedData: TransactionCheckpoint
190 ): void {
191 const currentTransactionContext = currentTransactionData.context
192 const storedContext = storedData.context
193
194 if (currentTransactionData.flow._v >= storedData.flow._v) {
195 for (const prop of flowMergeableProperties) {
196 if (
197 prop === "startedAt" ||
198 prop === "cancelledAt" ||
199 prop === "timedOutAt"
200 ) {
201 currentTransactionData.flow[prop] =
202 storedData.flow[prop] || currentTransactionData.flow[prop]
203 ? Math.max(
204 storedData.flow[prop] ?? 0,
205 currentTransactionData.flow[prop] ?? 0
206 )
207 : currentTransactionData.flow[prop] ??
208 storedData.flow[prop] ??
209 (undefined as any)
210 } else if (prop === "_v") {
211 currentTransactionData.flow[prop] = Math.max(
212 storedData.flow[prop] ?? 0,
213 currentTransactionData.flow[prop] ?? 0
214 )
215 } else if (prop === "state") {
216 const currentStateIndex =
217 stateFlowOrderMap.get(currentTransactionData.flow.state) ?? -1
218 const storedStateIndex =
219 stateFlowOrderMap.get(storedData.flow.state) ?? -1
220
221 if (storedStateIndex > currentStateIndex) {
222 currentTransactionData.flow.state = storedData.flow.state
223 } else if (
224 currentStateIndex < storedStateIndex &&
225 currentTransactionData.flow.state !==
226 TransactionState.WAITING_TO_COMPENSATE
227 ) {
228 throw new SkipExecutionError(
229 `Transaction is behind another execution`
230 )
231 }
232 } else if (
233 storedData.flow[prop] &&
234 !currentTransactionData.flow[prop]
235 ) {
236 currentTransactionData.flow[prop] = storedData.flow[prop]
237 }
238 }
239 }
240
241 const storedSteps = Object.values(storedData.flow.steps)
242
243 for (const storedStep of storedSteps) {
244 if (storedStep.id === "_root") {
245 continue
246 }
247
248 const stepName = storedStep.definition.action!
249 const stepId = storedStep.id
250
251 // Merge context responses
252 if (
253 storedContext.invoke[stepName] &&
254 !currentTransactionContext.invoke[stepName]
255 ) {
256 currentTransactionContext.invoke[stepName] =
257 storedContext.invoke[stepName]
258 }
259
260 if (
261 storedContext.compensate[stepName] &&
262 !currentTransactionContext.compensate[stepName]
263 ) {
264 currentTransactionContext.compensate[stepName] =
265 storedContext.compensate[stepName]
266 }
267
268 const currentStepVersion = currentTransactionData.flow.steps[stepId]._v!
269 const storedStepVersion = storedData.flow.steps[stepId]._v!
270
271 if (storedStepVersion > currentStepVersion) {
272 throw new SkipExecutionError(`Transaction is behind another execution`)
273 }
274
275 // Determine which state is further along in the process
276 const shouldUpdateInvoke = TransactionCheckpoint.#shouldUpdateStepState(
277 currentTransactionData.flow.steps[stepId].invoke,
278 storedStep.invoke
279 )
280
281 const shouldUpdateCompensate =
282 TransactionCheckpoint.#shouldUpdateStepState(
283 currentTransactionData.flow.steps[stepId].compensate,
284 storedStep.compensate
285 )
286
287 if (shouldUpdateInvoke) {
288 currentTransactionData.flow.steps[stepId].invoke = storedStep.invoke
289 }
290
291 if (shouldUpdateCompensate) {
292 currentTransactionData.flow.steps[stepId].compensate =
293 storedStep.compensate
294 }
295
296 mergeStep(currentTransactionData.flow.steps[stepId], storedStep)
297 }
298 }
299
300 /**
301 * Determines if the stored step state should replace the current step state.
302 * This validates both state and status transitions according to TransactionStep rules.
303 */
304 static #shouldUpdateStepState(
305 currentStepState: {
306 state: TransactionStepState
307 status: TransactionStepStatus
308 },
309 storedStepState: {
310 state: TransactionStepState
311 status: TransactionStepStatus
312 }
313 ): boolean {
314 if (
315 currentStepState.state === storedStepState.state &&
316 currentStepState.status === storedStepState.status
317 ) {
318 return false
319 }
320
321 // Check if state transition from stored to current is allowed
322 const allowedStatesFromCurrent =
323 TransactionCheckpoint.#ALLOWED_STATE_TRANSITIONS[
324 currentStepState.state
325 ] || []
326 const isStateTransitionValid = allowedStatesFromCurrent.includes(
327 storedStepState.state
328 )
329
330 if (currentStepState.state !== storedStepState.state) {
331 return isStateTransitionValid
332 }
333
334 // States are the same, check status transition
335 // Special case: WAITING status can always be transitioned
336 if (currentStepState.status === TransactionStepStatus.WAITING) {
337 return true
338 }
339
340 // Check if status transition from stored to current is allowed
341 const allowedStatusesFromCurrent =
342 TransactionCheckpoint.#ALLOWED_STATUS_TRANSITIONS[
343 currentStepState.status
344 ] || []
345
346 return allowedStatusesFromCurrent.includes(storedStepState.status)
347 }
348
349 static #mergeErrors(
350 currentErrors: TransactionStepError[],
351 incomingErrors: TransactionStepError[]
352 ): void {
353 const existingErrorSignatures = new Set(
354 currentErrors.map(getErrorSignature)
355 )
356
357 for (const error of incomingErrors) {
358 if (!existingErrorSignatures.has(getErrorSignature(error))) {
359 currentErrors.push(error)
360 existingErrorSignatures.add(getErrorSignature(error))
361 }
362 }
363 }
364 }
365
366 export class TransactionPayload {
367 /**
368 * @param metadata - The metadata of the transaction.
369 * @param data - The initial payload data to begin a transation.
370 * @param context - Object gathering responses of all steps flagged with saveResponse.
371 */
372 constructor(
373 public metadata: TransactionMetadata,
374 public data: Record<string, unknown>,
375 public context: TransactionContext
376 ) {}
377 }
378
379 /**
380 * DistributedTransaction represents a distributed transaction, which is a transaction that is composed of multiple steps that are executed in a specific order.
381 */
382
383 class DistributedTransaction extends EventEmitter {
384 public modelId: string
385 public transactionId: string
386 public runId: string
387
388 private errors: TransactionStepError[] = []
389 private context: TransactionContext = new TransactionContext()
390 private static keyValueStore: IDistributedTransactionStorage
391
392 /**
393 * Store data during the life cycle of the current transaction execution.
394 * Store non persistent data such as transformers results, temporary data, etc.
395 *
396 * @private
397 */
398 #temporaryStorage = new Map<string, unknown>()
399
400 public static setStorage(storage: IDistributedTransactionStorage) {
401 this.keyValueStore = storage
402 }
403
404 public static keyPrefix = "dtrx"
405
406 constructor(
407 private flow: TransactionFlow,
408 public handler: TransactionStepHandler,
409 public payload?: any,
410 errors?: TransactionStepError[],
411 context?: TransactionContext
412 ) {
413 super()
414
415 this.transactionId = flow.transactionId
416 this.modelId = flow.modelId
417 this.runId = flow.runId
418 if (errors) {
419 this.errors = errors
420 }
421
422 this.context.payload = payload
423 if (context) {
424 this.context = { ...context }
425 }
426 }
427
428 public getFlow() {
429 return this.flow
430 }
431
432 public getContext() {
433 return this.context
434 }
435
436 public getErrors(handlerType?: TransactionHandlerType) {
437 if (!isDefined(handlerType)) {
438 return this.errors
439 }
440
441 return this.errors.filter((error) => error.handlerType === handlerType)
442 }
443
444 public addError(
445 action: string,
446 handlerType: TransactionHandlerType,
447 error: Error | any
448 ) {
449 this.errors.push({
450 action,
451 handlerType,
452 error,
453 })
454 }
455
456 public addResponse(
457 action: string,
458 handlerType: TransactionHandlerType,
459 response: unknown
460 ) {
461 this.context[handlerType][action] = response
462 }
463
464 public hasFinished(): boolean {
465 return finishedStatesSet.has(this.getState())
466 }
467
468 public getState(): TransactionState {
469 return this.getFlow().state
470 }
471
472 public get isPartiallyCompleted(): boolean {
473 return !!this.getFlow().hasFailedSteps || !!this.getFlow().hasSkippedSteps
474 }
475
476 public canInvoke(): boolean {
477 return (
478 this.getFlow().state === TransactionState.NOT_STARTED ||
479 this.getFlow().state === TransactionState.INVOKING
480 )
481 }
482
483 public canRevert(): boolean {
484 return (
485 this.getFlow().state === TransactionState.DONE ||
486 this.getFlow().state === TransactionState.COMPENSATING
487 )
488 }
489
490 public hasTimeout(): boolean {
491 return !!this.getTimeout()
492 }
493
494 public getTimeout(): number | undefined {
495 return this.getFlow().options?.timeout
496 }
497
498 public async saveCheckpoint({
499 ttl = 0,
500 parallelSteps = 0,
501 stepId,
502 _v,
503 }: {
504 ttl?: number
505 parallelSteps?: number
506 stepId?: string
507 _v?: number
508 } = {}): Promise<TransactionCheckpoint | undefined> {
509 const options = {
510 ...(TransactionOrchestrator.getWorkflowOptions(this.modelId) ??
511 this.getFlow().options),
512 }
513
514 if (!options?.store) {
515 return
516 }
517
518 options.stepId = stepId
519 if (_v) {
520 options.parallelSteps = parallelSteps
521 options._v = _v
522 }
523
524 const key = TransactionOrchestrator.getKeyName(
525 DistributedTransaction.keyPrefix,
526 this.modelId,
527 this.transactionId
528 )
529
530 let checkpoint: TransactionCheckpoint
531
532 let retries = 0
533 let backoffMs = 50
534 const maxRetries = (options?.parallelSteps || 1) + 2
535 while (retries < maxRetries) {
536 checkpoint = this.#serializeCheckpointData()
537
538 try {
539 const savedCheckpoint = await DistributedTransaction.keyValueStore.save(
540 key,
541 checkpoint,
542 ttl,
543 options
544 )
545
546 return savedCheckpoint
547 } catch (error) {
548 if (TransactionOrchestrator.isExpectedError(error)) {
549 throw error
550 } else if (checkpoint.flow.state === TransactionState.NOT_STARTED) {
551 throw new SkipExecutionError(
552 "Transaction already started for transactionId: " +
553 this.transactionId
554 )
555 }
556
557 retries++
558 // Exponential backoff with jitter
559 const jitter = Math.random() * backoffMs
560
561 await setTimeoutPromise(backoffMs + jitter)
562
563 backoffMs = Math.min(backoffMs * 2, 500)
564
565 const lastCheckpoint = await DistributedTransaction.loadTransaction(
566 this.modelId,
567 this.transactionId
568 )
569
570 if (!lastCheckpoint) {
571 throw new SkipExecutionError("Transaction already finished")
572 }
573
574 /**
575 * Merge the stored checkpoint into the live flow, context and errors,
576 * mutating them in place.
577 *
578 * Steps that run concurrently hold a reference to their own
579 * TransactionStep instance, taken from the flow at the time they were
580 * scheduled. Swapping `this.flow` for a freshly built object graph
581 * would detach those references, so any state transition applied to them
582 * while this save is being retried would be written to an orphaned object
583 * and silently lost, leaving the transaction stuck.
584 */
585 TransactionCheckpoint.mergeCheckpoints(
586 new TransactionCheckpoint(this.flow, this.context, this.errors),
587 lastCheckpoint
588 )
589
590 continue
591 }
592 }
593
594 throw new Error(
595 `Max retries (${maxRetries}) exceeded for saving checkpoint due to version conflicts`
596 )
597 }
598
599 public static async loadTransaction(
600 modelId: string,
601 transactionId: string,
602 options?: { isCancelling?: boolean }
603 ): Promise<TransactionCheckpoint | null> {
604 const key = TransactionOrchestrator.getKeyName(
605 DistributedTransaction.keyPrefix,
606 modelId,
607 transactionId
608 )
609
610 const workflowOptions = TransactionOrchestrator.getWorkflowOptions(modelId)
611
612 const loadedData = await DistributedTransaction.keyValueStore.get(key, {
613 ...workflowOptions,
614 isCancelling: options?.isCancelling,
615 })
616
617 if (loadedData) {
618 return loadedData
619 }
620
621 return null
622 }
623
624 public async scheduleRetry(
625 step: TransactionStep,
626 interval: number
627 ): Promise<void> {
628 if (this.hasFinished()) {
629 return
630 }
631
632 await DistributedTransaction.keyValueStore.scheduleRetry(
633 this,
634 step,
635 Date.now(),
636 interval
637 )
638 }
639
640 public async clearRetry(step: TransactionStep): Promise<void> {
641 await DistributedTransaction.keyValueStore.clearRetry(this, step)
642 }
643
644 public async scheduleTransactionTimeout(interval: number): Promise<void> {
645 // schedule transaction timeout only if there are async steps
646 if (!this.getFlow().hasAsyncSteps) {
647 return
648 }
649
650 await DistributedTransaction.keyValueStore.scheduleTransactionTimeout(
651 this,
652 Date.now(),
653 interval
654 )
655 }
656
657 public async clearTransactionTimeout(): Promise<void> {
658 if (!this.getFlow().hasAsyncSteps) {
659 return
660 }
661
662 await DistributedTransaction.keyValueStore.clearTransactionTimeout(this)
663 }
664
665 public async scheduleStepTimeout(
666 step: TransactionStep,
667 interval: number
668 ): Promise<void> {
669 // schedule step timeout only if the step is async
670 if (!step.definition.async) {
671 return
672 }
673
674 await this.saveCheckpoint()
675 await DistributedTransaction.keyValueStore.scheduleStepTimeout(
676 this,
677 step,
678 Date.now(),
679 interval
680 )
681 }
682
683 public async clearStepTimeout(step: TransactionStep): Promise<void> {
684 if (!step.definition.async || step.isCompensating()) {
685 return
686 }
687
688 await DistributedTransaction.keyValueStore.clearStepTimeout(this, step)
689 }
690
691 public setTemporaryData(key: string, value: unknown) {
692 this.#temporaryStorage.set(key, value)
693 }
694
695 public getTemporaryData(key: string) {
696 return this.#temporaryStorage.get(key)
697 }
698
699 public hasTemporaryData(key: string) {
700 return this.#temporaryStorage.has(key)
701 }
702
703 /**
704 * Try to serialize the checkpoint data
705 * If it fails, it means that the context or the errors are not serializable
706 * and we should handle it
707 *
708 * @internal
709 * @returns
710 */
711 #serializeCheckpointData() {
712 try {
713 JSON.stringify(this.context)
714 } catch {
715 throw new NonSerializableCheckPointError(
716 "Unable to serialize context object. Please make sure the workflow input and steps response are serializable."
717 )
718 }
719
720 let errorsToUse = this.getErrors()
721 try {
722 JSON.stringify(errorsToUse)
723 } catch {
724 // Sanitize non-serializable errors
725 const sanitizedErrors: TransactionStepError[] = []
726 for (const error of this.errors) {
727 try {
728 JSON.stringify(error)
729 sanitizedErrors.push(error)
730 } catch {
731 sanitizedErrors.push({
732 action: error.action,
733 handlerType: error.handlerType,
734 error: {
735 name: error.error?.name || "Error",
736 message: error.error?.message || String(error.error),
737 stack: error.error?.stack,
738 },
739 })
740 }
741 }
742 errorsToUse = sanitizedErrors
743 this.errors = sanitizedErrors
744 }
745
746 return new TransactionCheckpoint(
747 JSON.parse(JSON.stringify(this.getFlow())),
748 this.getContext(),
749 [...errorsToUse]
750 )
751 }
752 }
753
754 DistributedTransaction.setStorage(
755 new BaseInMemoryDistributedTransactionStorage()
756 )
757
758 global.DistributedTransaction ??= DistributedTransaction
759 const GlobalDistributedTransaction =
760 global.DistributedTransaction as typeof DistributedTransaction
761
762 export {
763 GlobalDistributedTransaction as DistributedTransaction,
764 DistributedTransaction as DistributedTransactionType,
765 }