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:
2026-11-12 10:58:25 +05:30
co-authored by Claude Sonnet 5.5
parent ae696369ba
commit a04d65ba57
14 changed files with 509 additions and 5 deletions
@@ -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) {
@@ -0,0 +1,65 @@
package com.ankurm.resilience.r4j;
import com.ankurm.resilience.Transcript;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
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: 13-abandoned-work.txt, 14-bad-fallback-signature.txt, 15-defaults.txt. */
@SpringBootTest
@DirtiesContext
class ClaimsCheckTest {
@Autowired R4jTimeLimiterService timeLimited;
@Autowired R4jBadFallbackService bad;
@Test
void timeLimiterStopsWaitingButTheWorkStillFinishes() throws Exception {
Transcript t = Transcript.start("13-abandoned-work.txt", "What happens to the call the TimeLimiter gave up on?");
timeLimited.finishedWork().set(0);
String r = timeLimited.lookup("z", 1500).get();
t.line("caller got: " + r);
t.line("finished work right after timeout: " + timeLimited.finishedWork().get());
Thread.sleep(1500);
t.line("finished work 1.5s later: " + timeLimited.finishedWork().get());
assertThat(r).isEqualTo("TIMED_OUT:z");
assertThat(timeLimited.finishedWork().get()).isEqualTo(1);
t.save();
}
@Test
void mismatchedFallbackSignatureFailsAtCallTime() {
Transcript t = Transcript.start("14-bad-fallback-signature.txt", "Fallback whose parameters do not match the method");
t.line("application context started without complaint; the mistakes only show on a call");
t.blank();
Throwable mismatched = null;
try { bad.pay("o-1"); } catch (Throwable e) { mismatched = e; }
t.line("fallback exists, wrong parameters -> " + mismatched.getClass().getName() + ": " + mismatched.getMessage());
Throwable missing = null;
try { bad.payMissing("o-2"); } catch (Throwable e) { missing = e; }
t.line("fallback name does not exist -> " + missing.getClass().getName() + ": " + missing.getMessage());
assertThat(mismatched).isNotNull();
assertThat(missing).isNotNull();
t.save();
}
@Test
void printLibraryDefaults() {
Transcript t = Transcript.start("15-defaults.txt", "CircuitBreakerConfig.ofDefaults() in Resilience4j 2.4.0");
CircuitBreakerConfig c = CircuitBreakerConfig.ofDefaults();
t.line("slidingWindowType = " + c.getSlidingWindowType());
t.line("slidingWindowSize = " + c.getSlidingWindowSize());
t.line("minimumNumberOfCalls = " + c.getMinimumNumberOfCalls());
t.line("failureRateThreshold = " + c.getFailureRateThreshold());
t.line("slowCallRateThreshold = " + c.getSlowCallRateThreshold());
t.line("slowCallDurationThreshold = " + c.getSlowCallDurationThreshold());
t.line("waitIntervalFunctionInOpenState(1) = " + c.getWaitIntervalFunctionInOpenState().apply(1) + " ms");
t.line("permittedNumberOfCallsInHalfOpenState = " + c.getPermittedNumberOfCallsInHalfOpenState());
t.line("automaticTransitionFromOpenToHalfOpen = " + c.isAutomaticTransitionFromOpenToHalfOpenEnabled());
t.save();
}
}
@@ -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();
}
}
@@ -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();
}
}
@@ -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();
}
}