Skip to content

Commit

Permalink
Merge pull request ReactiveX#76 from cpilsworth/feature/retrofit-circ…
Browse files Browse the repository at this point in the history
…uitbreaker

Migrated cpilsworth/retrofit-circuitbreaker to the resilience4j project
  • Loading branch information
storozhukBM committed Mar 29, 2017
2 parents 20851c1 + 3831d19 commit debb93f
Show file tree
Hide file tree
Showing 9 changed files with 474 additions and 0 deletions.
6 changes: 6 additions & 0 deletions libraries.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ext {
metricsVersion = '3.1.2'
vertxVersion = '3.4.1'
springBootVersion = '1.4.3.RELEASE'
retrofitVersion = '2.1.0'

libraries = [
// compile
Expand Down Expand Up @@ -41,6 +42,11 @@ ext {
spring_boot_web: "org.springframework.boot:spring-boot-starter-web:${springBootVersion}",
spring_boot_test: "org.springframework.boot:spring-boot-starter-test:${springBootVersion}",

// retrofit addon
retrofit: "com.squareup.retrofit2:retrofit:${retrofitVersion}",
retrofit_test: "com.squareup.retrofit2:converter-scalars:${retrofitVersion}",
retrofit_wiremock: "com.github.tomakehurst:wiremock:1.58",

// circuitbreaker documentation
metrics: "io.dropwizard.metrics:metrics-core:${metricsVersion}",
metrics_healthcheck: "io.dropwizard.metrics:metrics-healthchecks:${metricsVersion}"
Expand Down
34 changes: 34 additions & 0 deletions resilience4j-documentation/src/docs/asciidoc/retrofit.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
= resilience4j-retrofit

https://square.github.io/retrofit/[Retrofit] client circuit breaking. Short-circuits http client calls based upon the policy
associated to the CircuitBreaker instance provided.

For circuit breaking triggered by timeout the thresholds can be set
on a OkHttpClient which can be set on the Retrofit.Builder.

[source,java]
----
// Create a CircuitBreaker
private final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
// Create a retrofit instance with CircuitBreaker call adapter
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
.baseUrl("http://localhost:8080/")
.build();
// Get an instance of your service with circuit breaking built in.
RetrofitService service = retrofit.create(RetrofitService.class);
----

By default, all exceptions and responses where `!Response.isSuccessful()` will be recorded as an error in the CircuitBreaker.

Customising what is considered a _successful_ response is possible like so:

[source,java]
----
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker, (r) -> r.code() < 500));
.baseUrl("http://localhost:8080/")
.build();
----
44 changes: 44 additions & 0 deletions resilience4j-retrofit/README.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
= resilience4j-retrofit

https://square.github.io/retrofit/[Retrofit] client circuit breaking. Short-circuits http client calls based upon the policy
associated to the CircuitBreaker instance provided.

For circuit breaking triggered by timeout the thresholds can be set
on a OkHttpClient which can be set on the Retrofit.Builder.

[source,java]
----
// Create a CircuitBreaker
private final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
// Create a retrofit instance with CircuitBreaker call adapter
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
.baseUrl("http://localhost:8080/")
.build();
// Get an instance of your service with circuit breaking built in.
RetrofitService service = retrofit.create(RetrofitService.class);
----

By default, all exceptions and responses where `!Response.isSuccessful()` will be recorded as an error in the CircuitBreaker.

Customising what is considered a _successful_ response is possible like so:

[source,java]
----
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker, (r) -> r.code() < 500));
.baseUrl("http://localhost:8080/")
.build();
----

== License

Copyright 2017 Christopher Pilsworth

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

http://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.
6 changes: 6 additions & 0 deletions resilience4j-retrofit/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
dependencies {
compile ( libraries.retrofit )
compile project(':resilience4j-circuitbreaker')
testCompile ( libraries.retrofit_test )
testCompile ( libraries.retrofit_wiremock )
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
*
* Copyright 2017 Christopher Pilsworth
*
* 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
*
* http://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.github.resilience4j.retrofit;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.Predicate;

/**
* Creates a Retrofit {@link CallAdapter.Factory} that decorates a Call to provide integration with a
* {@link CircuitBreaker} using {@link RetrofitCircuitBreaker}
*/
public final class CircuitBreakerCallAdapter extends CallAdapter.Factory {

private final CircuitBreaker circuitBreaker;
private final Predicate<Response> successResponse;

/**
* Create a circuit-breaking call adapter that decorates retrofit calls
* @param circuitBreaker circuit breaker to use
* @return a {@link CallAdapter.Factory} that can be passed into the {@link Retrofit.Builder}
*/
public static CircuitBreakerCallAdapter of(final CircuitBreaker circuitBreaker) {
return of(circuitBreaker, Response::isSuccessful);
}

/**
* Create a circuit-breaking call adapter that decorates retrofit calls
* @param circuitBreaker circuit breaker to use
* @param successResponse {@link Predicate} that determines whether the {@link Call} {@link Response} should be considered successful
* @return a {@link CallAdapter.Factory} that can be passed into the {@link Retrofit.Builder}
*/
public static CircuitBreakerCallAdapter of(final CircuitBreaker circuitBreaker, final Predicate<Response> successResponse) {
return new CircuitBreakerCallAdapter(circuitBreaker, successResponse);
}

private CircuitBreakerCallAdapter(final CircuitBreaker circuitBreaker, final Predicate<Response> successResponse) {
this.circuitBreaker = circuitBreaker;
this.successResponse = successResponse;
}

@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}

final Type responseType = getCallResponseType(returnType);
return new CallAdapter<Call<?>>() {
@Override
public Type responseType() {
return responseType;
}

@Override
public <R> Call<R> adapt(Call<R> call) {
return RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, successResponse);
}
};
}

private static Type getCallResponseType(Type returnType) {
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
return getParameterUpperBound(0, (ParameterizedType) returnType);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
*
* Copyright 2017 Christopher Pilsworth
*
* 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
*
* http://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.github.resilience4j.retrofit;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.utils.CircuitBreakerUtils;
import io.github.resilience4j.metrics.StopWatch;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.util.function.Predicate;

/**
* Decorates a Retrofit {@link Call} to inform a Javaslang {@link CircuitBreaker} when an exception is thrown.
* All exceptions are marked as errors or responses not matching the supplied predicate. For example:
* <p>
* <code>
* RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, Response::isSuccessful);
* </code>
*/
public interface RetrofitCircuitBreaker {

/**
* Decorate {@link Call}s allow {@link CircuitBreaker} functionality.
*
* @param circuitBreaker {@link CircuitBreaker} to apply
* @param call Call to decorate
* @param responseSuccess determines whether the response should be considered an expected response
* @param <T> Response type of call
* @return Original Call decorated with CircuitBreaker
*/
static <T> Call<T> decorateCall(final CircuitBreaker circuitBreaker, final Call<T> call, final Predicate<Response> responseSuccess) {
return new Call<T>() {
@Override
public Response<T> execute() throws IOException {
CircuitBreakerUtils.isCallPermitted(circuitBreaker);
final StopWatch stopWatch = StopWatch.start(circuitBreaker.getName());
try {
final Response<T> response = call.execute();

if (responseSuccess.test(response)) {
circuitBreaker.onSuccess(stopWatch.stop().getProcessingDuration());
} else {
final Throwable throwable = new Throwable("Response error: HTTP " + response.code() + " - " + response.message());
circuitBreaker.onError(stopWatch.stop().getProcessingDuration(), throwable);
}

return response;
} catch (Throwable throwable) {
circuitBreaker.onError(stopWatch.stop().getProcessingDuration(), throwable);
throw throwable;
}
}

@Override
public void enqueue(Callback<T> callback) {
call.enqueue(callback);
}

@Override
public boolean isExecuted() {
return call.isExecuted();
}

@Override
public void cancel() {
call.cancel();
}

@Override
public boolean isCanceled() {
return call.isCanceled();
}

@Override
public Call<T> clone() {
return decorateCall(circuitBreaker, call.clone(), responseSuccess);
}

@Override
public Request request() {
return call.request();
}
};
}

}
Loading

0 comments on commit debb93f

Please sign in to comment.