forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircuitBreaker.js
More file actions
158 lines (136 loc) · 4.15 KB
/
Copy pathcircuitBreaker.js
File metadata and controls
158 lines (136 loc) · 4.15 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
'use strict';
const logger = require('../logger');
const STATES = Object.freeze({
CLOSED: 'closed',
OPEN: 'open',
HALF_OPEN: 'half-open',
});
class CircuitBreaker {
constructor(name, options = {}) {
this.name = name;
this.failureThreshold = Math.max(1, options.failureThreshold ?? 3);
this.successThreshold = Math.max(1, options.successThreshold ?? 1);
this.timeoutMs = Math.max(1, options.timeoutMs ?? 30000);
this._now = options.now || Date.now;
this._logger = options.logger || logger;
this.state = STATES.CLOSED;
this.failureCount = 0;
this.successCount = 0;
this.openedAt = null;
this.halfOpenInFlight = false;
}
getState() {
this._moveToHalfOpenIfReady();
return this.state;
}
isOpen() {
return this.getState() === STATES.OPEN;
}
/**
* Wraps a call in the breaker's failure accounting. `fn` returning
* `null`/`undefined` is treated exactly like a thrown error — it counts
* as a failure and can trip the breaker OPEN.
*
* Contract for callers: only pass `fn` here for a call the wrapped source
* is actually expected to be able to answer. If a source can never serve
* a given request (e.g. an asset it doesn't track at all), that's a
* permanent, per-request condition, not a signal about the source's
* health — decide that *before* calling `call()`, and skip it entirely
* rather than letting a "not supported" response reach here as a `null`.
* priceOracle.js's `fetchFromAllSources` does this via each source's
* `isSupported(assetCode, issuer)` (see #130); any future caller wrapping
* a new per-item resource in a shared breaker should do the same.
*/
async call(fn) {
this._moveToHalfOpenIfReady();
if (this.state === STATES.OPEN) {
this._logger.info('Circuit breaker open, skipping source call', {
source: this.name,
state: this.state,
});
return null;
}
if (this.state === STATES.HALF_OPEN && this.halfOpenInFlight) {
this._logger.info('Circuit breaker half-open probe already in flight, skipping source call', {
source: this.name,
state: this.state,
});
return null;
}
const probing = this.state === STATES.HALF_OPEN;
if (probing) {
this.halfOpenInFlight = true;
}
try {
const result = await fn();
if (result === null || result === undefined) {
this.recordFailure();
} else {
this.recordSuccess();
}
return result ?? null;
} catch (err) {
this.recordFailure();
throw err;
} finally {
if (probing) {
this.halfOpenInFlight = false;
}
}
}
recordSuccess() {
if (this.state === STATES.HALF_OPEN) {
this.successCount += 1;
if (this.successCount >= this.successThreshold) {
this._transitionTo(STATES.CLOSED, { reason: 'success-threshold' });
}
return;
}
if (this.state === STATES.CLOSED) {
this.failureCount = 0;
}
}
recordFailure() {
if (this.state === STATES.HALF_OPEN) {
this._transitionTo(STATES.OPEN, { reason: 'half-open-failure' });
return;
}
if (this.state === STATES.CLOSED) {
this.failureCount += 1;
if (this.failureCount >= this.failureThreshold) {
this._transitionTo(STATES.OPEN, { reason: 'failure-threshold' });
}
}
}
reset() {
this._transitionTo(STATES.CLOSED, { reason: 'manual-reset' });
}
_moveToHalfOpenIfReady() {
if (this.state !== STATES.OPEN || this.openedAt === null) {
return;
}
if (this._now() - this.openedAt >= this.timeoutMs) {
this._transitionTo(STATES.HALF_OPEN, { reason: 'cooldown-elapsed' });
}
}
_transitionTo(nextState, metadata = {}) {
if (this.state === nextState) {
return;
}
const previousState = this.state;
this.state = nextState;
this.failureCount = 0;
this.successCount = 0;
this.openedAt = nextState === STATES.OPEN ? this._now() : null;
this._logger.info('Circuit breaker state changed', {
source: this.name,
from: previousState,
to: nextState,
...metadata,
});
}
}
module.exports = {
CircuitBreaker,
STATES,
};