Skip to content

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

[#2612] feat(client): Add Java client support for messaging catalog (#2722)

mchades4d423a7e41f0
diff --git a/api/src/main/java/com/datastrato/gravitino/Catalog.java b/api/src/main/java/com/datastrato/gravitino/Catalog.java
index e9339c6a6c..8ebeaf703e 100644
--- a/api/src/main/java/com/datastrato/gravitino/Catalog.java
+++ b/api/src/main/java/com/datastrato/gravitino/Catalog.java
@@ -27,7 +27,10 @@ public interface Catalog extends Auditable {
FILESET,
/** Catalog Type for Message Queue, like kafka://topic */
- MESSAGING
+ MESSAGING,
+
+ /** Catalog Type for test only. */
+ UNSUPPORTED
}
/**
diff --git a/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java b/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java
index 3d9389bb3e..b3c40bbdbc 100644
--- a/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java
+++ b/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java
@@ -185,6 +185,17 @@ public class NameIdentifier {
Namespace.checkFileset(ident.namespace);
}
+ /**
+ * Check the given {@link NameIdentifier} is a topic identifier. Throw an {@link
+ * IllegalNameIdentifierException} if it's not.
+ *
+ * @param ident The topic {@link NameIdentifier} to check.
+ */
+ public static void checkTopic(NameIdentifier ident) {
+ check(ident != null, "Topic identifier must not be null");
+ Namespace.checkTopic(ident.namespace);
+ }
+
/**
* Create a {@link NameIdentifier} from the given identifier string.
*
diff --git a/api/src/main/java/com/datastrato/gravitino/Namespace.java b/api/src/main/java/com/datastrato/gravitino/Namespace.java
index 3a38025cf7..ae469ff3d4 100644
--- a/api/src/main/java/com/datastrato/gravitino/Namespace.java
+++ b/api/src/main/java/com/datastrato/gravitino/Namespace.java
@@ -182,6 +182,19 @@ public class Namespace {
namespace);
}
+ /**
+ * Check if the given topic namespace is legal, throw an {@link IllegalNamespaceException} if it's
+ * illegal.
+ *
+ * @param namespace The topic namespace
+ */
+ public static void checkTopic(Namespace namespace) {
+ check(
+ namespace != null && namespace.length() == 3,
+ "Topic namespace must be non-null and have 3 levels, the input namespace is %s",
+ namespace);
+ }
+
private Namespace(String[] levels) {
this.levels = levels;
}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/DTOConverters.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/DTOConverters.java
index b040357aa8..5fdf05889d 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/DTOConverters.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/DTOConverters.java
@@ -15,7 +15,9 @@ import com.datastrato.gravitino.dto.requests.FilesetUpdateRequest;
import com.datastrato.gravitino.dto.requests.MetalakeUpdateRequest;
import com.datastrato.gravitino.dto.requests.SchemaUpdateRequest;
import com.datastrato.gravitino.dto.requests.TableUpdateRequest;
+import com.datastrato.gravitino.dto.requests.TopicUpdateRequest;
import com.datastrato.gravitino.file.FilesetChange;
+import com.datastrato.gravitino.messaging.TopicChange;
import com.datastrato.gravitino.rel.SchemaChange;
import com.datastrato.gravitino.rel.TableChange;
@@ -82,6 +84,15 @@ class DTOConverters {
.build();
case MESSAGING:
+ return MessagingCatalog.builder()
+ .withName(catalog.name())
+ .withType(catalog.type())
+ .withProvider(catalog.provider())
+ .withComment(catalog.comment())
+ .withProperties(catalog.properties())
+ .withAudit((AuditDTO) catalog.auditInfo())
+ .withRestClient(client)
+ .build();
default:
throw new UnsupportedOperationException("Unsupported catalog type: " + catalog.type());
}
@@ -183,6 +194,23 @@ class DTOConverters {
}
}
+ static TopicUpdateRequest toTopicUpdateRequest(TopicChange change) {
+ if (change instanceof TopicChange.UpdateTopicComment) {
+ return new TopicUpdateRequest.UpdateTopicCommentRequest(
+ ((TopicChange.UpdateTopicComment) change).getNewComment());
+ } else if (change instanceof TopicChange.SetProperty) {
+ return new TopicUpdateRequest.SetTopicPropertyRequest(
+ ((TopicChange.SetProperty) change).getProperty(),
+ ((TopicChange.SetProperty) change).getValue());
+ } else if (change instanceof TopicChange.RemoveProperty) {
+ return new TopicUpdateRequest.RemoveTopicPropertyRequest(
+ ((TopicChange.RemoveProperty) change).getProperty());
+ } else {
+ throw new IllegalArgumentException(
+ "Unknown change type: " + change.getClass().getSimpleName());
+ }
+ }
+
private static TableUpdateRequest toColumnUpdateRequest(TableChange.ColumnChange change) {
if (change instanceof TableChange.AddColumn) {
TableChange.AddColumn addColumn = (TableChange.AddColumn) change;
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
index 60b1ec49bc..61bac3470d 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
@@ -17,12 +17,14 @@ import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;
import com.datastrato.gravitino.exceptions.NoSuchPartitionException;
import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
import com.datastrato.gravitino.exceptions.NoSuchTableException;
+import com.datastrato.gravitino.exceptions.NoSuchTopicException;
import com.datastrato.gravitino.exceptions.NonEmptySchemaException;
import com.datastrato.gravitino.exceptions.NotFoundException;
import com.datastrato.gravitino.exceptions.PartitionAlreadyExistsException;
import com.datastrato.gravitino.exceptions.RESTException;
import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;
import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.TopicAlreadyExistsException;
import com.datastrato.gravitino.exceptions.UnauthorizedException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
@@ -112,6 +114,15 @@ public class ErrorHandlers {
return FilesetErrorHandler.INSTANCE;
}
+ /**
+ * Creates an error handler specific to Topic operations.
+ *
+ * @return A Consumer representing the Topic error handler.
+ */
+ public static Consumer<ErrorResponse> topicErrorHandler() {
+ return TopicErrorHandler.INSTANCE;
+ }
+
private ErrorHandlers() {}
/**
@@ -410,6 +421,41 @@ public class ErrorHandlers {
}
}
+ /** Error handler specific to Topic operations. */
+ @SuppressWarnings("FormatStringAnnotation")
+ private static class TopicErrorHandler extends RestErrorHandler {
+
+ private static final TopicErrorHandler INSTANCE = new TopicErrorHandler();
+
+ @Override
+ public void accept(ErrorResponse errorResponse) {
+ String errorMessage = formatErrorMessage(errorResponse);
+
+ switch (errorResponse.getCode()) {
+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:
+ throw new IllegalArgumentException(errorMessage);
+
+ case ErrorConstants.NOT_FOUND_CODE:
+ if (errorResponse.getType().equals(NoSuchSchemaException.class.getSimpleName())) {
+ throw new NoSuchSchemaException(errorMessage);
+ } else if (errorResponse.getType().equals(NoSuchTopicException.class.getSimpleName())) {
+ throw new NoSuchTopicException(errorMessage);
+ } else {
+ throw new NotFoundException(errorMessage);
+ }
+
+ case ErrorConstants.ALREADY_EXISTS_CODE:
+ throw new TopicAlreadyExistsException(errorMessage);
+
+ case ErrorConstants.INTERNAL_ERROR_CODE:
+ throw new RuntimeException(errorMessage);
+
+ default:
+ super.accept(errorResponse);
+ }
+ }
+ }
+
/** Generic error handler for REST requests. */
private static class RestErrorHandler extends ErrorHandler {
private static final ErrorHandler INSTANCE = new RestErrorHandler();
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/FilesetCatalog.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/FilesetCatalog.java
index 9ae5b1fe04..ff95b79e08 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/FilesetCatalog.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/FilesetCatalog.java
@@ -164,6 +164,7 @@ public class FilesetCatalog extends BaseSchemaCatalog
.map(DTOConverters::toFilesetUpdateRequest)
.collect(Collectors.toList());
FilesetUpdatesRequest req = new FilesetUpdatesRequest(updates);
+ req.validate();
FilesetResponse resp =
restClient.put(
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/MessagingCatalog.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/MessagingCatalog.java
new file mode 100644
index 0000000000..cd8f83781a
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/MessagingCatalog.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.client;
+
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.dto.AuditDTO;
+import com.datastrato.gravitino.dto.CatalogDTO;
+import com.datastrato.gravitino.dto.requests.TopicCreateRequest;
+import com.datastrato.gravitino.dto.requests.TopicUpdateRequest;
+import com.datastrato.gravitino.dto.requests.TopicUpdatesRequest;
+import com.datastrato.gravitino.dto.responses.DropResponse;
+import com.datastrato.gravitino.dto.responses.EntityListResponse;
+import com.datastrato.gravitino.dto.responses.TopicResponse;
+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
+import com.datastrato.gravitino.exceptions.NoSuchTopicException;
+import com.datastrato.gravitino.exceptions.TopicAlreadyExistsException;
+import com.datastrato.gravitino.messaging.DataLayout;
+import com.datastrato.gravitino.messaging.Topic;
+import com.datastrato.gravitino.messaging.TopicCatalog;
+import com.datastrato.gravitino.messaging.TopicChange;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * Messaging catalog is a catalog implementation that supports messaging-like metadata operations,
+ * for example, topics list, creation, update and deletion. A Messaging catalog is under the
+ * metalake.
+ */
+public class MessagingCatalog extends BaseSchemaCatalog implements TopicCatalog {
+
+ MessagingCatalog(
+ String name,
+ Type type,
+ String provider,
+ String comment,
+ Map<String, String> properties,
+ AuditDTO auditDTO,
+ RESTClient restClient) {
+ super(name, type, provider, comment, properties, auditDTO, restClient);
+ }
+
+ /** @return A new builder for {@link MessagingCatalog}. */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ @Override
+ public TopicCatalog asTopicCatalog() throws UnsupportedOperationException {
+ return this;
+ }
+
+ /**
+ * List all the topics under the given namespace.
+ *
+ * @param namespace The namespace to list the topics under it.
+ * @return An array of {@link NameIdentifier} of the topics under the specified namespace.
+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.
+ */
+ @Override
+ public NameIdentifier[] listTopics(Namespace namespace) throws NoSuchSchemaException {
+ Namespace.checkTopic(namespace);
+
+ EntityListResponse resp =
+ restClient.get(
+ formatTopicRequestPath(namespace),
+ EntityListResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.topicErrorHandler());
+
+ resp.validate();
+
+ return resp.identifiers();
+ }
+
+ /**
+ * Load the topic with the given identifier.
+ *
+ * @param ident The identifier of the topic to load.
+ * @return The {@link Topic} with the specified identifier.
+ * @throws NoSuchTopicException if the topic with the specified identifier does not exist.
+ */
+ @Override
+ public Topic loadTopic(NameIdentifier ident) throws NoSuchTopicException {
+ NameIdentifier.checkTopic(ident);
+
+ TopicResponse resp =
+ restClient.get(
+ formatTopicRequestPath(ident.namespace()) + "/" + ident.name(),
+ TopicResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.topicErrorHandler());
+ resp.validate();
+
+ return resp.getTopic();
+ }
+
+ /**
+ * Create a new topic with the given identifier, comment, data layout and properties.
+ *
+ * @param ident A topic identifier.
+ * @param comment The comment of the topic object. Null is set if no comment is specified.
+ * @param dataLayout The message schema of the topic object. Always null because it's not
+ * supported yet.
+ * @param properties The properties of the topic object. Empty map is set if no properties are
+ * specified.
+ * @return The created topic object.
+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.
+ * @throws TopicAlreadyExistsException if the topic with specified identifier already exists.
+ */
+ @Override
+ public Topic createTopic(
+ NameIdentifier ident, String comment, DataLayout dataLayout, Map<String, String> properties)
+ throws NoSuchSchemaException, TopicAlreadyExistsException {
+ NameIdentifier.checkTopic(ident);
+
+ TopicCreateRequest req =
+ TopicCreateRequest.builder()
+ .name(ident.name())
+ .comment(comment)
+ .properties(properties)
+ .build();
+
+ TopicResponse resp =
+ restClient.post(
+ formatTopicRequestPath(ident.namespace()),
+ req,
+ TopicResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.topicErrorHandler());
+ resp.validate();
+
+ return resp.getTopic();
+ }
+
+ /**
+ * Alter the topic with the given identifier.
+ *
+ * @param ident A topic identifier.
+ * @param changes The changes to apply to the topic.
+ * @return The altered topic object.
+ * @throws NoSuchTopicException if the topic with the specified identifier does not exist.
+ * @throws IllegalArgumentException if the changes are invalid.
+ */
+ @Override
+ public Topic alterTopic(NameIdentifier ident, TopicChange... changes)
+ throws NoSuchTopicException, IllegalArgumentException {
+ NameIdentifier.checkTopic(ident);
+
+ List<TopicUpdateRequest> updates =
+ Arrays.stream(changes)
+ .map(DTOConverters::toTopicUpdateRequest)
+ .collect(Collectors.toList());
+ TopicUpdatesRequest updatesRequest = new TopicUpdatesRequest(updates);
+ updatesRequest.validate();
+
+ TopicResponse resp =
+ restClient.put(
+ formatTopicRequestPath(ident.namespace()) + "/" + ident.name(),
+ updatesRequest,
+ TopicResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.topicErrorHandler());
+ resp.validate();
+
+ return resp.getTopic();
+ }
+
+ /**
+ * Drop the topic with the given identifier.
+ *
+ * @param ident A topic identifier.
+ * @return True if the topic is dropped successfully, false the topic does not exist.
+ */
+ @Override
+ public boolean dropTopic(NameIdentifier ident) {
+ NameIdentifier.checkTopic(ident);
+
+ DropResponse resp =
+ restClient.delete(
+ formatTopicRequestPath(ident.namespace()) + "/" + ident.name(),
+ DropResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.topicErrorHandler());
+ resp.validate();
+
+ return resp.dropped();
+ }
+
+ @VisibleForTesting
+ static String formatTopicRequestPath(Namespace ns) {
+ Namespace schemaNs = Namespace.of(ns.level(0), ns.level(1));
+ return formatSchemaRequestPath(schemaNs) + "/" + ns.level(2) + "/topics";
+ }
+
+ static class Builder extends CatalogDTO.Builder<Builder> {
+ /** The REST client to send the requests. */
+ private RESTClient restClient;
+
+ private Builder() {}
+
+ Builder withRestClient(RESTClient restClient) {
+ this.restClient = restClient;
+ return this;
+ }
+
+ @Override
+ public MessagingCatalog build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not be blank");
+ Preconditions.checkArgument(type != null, "type must not be null");
+ Preconditions.checkArgument(StringUtils.isNotBlank(provider), "provider must not be blank");
+ Preconditions.checkArgument(audit != null, "audit must not be null");
+ Preconditions.checkArgument(restClient != null, "restClient must be set");
+
+ return new MessagingCatalog(name, type, provider, comment, properties, audit, restClient);
+ }
+ }
+}
diff --git a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestGravitinoMetalake.java b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestGravitinoMetalake.java
index 46d5f1c612..b8f109736a 100644
--- a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestGravitinoMetalake.java
+++ b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestGravitinoMetalake.java
@@ -190,7 +190,7 @@ public class TestGravitinoMetalake extends TestBase {
CatalogDTO.builder()
.withName("mock")
.withComment("comment")
- .withType(Catalog.Type.MESSAGING)
+ .withType(Catalog.Type.UNSUPPORTED)
.withProvider("test")
.withAudit(
AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
@@ -250,7 +250,7 @@ public class TestGravitinoMetalake extends TestBase {
CatalogDTO.builder()
.withName("mock")
.withComment("comment")
- .withType(Catalog.Type.MESSAGING)
+ .withType(Catalog.Type.UNSUPPORTED)
.withProvider("test")
.withAudit(
AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
diff --git a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestMessagingCatalog.java b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestMessagingCatalog.java
new file mode 100644
index 0000000000..89b8b4050c
--- /dev/null
+++ b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestMessagingCatalog.java
@@ -0,0 +1,310 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.client;
+
+import static org.apache.hc.core5.http.HttpStatus.SC_CONFLICT;
+import static org.apache.hc.core5.http.HttpStatus.SC_NOT_FOUND;
+import static org.apache.hc.core5.http.HttpStatus.SC_OK;
+import static org.apache.hc.core5.http.HttpStatus.SC_SERVER_ERROR;
+
+import com.datastrato.gravitino.Catalog;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.dto.AuditDTO;
+import com.datastrato.gravitino.dto.CatalogDTO;
+import com.datastrato.gravitino.dto.messaging.TopicDTO;
+import com.datastrato.gravitino.dto.requests.CatalogCreateRequest;
+import com.datastrato.gravitino.dto.requests.TopicCreateRequest;
+import com.datastrato.gravitino.dto.requests.TopicUpdateRequest;
+import com.datastrato.gravitino.dto.requests.TopicUpdatesRequest;
+import com.datastrato.gravitino.dto.responses.CatalogResponse;
+import com.datastrato.gravitino.dto.responses.DropResponse;
+import com.datastrato.gravitino.dto.responses.EntityListResponse;
+import com.datastrato.gravitino.dto.responses.ErrorResponse;
+import com.datastrato.gravitino.dto.responses.TopicResponse;
+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
+import com.datastrato.gravitino.exceptions.NoSuchTopicException;
+import com.datastrato.gravitino.exceptions.TopicAlreadyExistsException;
+import com.datastrato.gravitino.messaging.Topic;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.time.Instant;
+import org.apache.hc.core5.http.Method;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestMessagingCatalog extends TestBase {
+ protected static Catalog catalog;
+
+ private static GravitinoMetalake metalake;
+
+ protected static final String metalakeName = "testMetalake";
+
+ protected static final String catalogName = "testMessagingCatalog";
+
+ private static final String provider = "test";
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ TestBase.setUp();
+
+ metalake = TestGravitinoMetalake.createMetalake(client, metalakeName);
+ CatalogDTO mockCatalog =
+ CatalogDTO.builder()
+ .withName(catalogName)
+ .withType(CatalogDTO.Type.MESSAGING)
+ .withProvider(provider)
+ .withComment("comment")
+ .withProperties(ImmutableMap.of("k1", "k2"))
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+
+ CatalogCreateRequest catalogCreateRequest =
+ new CatalogCreateRequest(
+ catalogName,
+ CatalogDTO.Type.MESSAGING,
+ provider,
+ "comment",
+ ImmutableMap.of("k1", "k2"));
+ CatalogResponse catalogResponse = new CatalogResponse(mockCatalog);
+ buildMockResource(
+ Method.POST,
+ "/api/metalakes/" + metalakeName + "/catalogs",
+ catalogCreateRequest,
+ catalogResponse,
+ SC_OK);
+
+ catalog =
+ metalake.createCatalog(
+ NameIdentifier.of(metalakeName, catalogName),
+ CatalogDTO.Type.MESSAGING,
+ provider,
+ "comment",
+ ImmutableMap.of("k1", "k2"));
+ }
+
+ @Test
+ public void testListTopics() throws Exception {
+ NameIdentifier topic1 = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic1");
+ NameIdentifier topic2 = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic2");
+ String topicPath = withSlash(MessagingCatalog.formatTopicRequestPath(topic1.namespace()));
+
+ EntityListResponse entityListResponse =
+ new EntityListResponse(new NameIdentifier[] {topic1, topic2});
+ buildMockResource(Method.GET, topicPath, null, entityListResponse, SC_OK);
+ NameIdentifier[] topics = ((MessagingCatalog) catalog).listTopics(topic1.namespace());
+
+ Assertions.assertEquals(2, topics.length);
+ Assertions.assertEquals(topic1, topics[0]);
+ Assertions.assertEquals(topic2, topics[1]);
+
+ // Throw schema not found exception
+ ErrorResponse errResp =
+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");
+ buildMockResource(Method.GET, topicPath, null, errResp, SC_NOT_FOUND);
+ Assertions.assertThrows(
+ NoSuchSchemaException.class,
+ () -> catalog.asTopicCatalog().listTopics(topic1.namespace()),
+ "schema not found");
+
+ // Throw Runtime exception
+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");
+ buildMockResource(Method.GET, topicPath, null, errResp2, SC_SERVER_ERROR);
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> catalog.asTopicCatalog().listTopics(topic1.namespace()),
+ "internal error");
+ }
+
+ @Test
+ public void testLoadTopic() throws JsonProcessingException {
+ NameIdentifier topic = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic1");
+ String topicPath =
+ withSlash(MessagingCatalog.formatTopicRequestPath(topic.namespace()) + "/" + topic.name());
+
+ TopicDTO mockTopic = mockTopicDTO(topic.name(), "comment", ImmutableMap.of("k1", "k2"));
+ TopicResponse topicResponse = new TopicResponse(mockTopic);
+ buildMockResource(Method.GET, topicPath, null, topicResponse, SC_OK);
+
+ Topic loadedTopic = catalog.asTopicCatalog().loadTopic(topic);
+ Assertions.assertNotNull(loadedTopic);
+ assertTopic(mockTopic, loadedTopic);
+
+ // test NoSuchSchemaException
+ ErrorResponse errResp =
+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");
+ buildMockResource(Method.GET, topicPath, null, errResp, SC_NOT_FOUND);
+ Exception ex =
+ Assertions.assertThrows(
+ NoSuchSchemaException.class, () -> catalog.asTopicCatalog().loadTopic(topic));
+ Assertions.assertEquals("schema not found", ex.getMessage());
+ }
+
+ @Test
+ public void testCreateTopic() throws JsonProcessingException {
+ NameIdentifier topic = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic1");
+ String topicPath = withSlash(MessagingCatalog.formatTopicRequestPath(topic.namespace()));
+
+ TopicDTO mockTopic = mockTopicDTO(topic.name(), "comment", ImmutableMap.of("k1", "k2"));
+
+ TopicCreateRequest topicCreateRequest =
+ new TopicCreateRequest(topic.name(), "comment", ImmutableMap.of("k1", "k2"));
+ TopicResponse topicResponse = new TopicResponse(mockTopic);
+ buildMockResource(Method.POST, topicPath, topicCreateRequest, topicResponse, SC_OK);
+
+ Topic createdTopic =
+ catalog.asTopicCatalog().createTopic(topic, "comment", null, ImmutableMap.of("k1", "k2"));
+ Assertions.assertNotNull(createdTopic);
+ assertTopic(mockTopic, createdTopic);
+
+ // test NoSuchSchemaException
+ ErrorResponse errResp =
+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");
+ buildMockResource(Method.POST, topicPath, topicCreateRequest, errResp, SC_NOT_FOUND);
+ Exception ex =
+ Assertions.assertThrows(
+ NoSuchSchemaException.class,
+ () ->
+ catalog
+ .asTopicCatalog()
+ .createTopic(topic, "comment", null, ImmutableMap.of("k1", "k2")));
+ Assertions.assertEquals("schema not found", ex.getMessage());
+
+ // test TopicAlreadyExistsException
+ ErrorResponse errResp2 =
+ ErrorResponse.alreadyExists(
+ TopicAlreadyExistsException.class.getSimpleName(), "topic already exists");
+ buildMockResource(Method.POST, topicPath, topicCreateRequest, errResp2, SC_CONFLICT);
+
+ Exception ex2 =
+ Assertions.assertThrows(
+ TopicAlreadyExistsException.class,
+ () ->
+ catalog
+ .asTopicCatalog()
+ .createTopic(topic, "comment", null, ImmutableMap.of("k1", "k2")));
+ Assertions.assertEquals("topic already exists", ex2.getMessage());
+
+ // test RuntimeException
+ ErrorResponse errResp3 = ErrorResponse.internalError("internal error");
+ buildMockResource(Method.POST, topicPath, topicCreateRequest, errResp3, SC_SERVER_ERROR);
+ Exception ex3 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ catalog
+ .asTopicCatalog()
+ .createTopic(topic, "comment", null, ImmutableMap.of("k1", "k2")));
+ Assertions.assertEquals("internal error", ex3.getMessage());
+ }
+
+ @Test
+ public void testAlterTopic() throws JsonProcessingException {
+ NameIdentifier topic = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic1");
+ String topicPath =
+ withSlash(MessagingCatalog.formatTopicRequestPath(topic.namespace()) + "/" + topic.name());
+
+ // test alter topic comment
+ TopicUpdateRequest req1 = new TopicUpdateRequest.UpdateTopicCommentRequest("new comment");
+ TopicDTO mockTopic1 = mockTopicDTO(topic.name(), "new comment", ImmutableMap.of("k1", "v1"));
+ TopicResponse resp1 = new TopicResponse(mockTopic1);
+ buildMockResource(
+ Method.PUT, topicPath, new TopicUpdatesRequest(ImmutableList.of(req1)), resp1, SC_OK);
+
+ Topic alteredTopic = catalog.asTopicCatalog().alterTopic(topic, req1.topicChange());
+ assertTopic(mockTopic1, alteredTopic);
+
+ // test set topic properties
+ TopicUpdateRequest req2 = new TopicUpdateRequest.SetTopicPropertyRequest("k2", "v2");
+ TopicDTO mockTopic2 =
+ mockTopicDTO(topic.name(), "new comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ TopicResponse resp2 = new TopicResponse(mockTopic2);
+ buildMockResource(
+ Method.PUT, topicPath, new TopicUpdatesRequest(ImmutableList.of(req2)), resp2, SC_OK);
+
+ alteredTopic = catalog.asTopicCatalog().alterTopic(topic, req2.topicChange());
+ assertTopic(mockTopic2, alteredTopic);
+
+ // test remove topic properties
+ TopicUpdateRequest req3 = new TopicUpdateRequest.RemoveTopicPropertyRequest("k2");
+ TopicDTO mockTopic3 = mockTopicDTO(topic.name(), "new comment", ImmutableMap.of("k1", "v1"));
+ TopicResponse resp3 = new TopicResponse(mockTopic3);
+ buildMockResource(
+ Method.PUT, topicPath, new TopicUpdatesRequest(ImmutableList.of(req3)), resp3, SC_OK);
+
+ alteredTopic = catalog.asTopicCatalog().alterTopic(topic, req3.topicChange());
+ assertTopic(mockTopic3, alteredTopic);
+
+ // test NoSuchTopicException
+ ErrorResponse errResp =
+ ErrorResponse.notFound(NoSuchTopicException.class.getSimpleName(), "topic not found");
+ buildMockResource(
+ Method.PUT,
+ topicPath,
+ new TopicUpdatesRequest(ImmutableList.of(req1)),
+ errResp,
+ SC_NOT_FOUND);
+ Exception ex =
+ Assertions.assertThrows(
+ NoSuchTopicException.class,
+ () -> catalog.asTopicCatalog().alterTopic(topic, req1.topicChange()));
+ Assertions.assertEquals("topic not found", ex.getMessage());
+
+ // test RuntimeException
+ errResp = ErrorResponse.internalError("internal error");
+ buildMockResource(
+ Method.PUT,
+ topicPath,
+ new TopicUpdatesRequest(ImmutableList.of(req1)),
+ errResp,
+ SC_SERVER_ERROR);
+ ex =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> catalog.asTopicCatalog().alterTopic(topic, req1.topicChange()));
+ Assertions.assertEquals("internal error", ex.getMessage());
+ }
+
+ @Test
+ public void testDropTopic() throws JsonProcessingException {
+ NameIdentifier topic = NameIdentifier.of(metalakeName, catalogName, "schema1", "topic1");
+ String topicPath =
+ withSlash(MessagingCatalog.formatTopicRequestPath(topic.namespace()) + "/" + topic.name());
+ DropResponse resp = new DropResponse(true);
+ buildMockResource(Method.DELETE, topicPath, null, resp, SC_OK);
+
+ Assertions.assertTrue(catalog.asTopicCatalog().dropTopic(topic));
+
+ resp = new DropResponse(false);
+ buildMockResource(Method.DELETE, topicPath, null, resp, SC_OK);
+ Assertions.assertFalse(catalog.asTopicCatalog().dropTopic(topic));
+
+ // test RuntimeException
+ ErrorResponse errResp = ErrorResponse.internalError("internal error");
+ buildMockResource(Method.DELETE, topicPath, null, errResp, SC_SERVER_ERROR);
+ Exception ex =
+ Assertions.assertThrows(
+ RuntimeException.class, () -> catalog.asTopicCatalog().dropTopic(topic));
+ Assertions.assertEquals("internal error", ex.getMessage());
+ }
+
+ private TopicDTO mockTopicDTO(
+ String name, String comment, ImmutableMap<String, String> properties) {
+ return TopicDTO.builder()
+ .withName(name)
+ .withComment(comment)
+ .withProperties(properties)
+ .withAudit(AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ private void assertTopic(TopicDTO expected, Topic actual) {
+ Assertions.assertEquals(expected.name(), actual.name());
+ Assertions.assertEquals(expected.comment(), actual.comment());
+ Assertions.assertEquals(expected.properties(), actual.properties());
+ }
+}