Skip to content

Commit

Permalink
refactor: extract control api client (#4276)
Browse files Browse the repository at this point in the history
  • Loading branch information
ndr-brt authored Jun 19, 2024
1 parent 8afa87d commit b2c451b
Show file tree
Hide file tree
Showing 19 changed files with 468 additions and 265 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@

package org.eclipse.edc.connector.core;

import org.eclipse.edc.api.auth.spi.ControlClientAuthenticationProvider;
import org.eclipse.edc.connector.core.agent.ParticipantAgentServiceImpl;
import org.eclipse.edc.connector.core.command.CommandHandlerRegistryImpl;
import org.eclipse.edc.connector.core.event.EventExecutorServiceContainer;
import org.eclipse.edc.connector.core.event.EventRouterImpl;
import org.eclipse.edc.connector.core.message.RemoteMessageDispatcherRegistryImpl;
import org.eclipse.edc.connector.core.validator.DataAddressValidatorRegistryImpl;
import org.eclipse.edc.connector.core.validator.JsonObjectValidatorRegistryImpl;
import org.eclipse.edc.http.client.ControlApiHttpClientImpl;
import org.eclipse.edc.http.spi.ControlApiHttpClient;
import org.eclipse.edc.http.spi.EdcHttpClient;
import org.eclipse.edc.json.JacksonTypeManager;
import org.eclipse.edc.policy.engine.PolicyEngineImpl;
import org.eclipse.edc.policy.engine.RuleBindingRegistryImpl;
Expand Down Expand Up @@ -69,6 +73,12 @@ public class CoreServicesExtension implements ServiceExtension {
@Inject(required = false)
private TypeManager typeManager;

@Inject
private EdcHttpClient edcHttpClient;

@Inject
private ControlClientAuthenticationProvider controlClientAuthenticationProvider;

private RuleBindingRegistry ruleBindingRegistry;

@Override
Expand Down Expand Up @@ -160,5 +170,10 @@ public CriterionOperatorRegistry criterionOperatorRegistry() {
return CriterionOperatorRegistryImpl.ofDefaults();
}

@Provider
public ControlApiHttpClient controlApiHttpClient() {
return new ControlApiHttpClientImpl(edcHttpClient, controlClientAuthenticationProvider);
}

}

5 changes: 3 additions & 2 deletions core/common/lib/http-lib/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@ plugins {
}

dependencies {
api(project(":spi:common:auth-spi"))
api(project(":spi:common:http-spi"))

implementation(libs.okhttp)
implementation(libs.dnsOverHttps)

testImplementation(project(":core:common:junit"))
testImplementation(project(":core:common:lib:json-lib"))
testImplementation(project(":core:common:lib:util-lib"))
testImplementation(libs.mockserver.netty)

testFixturesImplementation(libs.mockito.core)

testImplementation(libs.mockserver.netty)
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
*
*/

package org.eclipse.edc.http.client;

import okhttp3.Request;
import org.eclipse.edc.api.auth.spi.ControlClientAuthenticationProvider;
import org.eclipse.edc.http.spi.ControlApiHttpClient;
import org.eclipse.edc.http.spi.EdcHttpClient;
import org.eclipse.edc.http.spi.EdcHttpClientException;
import org.eclipse.edc.spi.result.ServiceResult;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import static java.lang.String.format;
import static org.eclipse.edc.http.spi.FallbackFactories.retryWhenStatusIsNotIn;

public class ControlApiHttpClientImpl implements ControlApiHttpClient {

private final EdcHttpClient httpClient;
private final ControlClientAuthenticationProvider authenticationProvider;

public ControlApiHttpClientImpl(EdcHttpClient httpClient, ControlClientAuthenticationProvider authenticationProvider) {
this.httpClient = httpClient;
this.authenticationProvider = authenticationProvider;
}

@Override
public ServiceResult<Void> execute(Request.Builder requestBuilder) {
return request(requestBuilder).mapEmpty();
}

@Override
public ServiceResult<String> request(Request.Builder requestBuilder) {
authenticationProvider.authenticationHeaders().forEach(requestBuilder::header);
try (
var response = httpClient.execute(requestBuilder.build(), List.of(retryWhenStatusIsNotIn(200, 204)));
var responseBody = response.body();
) {
var bodyAsString = responseBody == null ? null : responseBody.string();
if (response.isSuccessful()) {
return ServiceResult.success(bodyAsString);
} else {
return mapToFailure(response.code(), bodyAsString);
}
} catch (IOException exception) {
return ServiceResult.unexpected("Unexpected IOException. " + exception.getMessage());
} catch (EdcHttpClientException exception) {
return mapToFailure(exception.getStatusCode(), exception.getResponseBody());
}
}

private @NotNull ServiceResult<String> mapToFailure(int statusCode, String responseBody) {
return switch (statusCode) {
case 400 -> ServiceResult.badRequest("Remote API returned HTTP 400. " + responseBody);
case 401, 403 -> ServiceResult.unauthorized("Unauthorized. " + responseBody);
case 404 -> ServiceResult.notFound("Remote API returned HTTP 404. " + responseBody);
case 409 -> ServiceResult.conflict("Remote API returned HTTP 409. " + responseBody);
default ->
ServiceResult.unexpected(format("An unknown error happened, HTTP Status = %d. Body %s", statusCode, responseBody));
};
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
* Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
*
*/

package org.eclipse.edc.http.client;

import okhttp3.Request;
import org.eclipse.edc.api.auth.spi.ControlClientAuthenticationProvider;
import org.eclipse.edc.http.spi.ControlApiHttpClient;
import org.eclipse.edc.http.spi.EdcHttpClient;
import org.eclipse.edc.spi.result.ServiceFailure;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.mockserver.integration.ClientAndServer;

import java.util.Map;
import java.util.stream.Stream;

import static org.eclipse.edc.http.client.testfixtures.HttpTestUtils.testHttpClient;
import static org.eclipse.edc.junit.assertions.AbstractResultAssert.assertThat;
import static org.eclipse.edc.spi.result.ServiceFailure.Reason.BAD_REQUEST;
import static org.eclipse.edc.spi.result.ServiceFailure.Reason.CONFLICT;
import static org.eclipse.edc.spi.result.ServiceFailure.Reason.NOT_FOUND;
import static org.eclipse.edc.spi.result.ServiceFailure.Reason.UNAUTHORIZED;
import static org.eclipse.edc.spi.result.ServiceFailure.Reason.UNEXPECTED;
import static org.eclipse.edc.util.io.Ports.getFreePort;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.stop.Stop.stopQuietly;

class ControlApiHttpClientImplTest {

private final int port = getFreePort();
private final EdcHttpClient http = testHttpClient();
private final ControlClientAuthenticationProvider authenticationProvider = mock();
private ClientAndServer server;

private final ControlApiHttpClient client = new ControlApiHttpClientImpl(http, authenticationProvider);

@BeforeEach
public void startServer() {
server = ClientAndServer.startClientAndServer(port);
}

@AfterEach
public void stopServer() {
stopQuietly(server);
}

@Nested
class Execute {
@Test
void shouldSucceed_whenServerResponseIsSuccessful() {
server.when(request()).respond(response().withStatusCode(204));

var request = new Request.Builder()
.url("http://localhost:" + port);

var result = client.execute(request);

assertThat(result).isSucceeded();
}

@Test
void shouldIncludeAuthenticationHeaders() {
server.when(request()).respond(response().withStatusCode(204));
when(authenticationProvider.authenticationHeaders()).thenReturn(Map.of("Authorization", "authToken"));

var request = new Request.Builder()
.url("http://localhost:" + port);

client.execute(request);

server.verify(request().withHeader("Authorization", "authToken"));
}

@ParameterizedTest
@ArgumentsSource(FailingResponses.class)
void shouldFail_whenServerResponseIsNotSuccessful(int statusCode, ServiceFailure.Reason reason) {
server.when(request()).respond(response().withStatusCode(statusCode));

var request = new Request.Builder()
.url("http://localhost:" + port);

var result = client.execute(request);

assertThat(result).isFailed().extracting(ServiceFailure::getReason).isEqualTo(reason);
}

private static class FailingResponses implements ArgumentsProvider {

@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) {
return Stream.of(
arguments(400, BAD_REQUEST),
arguments(401, UNAUTHORIZED),
arguments(403, UNAUTHORIZED),
arguments(404, NOT_FOUND),
arguments(409, CONFLICT),
arguments(500, UNEXPECTED)
);
}
}
}

@Nested
class Response {

@Test
void shouldSucceed_whenServerResponseIsSuccessful() {
server.when(request()).respond(response().withStatusCode(200).withBody("response body"));

var request = new Request.Builder()
.url("http://localhost:" + port);

var result = client.request(request);

assertThat(result).isSucceeded().isEqualTo("response body");
}

@Test
void shouldIncludeAuthenticationHeaders() {
server.when(request()).respond(response().withStatusCode(204));
when(authenticationProvider.authenticationHeaders()).thenReturn(Map.of("Authorization", "authToken"));

var request = new Request.Builder()
.url("http://localhost:" + port);

client.request(request);

server.verify(request().withHeader("Authorization", "authToken"));
}

@ParameterizedTest
@ArgumentsSource(FailingResponses.class)
void shouldFail_whenServerResponseIsNotSuccessful(int statusCode, ServiceFailure.Reason reason) {
server.when(request()).respond(response().withStatusCode(statusCode));

var request = new Request.Builder()
.url("http://localhost:" + port);

var result = client.request(request);

assertThat(result).isFailed().extracting(ServiceFailure::getReason).isEqualTo(reason);
}

private static class FailingResponses implements ArgumentsProvider {

@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) {
return Stream.of(
arguments(400, BAD_REQUEST),
arguments(401, UNAUTHORIZED),
arguments(403, UNAUTHORIZED),
arguments(404, NOT_FOUND),
arguments(409, CONFLICT),
arguments(500, UNEXPECTED)
);
}
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@

package org.eclipse.edc.connector.controlplane.api.client;

import org.eclipse.edc.api.auth.spi.ControlClientAuthenticationProvider;
import org.eclipse.edc.connector.controlplane.api.client.spi.transferprocess.TransferProcessApiClient;
import org.eclipse.edc.connector.controlplane.api.client.transferprocess.TransferProcessHttpClient;
import org.eclipse.edc.connector.controlplane.api.client.transferprocess.model.TransferProcessFailRequest;
import org.eclipse.edc.http.spi.EdcHttpClient;
import org.eclipse.edc.http.spi.ControlApiHttpClient;
import org.eclipse.edc.runtime.metamodel.annotation.Extension;
import org.eclipse.edc.runtime.metamodel.annotation.Inject;
import org.eclipse.edc.runtime.metamodel.annotation.Provider;
Expand All @@ -35,12 +34,10 @@ public class ControlPlaneApiClientExtension implements ServiceExtension {

public static final String NAME = "Control Plane HTTP API client";

@Inject
private EdcHttpClient httpClient;
@Inject
private TypeManager typeManager;
@Inject
private ControlClientAuthenticationProvider authenticationProvider;
private ControlApiHttpClient httpClient;

@Override
public String name() {
Expand All @@ -51,7 +48,7 @@ public String name() {
public TransferProcessApiClient transferProcessApiClient(ServiceExtensionContext context) {
typeManager.registerTypes(TransferProcessFailRequest.class);

return new TransferProcessHttpClient(httpClient, typeManager.getMapper(), context.getMonitor(), authenticationProvider);
return new TransferProcessHttpClient(httpClient, typeManager.getMapper(), context.getMonitor());
}

}
Loading

0 comments on commit b2c451b

Please sign in to comment.