resilience4j-circuit-breaker: add state-transition, slow-call, TimeLimiter, ignoreExceptions and RateLimiter tests on Boot 4.1.2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b74uRrp2Tiu2PngyuY
This commit is contained in:
@@ -18,7 +18,7 @@ public final class Transcript {
|
||||
private final Path outFile;
|
||||
|
||||
private Transcript(String fileName) {
|
||||
this.outFile = Paths.get("docs/output", fileName);
|
||||
this.outFile = Paths.get(System.getProperty("transcript.dir", "docs/output"), fileName);
|
||||
}
|
||||
|
||||
public static Transcript start(String fileName, String header) {
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.resilience.r4j;
|
||||
|
||||
import com.ankurm.resilience.Transcript;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** Output: 11-ignore-exceptions.txt, 12-rate-limiter.txt. */
|
||||
@SpringBootTest
|
||||
@DirtiesContext
|
||||
class IgnoreExceptionsAndRateLimiterTest {
|
||||
|
||||
@Autowired R4jLookupService lookup;
|
||||
@Autowired R4jRateLimiterService limiter;
|
||||
@Autowired CircuitBreakerRegistry registry;
|
||||
|
||||
@Test
|
||||
void businessExceptionsShouldNotTripTheBreaker() {
|
||||
Transcript t = Transcript.start("11-ignore-exceptions.txt",
|
||||
"Same exception, two breakers, one line of YAML apart");
|
||||
CircuitBreaker counted = registry.circuitBreaker("lookupCounted");
|
||||
CircuitBreaker ignored = registry.circuitBreaker("lookupIgnored");
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
try { lookup.findCounted("p" + i); } catch (ProductNotFoundException ignoredEx) { }
|
||||
try { lookup.findIgnored("p" + i); } catch (ProductNotFoundException ignoredEx) { }
|
||||
}
|
||||
t.line("lookupCounted after 4 'not found': state=" + counted.getState()
|
||||
+ " failed=" + counted.getMetrics().getNumberOfFailedCalls());
|
||||
t.line("lookupIgnored after 4 'not found': state=" + ignored.getState()
|
||||
+ " failed=" + ignored.getMetrics().getNumberOfFailedCalls()
|
||||
+ " buffered=" + ignored.getMetrics().getNumberOfBufferedCalls());
|
||||
assertThat(counted.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||
assertThat(ignored.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
|
||||
assertThat(ignored.getMetrics().getNumberOfBufferedCalls()).isZero();
|
||||
t.save();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rateLimiterRejectsTheFourthCallInAOneSecondWindow() throws InterruptedException {
|
||||
Transcript t = Transcript.start("12-rate-limiter.txt", "limitForPeriod=3, limitRefreshPeriod=1s");
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
t.line("call " + i + " -> " + limiter.search("q" + i));
|
||||
}
|
||||
Thread.sleep(1100);
|
||||
String after = limiter.search("q5");
|
||||
t.line("after 1.1s -> " + after);
|
||||
assertThat(after).startsWith("results:");
|
||||
t.save();
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.ankurm.resilience.r4j;
|
||||
|
||||
import com.ankurm.resilience.Transcript;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Slow is a failure mode too. Output: 08-slow-call-rate.txt, 09-timelimiter.txt,
|
||||
* 10-timelimiter-plus-breaker.txt.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@DirtiesContext
|
||||
class LatencyAndTimeoutTest {
|
||||
|
||||
@Autowired R4jSlowCallService slow;
|
||||
@Autowired R4jTimeLimiterService timeLimited;
|
||||
@Autowired CircuitBreakerRegistry registry;
|
||||
|
||||
@Test
|
||||
void breakerOpensOnLatencyAloneWithZeroFailures() throws Exception {
|
||||
Transcript t = Transcript.start("08-slow-call-rate.txt",
|
||||
"slowCallDurationThreshold=200ms, slowCallRateThreshold=50: opens with zero failures");
|
||||
CircuitBreaker cb = registry.circuitBreaker("slowBreaker");
|
||||
long[] sleeps = {10, 400, 10, 400};
|
||||
for (int i = 0; i < sleeps.length; i++) {
|
||||
String r = slow.call("c" + (i + 1), sleeps[i]);
|
||||
t.line("call " + (i + 1) + " (" + sleeps[i] + "ms) -> " + r + " [state=" + cb.getState() + "]");
|
||||
}
|
||||
var m = cb.getMetrics();
|
||||
t.line("failureRate=" + m.getFailureRate() + "% slowCallRate=" + m.getSlowCallRate()
|
||||
+ "% numberOfFailedCalls=" + m.getNumberOfFailedCalls()
|
||||
+ " numberOfSlowCalls=" + m.getNumberOfSlowCalls());
|
||||
t.line("call 5 -> " + slow.call("c5", 10));
|
||||
assertThat(m.getNumberOfFailedCalls()).isZero();
|
||||
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||
t.save();
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeLimiterAnswersSlowCallsWithTheFallback() throws Exception {
|
||||
Transcript t = Transcript.start("09-timelimiter.txt", "@TimeLimiter timeoutDuration=500ms");
|
||||
long s1 = System.nanoTime();
|
||||
String fast = timeLimited.lookup("a", 100).get();
|
||||
t.line("100ms call -> " + fast + " (" + (System.nanoTime() - s1) / 1_000_000 / 100 * 100 + "ms bucket)");
|
||||
long s2 = System.nanoTime();
|
||||
String late = timeLimited.lookup("b", 2000).get();
|
||||
long ms = (System.nanoTime() - s2) / 1_000_000;
|
||||
t.line("2000ms call -> " + late + " (caller waited about 500ms, not 2000ms: " + (ms < 1000) + ")");
|
||||
assertThat(fast).isEqualTo("found:a");
|
||||
assertThat(late).isEqualTo("TIMED_OUT:b");
|
||||
assertThat(ms).isBetween(450L, 1000L);
|
||||
t.save();
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutsCountAsFailuresAndEventuallyOpenTheBreaker() throws Exception {
|
||||
Transcript t = Transcript.start("10-timelimiter-plus-breaker.txt",
|
||||
"@CircuitBreaker + @TimeLimiter: timeouts are recorded as failures");
|
||||
CircuitBreaker cb = registry.circuitBreaker("timeoutBreaker");
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
long s = System.nanoTime();
|
||||
String r = timeLimited.guardedLookup("k" + i, 2000).get();
|
||||
t.line("call " + i + " -> " + r + " [state=" + cb.getState() + ", took "
|
||||
+ ((System.nanoTime() - s) / 1_000_000 < 100 ? "<100ms" : "~500ms") + "]");
|
||||
}
|
||||
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||
t.save();
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.ankurm.resilience.r4j;
|
||||
|
||||
import com.ankurm.resilience.FlakyDownstream;
|
||||
import com.ankurm.resilience.Transcript;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Every state transition the post draws, observed through the breaker's own event stream
|
||||
* instead of guessed from return values. Output: 06-state-transitions.txt, 07-fast-state-tests.txt.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@DirtiesContext
|
||||
class StateTransitionsTest {
|
||||
|
||||
@Autowired R4jPaymentService service;
|
||||
@Autowired FlakyDownstream downstream;
|
||||
@Autowired CircuitBreakerRegistry registry;
|
||||
|
||||
@Test
|
||||
void halfOpenFailureSendsTheBreakerStraightBackToOpen() throws InterruptedException {
|
||||
Transcript t = Transcript.start("06-state-transitions.txt",
|
||||
"State transitions seen through the event publisher (downstream stays dead)");
|
||||
CircuitBreaker cb = registry.circuitBreaker("paymentService");
|
||||
cb.reset();
|
||||
List<String> transitions = new ArrayList<>();
|
||||
cb.getEventPublisher().onStateTransition(e ->
|
||||
transitions.add(e.getStateTransition().getFromState() + " -> " + e.getStateTransition().getToState()));
|
||||
downstream.configure(Integer.MAX_VALUE);
|
||||
|
||||
for (int i = 1; i <= 5; i++) service.pay("order-" + i);
|
||||
t.line("after 5 failing calls: state=" + cb.getState());
|
||||
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||
|
||||
int callsBefore = downstream.callsSoFar();
|
||||
Thread.sleep(2200); // waitDurationInOpenState=2s, automatic transition enabled
|
||||
t.line("after waiting 2.2s (no call): state=" + cb.getState());
|
||||
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.HALF_OPEN);
|
||||
|
||||
service.pay("probe-1");
|
||||
service.pay("probe-2");
|
||||
t.line("after 2 failing half-open probes: state=" + cb.getState()
|
||||
+ " (downstream calls during probing: " + (downstream.callsSoFar() - callsBefore) + ")");
|
||||
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||
|
||||
t.blank();
|
||||
t.line("transitions recorded, in order:");
|
||||
transitions.forEach(s -> t.line(" " + s));
|
||||
assertThat(transitions).containsExactly(
|
||||
"CLOSED -> OPEN", "OPEN -> HALF_OPEN", "HALF_OPEN -> OPEN");
|
||||
t.save();
|
||||
}
|
||||
|
||||
@Test
|
||||
void youCanTestFallbackWithoutSleepingByForcingTheState() {
|
||||
Transcript t = Transcript.start("07-fast-state-tests.txt",
|
||||
"Testing without sleeping: force the state, assert the behaviour");
|
||||
CircuitBreaker cb = registry.circuitBreaker("paymentService");
|
||||
cb.reset();
|
||||
downstream.configure(0); // healthy downstream
|
||||
long start = System.nanoTime();
|
||||
|
||||
cb.transitionToOpenState();
|
||||
String whileOpen = service.pay("order-x");
|
||||
t.line("OPEN -> " + whileOpen);
|
||||
assertThat(whileOpen).startsWith("FALLBACK").contains("CallNotPermittedException");
|
||||
assertThat(downstream.callsSoFar()).isZero();
|
||||
|
||||
cb.transitionToHalfOpenState();
|
||||
String probe = service.pay("order-y");
|
||||
t.line("HALF_OPEN -> " + probe);
|
||||
assertThat(probe).startsWith("OK");
|
||||
|
||||
cb.transitionToClosedState();
|
||||
t.line("CLOSED -> " + service.pay("order-z"));
|
||||
|
||||
cb.transitionToForcedOpenState();
|
||||
t.line("FORCED_OPEN -> " + service.pay("order-w"));
|
||||
cb.transitionToClosedState();
|
||||
|
||||
long ms = (System.nanoTime() - start) / 1_000_000;
|
||||
t.line("elapsed under 1s, no Thread.sleep: " + (ms < 1000));
|
||||
assertThat(ms).isLessThan(1000);
|
||||
t.save();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user