|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} Compensation Function`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this chapter, you'll learn what a compensation function is and how to add it to a step. |
|
8
|
|
|
9
|
## What is a Compensation Function |
|
10
|
|
|
11
|
A compensation function rolls back or undoes changes made by a step when an error occurs in the workflow. |
|
12
|
|
|
13
|
For example, if a step creates a record, the compensation function deletes the record when an error occurs later in the workflow. |
|
14
|
|
|
15
|
By using compensation functions, you provide a mechanism that guarantees data consistency in your application and across systems. |
|
16
|
|
|
17
|
--- |
|
18
|
|
|
19
|
## How to add a Compensation Function? |
|
20
|
|
|
21
|
A compensation function is passed as a second parameter to the `createStep` function. |
|
22
|
|
|
23
|
For example, create the file `src/workflows/hello-world.ts` with the following content: |
|
24
|
|
|
25
|
```ts title="src/workflows/hello-world.ts" highlights={[["15"], ["16"], ["17"]]} collapsibleLines="1-5" expandButtonLabel="Show Imports" |
|
26
|
import { |
|
27
|
createStep, |
|
28
|
StepResponse, |
|
29
|
} from "@medusajs/framework/workflows-sdk" |
|
30
|
|
|
31
|
const step1 = createStep( |
|
32
|
"step-1", |
|
33
|
async () => { |
|
34
|
const message = `Hello from step one!` |
|
35
|
|
|
36
|
console.log(message) |
|
37
|
|
|
38
|
return new StepResponse(message) |
|
39
|
}, |
|
40
|
async () => { |
|
41
|
console.log("Oops! Rolling back my changes...") |
|
42
|
} |
|
43
|
) |
|
44
|
``` |
|
45
|
|
|
46
|
Each step can have a compensation function. The compensation function only runs if an error occurs throughout the workflow. |
|
47
|
|
|
48
|
--- |
|
49
|
|
|
50
|
## Test the Compensation Function |
|
51
|
|
|
52
|
Create a step in the same `src/workflows/hello-world.ts` file that throws an error: |
|
53
|
|
|
54
|
```ts title="src/workflows/hello-world.ts" |
|
55
|
const step2 = createStep( |
|
56
|
"step-2", |
|
57
|
async () => { |
|
58
|
throw new MedusaError( |
|
59
|
MedusaError.Types.UNEXPECTED_STATE, |
|
60
|
"Throwing an error..." |
|
61
|
) |
|
62
|
} |
|
63
|
) |
|
64
|
``` |
|
65
|
|
|
66
|
Then, create a workflow that uses the steps: |
|
67
|
|
|
68
|
```ts title="src/workflows/hello-world.ts" collapsibleLines="1-8" expandButtonLabel="Show Imports" |
|
69
|
import { |
|
70
|
createWorkflow, |
|
71
|
WorkflowResponse, |
|
72
|
} from "@medusajs/framework/workflows-sdk" |
|
73
|
// other imports... |
|
74
|
|
|
75
|
// steps... |
|
76
|
|
|
77
|
const myWorkflow = createWorkflow( |
|
78
|
"hello-world", |
|
79
|
function (input) { |
|
80
|
const str1 = step1() |
|
81
|
step2() |
|
82
|
|
|
83
|
return new WorkflowResponse({ |
|
84
|
message: str1, |
|
85
|
}) |
|
86
|
}) |
|
87
|
|
|
88
|
export default myWorkflow |
|
89
|
``` |
|
90
|
|
|
91
|
Finally, execute the workflow from an API route: |
|
92
|
|
|
93
|
```ts title="src/api/workflow/route.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" |
|
94
|
import type { |
|
95
|
MedusaRequest, |
|
96
|
MedusaResponse, |
|
97
|
} from "@medusajs/framework/http" |
|
98
|
import myWorkflow from "../../../workflows/hello-world" |
|
99
|
|
|
100
|
export async function GET( |
|
101
|
req: MedusaRequest, |
|
102
|
res: MedusaResponse |
|
103
|
) { |
|
104
|
const { result } = await myWorkflow(req.scope) |
|
105
|
.run() |
|
106
|
|
|
107
|
res.send(result) |
|
108
|
} |
|
109
|
``` |
|
110
|
|
|
111
|
Run the Medusa application and send a `GET` request to `/workflow`: |
|
112
|
|
|
113
|
```bash |
|
114
|
curl http://localhost:9000/workflow |
|
115
|
``` |
|
116
|
|
|
117
|
In the console, you'll see: |
|
118
|
|
|
119
|
- `Hello from step one!` logged in the terminal, indicating that the first step ran successfully. |
|
120
|
- `Oops! Rolling back my changes...` logged in the terminal, indicating that the second step failed and the compensation function of the first step ran consequently. |
|
121
|
|
|
122
|
--- |
|
123
|
|
|
124
|
## Pass Input to Compensation Function |
|
125
|
|
|
126
|
If a step creates a record, the compensation function must receive the ID of the record to remove it. |
|
127
|
|
|
128
|
To pass input to the compensation function, pass a second parameter in the `StepResponse` returned by the step. |
|
129
|
|
|
130
|
For example: |
|
131
|
|
|
132
|
export const inputHighlights = [ |
|
133
|
["11", "", "The data to pass as an input to the compensation function."], |
|
134
|
["14", "{ message }", "The data received as an input from `StepResponse`'s second parameter."] |
|
135
|
] |
|
136
|
|
|
137
|
```ts highlights={inputHighlights} |
|
138
|
import { |
|
139
|
createStep, |
|
140
|
StepResponse, |
|
141
|
} from "@medusajs/framework/workflows-sdk" |
|
142
|
|
|
143
|
const step1 = createStep( |
|
144
|
"step-1", |
|
145
|
async () => { |
|
146
|
return new StepResponse( |
|
147
|
`Hello from step one!`, |
|
148
|
{ message: "Oops! Rolling back my changes..." } |
|
149
|
) |
|
150
|
}, |
|
151
|
async ({ message }) => { |
|
152
|
console.log(message) |
|
153
|
} |
|
154
|
) |
|
155
|
``` |
|
156
|
|
|
157
|
In this example, the step passes an object as a second parameter to `StepResponse`. |
|
158
|
|
|
159
|
The compensation function receives the object and uses its `message` property to log a message. |
|
160
|
|
|
161
|
--- |
|
162
|
|
|
163
|
## Resolve Resources from the Medusa Container |
|
164
|
|
|
165
|
The compensation function receives an object second parameter. The object has a `container` property that you use to resolve resources from the Medusa container. |
|
166
|
|
|
167
|
For example: |
|
168
|
|
|
169
|
export const containerHighlights = [ |
|
170
|
["15", "container", "Access the container in the second parameter object."], |
|
171
|
["16", "resolve", "Use the container to resolve resources."] |
|
172
|
] |
|
173
|
|
|
174
|
```ts |
|
175
|
import { |
|
176
|
createStep, |
|
177
|
StepResponse, |
|
178
|
} from "@medusajs/framework/workflows-sdk" |
|
179
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
180
|
|
|
181
|
const step1 = createStep( |
|
182
|
"step-1", |
|
183
|
async () => { |
|
184
|
return new StepResponse( |
|
185
|
`Hello from step one!`, |
|
186
|
{ message: "Oops! Rolling back my changes..." } |
|
187
|
) |
|
188
|
}, |
|
189
|
async ({ message }, { container }) => { |
|
190
|
const logger = container.resolve( |
|
191
|
ContainerRegistrationKeys.LOGGER |
|
192
|
) |
|
193
|
|
|
194
|
logger.info(message) |
|
195
|
} |
|
196
|
) |
|
197
|
``` |
|
198
|
|
|
199
|
In this example, you use the `container` property in the second object parameter of the compensation function to resolve the logger. |
|
200
|
|
|
201
|
You then use the logger to log a message. |
|
202
|
|
|
203
|
--- |
|
204
|
|
|
205
|
## Handle Step Errors in Loops |
|
206
|
|
|
207
|
<Note> |
|
208
|
|
|
209
|
This feature is only available after [Medusa v2.0.5](https://github.com/medusajs/medusa/releases/tag/v2.0.5). |
|
210
|
|
|
211
|
</Note> |
|
212
|
|
|
213
|
Consider you have a module that integrates a third-party ERP system, and you're creating a workflow that deletes items in that ERP. You may have the following step: |
|
214
|
|
|
215
|
```ts |
|
216
|
// other imports... |
|
217
|
import { promiseAll } from "@medusajs/framework/utils" |
|
218
|
|
|
219
|
type StepInput = { |
|
220
|
ids: string[] |
|
221
|
} |
|
222
|
|
|
223
|
const step1 = createStep( |
|
224
|
"step-1", |
|
225
|
async ({ ids }: StepInput, { container }) => { |
|
226
|
const erpModuleService = container.resolve( |
|
227
|
ERP_MODULE |
|
228
|
) |
|
229
|
const prevData: unknown[] = [] |
|
230
|
|
|
231
|
await promiseAll( |
|
232
|
ids.map(async (id) => { |
|
233
|
const data = await erpModuleService.retrieve(id) |
|
234
|
|
|
235
|
await erpModuleService.delete(id) |
|
236
|
|
|
237
|
prevData.push(id) |
|
238
|
}) |
|
239
|
) |
|
240
|
|
|
241
|
return new StepResponse(ids, prevData) |
|
242
|
} |
|
243
|
) |
|
244
|
``` |
|
245
|
|
|
246
|
In the step, you loop over the IDs to retrieve the item's data, store them in a `prevData` variable, then delete them using the ERP Module's service. You then pass the `prevData` variable to the compensation function. |
|
247
|
|
|
248
|
However, if an error occurs in the loop, the `prevData` variable won't be passed to the compensation function as the execution never reached the return statement. |
|
249
|
|
|
250
|
To handle errors in the loop so that the compensation function receives the last version of `prevData` before the error occurred, you wrap the loop in a try-catch block. Then, in the catch block, you invoke and return the `StepResponse.permanentFailure` function: |
|
251
|
|
|
252
|
export const highlights = [ |
|
253
|
["1", "try", "Wrap in a try-catch block."], |
|
254
|
["12", "permanentFailure", "Fail the step and the workflow."], |
|
255
|
["14", "prevData", "Data to pass to the compensation function."] |
|
256
|
] |
|
257
|
|
|
258
|
```ts highlights={highlights} |
|
259
|
try { |
|
260
|
await promiseAll( |
|
261
|
ids.map(async (id) => { |
|
262
|
const data = await erpModuleService.retrieve(id) |
|
263
|
|
|
264
|
await erpModuleService.delete(id) |
|
265
|
|
|
266
|
prevData.push(id) |
|
267
|
}) |
|
268
|
) |
|
269
|
} catch (e) { |
|
270
|
return StepResponse.permanentFailure( |
|
271
|
`An error occurred: ${e}`, |
|
272
|
prevData |
|
273
|
) |
|
274
|
} |
|
275
|
``` |
|
276
|
|
|
277
|
The `StepResponse.permanentFailure` fails the step and its workflow, triggering current and previous steps' compensation functions. The `permanentFailure` function accepts as a first parameter the error message, which is saved in the workflow's error details, and as a second parameter the data to pass to the compensation function. |
|
278
|
|
|
279
|
So, if an error occurs during the loop, the compensation function will still receive the `prevData` variable to undo the changes made before the step failed. |
|
280
|
|
|
281
|
<Note> |
|
282
|
|
|
283
|
For more details on error handling in workflows and steps, check the [Handling Errors chapter](../errors/page.mdx). |
|
284
|
|
|
285
|
</Note> |