-
Notifications
You must be signed in to change notification settings - Fork 1k
/
CircuitBreakerRetry.java
252 lines (228 loc) · 8.21 KB
/
CircuitBreakerRetry.java
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.retry.intercept;
import io.micronaut.context.event.ApplicationEventPublisher;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.retry.CircuitState;
import io.micronaut.retry.RetryStateBuilder;
import io.micronaut.retry.annotation.RetryPredicate;
import io.micronaut.retry.event.CircuitClosedEvent;
import io.micronaut.retry.event.CircuitOpenEvent;
import io.micronaut.retry.exception.CircuitOpenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.concurrent.atomic.AtomicReference;
/**
* A context object for storing the state of the Circuit.
*
* @author graemerocher
* @since 1.0
*/
class CircuitBreakerRetry implements MutableRetryState {
private static final Logger LOG = LoggerFactory.getLogger(DefaultRetryInterceptor.class);
private final RetryStateBuilder retryStateBuilder;
private final long openTimeout;
private final ExecutableMethod<?, ?> method;
private final ApplicationEventPublisher eventPublisher;
private final boolean throwWrappedException;
private AtomicReference<CircuitState> state = new AtomicReference<>(CircuitState.CLOSED);
private volatile Throwable lastError;
private volatile long time = System.currentTimeMillis();
private volatile MutableRetryState childState;
/**
* @param openTimeout The circuit open timeout in millis
* @param childStateBuilder The retry state builder
* @param method A compile time produced invocation of a method call
* @param eventPublisher To publish circuit events
* @param throwWrappedException If {@code true}, the original exception will be wrapped in {@link CircuitOpenException}
*/
CircuitBreakerRetry(
long openTimeout,
RetryStateBuilder childStateBuilder,
ExecutableMethod<?, ?> method,
ApplicationEventPublisher eventPublisher, boolean throwWrappedException) {
this.retryStateBuilder = childStateBuilder;
this.openTimeout = openTimeout;
this.childState = (MutableRetryState) childStateBuilder.build();
this.eventPublisher = eventPublisher;
this.method = method;
this.throwWrappedException = throwWrappedException;
}
@Override
public void close(@Nullable Throwable exception) {
if (exception == null && currentState() == CircuitState.HALF_OPEN) {
closeCircuit();
} else if (currentState() != CircuitState.OPEN) {
if (exception != null && getRetryPredicate().test(exception)) {
openCircuit(exception);
} else {
// reset state for successful operation
time = System.currentTimeMillis();
lastError = null;
this.childState = (MutableRetryState) retryStateBuilder.build();
}
}
}
@Override
public void open() {
if (currentState() == CircuitState.OPEN && lastError != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rethrowing existing exception for Open Circuit [{}]: {}", method, lastError.getMessage());
}
if (lastError instanceof RuntimeException && !throwWrappedException) {
throw (RuntimeException) lastError;
} else {
throw new CircuitOpenException("Circuit Open: " + lastError.getMessage(), lastError);
}
}
}
@Override
public long nextDelay() {
return childState.nextDelay();
}
@Override
public boolean canRetry(Throwable exception) {
if (exception == null) {
throw new IllegalArgumentException("Exception cause cannot be null");
}
try {
return currentState() != CircuitState.OPEN && childState.canRetry(exception);
} finally {
if (currentState() == CircuitState.HALF_OPEN) {
openCircuit(exception);
}
}
}
@Override
public int getMaxAttempts() {
return childState.getMaxAttempts();
}
@Override
public int currentAttempt() {
return childState.currentAttempt();
}
@Override
public OptionalDouble getMultiplier() {
return childState.getMultiplier();
}
@Override
public Duration getDelay() {
return childState.getDelay();
}
@Override
public Duration getOverallDelay() {
return childState.getOverallDelay();
}
@Override
public Optional<Duration> getMaxDelay() {
return childState.getMaxDelay();
}
@Override
public RetryPredicate getRetryPredicate() {
return childState.getRetryPredicate();
}
@Override
public Class<? extends Throwable> getCapturedException() {
return childState.getCapturedException();
}
/**
* @return The current state
*/
CircuitState currentState() {
if (state.get() == CircuitState.OPEN) {
long now = System.currentTimeMillis();
long timeout = time + openTimeout;
if (now > timeout) {
return halfOpenCircuit();
}
return state.get();
} else {
return state.get();
}
}
/**
* Opens the circuit.
*
* @return The current state
*/
private CircuitState openCircuit(Throwable cause) {
if (cause == null) {
throw new IllegalArgumentException("Exception cause cannot be null");
}
if (LOG.isDebugEnabled()) {
LOG.debug("Opening Circuit Breaker [{}] due to error: {}", method, cause.getMessage());
}
this.childState = (MutableRetryState) retryStateBuilder.build();
this.lastError = cause;
this.time = System.currentTimeMillis();
try {
return state.getAndSet(CircuitState.OPEN);
} finally {
if (eventPublisher != null) {
try {
eventPublisher.publishEvent(new CircuitOpenEvent(method, childState, cause));
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Error publishing CircuitOpen event: " + e.getMessage(), e);
}
}
}
}
}
/**
* Resets the circuit state to {@link CircuitState#CLOSED}.
*
* @return The current state
*/
private CircuitState closeCircuit() {
if (LOG.isDebugEnabled()) {
LOG.debug("Closing Circuit Breaker [{}]", method);
}
time = System.currentTimeMillis();
lastError = null;
this.childState = (MutableRetryState) retryStateBuilder.build();
try {
return state.getAndSet(CircuitState.CLOSED);
} finally {
if (eventPublisher != null) {
try {
eventPublisher.publishEvent(new CircuitClosedEvent(method));
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Error publishing CircuitClosedEvent: " + e.getMessage(), e);
}
}
}
}
}
/**
* Resets the circuit state to {@link CircuitState#HALF_OPEN}.
*
* @return The current state
*/
private CircuitState halfOpenCircuit() {
if (LOG.isDebugEnabled()) {
LOG.debug("Half Opening Circuit Breaker [{}]", method);
}
lastError = null;
this.childState = (MutableRetryState) retryStateBuilder.build();
return state.getAndSet(CircuitState.HALF_OPEN);
}
}