Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#64] feat(client): add REST Client for Graviton client module (#69)

Jerry Shaoc7dca4538297
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/RESTException.java b/api/src/main/java/com/datastrato/graviton/exceptions/RESTException.java
new file mode 100644
index 0000000000..d31f185a0b
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/exceptions/RESTException.java
@@ -0,0 +1,15 @@
+package com.datastrato.graviton.exceptions;
+
+import com.google.errorprone.annotations.FormatMethod;
+
+public class RESTException extends RuntimeException {
+ @FormatMethod
+ public RESTException(String message, Object... args) {
+ super(String.format(message, args));
+ }
+
+ @FormatMethod
+ public RESTException(Throwable cause, String message, Object... args) {
+ super(String.format(message, args), cause);
+ }
+}
diff --git a/client/build.gradle.kts b/client/build.gradle.kts
new file mode 100644
index 0000000000..3d0bfbb5b6
--- /dev/null
+++ b/client/build.gradle.kts
@@ -0,0 +1,39 @@
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+ id("com.diffplug.spotless")
+}
+
+dependencies {
+ implementation(project(":api"))
+ implementation(project(":common"))
+ implementation(libs.protobuf.java.util) {
+ exclude("com.google.guava", "guava")
+ .because("Brings in Guava for Andriod, which we don't want (and breaks multimaps).")
+ }
+ implementation(libs.substrait.java.core) {
+ exclude("org.slf4j")
+ exclude("com.fasterxml.jackson.core")
+ exclude("com.fasterxml.jackson.datatype")
+ }
+ implementation(libs.jackson.databind)
+ implementation(libs.jackson.annotations)
+ implementation(libs.jackson.datatype.jdk8)
+ implementation(libs.jackson.datatype.jsr310)
+ implementation(libs.guava)
+ implementation(libs.bundles.log4j)
+ implementation(libs.httpclient5)
+
+ compileOnly(libs.lombok)
+ annotationProcessor(libs.lombok)
+ testCompileOnly(libs.lombok)
+ testAnnotationProcessor(libs.lombok)
+
+ testImplementation(libs.junit.jupiter.api)
+ testImplementation(libs.junit.jupiter.params)
+ testRuntimeOnly(libs.junit.jupiter.engine)
+ testImplementation(libs.mockito.core)
+ testImplementation(libs.mockserver.netty)
+ testImplementation(libs.mockserver.client.java)
+}
\ No newline at end of file
diff --git a/client/src/main/java/com/datastrato/graviton/client/ErrorHandler.java b/client/src/main/java/com/datastrato/graviton/client/ErrorHandler.java
new file mode 100644
index 0000000000..fa6b954cb5
--- /dev/null
+++ b/client/src/main/java/com/datastrato/graviton/client/ErrorHandler.java
@@ -0,0 +1,9 @@
+package com.datastrato.graviton.client;
+
+import com.datastrato.graviton.dto.responses.BaseResponse;
+import java.util.function.Consumer;
+
+public abstract class ErrorHandler implements Consumer<BaseResponse> {
+
+ public abstract BaseResponse parseResponse(int code, String json);
+}
diff --git a/client/src/main/java/com/datastrato/graviton/client/HTTPClient.java b/client/src/main/java/com/datastrato/graviton/client/HTTPClient.java
new file mode 100644
index 0000000000..47dfa92d14
--- /dev/null
+++ b/client/src/main/java/com/datastrato/graviton/client/HTTPClient.java
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 com.datastrato.graviton.client;
+
+import com.datastrato.graviton.dto.responses.BaseResponse;
+import com.datastrato.graviton.dto.responses.ErrorType;
+import com.datastrato.graviton.exceptions.RESTException;
+import com.datastrato.graviton.json.JsonUtils;
+import com.datastrato.graviton.rest.RESTRequest;
+import com.datastrato.graviton.rest.RESTResponse;
+import com.datastrato.graviton.rest.RESTUtils;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
+import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Method;
+import org.apache.hc.core5.http.ParseException;
+import org.apache.hc.core5.http.impl.EnglishReasonPhraseCatalog;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.http.io.entity.StringEntity;
+import org.apache.hc.core5.http.message.BasicHeader;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.URIBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An HttpClient for usage with the REST catalog.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/rest/HTTPClient.java
+ */
+public class HTTPClient implements RESTClient {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HTTPClient.class);
+
+ private static final String VERSION_HEADER = "application/vnd.graviton.v1+json";
+
+ private final String uri;
+ private final CloseableHttpClient httpClient;
+ private final ObjectMapper mapper;
+
+ private HTTPClient(String uri, Map<String, String> baseHeaders, ObjectMapper objectMapper) {
+ this.uri = uri;
+ this.mapper = objectMapper;
+
+ HttpClientBuilder clientBuilder = HttpClients.custom();
+
+ if (baseHeaders != null) {
+ clientBuilder.setDefaultHeaders(
+ baseHeaders.entrySet().stream()
+ .map(e -> new BasicHeader(e.getKey(), e.getValue()))
+ .collect(Collectors.toList()));
+ }
+
+ this.httpClient = clientBuilder.build();
+ }
+
+ private static String extractResponseBodyAsString(CloseableHttpResponse response) {
+ try {
+ if (response.getEntity() == null) {
+ return null;
+ }
+
+ // EntityUtils.toString returns null when HttpEntity.getContent returns null.
+ return EntityUtils.toString(response.getEntity(), "UTF-8");
+ } catch (IOException | ParseException e) {
+ throw new RESTException(e, "Failed to convert HTTP response body to string");
+ }
+ }
+
+ // Per the spec, the only currently defined / used "success" responses are 200 and 202.
+ private static boolean isSuccessful(CloseableHttpResponse response) {
+ int code = response.getCode();
+ return code == HttpStatus.SC_OK
+ || code == HttpStatus.SC_ACCEPTED
+ || code == HttpStatus.SC_NO_CONTENT;
+ }
+
+ private static BaseResponse buildDefaultErrorResponse(CloseableHttpResponse response) {
+ String responseReason = response.getReasonPhrase();
+ String message =
+ responseReason != null && !responseReason.isEmpty()
+ ? responseReason
+ : EnglishReasonPhraseCatalog.INSTANCE.getReason(response.getCode(), null /* ignored */);
+ return BaseResponse.error(ErrorType.DEFAULT_ERROR, message);
+ }
+
+ // Process a failed response through the provided errorHandler, and throw a RESTException.java if
+ // the
+ // provided error handler doesn't already throw.
+ private static void throwFailure(
+ CloseableHttpResponse response, String responseBody, Consumer<BaseResponse> errorHandler) {
+ BaseResponse errorResponse = null;
+
+ if (responseBody != null) {
+ try {
+ if (errorHandler instanceof ErrorHandler) {
+ errorResponse =
+ ((ErrorHandler) errorHandler).parseResponse(response.getCode(), responseBody);
+ } else {
+ LOG.warn(
+ "Unknown error handler {}, response body won't be parsed",
+ errorHandler.getClass().getName());
+ errorResponse = BaseResponse.error(ErrorType.UNKNOWN, responseBody);
+ }
+
+ } catch (UncheckedIOException | IllegalArgumentException e) {
+ // It's possible to receive a non-successful response that isn't a properly defined
+ // BaseResponse
+ // without any bugs in the server implementation. So we ignore this exception and build an
+ // error response for the user.
+ //
+ // For example, the connection could time out before every reaching the server, in which
+ // case we'll
+ // likely get a 5xx with the load balancers default 5xx response.
+ LOG.error("Failed to parse an error response. Will create one instead.", e);
+ }
+ }
+
+ if (errorResponse == null) {
+ errorResponse = buildDefaultErrorResponse(response);
+ }
+
+ errorHandler.accept(errorResponse);
+
+ // Throw an exception in case the provided error handler does not throw.
+ throw new RESTException("Unhandled error: %s", errorResponse);
+ }
+
+ private URI buildUri(String path, Map<String, String> params) {
+ String baseUri = String.format("%s/%s", uri, path);
+ try {
+ URIBuilder builder = new URIBuilder(baseUri);
+ if (params != null) {
+ params.forEach(builder::addParameter);
+ }
+ return builder.build();
+ } catch (URISyntaxException e) {
+ throw new RESTException(
+ "Failed to create request URI from base %s, params %s", baseUri, params);
+ }
+ }
+
+ /**
+ * Method to execute an HTTP request and process the corresponding response.
+ *
+ * @param method - HTTP method, such as GET, POST, HEAD, etc.
+ * @param queryParams - A map of query parameters
+ * @param path - URL path to send the request to
+ * @param requestBody - Content to place in the request body
+ * @param responseType - Class of the Response type. Needs to have serializer registered with
+ * ObjectMapper
+ * @param errorHandler - Error handler delegated for HTTP responses which handles server error
+ * responses
+ * @param <T> - Class type of the response for deserialization. Must be registered with the
+ * ObjectMapper.
+ * @return The response entity, parsed and converted to its type T
+ */
+ private <T> T execute(
+ Method method,
+ String path,
+ Map<String, String> queryParams,
+ Object requestBody,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(
+ method, path, queryParams, requestBody, responseType, headers, errorHandler, h -> {});
+ }
+
+ /**
+ * Method to execute an HTTP request and process the corresponding response.
+ *
+ * @param method - HTTP method, such as GET, POST, HEAD, etc.
+ * @param queryParams - A map of query parameters
+ * @param path - URL path to send the request to
+ * @param requestBody - Content to place in the request body
+ * @param responseType - Class of the Response type. Needs to have serializer registered with
+ * ObjectMapper
+ * @param errorHandler - Error handler delegated for HTTP responses which handles server error
+ * responses
+ * @param responseHeaders The consumer of the response headers
+ * @param <T> - Class type of the response for deserialization. Must be registered with the
+ * ObjectMapper.
+ * @return The response entity, parsed and converted to its type T
+ */
+ private <T> T execute(
+ Method method,
+ String path,
+ Map<String, String> queryParams,
+ Object requestBody,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler,
+ Consumer<Map<String, String>> responseHeaders) {
+ if (path.startsWith("/")) {
+ throw new RESTException(
+ "Received a malformed path for a REST request: %s. Paths should not start with /", path);
+ }
+
+ HttpUriRequestBase request = new HttpUriRequestBase(method.name(), buildUri(path, queryParams));
+
+ if (requestBody instanceof Map) {
+ // encode maps as form data, application/x-www-form-urlencoded
+ addRequestHeaders(request, headers, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+ request.setEntity(toFormEncoding((Map<?, ?>) requestBody));
+ } else if (requestBody != null) {
+ // other request bodies are serialized as JSON, application/json
+ addRequestHeaders(request, headers, ContentType.APPLICATION_JSON.getMimeType());
+ request.setEntity(toJson(requestBody));
+ } else {
+ addRequestHeaders(request, headers, ContentType.APPLICATION_JSON.getMimeType());
+ }
+
+ try (CloseableHttpResponse response = httpClient.execute(request)) {
+ Map<String, String> respHeaders = Maps.newHashMap();
+ for (Header header : response.getHeaders()) {
+ respHeaders.put(header.getName(), header.getValue());
+ }
+
+ responseHeaders.accept(respHeaders);
+
+ // Skip parsing the response stream for any successful request not expecting a response body
+ if (response.getCode() == HttpStatus.SC_NO_CONTENT
+ || (responseType == null && isSuccessful(response))) {
+ return null;
+ }
+
+ String responseBody = extractResponseBodyAsString(response);
+
+ if (!isSuccessful(response)) {
+ // The provided error handler is expected to throw, but a RESTException.java is thrown if
+ // not.
+ throwFailure(response, responseBody, errorHandler);
+ }
+
+ if (responseBody == null) {
+ throw new RESTException(
+ "Invalid (null) response body for request (expected %s): method=%s, path=%s, status=%d",
+ responseType.getSimpleName(), method.name(), path, response.getCode());
+ }
+
+ try {
+ return mapper.readValue(responseBody, responseType);
+ } catch (JsonProcessingException e) {
+ throw new RESTException(
+ e,
+ "Received a success response code of %d, but failed to parse response body into %s",
+ response.getCode(),
+ responseType.getSimpleName());
+ }
+ } catch (IOException e) {
+ throw new RESTException(e, "Error occurred while processing %s request", method);
+ }
+ }
+
+ @Override
+ public void head(String path, Map<String, String> headers, Consumer<BaseResponse> errorHandler) {
+ execute(Method.HEAD, path, null, null, null, headers, errorHandler);
+ }
+
+ @Override
+ public <T extends RESTResponse> T get(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(Method.GET, path, queryParams, null, responseType, headers, errorHandler);
+ }
+
+ @Override
+ public <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(Method.POST, path, null, body, responseType, headers, errorHandler);
+ }
+
+ @Override
+ public <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler,
+ Consumer<Map<String, String>> responseHeaders) {
+ return execute(
+ Method.POST, path, null, body, responseType, headers, errorHandler, responseHeaders);
+ }
+
+ @Override
+ public <T extends RESTResponse> T delete(
+ String path,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(Method.DELETE, path, null, null, responseType, headers, errorHandler);
+ }
+
+ @Override
+ public <T extends RESTResponse> T delete(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(Method.DELETE, path, queryParams, null, responseType, headers, errorHandler);
+ }
+
+ @Override
+ public <T extends RESTResponse> T postForm(
+ String path,
+ Map<String, String> formData,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return execute(Method.POST, path, null, formData, responseType, headers, errorHandler);
+ }
+
+ private void addRequestHeaders(
+ HttpUriRequest request, Map<String, String> requestHeaders, String bodyMimeType) {
+ // Many systems require that content type is set regardless and will fail, even on an empty
+ // bodied request.
+ request.setHeader(HttpHeaders.CONTENT_TYPE, bodyMimeType);
+ request.setHeader(HttpHeaders.ACCEPT, VERSION_HEADER);
+ requestHeaders.forEach(request::setHeader);
+ }
+
+ @Override
+ public void close() throws IOException {
+ httpClient.close(CloseMode.GRACEFUL);
+ }
+
+ public static Builder builder(Map<String, String> properties) {
+ return new Builder(properties);
+ }
+
+ public static class Builder {
+ private final Map<String, String> properties;
+ private final Map<String, String> baseHeaders = Maps.newHashMap();
+ private String uri;
+ private ObjectMapper mapper = JsonUtils.objectMapper();
+
+ private Builder(Map<String, String> properties) {
+ this.properties = properties;
+ }
+
+ public Builder uri(String baseUri) {
+ Preconditions.checkNotNull(baseUri, "Invalid uri for http client: null");
+ this.uri = RESTUtils.stripTrailingSlash(baseUri);
+ return this;
+ }
+
+ public Builder withHeader(String key, String value) {
+ baseHeaders.put(key, value);
+ return this;
+ }
+
+ public Builder withHeaders(Map<String, String> headers) {
+ baseHeaders.putAll(headers);
+ return this;
+ }
+
+ public Builder withObjectMapper(ObjectMapper objectMapper) {
+ this.mapper = objectMapper;
+ return this;
+ }
+
+ public HTTPClient build() {
+ return new HTTPClient(uri, baseHeaders, mapper);
+ }
+ }
+
+ private StringEntity toJson(Object requestBody) {
+ try {
+ return new StringEntity(mapper.writeValueAsString(requestBody));
+ } catch (JsonProcessingException e) {
+ throw new RESTException(e, "Failed to write request body: %s", requestBody);
+ }
+ }
+
+ private StringEntity toFormEncoding(Map<?, ?> formData) {
+ return new StringEntity(RESTUtils.encodeFormData(formData));
+ }
+}
diff --git a/client/src/main/java/com/datastrato/graviton/client/RESTClient.java b/client/src/main/java/com/datastrato/graviton/client/RESTClient.java
new file mode 100644
index 0000000000..e879403a7b
--- /dev/null
+++ b/client/src/main/java/com/datastrato/graviton/client/RESTClient.java
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 com.datastrato.graviton.client;
+
+import com.datastrato.graviton.dto.responses.BaseResponse;
+import com.datastrato.graviton.rest.RESTRequest;
+import com.datastrato.graviton.rest.RESTResponse;
+import com.google.common.collect.ImmutableMap;
+import java.io.Closeable;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+/**
+ * Interface for a basic HTTP Client for interfacing with the REST catalog.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/rest/RESTClient.java
+ */
+public interface RESTClient extends Closeable {
+
+ default void head(
+ String path, Supplier<Map<String, String>> headers, Consumer<BaseResponse> errorHandler) {
+ head(path, headers.get(), errorHandler);
+ }
+
+ void head(String path, Map<String, String> headers, Consumer<BaseResponse> errorHandler);
+
+ default <T extends RESTResponse> T delete(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return delete(path, queryParams, responseType, headers.get(), errorHandler);
+ }
+
+ default <T extends RESTResponse> T delete(
+ String path,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return delete(path, ImmutableMap.of(), responseType, headers.get(), errorHandler);
+ }
+
+ <T extends RESTResponse> T delete(
+ String path,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler);
+
+ default <T extends RESTResponse> T delete(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ if (null != queryParams && !queryParams.isEmpty()) {
+ throw new UnsupportedOperationException("Query params are not supported");
+ }
+
+ return delete(path, responseType, headers, errorHandler);
+ }
+
+ default <T extends RESTResponse> T get(
+ String path,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return get(path, ImmutableMap.of(), responseType, headers, errorHandler);
+ }
+
+ default <T extends RESTResponse> T get(
+ String path,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return get(path, ImmutableMap.of(), responseType, headers, errorHandler);
+ }
+
+ default <T extends RESTResponse> T get(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return get(path, queryParams, responseType, headers.get(), errorHandler);
+ }
+
+ <T extends RESTResponse> T get(
+ String path,
+ Map<String, String> queryParams,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler);
+
+ default <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return post(path, body, responseType, headers.get(), errorHandler);
+ }
+
+ default <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler,
+ Consumer<Map<String, String>> responseHeaders) {
+ return post(path, body, responseType, headers.get(), errorHandler, responseHeaders);
+ }
+
+ default <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler,
+ Consumer<Map<String, String>> responseHeaders) {
+ if (null != responseHeaders) {
+ throw new UnsupportedOperationException("Returning response headers is not supported");
+ }
+
+ return post(path, body, responseType, headers, errorHandler);
+ }
+
+ <T extends RESTResponse> T post(
+ String path,
+ RESTRequest body,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler);
+
+ default <T extends RESTResponse> T postForm(
+ String path,
+ Map<String, String> formData,
+ Class<T> responseType,
+ Supplier<Map<String, String>> headers,
+ Consumer<BaseResponse> errorHandler) {
+ return postForm(path, formData, responseType, headers.get(), errorHandler);
+ }
+
+ <T extends RESTResponse> T postForm(
+ String path,
+ Map<String, String> formData,
+ Class<T> responseType,
+ Map<String, String> headers,
+ Consumer<BaseResponse> errorHandler);
+}
diff --git a/client/src/test/java/com/datastrato/graviton/client/TestHTTPClient.java b/client/src/test/java/com/datastrato/graviton/client/TestHTTPClient.java
new file mode 100644
index 0000000000..43d8381751
--- /dev/null
+++ b/client/src/test/java/com/datastrato/graviton/client/TestHTTPClient.java
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 com.datastrato.graviton.client;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockserver.integration.ClientAndServer.startClientAndServer;
+import static org.mockserver.model.HttpRequest.request;
+import static org.mockserver.model.HttpResponse.response;
+
+import com.datastrato.graviton.dto.responses.BaseResponse;
+import com.datastrato.graviton.dto.responses.ErrorType;
+import com.datastrato.graviton.json.JsonUtils;
+import com.datastrato.graviton.rest.RESTRequest;
+import com.datastrato.graviton.rest.RESTResponse;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Consumer;
+import org.apache.hc.core5.http.Method;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockserver.integration.ClientAndServer;
+import org.mockserver.model.HttpRequest;
+import org.mockserver.model.HttpResponse;
+
+/**
+ * * Exercises the RESTClient interface, specifically over a mocked-server using the actual
+ * HttpRESTClient code.
+ *
+ * <p>Referred from core/src/test/java/org/apache/iceberg/rest/TestHTTPClient.java
+ */
+public class TestHTTPClient {
+
+ private static final int PORT = 1080;
+ private static final String URI = String.format("http://127.0.0.1:%d", PORT);
+ private static final ObjectMapper MAPPER = JsonUtils.objectMapper();
+
+ private static ClientAndServer mockServer;
+ private static RESTClient restClient;
+
+ @BeforeAll
+ public static void beforeClass() {
+ mockServer = startClientAndServer(PORT);
+ restClient = HTTPClient.builder(ImmutableMap.of()).uri(URI).build();
+ }
+
+ @AfterAll
+ public static void stopServer() throws IOException {
+ mockServer.stop();
+ restClient.close();
+ }
+
+ @Test
+ public void testPostSuccess() throws Exception {
+ testHttpMethodOnSuccess(Method.POST, true, true);
+ }
+
+ @Test
+ public void testPostFailure() throws Exception {
+ testHttpMethodOnFailure(Method.POST, true, true);
+ }
+
+ @Test
+ public void testGetSuccess() throws Exception {
+ testHttpMethodOnSuccess(Method.GET, false, true);
+ }
+
+ @Test
+ public void testGetFailure() throws Exception {
+ testHttpMethodOnFailure(Method.GET, false, true);
+ }
+
+ @Test
+ public void testDeleteSuccess() throws Exception {
+ testHttpMethodOnSuccess(Method.DELETE, false, true);
+ }
+
+ @Test
+ public void testDeleteFailure() throws Exception {
+ testHttpMethodOnFailure(Method.DELETE, false, true);
+ }
+
+ @Test
+ public void testHeadSuccess() throws JsonProcessingException {
+ testHttpMethodOnSuccess(Method.HEAD, false, false);
+ }
+
+ @Test
+ public void testHeadFailure() throws JsonProcessingException {
+ testHttpMethodOnFailure(Method.HEAD, false, false);
+ }
+
+ public static void testHttpMethodOnSuccess(
+ Method method, boolean hasRequestBody, boolean hasResponseBody)
+ throws JsonProcessingException {
+ Item body = new Item(0L, "hank");
+ int statusCode = 200;
+
+ ErrorHandler onError = mock(ErrorHandler.class);
+ doThrow(new RuntimeException("Failure response")).when(onError).accept(any());
+
+ String path =
+ addRequestTestCaseAndGetPath(method, body, statusCode, hasRequestBody, hasResponseBody);
+
+ Item successResponse = doExecuteRequest(method, path, body, onError, h -> {});
+
+ if (hasResponseBody) {
+ Assertions.assertEquals(successResponse, body);
+ }
+
+ verify(onError, never()).accept(any());
+ }
+
+ public static void testHttpMethodOnFailure(
+ Method method, boolean hasRequestBody, boolean hasResponseBody)
+ throws JsonProcessingException {
+ Item body = new Item(0L, "hank");
+ int statusCode = 404;
+
+ ErrorHandler onError = mock(ErrorHandler.class);
+ doThrow(
+ new RuntimeException(
+ String.format(
+ "Called error handler for method %s due to status code: %d",
+ method, statusCode)))
+ .when(onError)
+ .accept(any());
+
+ String path =
+ addRequestTestCaseAndGetPath(method, body, statusCode, hasRequestBody, hasResponseBody);
+
+ Throwable exception =
+ Assertions.assertThrows(
+ RuntimeException.class, () -> doExecuteRequest(method, path, body, onError, h -> {}));
+ Assertions.assertEquals(
+ String.format(
+ "Called error handler for method %s due to status code: %d", method.name(), statusCode),
+ exception.getMessage());
+
+ verify(onError).accept(any());
+ }
+
+ // Adds a request that the mock-server can match against, based on the method, path, body, and
+ // headers.
+ // Return the path generated for the test case, so that the client can call that path to exercise
+ // it.
+ private static String addRequestTestCaseAndGetPath(
+ Method method, Item body, int statusCode, boolean hasRequestBody, boolean hasResponseBody)
+ throws JsonProcessingException {
+
+ // Build the path route, which must be unique per test case.
+ boolean isSuccess = statusCode == 200;
+ // Using different paths keeps the expectations unique for the test's mock server
+ String pathName = isSuccess ? "success" : "failure";
+ String path = String.format("%s_%s", method, pathName);
+
+ // Build the expected request
+ String asJson = body != null ? MAPPER.writeValueAsString(body) : null;
+ HttpRequest mockRequest =
+ request("/" + path).withMethod(method.name().toUpperCase(Locale.ROOT));
+
+ if (hasRequestBody) {
+ mockRequest = mockRequest.withBody(asJson);
+ }
+
+ // Build the expected response
+ HttpResponse mockResponse = response().withStatusCode(statusCode);
+
+ if (hasResponseBody) {
+ if (isSuccess) {
+ // Simply return the passed in item in the success case.
+ mockResponse = mockResponse.withBody(asJson);
+ } else {
+ BaseResponse response = BaseResponse.error(ErrorType.NOT_FOUND, "Not found");
+ mockResponse = mockResponse.withBody(MAPPER.writeValueAsString(response));
+ }
+ }
+
+ mockServer.when(mockRequest).respond(mockResponse);
+
+ return path;
+ }
+
+ private static Item doExecuteRequest(
+ Method method,
+ String path,
+ Item body,
+ ErrorHandler onError,
+ Consumer<Map<String, String>> responseHeaders) {
+ Map<String, String> headers = ImmutableMap.of();
+ switch (method) {
+ case POST:
+ return restClient.post(path, body, Item.class, headers, onError, responseHeaders);
+ case GET:
+ return restClient.get(path, Item.class, headers, onError);
+ case HEAD:
+ restClient.head(path, headers, onError);
+ return null;
+ case DELETE:
+ return restClient.delete(path, Item.class, () -> headers, onError);
+ default:
+ throw new IllegalArgumentException(String.format("Invalid method: %s", method));
+ }
+ }
+
+ public static class Item implements RESTRequest, RESTResponse {
+ @JsonProperty private Long id;
+ @JsonProperty private String data;
+
+ // Required for Jackson deserialization
+ @SuppressWarnings("unused")
+ public Item() {}
+
+ public Item(Long id, String data) {
+ this.id = id;
+ this.data = data;
+ }
+
+ @Override
+ public void validate() {}
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, data);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Item item = (Item) o;
+ return Objects.equals(id, item.id) && Objects.equals(data, item.data);
+ }
+ }
+}
diff --git a/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogCreateRequest.java b/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogCreateRequest.java
index 0c0db3f608..983b01a6ae 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogCreateRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogCreateRequest.java
@@ -1,7 +1,7 @@
package com.datastrato.graviton.dto.requests;
import com.datastrato.graviton.Catalog;
-import com.datastrato.graviton.dto.RESTRequest;
+import com.datastrato.graviton.rest.RESTRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.Map;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogUpdateRequest.java b/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogUpdateRequest.java
index 79d840eb91..3c875c9a3e 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogUpdateRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/requests/CatalogUpdateRequest.java
@@ -1,7 +1,7 @@
package com.datastrato.graviton.dto.requests;
import com.datastrato.graviton.CatalogChange;
-import com.datastrato.graviton.dto.RESTRequest;
+import com.datastrato.graviton.rest.RESTRequest;
import com.fasterxml.jackson.annotation.*;
import com.google.common.base.Preconditions;
import lombok.EqualsAndHashCode;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeCreateRequest.java b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeCreateRequest.java
index eeab22c5c2..02f7f6c0ba 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeCreateRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeCreateRequest.java
@@ -1,6 +1,6 @@
package com.datastrato.graviton.dto.requests;
-import com.datastrato.graviton.dto.RESTRequest;
+import com.datastrato.graviton.rest.RESTRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.Map;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdateRequest.java b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdateRequest.java
index ee78915ee4..f2cf32ef34 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdateRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdateRequest.java
@@ -1,7 +1,7 @@
package com.datastrato.graviton.dto.requests;
import com.datastrato.graviton.MetalakeChange;
-import com.datastrato.graviton.dto.RESTRequest;
+import com.datastrato.graviton.rest.RESTRequest;
import com.fasterxml.jackson.annotation.*;
import com.google.common.base.Preconditions;
import lombok.EqualsAndHashCode;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdatesRequest.java b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdatesRequest.java
index 79a57500c3..b51c63aeb7 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdatesRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/requests/MetalakeUpdatesRequest.java
@@ -1,6 +1,6 @@
package com.datastrato.graviton.dto.requests;
-import com.datastrato.graviton.dto.RESTRequest;
+import com.datastrato.graviton.rest.RESTRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.EqualsAndHashCode;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/responses/BaseResponse.java b/common/src/main/java/com/datastrato/graviton/dto/responses/BaseResponse.java
index b54128aa7a..b7173d27a8 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/responses/BaseResponse.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/responses/BaseResponse.java
@@ -1,6 +1,6 @@
package com.datastrato.graviton.dto.responses;
-import com.datastrato.graviton.dto.RESTResponse;
+import com.datastrato.graviton.rest.RESTResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import javax.annotation.Nullable;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/responses/ErrorType.java b/common/src/main/java/com/datastrato/graviton/dto/responses/ErrorType.java
index d958cdf3cb..8f897e214c 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/responses/ErrorType.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/responses/ErrorType.java
@@ -1,6 +1,7 @@
package com.datastrato.graviton.dto.responses;
public enum ErrorType {
+ DEFAULT_ERROR(1000, "default_error"),
INVALID_ARGUMENTS(1001, "invalid_arguments"),
INTERNAL_ERROR(1002, "internal_error"),
NOT_FOUND(1003, "not_found"),
@@ -9,7 +10,7 @@ public enum ErrorType {
CONFLICT(1006, "conflict"),
TOO_MANY_REQUESTS(1007, "too_many_requests"),
SERVICE_UNAVAILABLE(1008, "service_unavailable"),
- UNKNOWN(1009, "unknown");
+ UNKNOWN(1100, "unknown");
private final int errorCode;
diff --git a/common/src/main/java/com/datastrato/graviton/dto/RESTMessage.java b/common/src/main/java/com/datastrato/graviton/rest/RESTMessage.java
similarity index 90%
rename from common/src/main/java/com/datastrato/graviton/dto/RESTMessage.java
rename to common/src/main/java/com/datastrato/graviton/rest/RESTMessage.java
index 7475a1ffba..f22891e755 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/RESTMessage.java
+++ b/common/src/main/java/com/datastrato/graviton/rest/RESTMessage.java
@@ -1,4 +1,4 @@
-package com.datastrato.graviton.dto;
+package com.datastrato.graviton.rest;
public interface RESTMessage {
diff --git a/common/src/main/java/com/datastrato/graviton/dto/RESTRequest.java b/common/src/main/java/com/datastrato/graviton/rest/RESTRequest.java
similarity index 71%
rename from common/src/main/java/com/datastrato/graviton/dto/RESTRequest.java
rename to common/src/main/java/com/datastrato/graviton/rest/RESTRequest.java
index 1bdd5b1808..571705feb8 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/RESTRequest.java
+++ b/common/src/main/java/com/datastrato/graviton/rest/RESTRequest.java
@@ -1,4 +1,4 @@
-package com.datastrato.graviton.dto;
+package com.datastrato.graviton.rest;
/** Interface to mark a REST request. */
public interface RESTRequest extends RESTMessage {}
diff --git a/common/src/main/java/com/datastrato/graviton/dto/RESTResponse.java b/common/src/main/java/com/datastrato/graviton/rest/RESTResponse.java
similarity index 71%
rename from common/src/main/java/com/datastrato/graviton/dto/RESTResponse.java
rename to common/src/main/java/com/datastrato/graviton/rest/RESTResponse.java
index 3099ac5905..aefd57c0c0 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/RESTResponse.java
+++ b/common/src/main/java/com/datastrato/graviton/rest/RESTResponse.java
@@ -1,4 +1,4 @@
-package com.datastrato.graviton.dto;
+package com.datastrato.graviton.rest;
/** Interface to mark a REST response */
public interface RESTResponse extends RESTMessage {}
diff --git a/common/src/main/java/com/datastrato/graviton/rest/RESTUtils.java b/common/src/main/java/com/datastrato/graviton/rest/RESTUtils.java
new file mode 100644
index 0000000000..46d41ced7b
--- /dev/null
+++ b/common/src/main/java/com/datastrato/graviton/rest/RESTUtils.java
@@ -0,0 +1,68 @@
+package com.datastrato.graviton.rest;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableMap;
+import java.io.UncheckedIOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+public class RESTUtils {
+
+ private static final Joiner.MapJoiner FORM_JOINER = Joiner.on("&").withKeyValueSeparator("=");
+ private static final Splitter.MapSplitter FORM_SPLITTER =
+ Splitter.on("&").withKeyValueSeparator("=");
+
+ private RESTUtils() {}
+
+ public static String stripTrailingSlash(String path) {
+ if (path == null) {
+ return null;
+ }
+
+ String result = path;
+ while (result.endsWith("/")) {
+ result = result.substring(0, result.length() - 1);
+ }
+ return result;
+ }
+
+ public static String encodeFormData(Map<?, ?> formData) {
+ ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+ formData.forEach(
+ (key, value) ->
+ builder.put(encodeString(String.valueOf(key)), encodeString(String.valueOf(value))));
+ return FORM_JOINER.join(builder.build());
+ }
+
+ public static Map<String, String> decodeFormData(String formString) {
+ return FORM_SPLITTER.split(formString).entrySet().stream()
+ .collect(
+ ImmutableMap.toImmutableMap(
+ e -> decodeString(e.getKey()), e -> decodeString(e.getValue())));
+ }
+
+ public static String encodeString(String toEncode) {
+ Preconditions.checkArgument(toEncode != null, "Invalid string to encode: null");
+ try {
+ return URLEncoder.encode(toEncode, StandardCharsets.UTF_8.name());
+ } catch (UnsupportedEncodingException e) {
+ throw new UncheckedIOException(
+ String.format("Failed to URL encode '%s': UTF-8 encoding is not supported", toEncode), e);
+ }
+ }
+
+ public static String decodeString(String encoded) {
+ Preconditions.checkArgument(encoded != null, "Invalid string to decode: null");
+ try {
+ return URLDecoder.decode(encoded, StandardCharsets.UTF_8.name());
+ } catch (UnsupportedEncodingException e) {
+ throw new UncheckedIOException(
+ String.format("Failed to URL decode '%s': UTF-8 encoding is not supported", encoded), e);
+ }
+ }
+}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 9838ac3382..274ce1195a 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -14,6 +14,8 @@ airlift-units = "1.8"
airlift-log = "231"
hive2 = "2.3.9"
hadoop2 = "2.7.3"
+httpclient5 = "5.2.1"
+mockserver = "5.13.2"
protobuf-plugin = "0.9.2"
spotless-plugin = '6.11.0'
@@ -56,6 +58,9 @@ airlift-units = { group = "io.airlift", name = "units", version.ref = "airlift-u
airlift-log = { group = "io.airlift", name = "log", version.ref = "airlift-log"}
hadoop2-common = { group = "org.apache.hadoop", name = "hadoop-common", version.ref = "hadoop2"}
hadoop2-mapreduce-client-core = { group = "org.apache.hadoop", name = "hadoop-mapreduce-client-core", version.ref = "hadoop2"}
+httpclient5 = { group = "org.apache.httpcomponents.client5", name = "httpclient5", version.ref = "httpclient5" }
+mockserver-netty = { group = "org.mock-server", name = "mockserver-netty", version.ref = "mockserver" }
+mockserver-client-java = { group = "org.mock-server", name = "mockserver-client-java", version.ref = "mockserver" }
[bundles]
log4j = ["slf4j-api", "log4j-slf4j2-impl", "log4j-api", "log4j-core", "log4j-12-api"]
diff --git a/server/src/main/java/com/datastrato/graviton/server/web/Utils.java b/server/src/main/java/com/datastrato/graviton/server/web/Utils.java
index 19636d693c..b4a3b30250 100644
--- a/server/src/main/java/com/datastrato/graviton/server/web/Utils.java
+++ b/server/src/main/java/com/datastrato/graviton/server/web/Utils.java
@@ -22,7 +22,7 @@ public class Utils {
}
public static Response ok() {
- return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).build();
+ return Response.status(Response.Status.NO_CONTENT).type(MediaType.APPLICATION_JSON).build();
}
public static Response illegalArguments(String message) {
diff --git a/server/src/test/java/com/datastrato/graviton/server/web/rest/TestMetalakesOperations.java b/server/src/test/java/com/datastrato/graviton/server/web/rest/TestMetalakesOperations.java
index b05d77195d..cbc0303ed6 100644
--- a/server/src/test/java/com/datastrato/graviton/server/web/rest/TestMetalakesOperations.java
+++ b/server/src/test/java/com/datastrato/graviton/server/web/rest/TestMetalakesOperations.java
@@ -273,7 +273,7 @@ public class TestMetalakesOperations extends JerseyTest {
.accept("application/vnd.graviton.v1+json")
.delete();
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus());
// Test throw an exception when deleting tenant.
doThrow(new RuntimeException("Internal error")).when(metalakesOperations).dropMetalake(any());