1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| // Saga执行器
class SagaOrchestrator {
private sagaLog: SagaLog;
async execute(
sagaDef: SagaDefinition,
initialState: any
): Promise<any> {
let state = initialState;
const executedSteps: SagaStep[] = [];
try {
// 正向执行所有步骤
for (const step of sagaDef.steps) {
const result = await this.executeStep(step, state);
state = { ...state, ...result };
// 记录已执行的步骤
await this.sagaLog.saveStep({
sagaId: sagaDef.id,
stepName: step.name,
status: 'completed',
result
});
executedSteps.push(step);
}
return state;
} catch (error) {
// 发生错误,执行补偿
await this.compensate(executedSteps.reverse());
throw error;
}
}
private async compensate(steps: SagaStep[]): Promise<void> {
for (const step of steps) {
try {
if (step.compensate) {
await step.compensate();
await this.sagaLog.updateStep(
step.name,
'compensated'
);
}
} catch (error) {
console.error(
`Compensation failed for ${step.name}:`,
error
);
// 继续执行其他补偿
}
}
}
}
// 订单处理Saga示例
class OrderSaga {
private orchestrator = new SagaOrchestrator();
async processOrder(orderDto: OrderDTO): Promise<Order> {
const sagaDefinition: SagaDefinition = {
id: uuidv4(),
name: 'order-processing',
steps: [
{
name: 'create-order',
action: async () => {
return await this.orderService.create(orderDto);
},
compensate: async (order) => {
await this.orderService.cancel(order.id);
}
},
{
name: 'reserve-inventory',
action: async (state) => {
return await this.inventoryService.reserve({
orderId: state.order.id,
items: orderDto.items
});
},
compensate: async (state) => {
await this.inventoryService.release(
state.order.id
);
}
},
{
name: 'process-payment',
action: async (state) => {
return await this.paymentService.charge({
orderId: state.order.id,
amount: state.order.total,
method: orderDto.paymentMethod
});
},
compensate: async (state) => {
await this.paymentService.refund(
state.payment.id
);
}
},
{
name: 'confirm-order',
action: async (state) => {
return await this.orderService.confirm(
state.order.id
);
}
// 最后一步无需补偿
}
]
};
return await this.orchestrator.execute(
sagaDefinition,
{}
);
}
}
|