1 import { MedusaError, TransactionStepState } from "@medusajs/utils"
2 import {
3 DistributedTransactionType,
4 TransactionPayload,
5 } from "./distributed-transaction"
6 import { TransactionOrchestrator } from "./transaction-orchestrator"
7 import {
8 TransactionHandlerType,
9 TransactionState,
10 TransactionStepStatus,
11 TransactionStepsDefinition,
12 } from "./types"
13
14 export type TransactionStepHandler = (
15 actionId: string,
16 handlerType: TransactionHandlerType,
17 payload: TransactionPayload,
18 transaction: DistributedTransactionType,
19 step: TransactionStep,
20 orchestrator: TransactionOrchestrator
21 ) => Promise<unknown>
22
23 /**
24 * @class TransactionStep
25 * @classdesc A class representing a single step in a transaction flow
26 */
27 export class TransactionStep {
28 /**
29 * @member id - The id of the step
30 * @member depth - The depth of the step in the flow
31 * @member definition - The definition of the step
32 * @member invoke - The current state and status of the invoke action of the step
33 * @member compensate - The current state and status of the compensate action of the step
34 * @member attempts - The number of attempts made to execute the step
35 * @member failures - The number of failures encountered while executing the step
36 * @member lastAttempt - The timestamp of the last attempt made to execute the step
37 * @member hasScheduledRetry - A flag indicating if a retry has been scheduled
38 * @member retryRescheduledAt - The timestamp of the last retry scheduled
39 * @member next - The ids of the next steps in the flow
40 * @member saveResponse - A flag indicating if the response of a step should be shared in the transaction context and available to subsequent steps - default is true
41 */
42 private stepFailed = false
43 id: string
44 uuid?: string
45 depth: number
46 definition: TransactionStepsDefinition
47 invoke: {
48 state: TransactionStepState
49 status: TransactionStepStatus
50 }
51 compensate: {
52 state: TransactionStepState
53 status: TransactionStepStatus
54 }
55 attempts: number
56 failures: number
57 temporaryFailedAt: number | null
58 lastAttempt: number | null
59 retryRescheduledAt: number | null
60 hasScheduledRetry: boolean
61 timedOutAt: number | null
62 startedAt?: number
63 next: string[]
64 saveResponse: boolean
65 _v?: number
66
67 public getStates() {
68 return this.isCompensating() ? this.compensate : this.invoke
69 }
70
71 public beginCompensation() {
72 if (this.isCompensating()) {
73 return
74 }
75
76 this.stepFailed = true
77 this.attempts = 0
78 this.failures = 0
79 this.lastAttempt = null
80 }
81
82 public isCompensating() {
83 return this.stepFailed
84 }
85
86 public isInvoking() {
87 return !this.stepFailed
88 }
89
90 public changeState(toState: TransactionStepState) {
91 const allowed = {
92 [TransactionStepState.DORMANT]: [TransactionStepState.NOT_STARTED],
93 [TransactionStepState.NOT_STARTED]: [
94 TransactionStepState.INVOKING,
95 TransactionStepState.COMPENSATING,
96 TransactionStepState.FAILED,
97 TransactionStepState.SKIPPED,
98 TransactionStepState.SKIPPED_FAILURE,
99 ],
100 [TransactionStepState.INVOKING]: [
101 TransactionStepState.FAILED,
102 TransactionStepState.DONE,
103 TransactionStepState.TIMEOUT,
104 TransactionStepState.SKIPPED,
105 ],
106 [TransactionStepState.COMPENSATING]: [
107 TransactionStepState.REVERTED,
108 TransactionStepState.FAILED,
109 ],
110 [TransactionStepState.DONE]: [TransactionStepState.COMPENSATING],
111 }
112
113 const curState = this.getStates()
114 if (
115 curState.state === toState ||
116 allowed?.[curState.state]?.includes(toState)
117 ) {
118 curState.state = toState
119 return
120 }
121
122 throw new MedusaError(
123 MedusaError.Types.NOT_ALLOWED,
124 `Updating State from "${curState.state}" to "${toState}" is not allowed.`
125 )
126 }
127
128 public changeStatus(toStatus: TransactionStepStatus) {
129 const allowed = {
130 [TransactionStepStatus.WAITING]: [
131 TransactionStepStatus.OK,
132 TransactionStepStatus.TEMPORARY_FAILURE,
133 TransactionStepStatus.PERMANENT_FAILURE,
134 ],
135 [TransactionStepStatus.TEMPORARY_FAILURE]: [
136 TransactionStepStatus.IDLE,
137 TransactionStepStatus.PERMANENT_FAILURE,
138 ],
139 [TransactionStepStatus.PERMANENT_FAILURE]: [TransactionStepStatus.IDLE],
140 }
141
142 const curState = this.getStates()
143 if (
144 curState.status === toStatus ||
145 toStatus === TransactionStepStatus.WAITING ||
146 allowed?.[curState.status]?.includes(toStatus)
147 ) {
148 curState.status = toStatus
149 return
150 }
151
152 throw new MedusaError(
153 MedusaError.Types.NOT_ALLOWED,
154 `Updating Status from "${curState.status}" to "${toStatus}" is not allowed.`
155 )
156 }
157
158 hasRetryScheduled(): boolean {
159 return !!this.hasScheduledRetry
160 }
161
162 hasRetryInterval(): boolean {
163 return !!this.definition.retryInterval
164 }
165
166 hasTimeout(): boolean {
167 return !!this.getTimeout()
168 }
169
170 getTimeout(): number | undefined {
171 return this.definition.timeout
172 }
173
174 canRetry(): boolean {
175 return (
176 !this.definition.retryInterval ||
177 !!(
178 this.lastAttempt &&
179 this.definition.retryInterval &&
180 Date.now() - this.lastAttempt >= this.definition.retryInterval * 1e3
181 )
182 )
183 }
184
185 hasAwaitingRetry(): boolean {
186 return !!this.definition.retryIntervalAwaiting
187 }
188
189 canRetryAwaiting(): boolean {
190 return !!(
191 this.hasAwaitingRetry() &&
192 this.lastAttempt &&
193 Date.now() - this.lastAttempt >
194 this.definition.retryIntervalAwaiting! * 1e3 &&
195 // For compensating steps, ignore maxAwaitingRetries and retry indefinitely
196 // Compensation must complete, so we keep checking until the nested workflow finishes
197 (!("maxAwaitingRetries" in this.definition) ||
198 (this.isCompensating()
199 ? this.attempts < this.definition.maxAwaitingRetries! * 2
200 : this.attempts < this.definition.maxAwaitingRetries!))
201 )
202 }
203
204 canInvoke(flowState: TransactionState): boolean {
205 const { status, state } = this.getStates()
206 return (
207 (!this.isCompensating() &&
208 state === TransactionStepState.NOT_STARTED &&
209 flowState === TransactionState.INVOKING) ||
210 (status === TransactionStepStatus.TEMPORARY_FAILURE &&
211 !this.temporaryFailedAt)
212 )
213 }
214
215 canCompensate(flowState: TransactionState): boolean {
216 return (
217 this.isCompensating() &&
218 this.getStates().state === TransactionStepState.NOT_STARTED &&
219 flowState === TransactionState.COMPENSATING
220 )
221 }
222
223 canCancel(): boolean {
224 return (
225 !this.isCompensating() &&
226 [
227 TransactionStepStatus.WAITING,
228 TransactionStepStatus.TEMPORARY_FAILURE,
229 ].includes(this.getStates().status)
230 )
231 }
232 }