-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-orchestration.js
More file actions
189 lines (167 loc) · 4.96 KB
/
2-orchestration.js
File metadata and controls
189 lines (167 loc) · 4.96 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict';
class BankAccount {
constructor(name, balance = 0, maxBalance = -1) {
this.name = name;
this.balance = balance;
this.maxBalance = maxBalance;
}
debit(amount) {
if (amount > this.balance) {
throw new Error(`Insufficient funds on ${this.name}`);
}
this.balance -= amount;
}
credit(amount) {
const { name, balance, maxBalance } = this;
const value = balance + amount;
if (maxBalance > 0 && value > maxBalance) {
throw new Error(`Account ${name} cannot exceed balance ${maxBalance}`);
}
this.balance = value;
}
}
class Bank {
constructor(accounts) {
this.accounts = new Map(
accounts.map((account) => {
const { name, balance, maxBalance = -1 } = account;
const bankAccount = new BankAccount(name, balance, maxBalance);
return [name, bankAccount];
}),
);
}
getBalance(name) {
const account = this.accounts.get(name);
if (!account) throw new Error(`Account ${name} not found`);
return account.balance;
}
debit(name, amount) {
const account = this.accounts.get(name);
if (!account) throw new Error(`Account ${name} not found`);
account.debit(amount);
}
credit(name, amount) {
const account = this.accounts.get(name);
if (!account) throw new Error(`Account ${name} not found`);
account.credit(amount);
}
}
class FraudService {
constructor(blockedRecipients = []) {
this.blockedRecipients = new Set(blockedRecipients);
}
ensureNotBlocked({ to }) {
if (this.blockedRecipients.has(to)) {
throw new Error(`Fraud check failed for ${to}`);
}
}
}
class NotificationService {
constructor(unreliableRecipients = []) {
this.unreliableRecipients = new Set(unreliableRecipients);
}
sendReceipt({ to, amount }) {
if (this.unreliableRecipients.has(to)) {
throw new Error(`Notification service unavailable for ${to}`);
}
console.log(`Notification: receipt sent to ${to} for ${amount}`);
}
}
class SagaStep {
constructor({ name, action, compensation = null }) {
this.name = name;
this.action = action;
this.compensation = compensation;
}
}
class SagaOrchestrator {
constructor(steps) {
this.steps = steps;
}
run(context) {
const completed = [];
for (const step of this.steps) {
const { name } = step;
try {
step.action(context);
completed.push(step);
console.log(`✓ ${name}`);
} catch (error) {
const { message } = error;
console.error(`✗ ${name}: ${message}`);
this.rollback(context, completed);
throw new Error(`Saga failed at step "${name}": ${message}`);
}
}
return context;
}
rollback(context, completedSteps) {
const steps = completedSteps.toReversed();
for (const step of steps) {
const { name } = step;
if (!step.compensation) continue;
if (!this.steps.includes(step)) {
throw new Error(`Step ${name} is not part of the saga`);
}
try {
step.compensation(context);
console.log(`↩ Compensation applied for ${name}`);
} catch (compensationError) {
const { message } = compensationError;
console.error(`⚠ Failed to compensate ${name}: ${message}`);
}
}
}
}
const bank = new Bank([
{ name: 'Marcus Aurelius', balance: 100, maxBalance: 120 },
{ name: 'Antoninus Pius', balance: 1000 },
{ name: 'Commodus', balance: 50 },
]);
const fraudService = new FraudService(['Commodus']);
const notificationService = new NotificationService(['Antoninus Pius']);
const transferSaga = new SagaOrchestrator([
new SagaStep({
name: 'Fraud check recipient',
action: (ctx) => fraudService.ensureNotBlocked(ctx),
}),
new SagaStep({
name: 'Debit sender account',
action: (ctx) => bank.debit(ctx.from, ctx.amount),
compensation: (ctx) => bank.credit(ctx.from, ctx.amount),
}),
new SagaStep({
name: 'Credit recipient account',
action: (ctx) => bank.credit(ctx.to, ctx.amount),
compensation: (ctx) => bank.debit(ctx.to, ctx.amount),
}),
new SagaStep({
name: 'Send receipt',
action: (ctx) => notificationService.sendReceipt(ctx),
}),
]);
const showBalances = () => {
console.log('--- Balances ---');
for (const [name] of bank.accounts) {
const balance = bank.getBalance(name);
console.log(`${name}: ${balance}`);
}
};
const runScenario = (context) => {
try {
const { from, to } = context;
console.log(`\nRunning saga orchestrated transfer ${from} -> ${to}`);
transferSaga.run(context);
console.log('Saga completed successfully');
} catch (error) {
console.error(error.message);
} finally {
showBalances();
}
};
console.log('Services ready: Saga Orchestrator');
console.log('\nInitial balances:');
showBalances();
runScenario({ from: 'Antoninus Pius', to: 'Marcus Aurelius', amount: 10 });
runScenario({ from: 'Antoninus Pius', to: 'Marcus Aurelius', amount: 30 });
runScenario({ from: 'Antoninus Pius', to: 'Commodus', amount: 100 });