org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException Java Examples

The following examples show how to use org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CircuitBreakerStateTest.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncCircuitBreaker(HelloService helloService, HelloService.CB cb) {
    for (int i = 0; i < HelloService.THRESHOLD; i++) {
        assertThrows(IOException.class, () -> {
            helloService.hello(new IOException());
        });
    }

    assertEquals(CircuitBreakerState.OPEN, cb.state);

    await().atMost(HelloService.DELAY * 2, TimeUnit.MILLISECONDS)
            .ignoreException(CircuitBreakerOpenException.class)
            .untilAsserted(() -> {
                assertEquals(HelloService.OK, helloService.hello(null));
            });

    assertEquals(CircuitBreakerState.CLOSED, cb.state);
}
 
Example #2
Source File: CompletionStageCircuitBreaker.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
private CompletionStage<V> inOpen(InvocationContext<CompletionStage<V>> ctx, CircuitBreaker.State state) throws Exception {
    if (state.runningStopwatch.elapsedTimeInMillis() < delayInMillis) {
        metricsRecorder.circuitBreakerRejected();
        listeners.forEach(CircuitBreakerListener::rejected);
        return failedStage(new CircuitBreakerOpenException(description + " circuit breaker is open"));
    } else {
        long now = System.nanoTime();

        halfOpenStart = now;
        previousOpenTime.addAndGet(now - openStart);

        toHalfOpen(state, ctx);
        // start over to re-read current state; no hard guarantee that it's HALF_OPEN at this point
        return apply(ctx);
    }
}
 
Example #3
Source File: CircuitBreaker.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
private V inOpen(InvocationContext<V> ctx, State state) throws Exception {
    if (state.runningStopwatch.elapsedTimeInMillis() < delayInMillis) {
        metricsRecorder.circuitBreakerRejected();
        listeners.forEach(CircuitBreakerListener::rejected);
        throw new CircuitBreakerOpenException(description + " circuit breaker is open");
    } else {
        long now = System.nanoTime();

        halfOpenStart = now;
        previousOpenTime.addAndGet(now - openStart);

        toHalfOpen(state, ctx);
        // start over to re-read current state; no hard guarantee that it's HALF_OPEN at this point
        return apply(ctx);
    }
}
 
Example #4
Source File: CommandInterceptorTest.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * A test to exercise Circuit Breaker thresholds with sufficient retries to open the Circuit and result in a
 * CircuitBreakerOpenException.
 */
@Test
public void testCircuitOpenWithMoreRetries() {
    int invokeCounter = 0;
    try {
        serviceRetry.sayHelloRetry();
        invokeCounter = serviceRetry.getSayHelloRetry();
        if (invokeCounter < 4) {
            fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration " + invokeCounter);
        }
    } catch (CircuitBreakerOpenException cboe) {
        // Expected on iteration 4
        invokeCounter = serviceRetry.getSayHelloRetry();
        if (invokeCounter < 4) {
            fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration " + invokeCounter);
        }
    } catch (Exception ex) {
        // Not Expected
        invokeCounter = serviceRetry.getSayHelloRetry();
        fail("serviceA should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMoreRetries on iteration "
                + invokeCounter);
    }

    invokeCounter = serviceRetry.getSayHelloRetry();
    assertEquals("The number of executions should be 4", 4, invokeCounter);
}
 
Example #5
Source File: CircuitBreakerLifecycleTest.java    From microprofile-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
public void noSharingBetweenMethodsOfOneClass() {
    MutlipleMethodsCircuitBreakerLifecycleService multipleMethodsService1 = multipleMethodsService.get();
    MutlipleMethodsCircuitBreakerLifecycleService multipleMethodsService2 = multipleMethodsService.get();

    try {
        for (int i = 0; i < 4; i++) {
            assertThrows(IOException.class, multipleMethodsService1::service1);
            assertThrows(IOException.class, multipleMethodsService1::service2);
            assertThrows(IOException.class, multipleMethodsService2::service1);
            assertThrows(IOException.class, multipleMethodsService2::service2);
        }

        assertThrows(CircuitBreakerOpenException.class, multipleMethodsService1::service1);
        assertThrows(CircuitBreakerOpenException.class, multipleMethodsService1::service2);
        assertThrows(CircuitBreakerOpenException.class, multipleMethodsService2::service1);
        assertThrows(CircuitBreakerOpenException.class, multipleMethodsService2::service2);
    }
    finally {
        multipleMethodsService.destroy(multipleMethodsService1);
        multipleMethodsService.destroy(multipleMethodsService2);
    }
}
 
Example #6
Source File: CircuitBreakerAndRetryTest.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRetryCircuitBreakerInHalfOpenOrOpenAndFail() {
    CircuitBreakerRecorder recorder = new CircuitBreakerRecorder();

    // fail 5x and then succeed
    // CB volume threshold = 5, so the CB will open right after all the failures and before the success
    // CB delay is > 0, so the successful attempt will be prevented, because the CB will be open
    // doing 11 attemps (1 initial + 10 retries, because max retries = 10)
    FaultToleranceStrategy<String> operation = retry(
            circuitBreaker(
                    TestInvocation.initiallyFailing(5, TestException::new, () -> "foobar"),
                    100, recorder));

    assertThatThrownBy(() -> operation.apply(null)).isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThat(recorder.failureCount.get()).isEqualTo(5);
    assertThat(recorder.rejectedCount.get()).isEqualTo(6);
    assertThat(recorder.successCount.get()).isEqualTo(0);
}
 
Example #7
Source File: CompletionStageCircuitBreakerTest.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTreatCompletionStageFailureAsCBFailure() throws Exception {
    TestException exception = new TestException();

    CompletionStageCircuitBreaker<String> cb = new CompletionStageCircuitBreaker<>(invocation(), "test invocation",
            testException, SetOfThrowables.EMPTY,
            1000, 4, 0.5, 2, stopwatch, null);

    assertThatThrownBy(cb.apply(eventuallyFailingWith(exception)).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCause(exception);
    assertThatThrownBy(cb.apply(eventuallyFailingWith(exception)).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCause(exception);
    assertThatThrownBy(cb.apply(eventuallyFailingWith(exception)).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCause(exception);
    assertThatThrownBy(cb.apply(eventuallyFailingWith(exception)).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCause(exception);

    assertThatThrownBy(cb.apply(eventuallyFailingWith(exception)).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
}
 
Example #8
Source File: DisableAnnotationGloballyEnableOnClassTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #9
Source File: DisableAnnotationOnClassEnableOnMethodTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #10
Source File: CircuitBreakerMetricTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@BeforeTest
public void closeTheCircuit() throws Exception {

    // Condition is needed because BeforeTest runs on both client and server
    if (cbBean != null) {
        
        // Assume the circuit is open
        // Attempt to put successful work through it until it stops throwing CircuitBreakerOpenExceptions
        boolean circuitOpen = true;
        long startTime = System.nanoTime();
        while (circuitOpen && System.nanoTime() - startTime < CB_CLOSE_TIMEOUT) {
            try {
                for (int i = 0; i < 2; i++) {
                    cbBean.doWork(Result.PASS);
                }
                circuitOpen = false;
            }
            catch (CircuitBreakerOpenException e) {
                Thread.sleep(100);
            }
        }
        
        if (circuitOpen) {
            throw new RuntimeException("Timed out waiting for circuit breaker to close");
        }
    }
}
 
Example #11
Source File: CircuitBreakerLifecycleTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void noSharingBetweenClasses() {
    CircuitBreakerLifecycleService1 service1a = service1.get();
    CircuitBreakerLifecycleService1 service1b = service1.get();

    CircuitBreakerLifecycleService2 service2a = service2.get();
    CircuitBreakerLifecycleService2 service2b = service2.get();

    try {
        for (int i = 0; i < 4; i++) {
            assertThrows(IOException.class, service1a::service);
            assertThrows(IOException.class, service2a::service);
            assertThrows(IOException.class, service1b::service);
            assertThrows(IOException.class, service2b::service);
        }

        assertThrows(CircuitBreakerOpenException.class, service1a::service);
        assertThrows(CircuitBreakerOpenException.class, service2a::service);
        assertThrows(CircuitBreakerOpenException.class, service1b::service);
        assertThrows(CircuitBreakerOpenException.class, service2b::service);
    }
    finally {
        service1.destroy(service1a);
        service1.destroy(service1b);
        service2.destroy(service2a);
        service2.destroy(service2b);
    }
}
 
Example #12
Source File: CircuitBreakerClientWithRetryAsync.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Has a CircuitBreaker and Retries on CircuitBreakerOpenException
 * 
 * @param throwException whether this method should throw a runtime exception to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(retryOn = CircuitBreakerOpenException.class, maxRetries = 20, delay = 100, jitter = 0)
@Asynchronous
// Scaled via config
public Future<String> serviceWithRetryOnCbOpen(boolean throwException) {
    if (throwException) {
        throw new TestException("Test Exception");
    }
    else {
        return CompletableFuture.completedFuture("OK");
    }
}
 
Example #13
Source File: CircuitBreakerClientWithRetryAsync.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Has a CircuitBreaker and Retries on all exceptions except TestException and CircuitBreakerOpenException
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(abortOn = { TestException.class, CircuitBreakerOpenException.class }, maxRetries = 20, delay = 200)
@Asynchronous
// Delays scaled via config
public Future<String> serviceWithRetryFailOnCbOpen(boolean throwException) {
    if (throwException) {
        throw new TestException("Test Exception");
    }
    else {
        return CompletableFuture.completedFuture("OK");
    }
}
 
Example #14
Source File: CircuitBreakerClientWithRetry.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Has a CircuitBreaker and Retries on CircuitBreakerOpenException
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(retryOn = CircuitBreakerOpenException.class, maxRetries = 20, delay = 100, jitter = 0)
// Scaled via config
public String serviceWithRetryOnCbOpen(boolean throwException) {
    if (throwException) {
        throw new TestException();
    }
    else {
        return "OK";
    }
}
 
Example #15
Source File: CircuitBreakerClientWithRetry.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Has a CircuitBreaker and Retries on all exceptions except TestException and CircuitBreakerOpenException
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(abortOn = { TestException.class, CircuitBreakerOpenException.class }, maxRetries = 20, delay = 200)
// Scaled via config
public String serviceWithRetryFailOnCbOpen(boolean throwException) {
    if (throwException) {
        throw new TestException();
    }
    else {
        return "OK";
    }
}
 
Example #16
Source File: CircuitBreakerRetryTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * A test to exercise Circuit Breaker thresholds with sufficient retries to open the
 * Circuit and result in a CircuitBreakerOpenException.
 */
@Test
public void testCircuitOpenWithMoreRetries() {
    int invokeCounter = 0;
    try {
        clientForCBWithRetry.serviceA();

        // serviceA should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException
        // should be thrown. Assert if this does not happen.
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }
    catch (CircuitBreakerOpenException cboe) {
        // Expected on iteration 4
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceA();
        if (invokeCounter < 4) {
            Assert.fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration "
                            + invokeCounter);
        }
    }
    catch (Exception ex) {
        // Not Expected
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }

    invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceA();
    Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4");
}
 
Example #17
Source File: CircuitBreakerRetryTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Analogous to testCircuitOpenWithMoreRetries with Class level @CircuitBreaker and @Retry annotations
 * that are inherited by serviceA
 */
@Test
public void testClassLevelCircuitOpenWithMoreRetries() {
    int invokeCounter = 0;
    try {
        clientForClassLevelCBWithRetry.serviceA();

        // serviceA should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException
        // should be thrown. Assert if this does not happen.
        invokeCounter = clientForClassLevelCBWithRetry.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry in testClassLevelCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }
    catch (CircuitBreakerOpenException cboe) {
        // Expected on iteration 4
        invokeCounter = clientForClassLevelCBWithRetry.getCounterForInvokingServiceA();
        if (invokeCounter < 4) {
            Assert.fail("serviceA should retry in testClassLevelCircuitOpenWithMoreRetries on iteration "
                            + invokeCounter);
        }
    }
    catch (Exception ex) {
        // Not Expected
        invokeCounter = clientForClassLevelCBWithRetry.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry or throw a CircuitBreakerOpenException in testClassLevelCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }

    invokeCounter = clientForClassLevelCBWithRetry.getCounterForInvokingServiceA();
    Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4");
}
 
Example #18
Source File: CircuitBreakerRetryTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Analogous to testCircuitOpenWithMoreRetries but execution failures are caused by timeouts.
 */
@Test
public void testCircuitOpenWithMultiTimeouts() {
    int invokeCounter = 0;
    try {
        clientForCBWithRetry.serviceC();

        // serviceC should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException
        // should be thrown. Assert if this does not happen.
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceC();
        Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration "
                            + invokeCounter);

    }
    catch (CircuitBreakerOpenException cboe) {
        // Expected on iteration 4
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceC();
        if (invokeCounter < 4) {
            Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration "
                            + invokeCounter);
        }
    }
    catch (Exception ex) {
        // Not Expected
        invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceC();
        Assert.fail("serviceC should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMultiTimeouts on iteration "
                        + invokeCounter + ", caught exception: " + ex);
    }

    invokeCounter = clientForCBWithRetry.getCounterForInvokingServiceC();
    Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4");
}
 
Example #19
Source File: CircuitBreakerRetryTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * A test to exercise Circuit Breaker thresholds with sufficient retries to open the
 * Circuit and result in a CircuitBreakerOpenException using an Asynchronous call.
 */
@Test
public void testCircuitOpenWithMoreRetriesAsync() {
    int invokeCounter = 0;
    Future<Connection> result = clientForCBWithRetryAsync.serviceA();
    try {
        result.get(TCKConfig.getConfig().getTimeoutInMillis(5000), TimeUnit.MILLISECONDS);

        // serviceA should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException
        // should be thrown. Assert if this does not happen.
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }
    catch (ExecutionException executionException) {
        // Expected execution exception wrapping CircuitBreakerOpenException
        MatcherAssert.assertThat("Thrown exception is the wrong type",
                                 executionException.getCause(),
                                 instanceOf(CircuitBreakerOpenException.class));

        // Expected on iteration 4
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceA();
        if (invokeCounter < 4) {
            Assert.fail("serviceA should retry in testCircuitOpenWithMoreRetries on iteration "
                            + invokeCounter);
        }
    }
    catch (Exception ex) {
        // Not Expected
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceA();
        Assert.fail("serviceA should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMoreRetries on iteration "
                        + invokeCounter);
    }

    invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceA();
    Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4");
}
 
Example #20
Source File: CircuitBreakerRetryTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Analogous to testCircuitOpenWithMoreRetriesAsync but execution failures are caused by timeouts.
 */
@Test
public void testCircuitOpenWithMultiTimeoutsAsync() {
    int invokeCounter = 0;
    Future<Connection> result = clientForCBWithRetryAsync.serviceC();
    try {
        result.get(TCKConfig.getConfig().getTimeoutInMillis(10000), TimeUnit.MILLISECONDS); // Expected to finish after < 1 second

        // serviceC should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException
        // should be thrown. Assert if this does not happen.
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC();
        Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration "
                            + invokeCounter);

    }
    catch (ExecutionException executionException) {
        // Expected execution exception wrapping CircuitBreakerOpenException
        MatcherAssert.assertThat("Thrown exception is the wrong type",
                                 executionException.getCause(),
                                 instanceOf(CircuitBreakerOpenException.class));

        // Expected on iteration 4
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC();
        if (invokeCounter < 4) {
            Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration "
                            + invokeCounter);
        }
    }
    catch (Exception ex) {
        // Not Expected
        invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC();
        Assert.fail("serviceC should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMultiTimeouts on iteration "
                        + invokeCounter + ", caught exception: " + ex);
    }

    invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC();
    Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4");
}
 
Example #21
Source File: DisableAnnotationGloballyEnableOnMethodTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #22
Source File: DisableFTEnableOnClassTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #23
Source File: DisableFTEnableOnMethodTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #24
Source File: DisableFTEnableGloballyTest.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * CircuitBreaker is enabled on the method so the policy should be applied
 */
@Test
public void testCircuitBreaker() {
    // Always get TestException on first execution
    Assert.assertThrows(TestException.class, () -> disableClient.failWithCircuitBreaker());
    // Should get CircuitBreakerOpenException on second execution because CircuitBreaker is enabled
    Assert.assertThrows(CircuitBreakerOpenException.class, () -> disableClient.failWithCircuitBreaker());
}
 
Example #25
Source File: FaultToleranceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircuitBreaker() {
    circuitbreaker.breakCircuit();
    assertThrows(RuntimeException.class, () -> circuitbreaker.breakCircuit());
    assertThrows(RuntimeException.class, () -> circuitbreaker.breakCircuit());
    assertThrows(RuntimeException.class, () -> circuitbreaker.breakCircuit());
    assertThrows(RuntimeException.class, () -> circuitbreaker.breakCircuit());
    assertThrows(CircuitBreakerOpenException.class, () -> circuitbreaker.breakCircuit());
    assertTrue(circuitBreakerObserver.isOpen());
}
 
Example #26
Source File: CompletionStageCircuitBreakerTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void test2() throws Exception {
    CompletionStageCircuitBreaker<String> cb = new CompletionStageCircuitBreaker<>(invocation(), "test invocation",
            testException, SetOfThrowables.EMPTY,
            1000, 4, 0.5, 2, stopwatch, null);

    // circuit breaker is closed
    assertThat(cb.apply(returning("foobar1")).toCompletableFuture().get()).isEqualTo("foobar1");
    assertThatThrownBy(cb.apply(immediatelyFailingWith(new TestException())).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(TestException.class);
    assertThatThrownBy(cb.apply(immediatelyFailingWith(new TestException())).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(TestException.class);
    assertThat(cb.apply(returning("foobar2")).toCompletableFuture().get()).isEqualTo("foobar2");
    // circuit breaker is open
    assertThatThrownBy(cb.apply(returning("ignored")).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(cb.apply(returning("ignored")).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(cb.apply(returning("ignored")).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(cb.apply(returning("ignored")).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(cb.apply(returning("ignored")).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class).hasCauseInstanceOf(CircuitBreakerOpenException.class);
    stopwatch.setCurrentValue(1500);
    assertThat(cb.apply(returning("foobar3")).toCompletableFuture().get()).isEqualTo("foobar3");
    // circuit breaker is half-open
    assertThat(cb.apply(returning("foobar4")).toCompletableFuture().get()).isEqualTo("foobar4");
    // circuit breaker is closed
    assertThat(cb.apply(returning("foobar5")).toCompletableFuture().get()).isEqualTo("foobar5");
}
 
Example #27
Source File: CircuitBreakerTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void test2() throws Exception {
    CircuitBreaker<String> cb = new CircuitBreaker<>(invocation(), "test invocation", testException,
            SetOfThrowables.EMPTY, 1000, 4, 0.5, 2, stopwatch, null);

    // circuit breaker is closed
    assertThat(cb.apply(new InvocationContext<>(() -> "foobar1"))).isEqualTo("foobar1");
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(TestException::doThrow)))
            .isExactlyInstanceOf(TestException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(TestException::doThrow)))
            .isExactlyInstanceOf(TestException.class);
    assertThat(cb.apply(new InvocationContext<>(() -> "foobar2"))).isEqualTo("foobar2");
    // circuit breaker is open
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> "ignored")))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> "ignored")))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> "ignored")))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> "ignored")))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> "ignored")))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    stopwatch.setCurrentValue(1500);
    assertThat(cb.apply(new InvocationContext<>(() -> "foobar3"))).isEqualTo("foobar3");
    // circuit breaker is half-open
    assertThat(cb.apply(new InvocationContext<>(() -> "foobar4"))).isEqualTo("foobar4");
    // circuit breaker is closed
    assertThat(cb.apply(new InvocationContext<>(() -> "foobar5"))).isEqualTo("foobar5");
}
 
Example #28
Source File: FutureCircuitBreakerTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void test2() throws Exception {
    CircuitBreaker<Future<String>> cb = new CircuitBreaker<>(invocation(),
            "test invocation", testException, SetOfThrowables.EMPTY,
            1000, 4, 0.5, 2, stopwatch, null);

    // circuit breaker is closed
    Future<String> foobar1 = cb.apply(new InvocationContext<>(() -> completedFuture("foobar1")));
    assertThat(foobar1.get()).isEqualTo("foobar1");
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(TestException::doThrow)))
            .isExactlyInstanceOf(TestException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(TestException::doThrow)))
            .isExactlyInstanceOf(TestException.class);
    Future<String> foobar2 = cb.apply(new InvocationContext<>(() -> completedFuture("foobar2")));
    assertThat(foobar2.get()).isEqualTo("foobar2");
    // circuit breaker is open
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> completedFuture("ignored"))))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> completedFuture("ignored"))))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> completedFuture("ignored"))))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> completedFuture("ignored"))))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    assertThatThrownBy(() -> cb.apply(new InvocationContext<>(() -> completedFuture("ignored"))))
            .isExactlyInstanceOf(CircuitBreakerOpenException.class);
    stopwatch.setCurrentValue(1500);
    assertThat(cb.apply(new InvocationContext<>(() -> completedFuture("foobar3"))).get()).isEqualTo("foobar3");
    // circuit breaker is half-open
    assertThat(cb.apply(new InvocationContext<>(() -> completedFuture("foobar4"))).get()).isEqualTo("foobar4");
    // circuit breaker is closed
    assertThat(cb.apply(new InvocationContext<>(() -> completedFuture("foobar5"))).get()).isEqualTo("foobar5");
}
 
Example #29
Source File: AsyncHelloService.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Retry(retryOn = IOException.class)
@CircuitBreaker(failOn = IOException.class, requestVolumeThreshold = 5, successThreshold = 3, delay = 2, delayUnit = ChronoUnit.SECONDS, failureRatio = 0.75)
@Fallback(fallbackMethod = "fallback", applyOn = { IOException.class, CircuitBreakerOpenException.class })
public CompletionStage<String> helloFailAsync(int counter) {
    // 3/4 requests trigger IOException
    if (counter % 4 != 0) {
        CompletableFuture<String> result = new CompletableFuture<>();
        result.completeExceptionally(new IOException("Simulated IOException"));
        return result;
    }

    return completedFuture("Hello" + counter);
}
 
Example #30
Source File: AsyncHelloService.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Retry(retryOn = IOException.class)
@CircuitBreaker(failOn = IOException.class, requestVolumeThreshold = 5, successThreshold = 3, delay = 2, delayUnit = ChronoUnit.SECONDS, failureRatio = 0.75)
@Fallback(fallbackMethod = "fallback", applyOn = { IOException.class, CircuitBreakerOpenException.class })
public CompletionStage<String> hello(int counter) throws IOException {
    // 3/4 requests trigger IOException
    if (counter % 4 != 0) {
        throw new IOException("Simulated IOException");
    }

    return completedFuture("Hello" + counter);
}