World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2611] feat(server): Add server-side REST API support for topic (#2703)
mchadesfc90986d7a75
diff --git a/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java b/api/src/main/java/com/datastrato/gravitino/NameIdentifier.javaindex 6a79a4f188..3d9389bb3e 100644--- a/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java+++ b/api/src/main/java/com/datastrato/gravitino/NameIdentifier.java@@ -113,6 +113,21 @@ public class NameIdentifier {return NameIdentifier.of(metalake, catalog, schema, fileset);}+ /**+ * Create the topic {@link NameIdentifier} with the given metalake, catalog, schema and topic+ * name.+ *+ * @param metalake The metalake name+ * @param catalog The catalog name+ * @param schema The schema name+ * @param topic The topic name+ * @return The created topic {@link NameIdentifier}+ */+ public static NameIdentifier ofTopic(+ String metalake, String catalog, String schema, String topic) {+ return NameIdentifier.of(metalake, catalog, schema, topic);+ }+/*** Check the given {@link NameIdentifier} is a metalake identifier. Throw an {@link* IllegalNameIdentifierException} if it's not.diff --git a/api/src/main/java/com/datastrato/gravitino/Namespace.java b/api/src/main/java/com/datastrato/gravitino/Namespace.javaindex d61e7ec46a..3a38025cf7 100644--- a/api/src/main/java/com/datastrato/gravitino/Namespace.java+++ b/api/src/main/java/com/datastrato/gravitino/Namespace.java@@ -105,6 +105,18 @@ public class Namespace {return of(metalake, catalog, schema);}+ /**+ * Create a namespace for topic.+ *+ * @param metalake The metalake name+ * @param catalog The catalog name+ * @param schema The schema name+ * @return A namespace for topic+ */+ public static Namespace ofTopic(String metalake, String catalog, String schema) {+ return of(metalake, catalog, schema);+ }+/*** Check if the given metalake namespace is legal, throw an {@link IllegalNamespaceException} if* it's illegal.diff --git a/common/src/main/java/com/datastrato/gravitino/dto/messaging/TopicDTO.java b/common/src/main/java/com/datastrato/gravitino/dto/messaging/TopicDTO.javanew file mode 100644index 0000000000..6c0116dd78--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/messaging/TopicDTO.java@@ -0,0 +1,129 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.messaging;++import com.datastrato.gravitino.Audit;+import com.datastrato.gravitino.dto.AuditDTO;+import com.datastrato.gravitino.messaging.Topic;+import com.fasterxml.jackson.annotation.JsonProperty;+import java.util.Map;+import javax.annotation.Nullable;++/** Represents a topic DTO (Data Transfer Object). */+public class TopicDTO implements Topic {++ /** @return a new builder for constructing a Topic DTO. */+ public static Builder builder() {+ return new Builder();+ }++ @JsonProperty("name")+ private String name;++ @JsonProperty("comment")+ private String comment;++ @JsonProperty("properties")+ private Map<String, String> properties;++ @JsonProperty("audit")+ private AuditDTO audit;++ private TopicDTO() {}++ /**+ * Constructs a Topic DTO.+ *+ * @param name The name of the topic.+ * @param comment The comment associated with the topic.+ * @param properties The properties associated with the topic.+ * @param audit The audit information for the topic.+ */+ private TopicDTO(String name, String comment, Map<String, String> properties, AuditDTO audit) {+ this.name = name;+ this.comment = comment;+ this.properties = properties;+ this.audit = audit;+ }++ @Override+ public String name() {+ return name;+ }++ @Nullable+ @Override+ public String comment() {+ return comment;+ }++ @Override+ public Map<String, String> properties() {+ return properties;+ }++ @Override+ public Audit auditInfo() {+ return audit;+ }++ /** A builder for constructing a Topic DTO. */+ public static class Builder {+ private final TopicDTO topic;++ private Builder() {+ topic = new TopicDTO();+ }++ /**+ * Sets the name of the topic.+ *+ * @param name The name of the topic.+ * @return The builder instance.+ */+ public Builder withName(String name) {+ topic.name = name;+ return this;+ }++ /**+ * Sets the comment associated with the topic.+ *+ * @param comment The comment associated with the topic.+ * @return The builder instance.+ */+ public Builder withComment(String comment) {+ topic.comment = comment;+ return this;+ }++ /**+ * Sets the properties associated with the topic.+ *+ * @param properties The properties associated with the topic.+ * @return The builder instance.+ */+ public Builder withProperties(Map<String, String> properties) {+ topic.properties = properties;+ return this;+ }++ /**+ * Sets the audit information for the topic.+ *+ * @param audit The audit information for the topic.+ * @return The builder instance.+ */+ public Builder withAudit(AuditDTO audit) {+ topic.audit = audit;+ return this;+ }++ /** @return The constructed Topic DTO. */+ public TopicDTO build() {+ return topic;+ }+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicCreateRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicCreateRequest.javanew file mode 100644index 0000000000..df4ca50712--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicCreateRequest.java@@ -0,0 +1,61 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.requests;++import com.datastrato.gravitino.rest.RESTRequest;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import java.util.Map;+import javax.annotation.Nullable;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import lombok.extern.jackson.Jacksonized;+import org.apache.commons.lang3.StringUtils;++/** Represents a request to create a topic. */+@Getter+@EqualsAndHashCode+@ToString+@Builder+@Jacksonized+public class TopicCreateRequest implements RESTRequest {+ @JsonProperty("name")+ private final String name;++ @Nullable+ @JsonProperty("comment")+ private final String comment;++ @Nullable+ @JsonProperty("properties")+ private final Map<String, String> properties;++ /** Default constructor for Jackson deserialization. */+ public TopicCreateRequest() {+ this(null, null, null);+ }++ /**+ * Creates a topic create request.+ *+ * @param name The name of the topic.+ * @param comment The comment of the topic.+ * @param properties The properties of the topic.+ */+ public TopicCreateRequest(+ String name, @Nullable String comment, @Nullable Map<String, String> properties) {+ this.name = name;+ this.comment = comment;+ this.properties = properties;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdateRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdateRequest.javanew file mode 100644index 0000000000..1d1f9918b1--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdateRequest.java@@ -0,0 +1,175 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.requests;++import com.datastrato.gravitino.messaging.TopicChange;+import com.datastrato.gravitino.rest.RESTRequest;+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.annotation.JsonSubTypes;+import com.fasterxml.jackson.annotation.JsonTypeInfo;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.commons.lang3.StringUtils;++/** Represents a request to update a topic. */+@JsonIgnoreProperties(ignoreUnknown = true)+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)+@JsonSubTypes({+ @JsonSubTypes.Type(+ value = TopicUpdateRequest.UpdateTopicCommentRequest.class,+ name = "updateComment"),+ @JsonSubTypes.Type(+ value = TopicUpdateRequest.SetTopicPropertyRequest.class,+ name = "setProperty"),+ @JsonSubTypes.Type(+ value = TopicUpdateRequest.RemoveTopicPropertyRequest.class,+ name = "removeProperty")+})+public interface TopicUpdateRequest extends RESTRequest {++ /** @return The topic change. */+ TopicChange topicChange();++ /** Represents a request to update the comment of a topic. */+ @EqualsAndHashCode+ @ToString+ @Getter+ class UpdateTopicCommentRequest implements TopicUpdateRequest {++ @JsonProperty("newComment")+ private final String newComment;++ /**+ * Constructor for UpdateTopicCommentRequest.+ *+ * @param newComment the new comment of the topic+ */+ public UpdateTopicCommentRequest(String newComment) {+ this.newComment = newComment;+ }++ /** Default constructor for Jackson deserialization. */+ public UpdateTopicCommentRequest() {+ this(null);+ }++ /**+ * Validates the request.+ *+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(newComment),+ "\"newComment\" field is required and cannot be empty");+ }++ /**+ * Returns the topic change.+ *+ * @return An instance of TopicChange.+ */+ @Override+ public TopicChange topicChange() {+ return TopicChange.updateComment(newComment);+ }+ }++ /** Represents a request to set a property of a Topic. */+ @EqualsAndHashCode+ @ToString+ @Getter+ class SetTopicPropertyRequest implements TopicUpdateRequest {++ @JsonProperty("property")+ private final String property;++ @JsonProperty("value")+ private final String value;++ /**+ * Constructor for SetTopicPropertyRequest.+ *+ * @param property the property to set+ * @param value the value to set+ */+ public SetTopicPropertyRequest(String property, String value) {+ this.property = property;+ this.value = value;+ }++ /** Default constructor for Jackson deserialization. */+ public SetTopicPropertyRequest() {+ this(null, null);+ }++ /**+ * Validates the request.+ *+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");+ Preconditions.checkArgument(value != null, "\"value\" field is required and cannot be null");+ }++ /**+ * Returns the topic change.+ *+ * @return An instance of TopicChange.+ */+ @Override+ public TopicChange topicChange() {+ return TopicChange.setProperty(property, value);+ }+ }++ /** Represents a request to remove a property of a topic. */+ @EqualsAndHashCode+ @ToString+ @Getter+ class RemoveTopicPropertyRequest implements TopicUpdateRequest {++ @JsonProperty("property")+ private final String property;++ /**+ * Constructor for RemoveTopicPropertyRequest.+ *+ * @param property the property to remove+ */+ public RemoveTopicPropertyRequest(String property) {+ this.property = property;+ }++ /** Default constructor for Jackson deserialization. */+ public RemoveTopicPropertyRequest() {+ this(null);+ }++ /**+ * Validates the request.+ *+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");+ }++ /** @return An instance of TopicChange. */+ @Override+ public TopicChange topicChange() {+ return TopicChange.removeProperty(property);+ }+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdatesRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdatesRequest.javanew file mode 100644index 0000000000..e7ea29edf3--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/TopicUpdatesRequest.java@@ -0,0 +1,46 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.requests;++import com.datastrato.gravitino.rest.RESTRequest;+import com.fasterxml.jackson.annotation.JsonProperty;+import java.util.List;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;++/** Represents a request to update a topic. */+@Getter+@EqualsAndHashCode+@ToString+public class TopicUpdatesRequest implements RESTRequest {++ @JsonProperty("updates")+ private final List<TopicUpdateRequest> updates;++ /**+ * Creates a new TopicUpdatesRequest.+ *+ * @param updates The updates to apply to the topic.+ */+ public TopicUpdatesRequest(List<TopicUpdateRequest> updates) {+ this.updates = updates;+ }++ /** This is the constructor that is used by Jackson deserializer */+ public TopicUpdatesRequest() {+ this(null);+ }++ /**+ * Validates the request.+ *+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ updates.forEach(RESTRequest::validate);+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/TopicResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/TopicResponse.javanew file mode 100644index 0000000000..d51561abb7--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/TopicResponse.java@@ -0,0 +1,48 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.responses;++import com.datastrato.gravitino.dto.messaging.TopicDTO;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.commons.lang3.StringUtils;++/** Represents a response to a topic. */+@Getter+@ToString+@EqualsAndHashCode(callSuper = true)+public class TopicResponse extends BaseResponse {++ @JsonProperty("topic")+ private final TopicDTO topic;++ /**+ * Creates a new TopicResponse.+ *+ * @param topic The topic DTO object.+ */+ public TopicResponse(TopicDTO topic) {+ super(0);+ this.topic = topic;+ }++ /** This is the constructor that is used by Jackson deserializer */+ public TopicResponse() {+ super();+ this.topic = null;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ super.validate();++ Preconditions.checkArgument(topic != null, "topic must not be null");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(topic.name()), "topic 'name' must not be null and empty");+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.javaindex 049c86bf0b..e9868b9b37 100644--- a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java+++ b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java@@ -15,6 +15,7 @@ import com.datastrato.gravitino.dto.CatalogDTO;import com.datastrato.gravitino.dto.MetalakeDTO;import com.datastrato.gravitino.dto.authorization.UserDTO;import com.datastrato.gravitino.dto.file.FilesetDTO;+import com.datastrato.gravitino.dto.messaging.TopicDTO;import com.datastrato.gravitino.dto.rel.ColumnDTO;import com.datastrato.gravitino.dto.rel.DistributionDTO;import com.datastrato.gravitino.dto.rel.SchemaDTO;@@ -42,6 +43,7 @@ import com.datastrato.gravitino.dto.rel.partitions.ListPartitionDTO;import com.datastrato.gravitino.dto.rel.partitions.PartitionDTO;import com.datastrato.gravitino.dto.rel.partitions.RangePartitionDTO;import com.datastrato.gravitino.file.Fileset;+import com.datastrato.gravitino.messaging.Topic;import com.datastrato.gravitino.rel.Column;import com.datastrato.gravitino.rel.Schema;import com.datastrato.gravitino.rel.Table;@@ -417,6 +419,21 @@ public class DTOConverters {.build();}+ /**+ * Converts a Topic to a TopicDTO.+ *+ * @param topic The topic to be converted.+ * @return The topic DTO.+ */+ public static TopicDTO toDTO(Topic topic) {+ return TopicDTO.builder()+ .withName(topic.name())+ .withComment(topic.comment())+ .withProperties(topic.properties())+ .withAudit(toDTO(topic.auditInfo()))+ .build();+ }+/*** Converts an array of Columns to an array of ColumnDTOs.*diff --git a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.javaindex aae0fe8e86..5570277656 100644--- a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java+++ b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java@@ -86,6 +86,9 @@ public class GravitinoServer extends ResourceConfig {bind(gravitinoEnv.filesetOperationDispatcher()).to(FilesetOperationDispatcher.class).ranked(1);+ bind(gravitinoEnv.topicOperationDispatcher())+ .to(com.datastrato.gravitino.catalog.TopicOperationDispatcher.class)+ .ranked(1);}});register(ObjectMapperProvider.class).register(JacksonFeature.class);diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.javaindex 8af5693608..2c4c9e5f5c 100644--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java@@ -13,6 +13,7 @@ import com.datastrato.gravitino.exceptions.NotFoundException;import com.datastrato.gravitino.exceptions.PartitionAlreadyExistsException;import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;+import com.datastrato.gravitino.exceptions.TopicAlreadyExistsException;import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;import com.datastrato.gravitino.server.web.Utils;import com.google.common.annotations.VisibleForTesting;@@ -61,6 +62,11 @@ public class ExceptionHandlers {return UserExceptionHandler.INSTANCE.handle(op, user, metalake, e);}+ public static Response handleTopicException(+ OperationType op, String topic, String schema, Exception e) {+ return TopicExceptionHandler.INSTANCE.handle(op, topic, schema, e);+ }+private static class PartitionExceptionHandler extends BaseExceptionHandler {private static final ExceptionHandler INSTANCE = new PartitionExceptionHandler();@@ -292,6 +298,37 @@ public class ExceptionHandlers {}}+ private static class TopicExceptionHandler extends BaseExceptionHandler {+ private static final ExceptionHandler INSTANCE = new TopicExceptionHandler();++ private static String getTopicErrorMsg(+ String topic, String operation, String schema, String reason) {+ return String.format(+ "Failed to operate topic(s)%s operation [%s] under schema [%s], reason [%s]",+ topic, operation, schema, reason);+ }++ @Override+ public Response handle(OperationType op, String topic, String schema, Exception e) {+ String formatted = StringUtil.isBlank(topic) ? "" : " [" + topic + "]";+ String errorMsg = getTopicErrorMsg(formatted, op.name(), schema, getErrorMsg(e));+ LOG.warn(errorMsg, e);++ if (e instanceof IllegalArgumentException) {+ return Utils.illegalArguments(errorMsg, e);++ } else if (e instanceof NotFoundException) {+ return Utils.notFound(errorMsg, e);++ } else if (e instanceof TopicAlreadyExistsException) {+ return Utils.alreadyExists(errorMsg, e);++ } else {+ return super.handle(op, topic, schema, e);+ }+ }+ }+@VisibleForTestingstatic class BaseExceptionHandler extends ExceptionHandler {diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/TopicOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TopicOperations.javanew file mode 100644index 0000000000..e09440432b--- /dev/null+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TopicOperations.java@@ -0,0 +1,207 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.server.web.rest;++import com.codahale.metrics.annotation.ResponseMetered;+import com.codahale.metrics.annotation.Timed;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.catalog.TopicOperationDispatcher;+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.dto.util.DTOConverters;+import com.datastrato.gravitino.lock.LockType;+import com.datastrato.gravitino.lock.TreeLockUtils;+import com.datastrato.gravitino.messaging.Topic;+import com.datastrato.gravitino.messaging.TopicChange;+import com.datastrato.gravitino.metrics.MetricNames;+import com.datastrato.gravitino.server.web.Utils;+import javax.inject.Inject;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.PUT;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.Response;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++@Path("/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/topics")+public class TopicOperations {+ private static final Logger LOG = LoggerFactory.getLogger(TopicOperations.class);++ private final TopicOperationDispatcher dispatcher;++ @Context private HttpServletRequest httpRequest;++ @Inject+ public TopicOperations(TopicOperationDispatcher dispatcher) {+ this.dispatcher = dispatcher;+ }++ @GET+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "list-topic." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ public Response listTopics(+ @PathParam("metalake") String metalake,+ @PathParam("catalog") String catalog,+ @PathParam("schema") String schema) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ LOG.info("Listing topics under schema: {}.{}.{}", metalake, catalog, schema);+ Namespace topicNS = Namespace.ofTopic(metalake, catalog, schema);+ NameIdentifier[] topics =+ TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(metalake, catalog, schema),+ LockType.WRITE,+ () -> dispatcher.listTopics(topicNS));+ return Utils.ok(new EntityListResponse(topics));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleFilesetException(OperationType.LIST, "", schema, e);+ }+ }++ @POST+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "create-topic." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "create-topic", absolute = true)+ public Response createTopic(+ @PathParam("metalake") String metalake,+ @PathParam("catalog") String catalog,+ @PathParam("schema") String schema,+ TopicCreateRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ LOG.info(+ "Creating topic under schema: {}.{}.{}.{}",+ metalake,+ catalog,+ schema,+ request.getName());+ request.validate();+ NameIdentifier ident =+ NameIdentifier.ofTopic(metalake, catalog, schema, request.getName());++ Topic topic =+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.WRITE,+ () ->+ dispatcher.createTopic(+ ident,+ request.getComment(),+ null /* dataLayout, always null because it's not supported yet.*/,+ request.getProperties()));+ return Utils.ok(new TopicResponse(DTOConverters.toDTO(topic)));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTopicException(+ OperationType.CREATE, request.getName(), schema, e);+ }+ }++ @GET+ @Path("/{topic}")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "load-topic." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "load-topic", absolute = true)+ public Response loadTopic(+ @PathParam("metalake") String metalake,+ @PathParam("catalog") String catalog,+ @PathParam("schema") String schema,+ @PathParam("topic") String topic) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ LOG.info("Loading topic: {}.{}.{}.{}", metalake, catalog, schema, topic);+ NameIdentifier ident = NameIdentifier.ofTopic(metalake, catalog, schema, topic);+ Topic t =+ TreeLockUtils.doWithTreeLock(+ ident, LockType.READ, () -> dispatcher.loadTopic(ident));+ return Utils.ok(new TopicResponse(DTOConverters.toDTO(t)));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTopicException(OperationType.LOAD, topic, schema, e);+ }+ }++ @PUT+ @Path("/{topic}")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "alter-topic." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "alter-topic", absolute = true)+ public Response alterTopic(+ @PathParam("metalake") String metalake,+ @PathParam("catalog") String catalog,+ @PathParam("schema") String schema,+ @PathParam("topic") String topic,+ TopicUpdatesRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ LOG.info("Altering topic: {}.{}.{}.{}", metalake, catalog, schema, topic);+ request.validate();+ NameIdentifier ident = NameIdentifier.ofTopic(metalake, catalog, schema, topic);+ TopicChange[] changes =+ request.getUpdates().stream()+ .map(TopicUpdateRequest::topicChange)+ .toArray(TopicChange[]::new);++ Topic t =+ TreeLockUtils.doWithTreeLock(+ ident, LockType.WRITE, () -> dispatcher.alterTopic(ident, changes));+ return Utils.ok(new TopicResponse(DTOConverters.toDTO(t)));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTopicException(OperationType.ALTER, topic, schema, e);+ }+ }++ @DELETE+ @Path("/{topic}")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "drop-topic." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "drop-topic", absolute = true)+ public Response dropTopic(+ @PathParam("metalake") String metalake,+ @PathParam("catalog") String catalog,+ @PathParam("schema") String schema,+ @PathParam("topic") String topic) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ LOG.info("Dropping topic under schema: {}.{}.{}", metalake, catalog, schema);+ NameIdentifier ident = NameIdentifier.ofTopic(metalake, catalog, schema, topic);+ boolean dropped =+ TreeLockUtils.doWithTreeLock(+ ident, LockType.WRITE, () -> dispatcher.dropTopic(ident));++ if (!dropped) {+ LOG.warn("Failed to drop topic {} under schema {}", topic, schema);+ }++ return Utils.ok(new DropResponse(dropped));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTopicException(OperationType.DROP, topic, schema, e);+ }+ }+}diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTopicOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTopicOperations.javanew file mode 100644index 0000000000..35acfedf27--- /dev/null+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTopicOperations.java@@ -0,0 +1,398 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.server.web.rest;++import static com.datastrato.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;+import static com.datastrato.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;+import static com.datastrato.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import com.datastrato.gravitino.Audit;+import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.GravitinoEnv;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.catalog.TopicOperationDispatcher;+import com.datastrato.gravitino.dto.messaging.TopicDTO;+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.ErrorConstants;+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.TopicAlreadyExistsException;+import com.datastrato.gravitino.lock.LockManager;+import com.datastrato.gravitino.messaging.Topic;+import com.datastrato.gravitino.messaging.TopicChange;+import com.datastrato.gravitino.rest.RESTUtils;+import com.google.common.collect.ImmutableList;+import com.google.common.collect.ImmutableMap;+import java.io.IOException;+import java.time.Instant;+import java.util.Map;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.client.Entity;+import javax.ws.rs.core.Application;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;+import org.glassfish.jersey.internal.inject.AbstractBinder;+import org.glassfish.jersey.server.ResourceConfig;+import org.glassfish.jersey.test.JerseyTest;+import org.glassfish.jersey.test.TestProperties;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++public class TestTopicOperations extends JerseyTest {++ private static class MockServletRequestFactory extends ServletRequestFactoryBase {+ @Override+ public HttpServletRequest get() {+ HttpServletRequest request = mock(HttpServletRequest.class);+ when(request.getRemoteUser()).thenReturn(null);+ return request;+ }+ }++ private TopicOperationDispatcher dispatcher = mock(TopicOperationDispatcher.class);+ private final String metalake = "metalake";+ private final String catalog = "catalog1";+ private final String schema = "default";++ @BeforeAll+ public static void setup() {+ Config config = mock(Config.class);+ Mockito.doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);+ Mockito.doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);+ Mockito.doReturn(36000L).when(config).get(TREE_LOCK_CLEAN_INTERVAL);+ GravitinoEnv.getInstance().setLockManager(new LockManager(config));+ }++ @Override+ protected Application configure() {+ try {+ forceSet(+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ ResourceConfig resourceConfig = new ResourceConfig();+ resourceConfig.register(TopicOperations.class);+ resourceConfig.register(+ new AbstractBinder() {+ @Override+ protected void configure() {+ bind(dispatcher).to(TopicOperationDispatcher.class).ranked(2);+ bindFactory(TestTopicOperations.MockServletRequestFactory.class)+ .to(HttpServletRequest.class);+ }+ });++ return resourceConfig;+ }++ @Test+ public void testListTopics() {+ NameIdentifier topic1 = NameIdentifier.of(metalake, catalog, schema, "topic1");+ NameIdentifier topic2 = NameIdentifier.of(metalake, catalog, schema, "topic2");++ when(dispatcher.listTopics(any())).thenReturn(new NameIdentifier[] {topic1, topic2});++ Response resp =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());++ EntityListResponse listResp = resp.readEntity(EntityListResponse.class);+ Assertions.assertEquals(0, listResp.getCode());++ NameIdentifier[] topics = listResp.identifiers();+ Assertions.assertEquals(2, topics.length);+ Assertions.assertEquals(topic1, topics[0]);+ Assertions.assertEquals(topic2, topics[1]);++ // Test throw NoSuchSchemaException+ doThrow(new NoSuchSchemaException("mock error")).when(dispatcher).listTopics(any());+ Response resp1 =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());++ ErrorResponse errorResp = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());+ Assertions.assertEquals(NoSuchSchemaException.class.getSimpleName(), errorResp.getType());++ // Test throw RuntimeException+ doThrow(new RuntimeException("mock error")).when(dispatcher).listTopics(any());+ Response resp2 =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp2.getStatus());++ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp2.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp2.getType());+ }++ @Test+ public void testLoadTopic() {+ Topic topic = mockTopic("topic1", "comment", ImmutableMap.of("key1", "value1"));+ when(dispatcher.loadTopic(any())).thenReturn(topic);++ Response resp =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());++ TopicResponse topicResp = resp.readEntity(TopicResponse.class);+ Assertions.assertEquals(0, topicResp.getCode());++ TopicDTO topicDTO = topicResp.getTopic();+ Assertions.assertEquals("topic1", topicDTO.name());+ Assertions.assertEquals("comment", topicDTO.comment());+ Assertions.assertEquals(ImmutableMap.of("key1", "value1"), topicDTO.properties());++ // Test throw NoSuchSchemaException+ doThrow(new NoSuchSchemaException("mock error")).when(dispatcher).loadTopic(any());+ Response resp1 =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());++ ErrorResponse errorResp = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());+ Assertions.assertEquals(NoSuchSchemaException.class.getSimpleName(), errorResp.getType());++ // Test throw RuntimeException+ doThrow(new RuntimeException("mock error")).when(dispatcher).loadTopic(any());++ Response resp2 =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp2.getStatus());++ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp2.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp2.getType());+ }++ @Test+ public void testCreateTopic() {+ Topic topic = mockTopic("topic1", "comment", ImmutableMap.of("key1", "value1"));+ when(dispatcher.createTopic(any(), any(), any(), any())).thenReturn(topic);++ TopicCreateRequest req =+ TopicCreateRequest.builder()+ .name("topic1")+ .comment("comment")+ .properties(ImmutableMap.of("key1", "value1"))+ .build();+ Response resp =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());++ TopicResponse topicResp = resp.readEntity(TopicResponse.class);+ Assertions.assertEquals(0, topicResp.getCode());++ TopicDTO topicDTO = topicResp.getTopic();+ Assertions.assertEquals("topic1", topicDTO.name());+ Assertions.assertEquals("comment", topicDTO.comment());+ Assertions.assertEquals(ImmutableMap.of("key1", "value1"), topicDTO.properties());++ // Test throw NoSuchSchemaException+ doThrow(new NoSuchSchemaException("mock error"))+ .when(dispatcher)+ .createTopic(any(), any(), any(), any());++ Response resp1 =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());++ ErrorResponse errorResp = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());+ Assertions.assertEquals(NoSuchSchemaException.class.getSimpleName(), errorResp.getType());++ // Test throw TopicAlreadyExistsException+ doThrow(new TopicAlreadyExistsException("mock error"))+ .when(dispatcher)+ .createTopic(any(), any(), any(), any());++ Response resp2 =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), resp2.getStatus());++ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResp2.getCode());+ Assertions.assertEquals(+ TopicAlreadyExistsException.class.getSimpleName(), errorResp2.getType());++ // Test throw RuntimeException+ doThrow(new RuntimeException("mock error"))+ .when(dispatcher)+ .createTopic(any(), any(), any(), any());++ Response resp3 =+ target(topicPath(metalake, catalog, schema))+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());++ ErrorResponse errorResp3 = resp3.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp3.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp3.getType());+ }++ @Test+ public void testSetTopicProperties() {+ TopicUpdateRequest req = new TopicUpdateRequest.SetTopicPropertyRequest("key1", "value1");+ Topic topic = mockTopic("topic1", "comment", ImmutableMap.of("key1", "value1"));+ assertUpdateTopic(new TopicUpdatesRequest(ImmutableList.of(req)), topic);+ }++ @Test+ public void testRemoveTopicProperties() {+ TopicUpdateRequest req = new TopicUpdateRequest.RemoveTopicPropertyRequest("key1");+ Topic topic = mockTopic("topic1", "comment", ImmutableMap.of());+ assertUpdateTopic(new TopicUpdatesRequest(ImmutableList.of(req)), topic);+ }++ @Test+ public void testUpdateTopicComment() {+ TopicUpdateRequest req = new TopicUpdateRequest.UpdateTopicCommentRequest("new comment");+ Topic topic = mockTopic("topic1", "new comment", ImmutableMap.of());+ assertUpdateTopic(new TopicUpdatesRequest(ImmutableList.of(req)), topic);+ }++ @Test+ public void testMultiUpdateRequest() {+ TopicUpdateRequest req1 = new TopicUpdateRequest.UpdateTopicCommentRequest("new comment");+ TopicUpdateRequest req2 = new TopicUpdateRequest.SetTopicPropertyRequest("key1", "value1");+ // update key1=value2+ TopicUpdateRequest req3 = new TopicUpdateRequest.SetTopicPropertyRequest("key1", "value2");+ TopicUpdateRequest req4 = new TopicUpdateRequest.SetTopicPropertyRequest("key2", "value2");+ // remove key2+ TopicUpdateRequest req5 = new TopicUpdateRequest.RemoveTopicPropertyRequest("key2");++ Topic topic = mockTopic("topic1", "new comment", ImmutableMap.of("key1", "value1"));+ assertUpdateTopic(+ new TopicUpdatesRequest(ImmutableList.of(req1, req2, req3, req4, req5)), topic);+ }++ @Test+ public void testDropTopic() {+ when(dispatcher.dropTopic(any())).thenReturn(true);+ Response resp =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .delete();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());++ DropResponse dropResp = resp.readEntity(DropResponse.class);+ Assertions.assertEquals(0, dropResp.getCode());+ Assertions.assertTrue(dropResp.dropped());++ // test dropTopic return false+ when(dispatcher.dropTopic(any())).thenReturn(false);+ Response resp1 =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .delete();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp1.getStatus());++ DropResponse dropResp1 = resp1.readEntity(DropResponse.class);+ Assertions.assertEquals(0, dropResp1.getCode());+ Assertions.assertFalse(dropResp1.dropped());++ // test throw RuntimeException+ doThrow(new RuntimeException("mock error")).when(dispatcher).dropTopic(any());+ Response resp2 =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .delete();++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp2.getStatus());++ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp2.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp2.getType());+ }++ private void assertUpdateTopic(TopicUpdatesRequest req, Topic updatedTopic) {+ when(dispatcher.alterTopic(any(), any(TopicChange.class))).thenReturn(updatedTopic);++ Response resp1 =+ target(topicPath(metalake, catalog, schema) + "/topic1")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp1.getStatus());++ TopicResponse topicResp = resp1.readEntity(TopicResponse.class);+ Assertions.assertEquals(0, topicResp.getCode());++ TopicDTO topicDTO = topicResp.getTopic();+ Assertions.assertEquals(updatedTopic.name(), topicDTO.name());+ Assertions.assertEquals(updatedTopic.comment(), topicDTO.comment());+ Assertions.assertEquals(updatedTopic.properties(), topicDTO.properties());+ }++ private Topic mockTopic(String name, String comment, Map<String, String> properties) {+ Topic mockedTopic = mock(Topic.class);+ when(mockedTopic.name()).thenReturn(name);+ when(mockedTopic.comment()).thenReturn(comment);+ when(mockedTopic.properties()).thenReturn(properties);++ Audit mockAudit = mock(Audit.class);+ when(mockAudit.creator()).thenReturn("gravitino");+ when(mockAudit.createTime()).thenReturn(Instant.now());+ when(mockedTopic.auditInfo()).thenReturn(mockAudit);++ return mockedTopic;+ }++ private String topicPath(String metalake, String catalog, String schema) {+ return "/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas/" + schema + "/topics";+ }+}