diff --git a/libraries.gradle b/libraries.gradle index f3ff4ba771..e706380dbe 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -14,6 +14,7 @@ ext { metricsVersion = '3.1.2' vertxVersion = '3.4.1' springBootVersion = '1.4.3.RELEASE' + retrofitVersion = '2.1.0' libraries = [ // compile @@ -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}" diff --git a/resilience4j-documentation/src/docs/asciidoc/retrofit.adoc b/resilience4j-documentation/src/docs/asciidoc/retrofit.adoc new file mode 100644 index 0000000000..a7b4d60fbc --- /dev/null +++ b/resilience4j-documentation/src/docs/asciidoc/retrofit.adoc @@ -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(); +---- \ No newline at end of file diff --git a/resilience4j-retrofit/README.adoc b/resilience4j-retrofit/README.adoc new file mode 100644 index 0000000000..f2ce755df0 --- /dev/null +++ b/resilience4j-retrofit/README.adoc @@ -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. \ No newline at end of file diff --git a/resilience4j-retrofit/build.gradle b/resilience4j-retrofit/build.gradle new file mode 100644 index 0000000000..082b7fcce7 --- /dev/null +++ b/resilience4j-retrofit/build.gradle @@ -0,0 +1,6 @@ +dependencies { + compile ( libraries.retrofit ) + compile project(':resilience4j-circuitbreaker') + testCompile ( libraries.retrofit_test ) + testCompile ( libraries.retrofit_wiremock ) +} \ No newline at end of file diff --git a/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/CircuitBreakerCallAdapter.java b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/CircuitBreakerCallAdapter.java new file mode 100644 index 0000000000..b0f3f12de4 --- /dev/null +++ b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/CircuitBreakerCallAdapter.java @@ -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 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 successResponse) { + return new CircuitBreakerCallAdapter(circuitBreaker, successResponse); + } + + private CircuitBreakerCallAdapter(final CircuitBreaker circuitBreaker, final Predicate 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>() { + @Override + public Type responseType() { + return responseType; + } + + @Override + public Call adapt(Call 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 or Call"); + } + return getParameterUpperBound(0, (ParameterizedType) returnType); + } + +} \ No newline at end of file diff --git a/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java new file mode 100644 index 0000000000..d9748e4c89 --- /dev/null +++ b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java @@ -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: + *

+ * + * RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, Response::isSuccessful); + * + */ +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 Response type of call + * @return Original Call decorated with CircuitBreaker + */ + static Call decorateCall(final CircuitBreaker circuitBreaker, final Call call, final Predicate responseSuccess) { + return new Call() { + @Override + public Response execute() throws IOException { + CircuitBreakerUtils.isCallPermitted(circuitBreaker); + final StopWatch stopWatch = StopWatch.start(circuitBreaker.getName()); + try { + final Response 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 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 clone() { + return decorateCall(circuitBreaker, call.clone(), responseSuccess); + } + + @Override + public Request request() { + return call.request(); + } + }; + } + +} \ No newline at end of file diff --git a/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitCircuitBreakerTest.java b/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitCircuitBreakerTest.java new file mode 100644 index 0000000000..131c86845a --- /dev/null +++ b/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitCircuitBreakerTest.java @@ -0,0 +1,155 @@ +/* + * + * 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 com.github.tomakehurst.wiremock.junit.WireMockRule; +import io.github.resilience4j.circuitbreaker.CircuitBreaker; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import okhttp3.OkHttpClient; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import retrofit2.Call; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; + +/** + * Tests the integration of the Retrofit HTTP client and {@link CircuitBreaker} + */ +public class RetrofitCircuitBreakerTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(); + + private RetrofitService service; + private final CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .ringBufferSizeInClosedState(3) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .build(); + private final CircuitBreaker circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig); + + @Before + public void setUp() { + final long TIMEOUT = 300; // ms + OkHttpClient client = new OkHttpClient.Builder() + .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS) + .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS) + .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS) + .build(); + + this.service = new Retrofit.Builder() + .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker)) + .addConverterFactory(ScalarsConverterFactory.create()) + .baseUrl("http://localhost:8080/") + .client(client) + .build() + .create(RetrofitService.class); + } + + @Test + public void decorateSuccessfulCall() throws Exception { + stubFor(get(urlPathEqualTo("/greeting")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/plain") + .withBody("hello world"))); + + service.greeting().execute(); + + verify(1, getRequestedFor(urlPathEqualTo("/greeting"))); + } + + @Test + public void decorateTimingOutCall() throws Exception { + stubFor(get(urlPathEqualTo("/greeting")) + .willReturn(aResponse() + .withFixedDelay(500) + .withStatus(200) + .withHeader("Content-Type", "text/plain") + .withBody("hello world"))); + + try { + service.greeting().execute(); + } catch (Throwable ignored) { + } + + final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); + assertEquals(1, metrics.getNumberOfFailedCalls()); + + // Circuit breaker should still be closed, not hit open threshold + assertEquals(CircuitBreaker.State.CLOSED, circuitBreaker.getState()); + + try { + service.greeting().execute(); + } catch (Throwable ignored) { + } + + try { + service.greeting().execute(); + } catch (Throwable ignored) { + } + + assertEquals(3, metrics.getNumberOfFailedCalls()); + // Circuit breaker should be OPEN, threshold met + assertEquals(CircuitBreaker.State.OPEN, circuitBreaker.getState()); + } + + @Test + public void passThroughCallsToDecoratedObject() { + final Call call = mock(StringCall.class); + final Call decorated = RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, Response::isSuccessful); + + decorated.cancel(); + Mockito.verify(call).cancel(); + + decorated.enqueue(null); + Mockito.verify(call).enqueue(any()); + + decorated.isExecuted(); + Mockito.verify(call).isExecuted(); + + decorated.isCanceled(); + Mockito.verify(call).isCanceled(); + + decorated.clone(); + Mockito.verify(call).clone(); + + decorated.request(); + Mockito.verify(call).request(); + } + + private interface StringCall extends Call { + } + +} \ No newline at end of file diff --git a/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitService.java b/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitService.java new file mode 100644 index 0000000000..ec456dba33 --- /dev/null +++ b/resilience4j-retrofit/src/test/java/io/github/resilience4j/retrofit/RetrofitService.java @@ -0,0 +1,29 @@ +/* + * + * 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 retrofit2.Call; +import retrofit2.http.GET; + +public interface RetrofitService { + + @GET("greeting") + Call greeting(); + +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 62d4039b54..0a57c8f21f 100644 --- a/settings.gradle +++ b/settings.gradle @@ -11,4 +11,5 @@ include 'resilience4j-consumer' include 'resilience4j-test' include 'resilience4j-vertx' include 'resilience4j-spring-boot' +include 'resilience4j-retrofit'