public Object ifNotOpen()

in safeguard-impl/src/main/java/org/apache/safeguard/impl/circuitbreaker/CircuitBreakerInterceptor.java [54:92]


    public Object ifNotOpen(final InvocationContext context) throws Exception {
        final Map<Key, CircuitBreakerImpl> circuitBreakers = cache.getCircuitBreakers();
        final Key key = new Key(context, cache.getUnwrappedCache().getUnwrappedCache());
        CircuitBreakerImpl circuitBreaker = circuitBreakers.get(key);
        if (circuitBreaker == null) {
            circuitBreaker = cache.create(context);
            final CircuitBreakerImpl existing = circuitBreakers.putIfAbsent(key, circuitBreaker);
            if (existing != null) {
                circuitBreaker = existing;
            } else {
                cache.postCreate(circuitBreaker, context);
            }
        }
        if (circuitBreaker.disabled) {
            return context.proceed();
        }

        final CheckResult state = circuitBreaker.performStateCheck(CheckType.READ_ONLY);
        if (state == CheckResult.OPEN) {
            circuitBreaker.callsPrevented.inc();
            throw new CircuitBreakerOpenException(context.getMethod() + " circuit breaker is open");
        }
        try {
            final Object result = context.proceed();
            if (state != CheckResult.CLOSED_CHANGED) { // a change triggers a reset we want to preserve
                circuitBreaker.onSuccess();
            }
            circuitBreaker.callsSucceeded.inc();
            return result;
        } catch (final Exception e) {
            if (circuitBreaker.failOn.length > 0 &&
                    Stream.of(circuitBreaker.failOn).anyMatch(it -> it.isInstance(e) || it.isInstance(e.getCause()))) {
                circuitBreaker.onFailure();
            } else {
                circuitBreaker.callsSucceeded.inc();
            }
            throw e;
        }
    }