You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "mchades (via GitHub)" <gi...@apache.org> on 2026/08/26 04:22:50 UTC
[PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
mchades opened a new pull request, #12625:
URL: https://github.com/apache/gravitino/pull/12625
### What changes were proposed in this pull request?
This PR adds Semantic Model REST APIs for create and load, including request and response DTOs, DTO conversion, server routing, exception mapping, and focused tests.
This draft is stacked on the unmerged Semantic Model Core create/load work for #12604 and Definition DTO PR #12624. The feature commit itself contains only create/load changes under common and server.
### Why are the changes needed?
These APIs expose Semantic Model creation and retrieval through the Gravitino REST server while preserving structured definitions, null-versus-empty values, request validation, and Semantic Model-specific errors.
Fix: #12607
### Does this PR introduce _any_ user-facing change?
Yes. It adds POST create and GET load REST operations for schema-scoped Semantic Models. List, alter, drop, OpenAPI, and client changes are outside this feature commit.
### How was this patch tested?
The following local checks passed:
- Semantic Model create/load DTO and REST focused tests
- ./gradlew :common:check :server:check -PskipITs
- ./gradlew :common:spotlessApply :server:spotlessApply
- git diff --check
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4120012301
##########
common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * 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 org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** Represents a request to create a Semantic Model. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties"})
+public class SemanticModelCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private final String comment;
+
+ @JsonProperty("definition")
+ private final SemanticModelDefinitionDTO definition;
+
+ @Nullable
+ @JsonProperty("properties")
+ private final Map<String, String> properties;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelCreateRequest() {
+ this(null, null, null, null);
+ }
+
+ /**
+ * Creates a Semantic Model create request.
+ *
+ * @param name The Semantic Model name.
+ * @param comment The comment, or {@code null} if it is not set.
+ * @param definition The required Semantic Model definition.
+ * @param properties The Gravitino-specific properties, or {@code null} if none are set.
+ */
+ public SemanticModelCreateRequest(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ @Nullable Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = properties;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ definition != null, "\"definition\" field is required and cannot be null");
+ }
Review Comment:
This is deliberate. `SemanticModelCreateRequest.validate()` only checks the required wire fields, while the REST resource owns the single DTO-to-API conversion and nested definition validation. The Java client accepts an already-built `SemanticModelDefinition`, whose builder rejects null definition members before `SemanticModelDefinitionDTO.fromDefinition(...)` constructs the request, so normal client usage still fails locally. I’ll keep #12628 aligned and avoid reintroducing the eager conversion in `validate()`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades merged PR #12625:
URL: https://github.com/apache/gravitino/pull/12625
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4118393397
##########
server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java:
##########
@@ -990,6 +1005,46 @@ public Response handle(OperationType op, String function, String schema, Excepti
}
}
+ private static class SemanticModelExceptionHandler extends BaseExceptionHandler {
+ private static final ExceptionHandler INSTANCE = new SemanticModelExceptionHandler();
+
+ private static String getSemanticModelErrorMsg(
+ String semanticModel, String operation, String schema, String reason) {
+ return String.format(
+ "Failed to operate Semantic Model(s)%s operation [%s] under schema [%s], reason [%s]",
+ semanticModel, operation, schema, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String semanticModel, String schema, Exception e) {
+ String formatted = StringUtil.isBlank(semanticModel) ? "" : " [" + semanticModel + "]";
+ String errorMsg = getSemanticModelErrorMsg(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 SemanticModelAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ return Utils.unsupportedOperation(errorMsg, e);
+
+ } else if (e instanceof ConnectionFailedException) {
+ return Utils.connectionFailed(errorMsg, e);
+
+ } else {
Review Comment:
[Important] `NotInUseException` is not mapped, so a disabled metalake yields 500 instead of 409.
Both new endpoints call `SemanticModelOperationDispatcher.checkRelationalCatalog()` (`core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java:106-108`) -> `CatalogManager.loadCatalog()` (`core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java:786-796`) -> `baseCatalog.checkMetalakeInUse()` (`core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java:257-265`), which throws `MetalakeNotInUseException`. `createSemanticModel`/`loadSemanticModel` additionally go through `schemaDispatcher.loadSchema`/`schemaExists`, which can raise `CatalogNotInUseException`.
`MetalakeNotInUseException extends NotInUseException extends GravitinoRuntimeException`, so it matches none of the six branches here and falls through to `super.handle(...)`. `BaseExceptionHandler` (lines 1216-1251) only special-cases `ConnectionFailedException`, `OptimisticLockException`, `UnmodifiableStatisticException` and `UnsupportedOperationException`, then returns `Utils.internalError(...)` — HTTP 500 with `INTERNAL_ERROR_CODE` and a stack trace. Every other resource returns 409 `NOT_IN_USE_CODE` via `Utils.notInUse` (`server-common/src/main/java/org/apache/gravitino/server/web/Utils.java:163-168`); `grep -n NotInUseException ExceptionHandlers.java` shows the branch in all 22 sibling handlers (lines 242, 284, 325, 366, 410, 451, 535, 576, 611, 649, 687, 754, 783, 811, 852, 892, 924, 962, 999, 1080, 1118). A client would also fail to reconstruct `MetalakeNotInUseException` from the error code.
Add the branch before the `else` (`NotInUseException` is already imported at line 45, so no new import):
```java
} else if (e instanceof NotInUseException) {
return Utils.notInUse(errorMsg, e);
}
```
and a `TestSemanticModelOperations` case asserting 409 + `ErrorConstants.NOT_IN_USE_CODE` for a `MetalakeNotInUseException` thrown by the mock dispatcher.
Verified by: read the full handler and `BaseExceptionHandler` fallback in this file; traced the exception to its throw site through the three core files cited; confirmed the class hierarchy in `api/src/main/java/org/apache/gravitino/exceptions/{MetalakeNotInUseException,NotInUseException}.java` and the status code in `Utils.notInUse`. Not reproduced at runtime — the build rejects JDK 21.
---
_Generated by [Claude Code](https://claude.ai/code)_
##########
common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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 org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** Represents a request to create a Semantic Model. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties"})
+public class SemanticModelCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private final String comment;
+
+ @JsonProperty("definition")
+ private final SemanticModelDefinitionDTO definition;
+
+ @JsonProperty("properties")
+ private final Map<String, String> properties;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelCreateRequest() {
+ this(null, null, null, null);
+ }
+
+ /**
+ * Creates a Semantic Model create request.
+ *
+ * @param name The Semantic Model name.
+ * @param comment The comment, or {@code null} if it is not set.
+ * @param definition The required Semantic Model definition.
+ * @param properties The required Gravitino-specific properties.
+ */
+ public SemanticModelCreateRequest(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = properties;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ definition != null, "\"definition\" field is required and cannot be null");
+ Preconditions.checkArgument(
+ properties != null, "\"properties\" field is required and cannot be null");
Review Comment:
[Question] Is `properties` intended to be a mandatory wire field? This is stricter than every other Gravitino create API.
Rejecting a null `properties` means an HTTP caller must always send `"properties": {}`; omitting the key is a 400. No other create request does this — `SchemaCreateRequest.validate()` (`common/src/main/java/org/apache/gravitino/dto/requests/SchemaCreateRequest.java:108-111`) checks only `name`, and `ModelRegisterRequest` likewise leaves `properties` unvalidated. Since REST request shape is hard to relax once released, it seems worth settling now.
`SemanticModelOperationDispatcher.createSemanticModel` also asserts non-null (line 78), so the strictness is consistent with core — but the REST layer could absorb it by defaulting instead, e.g. pass `properties == null ? Collections.emptyMap() : properties` and drop this precondition. That keeps the core contract intact while matching the rest of the API surface. If mandatory is deliberate, could you note it in the OpenAPI spec when it lands so clients aren't surprised?
Either way there is no test covering a create request with `properties` absent from the JSON (the existing cases always pass a map), so the current behaviour is unpinned.
Verified by: read `validate()` here and compared against `SchemaCreateRequest.validate()` and `ModelRegisterRequest`; checked the core precondition at `SemanticModelOperationDispatcher.java:78`; grepped `TestSemanticModelCreateRequest` and `TestSemanticModelOperations` for an omitted-`properties` case and found none.
---
_Generated by [Claude Code](https://claude.ai/code)_
##########
server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java:
##########
@@ -990,6 +1005,46 @@ public Response handle(OperationType op, String function, String schema, Excepti
}
}
+ private static class SemanticModelExceptionHandler extends BaseExceptionHandler {
+ private static final ExceptionHandler INSTANCE = new SemanticModelExceptionHandler();
+
+ private static String getSemanticModelErrorMsg(
+ String semanticModel, String operation, String schema, String reason) {
+ return String.format(
+ "Failed to operate Semantic Model(s)%s operation [%s] under schema [%s], reason [%s]",
+ semanticModel, operation, schema, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String semanticModel, String schema, Exception e) {
+ String formatted = StringUtil.isBlank(semanticModel) ? "" : " [" + semanticModel + "]";
+ String errorMsg = getSemanticModelErrorMsg(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 SemanticModelAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ return Utils.unsupportedOperation(errorMsg, e);
+
+ } else if (e instanceof ConnectionFailedException) {
+ return Utils.connectionFailed(errorMsg, e);
Review Comment:
[Nit] These two branches are redundant — `BaseExceptionHandler` already maps both identically.
`super.handle(...)` returns `Utils.unsupportedOperation(errorMsg, e)` for `UnsupportedOperationException` (lines 1244-1247) and `Utils.connectionFailed(errorMsg, e)` for `ConnectionFailedException` (lines 1226-1229), i.e. the same responses these branches produce. Dropping them leaves behaviour unchanged and keeps this handler shaped like its siblings (`FunctionExceptionHandler`, starting at line 971, carries neither). The existing assertions for 501 and 502 in `TestSemanticModelOperations` pass either way, since the fallback produces the same status and error code.
Minor, and the reason it is worth a line at all: the handler grew two branches it does not need while missing the one it does (see the `NotInUseException` comment below).
Verified by: read both branches here and the full `BaseExceptionHandler.handle` body at lines 1216-1251; compared against `FunctionExceptionHandler` in the same file.
---
_Generated by [Claude Code](https://claude.ai/code)_
##########
common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelResponse.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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 org.apache.gravitino.dto.responses;
+
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDTO;
+
+/** Represents a response containing one Semantic Model. */
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class SemanticModelResponse extends BaseResponse {
+
+ @JsonProperty("semanticModel")
+ private final SemanticModelDTO semanticModel;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelResponse() {
+ super();
+ this.semanticModel = null;
+ }
+
+ /**
+ * Creates a successful Semantic Model response.
+ *
+ * @param semanticModel The Semantic Model DTO.
+ */
+ public SemanticModelResponse(SemanticModelDTO semanticModel) {
+ super(0);
+ this.semanticModel = semanticModel;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+ Preconditions.checkArgument(semanticModel != null, "semanticModel must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(semanticModel.name()),
+ "semanticModel 'name' must not be null or empty");
+ semanticModel.definition();
Review Comment:
[Nit] This bare statement validates by side effect only — easy to mistake for dead code.
`semanticModel.definition()` is called and the result thrown away. It does do something: `SemanticModelDTO.definition()` runs `Preconditions.checkArgument(definition != null, ...)` and then `definition.toDefinition()`, which re-validates the whole definition (`SemanticModelDTO.java:86-89`). But nothing on this line says so, and it sits between two explicit `Preconditions` calls, so a future reader or an IDE "result unused" cleanup could delete it and silently drop the check.
Worth either a one-line comment saying the call is for its validation side effect, or making the intent explicit. Note this also means every client `validate()` on a load/create response pays a full definition conversion; if that is unwanted, checking the raw DTO for null would be cheaper (it would need a getter on `SemanticModelDTO`, which currently exposes only the `SemanticModel` interface methods).
Verified by: read `validate()` here and `SemanticModelDTO.definition()` at `common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java:85-89`, plus `SemanticModelDefinitionDTO.toDefinition()` to confirm the conversion is not memoized.
---
_Generated by [Claude Code](https://claude.ai/code)_
##########
server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST create and load operations for schema-scoped Semantic Models. */
+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models")
+public class SemanticModelOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SemanticModelOperations.class);
+
+ private final SemanticModelDispatcher dispatcher;
+
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates Semantic Model REST operations.
+ *
+ * @param dispatcher The Semantic Model dispatcher.
+ */
+ @Inject
+ public SemanticModelOperations(SemanticModelDispatcher dispatcher) {
+ this.dispatcher = dispatcher;
+ }
+
+ /**
+ * Creates a Semantic Model.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param request The structured Semantic Model create request.
+ * @return A response containing the created Semantic Model.
+ */
+ @POST
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "create-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "create-semantic-model", absolute = true)
+ public Response createSemanticModel(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ SemanticModelCreateRequest request) {
+ String name = request == null ? "" : request.getName();
+ LOG.info(
+ "Received create Semantic Model request: {}.{}.{}.{}", metalake, catalog, schema, name);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ if (request == null) {
+ throw new IllegalArgumentException("Request body must not be null");
+ }
+ request.validate();
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, request.getName());
+ SemanticModel semanticModel =
+ dispatcher.createSemanticModel(
+ ident, request.getComment(), request.toDefinition(), request.getProperties());
Review Comment:
[Nit] The whole definition object graph is converted twice on every create.
`request.validate()` on line 92 already calls `toDefinition()` (`SemanticModelCreateRequest.java:93`) purely to surface validation errors, and discards the result. Line 97 then calls `request.toDefinition()` again, so `SemanticModelDefinitionDTO.toDefinition()` rebuilds every dataset, field, metric, relationship and custom extension a second time (`SemanticModelDefinitionDTO.java:137-155`, each element via `SemanticDTOUtils.convertArray`). For a large semantic model that is a needless full walk of the graph plus the garbage it produces.
Converting once and reusing it reads better and avoids the duplicate work:
```java
request.validate();
SemanticModelDefinition definition = request.toDefinition();
...
dispatcher.createSemanticModel(ident, request.getComment(), definition, request.getProperties());
```
Verified by: read `validate()` and `toDefinition()` in `SemanticModelCreateRequest`, and `SemanticModelDefinitionDTO.toDefinition()`, confirming both call sites perform the same full conversion with no caching.
---
_Generated by [Claude Code](https://claude.ai/code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4120101699
##########
common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelResponse.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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 org.apache.gravitino.dto.responses;
+
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDTO;
+
+/** Represents a response containing one Semantic Model. */
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class SemanticModelResponse extends BaseResponse {
+
+ @JsonProperty("semanticModel")
+ private final SemanticModelDTO semanticModel;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelResponse() {
+ super();
+ this.semanticModel = null;
+ }
+
+ /**
+ * Creates a successful Semantic Model response.
+ *
+ * @param semanticModel The Semantic Model DTO.
+ */
+ public SemanticModelResponse(SemanticModelDTO semanticModel) {
+ super(0);
+ this.semanticModel = semanticModel;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+ Preconditions.checkArgument(semanticModel != null, "semanticModel must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(semanticModel.name()),
+ "semanticModel 'name' must not be null or empty");
+ Preconditions.checkArgument(semanticModel.hasDefinition(), "definition must not be null");
Review Comment:
Updated the definition precondition message to `semanticModel 'definition' must not be null` and adjusted the matching test assertion for consistency with the adjacent checks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4119886019
##########
common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java:
##########
@@ -0,0 +1,206 @@
+/*
+ * 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 org.apache.gravitino.dto.semantic;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** DTO for a schema-scoped Semantic Model. */
+@EqualsAndHashCode
+@ToString
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties", "audit"})
+public class SemanticModelDTO implements SemanticModel {
+
+ @JsonProperty("name")
+ private String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private String comment;
+
+ @JsonProperty("definition")
+ private SemanticModelDefinitionDTO definition;
+
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ private SemanticModelDTO() {}
+
+ private SemanticModelDTO(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ @Nullable Map<String, String> properties,
+ AuditDTO audit) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = immutableProperties(properties);
+ this.audit = audit;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ @Nullable
+ public String comment() {
+ return comment;
+ }
+
+ /**
+ * Returns whether this DTO contains a Semantic Model definition.
+ *
+ * @return {@code true} if the definition is present, otherwise {@code false}.
+ */
+ public boolean hasDefinition() {
+ return definition != null;
+ }
+
+ @Override
+ public SemanticModelDefinition definition() {
+ Preconditions.checkArgument(definition != null, "definition must not be null");
+ return definition.toDefinition();
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return immutableProperties(properties);
+ }
+
+ @Override
+ public AuditDTO auditInfo() {
+ return audit;
+ }
+
+ /**
+ * Creates a builder for a Semantic Model DTO.
+ *
+ * @return A new builder.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for {@link SemanticModelDTO}. */
+ public static final class Builder {
+
+ private String name;
+ @Nullable private String comment;
+ private SemanticModelDefinitionDTO definition;
+ @Nullable private Map<String, String> properties;
+ private AuditDTO audit;
+
+ private Builder() {}
+
+ /**
+ * Sets the Semantic Model name.
+ *
+ * @param name The Semantic Model name.
+ * @return This builder.
+ */
+ public Builder withName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model comment.
+ *
+ * @param comment The comment, or {@code null} if it is not set.
+ * @return This builder.
+ */
+ public Builder withComment(@Nullable String comment) {
+ this.comment = comment;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model definition.
+ *
+ * @param definition The complete definition DTO.
+ * @return This builder.
+ */
+ public Builder withDefinition(SemanticModelDefinitionDTO definition) {
+ this.definition = definition;
+ return this;
+ }
+
+ /**
+ * Sets the Gravitino-specific Semantic Model properties.
+ *
+ * @param properties The properties, or {@code null} if none are set.
+ * @return This builder.
+ */
+ public Builder withProperties(@Nullable Map<String, String> properties) {
+ this.properties = properties;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model audit information.
+ *
+ * @param audit The audit information.
+ * @return This builder.
+ */
+ public Builder withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return this;
+ }
+
+ /**
+ * Builds a Semantic Model DTO.
+ *
+ * @return The Semantic Model DTO.
+ * @throws IllegalArgumentException If a required field is missing.
+ */
+ public SemanticModelDTO build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be null or empty");
+ Preconditions.checkArgument(definition != null, "definition cannot be null");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+
+ return new SemanticModelDTO(name, comment, definition, properties, audit);
Review Comment:
[Question] `build()` now stores the caller's definition DTO directly - two side effects worth confirming.
Removing the `toDefinition()`/`fromDefinition()` round trip removes the extra traversal, which was the point. It also changes two things that the new tests now pin as intended, so I want to check they are intended rather than incidental:
1. No nested validation at build time. `TestSemanticModelDTO.java:151-161` now asserts that a definition with `new DatasetDTO[] {null}` builds successfully, and `TestSemanticModelResponse.java:94-99` asserts such a payload passes `SemanticModelResponse.validate()`. A client would therefore accept the response and fail later, from `definition()` at line 95, at whatever call site first touches it. That is consistent with other response DTOs being shallow, and the server side cannot produce it (`DTOConverters.toDTO` always builds the definition via `fromDefinition`, so it is well formed by construction) - but it does mean `validate()` is now a presence check only.
2. No defensive copy. The DTO now aliases the caller's `SemanticModelDefinitionDTO`, which holds mutable arrays (`DatasetDTO[]` and friends). No current caller mutates one after `build()` - the only production caller is `DTOConverters.toDTO`, which passes a freshly created instance - so this is latent, not a bug today.
If both are intended, no change needed; a short comment on `build()` saying the definition is stored as given and validated on access would save the next reader the same trip.
Verified by: read `build()`, `definition()` and `hasDefinition()` on this head; read the only production caller `DTOConverters.toDTO(SemanticModel)` (`common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java:330-338`); grepped `SemanticModelDTO` repo-wide - the only other references are the three test classes; read the two new `assertDoesNotThrow` assertions. Not run - the build rejects JDK 21.
##########
common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * 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 org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** Represents a request to create a Semantic Model. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties"})
+public class SemanticModelCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private final String comment;
+
+ @JsonProperty("definition")
+ private final SemanticModelDefinitionDTO definition;
+
+ @Nullable
+ @JsonProperty("properties")
+ private final Map<String, String> properties;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelCreateRequest() {
+ this(null, null, null, null);
+ }
+
+ /**
+ * Creates a Semantic Model create request.
+ *
+ * @param name The Semantic Model name.
+ * @param comment The comment, or {@code null} if it is not set.
+ * @param definition The required Semantic Model definition.
+ * @param properties The Gravitino-specific properties, or {@code null} if none are set.
+ */
+ public SemanticModelCreateRequest(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ @Nullable Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = properties;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ definition != null, "\"definition\" field is required and cannot be null");
+ }
Review Comment:
[Question] `validate()` no longer covers the definition contents - deliberate for the client contract too?
Dropping `toDefinition()` from here was the right fix for the double conversion, and the REST path is unaffected: `SemanticModelOperations.java:95` calls `toDefinition()` inside the same `Utils.doAs` try block, so a malformed definition still maps to 400 through the `IllegalArgumentException` branch at `ExceptionHandlers.java:1023`, and `testCreateSemanticModelErrors` (`TestSemanticModelOperations.java:254-276`) still proves it.
What changes is the meaning of `RESTRequest.validate()` for anyone who is not this resource. The Java client convention is to call `validate()` on a request before putting it on the wire, so once the client PR lands, a caller passing a dataset array with a null element will now get a server 400 instead of a local `IllegalArgumentException`. If that is the intent, fine - it matches `SchemaCreateRequest.validate()`, which is also shallow. If you would rather keep local failure, the cheap version is to keep the conversion out of `validate()` (as now) and have the client call `toDefinition()` itself before sending.
Not blocking either way; mostly worth being explicit about so the client PR does not re-add the eager call and reintroduce the double conversion.
Verified by: read `validate()` and `toDefinition()` here on this head; traced the REST call order at `SemanticModelOperations.java:92-102`; confirmed the 400 branch in `SemanticModelExceptionHandler` and the surviving REST cases in `TestSemanticModelOperations`; compared against `SchemaCreateRequest.validate()`. Not run - the build rejects JDK 21.
##########
common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelResponse.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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 org.apache.gravitino.dto.responses;
+
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDTO;
+
+/** Represents a response containing one Semantic Model. */
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class SemanticModelResponse extends BaseResponse {
+
+ @JsonProperty("semanticModel")
+ private final SemanticModelDTO semanticModel;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelResponse() {
+ super();
+ this.semanticModel = null;
+ }
+
+ /**
+ * Creates a successful Semantic Model response.
+ *
+ * @param semanticModel The Semantic Model DTO.
+ */
+ public SemanticModelResponse(SemanticModelDTO semanticModel) {
+ super(0);
+ this.semanticModel = semanticModel;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+ Preconditions.checkArgument(semanticModel != null, "semanticModel must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(semanticModel.name()),
+ "semanticModel 'name' must not be null or empty");
+ Preconditions.checkArgument(semanticModel.hasDefinition(), "definition must not be null");
Review Comment:
[Nit] Message does not match the two it sits between.
The neighbouring preconditions read `semanticModel 'name' must not be null or empty` (line 60) and `semanticModel 'audit' must not be null` (line 63); this one is bare `definition must not be null`, so a client surfacing the failure loses the object prefix the other two carry. `semanticModel 'definition' must not be null` would line it up. `TestSemanticModelResponse.java:88-90` asserts the current string exactly, so that assertion needs updating in the same change.
Verified by: read all four preconditions in this `validate()` on this head, and read the matching assertions in `TestSemanticModelResponse` (lines 84-93), which pin all three messages verbatim.
##########
server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java:
##########
@@ -0,0 +1,495 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.ErrorConstants;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.semantic.DatasetDTO;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.exceptions.MetalakeNotInUseException;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dialects;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+/** Tests the Semantic Model create/load REST resource and its error mappings. */
+public class TestSemanticModelOperations extends BaseOperationsTest {
+
+ private static final String VND_V1_JSON = "application/vnd.gravitino.v1+json";
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+ @Override
+ public HttpServletRequest get() {
+ return mock(HttpServletRequest.class);
+ }
+ }
+
+ private final SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class);
+ private final String metalake = "semantic_model_metalake";
+ private final String catalog = "semantic_model_catalog";
+ private final String schema = "semantic_model_schema";
+ private final Namespace namespace = NamespaceUtil.ofSemanticModel(metalake, catalog, schema);
+
+ /** {@inheritDoc} */
+ @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(SemanticModelOperations.class);
+ resourceConfig.register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(dispatcher).to(SemanticModelDispatcher.class).ranked(2);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+ return resourceConfig;
+ }
+
+ @BeforeEach
+ void resetDispatcher() {
+ reset(dispatcher);
+ }
+
+ @Test
+ void testLoadSemanticModelReturnsCompleteDefinitionWithoutWrites() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ SemanticModel semanticModel = semanticModel("sales", "Sales definitions");
+ when(dispatcher.loadSemanticModel(ident)).thenReturn(semanticModel);
+
+ Response response = get(semanticModelPath() + "/sales");
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ SemanticModelResponse body = response.readEntity(SemanticModelResponse.class);
+ body.validate();
+ Assertions.assertEquals("sales", body.getSemanticModel().name());
+ Assertions.assertEquals("Sales definitions", body.getSemanticModel().comment());
+ Assertions.assertEquals(semanticModel.definition(), body.getSemanticModel().definition());
+ Assertions.assertEquals("orders", body.getSemanticModel().definition().datasets()[0].name());
+ Assertions.assertEquals(
+ "order_total", body.getSemanticModel().definition().metrics()[0].name());
+ Assertions.assertEquals(
+ "acme", body.getSemanticModel().definition().customExtensions()[0].vendorName());
+ Assertions.assertEquals(Map.of("domain", "sales"), body.getSemanticModel().properties());
+ Assertions.assertEquals("tester", body.getSemanticModel().auditInfo().creator());
+ verify(dispatcher).loadSemanticModel(ident);
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testLoadSemanticModelNotFound() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ doThrow(new NoSuchSemanticModelException("sales does not exist"))
+ .when(dispatcher)
+ .loadSemanticModel(ident);
+
+ assertError(
+ get(semanticModelPath() + "/sales"),
+ Response.Status.NOT_FOUND,
+ ErrorConstants.NOT_FOUND_CODE,
+ NoSuchSemanticModelException.class.getSimpleName(),
+ "sales does not exist");
+ }
+
+ @Test
+ void testLoadSemanticModelNotInUse() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ doThrow(new MetalakeNotInUseException("metalake is not in use"))
+ .when(dispatcher)
+ .loadSemanticModel(ident);
+
+ assertError(
+ get(semanticModelPath() + "/sales"),
+ Response.Status.CONFLICT,
+ ErrorConstants.NOT_IN_USE_CODE,
+ MetalakeNotInUseException.class.getSimpleName(),
+ "metalake is not in use");
+ }
Review Comment:
[Nit] The not-in-use case is covered on load only; create reaches the same check.
This test pins the fix well. The asymmetry is that `createSemanticModel` runs the identical path - `SemanticModelOperationDispatcher.checkRelationalCatalog()` (`core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java:97`, the load side being line 81) -> `CatalogManager.loadCatalog()` -> `BaseCatalog.checkMetalakeInUse()` - and additionally goes through `schemaDispatcher.loadSchema` (line 99), which can raise `CatalogNotInUseException`. Both resolve through the same new branch, so the risk of a real regression is low; but a create-side twin (or a `CatalogNotInUseException` variant) would cover the other `NotInUseException` subclass and the other endpoint for about four lines.
Verified by: read this test and `testCreateSemanticModelErrors` on this head - no create case throws a `NotInUseException` subclass; re-read the dispatcher call path cited above; confirmed `CatalogNotInUseException` and `MetalakeNotInUseException` both extend `NotInUseException` (`api/src/main/java/org/apache/gravitino/exceptions/NotInUseException.java:25`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4118823100
##########
server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java:
##########
@@ -990,6 +1005,46 @@ public Response handle(OperationType op, String function, String schema, Excepti
}
}
+ private static class SemanticModelExceptionHandler extends BaseExceptionHandler {
+ private static final ExceptionHandler INSTANCE = new SemanticModelExceptionHandler();
+
+ private static String getSemanticModelErrorMsg(
+ String semanticModel, String operation, String schema, String reason) {
+ return String.format(
+ "Failed to operate Semantic Model(s)%s operation [%s] under schema [%s], reason [%s]",
+ semanticModel, operation, schema, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String semanticModel, String schema, Exception e) {
+ String formatted = StringUtil.isBlank(semanticModel) ? "" : " [" + semanticModel + "]";
+ String errorMsg = getSemanticModelErrorMsg(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 SemanticModelAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ return Utils.unsupportedOperation(errorMsg, e);
+
+ } else if (e instanceof ConnectionFailedException) {
+ return Utils.connectionFailed(errorMsg, e);
Review Comment:
These branches are not behaviorally redundant. The direct mappings preserve the Semantic Model-specific error message. Falling through to `BaseExceptionHandler` rebuilds a generic `Failed to operate object...` message and logs the same exception again.
The HTTP status and application error code would remain 501/502, but the response message and logging would change, so I’ll keep the explicit branches.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4119803174
##########
common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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 org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** Represents a request to create a Semantic Model. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties"})
+public class SemanticModelCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private final String comment;
+
+ @JsonProperty("definition")
+ private final SemanticModelDefinitionDTO definition;
+
+ @JsonProperty("properties")
+ private final Map<String, String> properties;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelCreateRequest() {
+ this(null, null, null, null);
+ }
+
+ /**
+ * Creates a Semantic Model create request.
+ *
+ * @param name The Semantic Model name.
+ * @param comment The comment, or {@code null} if it is not set.
+ * @param definition The required Semantic Model definition.
+ * @param properties The required Gravitino-specific properties.
+ */
+ public SemanticModelCreateRequest(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = properties;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ definition != null, "\"definition\" field is required and cannot be null");
+ Preconditions.checkArgument(
+ properties != null, "\"properties\" field is required and cannot be null");
Review Comment:
`properties` is now optional on the wire. The request keeps an omitted field as null, and the REST resource passes an empty map to the dispatcher. Added DTO and REST coverage for the omitted field.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#issuecomment-5421190491
<!-- coverage-report -->
### Code Coverage Report
|Overall Project|68.44% **`+0.3%`**|:green_circle:|
|:-|:-|:-:|
|Files changed|74.81%|:green_circle:|
<br>
|Module|Coverage||
|:-|:-|:-:|
|aliyun|19.74%|:red_circle:|
|api|52.94%|:green_circle:|
|authorization-common|85.96%|:green_circle:|
|authorization-ranger|4.38%|:red_circle:|
|aws|53.54%|:green_circle:|
|azure|32.1%|:red_circle:|
|catalog-common|9.9%|:red_circle:|
|catalog-fileset|80.02%|:green_circle:|
|catalog-glue|69.24%|:green_circle:|
|catalog-hive|82.96%|:green_circle:|
|catalog-jdbc-common|45.69%|:green_circle:|
|catalog-jdbc-doris|82.44%|:green_circle:|
|catalog-jdbc-mysql|79.33%|:green_circle:|
|catalog-jdbc-postgresql|83.39%|:green_circle:|
|catalog-jdbc-starrocks|79.16%|:green_circle:|
|catalog-kafka|76.99%|:green_circle:|
|catalog-lakehouse-generic|59.35%|:green_circle:|
|catalog-lakehouse-hudi|79.1%|:green_circle:|
|catalog-lakehouse-iceberg|85.86%|:green_circle:|
|catalog-lakehouse-paimon|84.26%|:green_circle:|
|catalog-model|77.99%|:green_circle:|
|cli|44.48%|:green_circle:|
|client-java|78.07%|:green_circle:|
|common|55.43% **`+0.72%`**|:green_circle:|
|core|83.5% **`-0.4%`**|:green_circle:|
|filesystem-hadoop3|76.45%|:green_circle:|
|flink|0.0%|:red_circle:|
|flink-common|50.29%|:green_circle:|
|flink-runtime|0.0%|:red_circle:|
|gcp|32.2%|:red_circle:|
|hadoop-auth|68.0%|:green_circle:|
|hadoop-common|17.84%|:red_circle:|
|hive-metastore-common|53.4%|:green_circle:|
|iceberg-aliyun-bundle|0.0%|:red_circle:|
|iceberg-common|64.75%|:green_circle:|
|iceberg-rest-server|75.31%|:green_circle:|
|idp-basic|85.98%|:green_circle:|
|integration-test-common|0.0%|:red_circle:|
|jobs|62.92%|:green_circle:|
|lance-common|32.81%|:red_circle:|
|lance-rest-server|64.78%|:green_circle:|
|lineage|53.02%|:green_circle:|
|optimizer|83.24%|:green_circle:|
|optimizer-api|21.95%|:red_circle:|
|server|87.67% **`-1.71%`**|:green_circle:|
|server-common|79.59%|:green_circle:|
|spark|28.57%|:red_circle:|
|spark-common|48.92%|:green_circle:|
|tencent|69.84%|:green_circle:|
|trino-connector|47.41%|:green_circle:|
<details>
<summary>Files</summary>
|Module|File|Coverage||
|:-|:-|:-|:-:|
|common|[CustomExtensionDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/CustomExtensionDTO.java)|100.0%|:green_circle:|
||[DatasetDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/DatasetDTO.java)|100.0%|:green_circle:|
||[DialectExpressionDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/DialectExpressionDTO.java)|100.0%|:green_circle:|
||[DimensionDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/DimensionDTO.java)|100.0%|:green_circle:|
||[ExpressionDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/ExpressionDTO.java)|100.0%|:green_circle:|
||[FieldDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/FieldDTO.java)|100.0%|:green_circle:|
||[MetricDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/MetricDTO.java)|100.0%|:green_circle:|
||[RelationshipDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/RelationshipDTO.java)|100.0%|:green_circle:|
||[SemanticModelDefinitionDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionDTO.java)|100.0%|:green_circle:|
||[AIContextDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/AIContextDTO.java)|94.74%|:green_circle:|
||[SemanticModelDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java)|94.29%|:green_circle:|
||[AIContextObjectDTO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/AIContextObjectDTO.java)|89.87%|:green_circle:|
||[SemanticDTOUtils.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticDTOUtils.java)|89.74%|:green_circle:|
||[SemanticModelResponse.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelResponse.java)|88.24%|:green_circle:|
||[SemanticModelCreateRequest.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java)|81.82%|:green_circle:|
||[DTOConverters.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java)|30.51%|:red_circle:|
|core|[Entity.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/Entity.java)|100.0%|:green_circle:|
||[ManagedSemanticModelOperations.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java)|100.0%|:green_circle:|
||[DefaultMapperPackageProvider.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java)|100.0%|:green_circle:|
||[SchemaMetaService.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java)|97.59%|:green_circle:|
||[Capability.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/connector/capability/Capability.java)|97.44%|:green_circle:|
||[SemanticModelEntity.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java)|97.14%|:green_circle:|
||[SemanticModelNormalizeDispatcher.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java)|96.3%|:green_circle:|
||[BaseEntityCache.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java)|92.31%|:green_circle:|
||[SemanticModelValidator.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java)|92.21%|:green_circle:|
||[SemanticModelPO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java)|92.0%|:green_circle:|
||[SemanticModelDefinitionSerDe.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java)|89.16%|:green_circle:|
||[NamespaceUtil.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java)|88.41%|:green_circle:|
||[SemanticModelMetaService.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java)|87.1%|:green_circle:|
||[JDBCBackend.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java)|84.48%|:green_circle:|
||[SemanticModelVersionInfoSQLProviderFactory.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java)|83.33%|:green_circle:|
||[RelationalEntityStoreIdResolver.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java)|78.9%|:green_circle:|
||[SemanticModelOperationDispatcher.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java)|78.38%|:green_circle:|
||[CapabilityHelpers.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java)|78.32%|:green_circle:|
||[SemanticModelVersionInfoPO.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java)|75.61%|:green_circle:|
||[NameIdentifierUtil.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java)|74.06%|:green_circle:|
||[SemanticModelMetaSQLProviderFactory.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java)|68.75%|:green_circle:|
||[SemanticModelVersionInfoBaseSQLProvider.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java)|66.67%|:green_circle:|
||[MetadataObjectUtil.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java)|58.33%|:red_circle:|
||[SemanticModelMetaPostgreSQLProvider.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java)|50.0%|:red_circle:|
||[SemanticModelVersionInfoPostgreSQLProvider.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java)|50.0%|:red_circle:|
||[SemanticModelMetaBaseSQLProvider.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java)|42.86%|:red_circle:|
||[GravitinoEnv.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/GravitinoEnv.java)|29.82%|:red_circle:|
||[SemanticModelPOStorageOps.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java)|27.27%|:red_circle:|
||[SemanticModelDispatcher.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java)|0.0%|:red_circle:|
||[SemanticModelMetaMapper.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java)|0.0%|:red_circle:|
||[SemanticModelVersionInfoMapper.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java)|0.0%|:red_circle:|
|server|[SemanticModelOperations.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java)|100.0%|:green_circle:|
||[ExceptionHandlers.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java)|83.81%|:green_circle:|
||[GravitinoServer.java](https://github.com/mchades/gravitino/blob/cb7e2e79317225a0a934138d7d472a5e05e75c17/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java)|63.04%|:green_circle:|
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4118928638
##########
common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelResponse.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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 org.apache.gravitino.dto.responses;
+
+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;
+import org.apache.gravitino.dto.semantic.SemanticModelDTO;
+
+/** Represents a response containing one Semantic Model. */
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class SemanticModelResponse extends BaseResponse {
+
+ @JsonProperty("semanticModel")
+ private final SemanticModelDTO semanticModel;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelResponse() {
+ super();
+ this.semanticModel = null;
+ }
+
+ /**
+ * Creates a successful Semantic Model response.
+ *
+ * @param semanticModel The Semantic Model DTO.
+ */
+ public SemanticModelResponse(SemanticModelDTO semanticModel) {
+ super(0);
+ this.semanticModel = semanticModel;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+ Preconditions.checkArgument(semanticModel != null, "semanticModel must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(semanticModel.name()),
+ "semanticModel 'name' must not be null or empty");
+ semanticModel.definition();
Review Comment:
Replaced the side-effect call with an explicit shallow `hasDefinition()` presence check, consistent with other response DTO validators. `SemanticModelDTO.Builder` now keeps the supplied definition DTO instead of round-tripping it through the API model, removing the extra validation-only traversal.
##########
server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java:
##########
@@ -990,6 +1005,46 @@ public Response handle(OperationType op, String function, String schema, Excepti
}
}
+ private static class SemanticModelExceptionHandler extends BaseExceptionHandler {
+ private static final ExceptionHandler INSTANCE = new SemanticModelExceptionHandler();
+
+ private static String getSemanticModelErrorMsg(
+ String semanticModel, String operation, String schema, String reason) {
+ return String.format(
+ "Failed to operate Semantic Model(s)%s operation [%s] under schema [%s], reason [%s]",
+ semanticModel, operation, schema, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String semanticModel, String schema, Exception e) {
+ String formatted = StringUtil.isBlank(semanticModel) ? "" : " [" + semanticModel + "]";
+ String errorMsg = getSemanticModelErrorMsg(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 SemanticModelAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ return Utils.unsupportedOperation(errorMsg, e);
+
+ } else if (e instanceof ConnectionFailedException) {
+ return Utils.connectionFailed(errorMsg, e);
+
+ } else {
Review Comment:
Added the `NotInUseException` mapping to `Utils.notInUse(...)` and a REST test covering `MetalakeNotInUseException` as HTTP 409 with `NOT_IN_USE_CODE`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4105411778
##########
server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST create and load operations for schema-scoped Semantic Models. */
+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models")
Review Comment:
Authorization is intentionally out of scope for this PR and is tracked by #12594 / #12867. That work owns the Semantic Model privileges, ownership hook, authorization expressions, filtering, and REST enforcement.
Since `SemanticModelOperations` is introduced by this PR, #12867 will need to rebase after this change and add the resource to `GravitinoInterceptionService` together with the endpoint authorization annotations. No authorization changes are planned in this PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4095110149
##########
server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST create and load operations for schema-scoped Semantic Models. */
+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models")
Review Comment:
This new resource is not covered by the server's authorization interceptor: `GravitinoInterceptionService.getDescriptorFilter()` has an explicit allowlist that does not include `SemanticModelOperations`, and neither endpoint declares `@AuthorizationExpression`/`@AuthorizationMetadata`. With authorization enabled, these requests bypass the metadata authorization checks applied to tables, views, and functions, allowing callers without the required privileges to create or load Semantic Models. Add this resource to the interceptor allowlist and apply the appropriate schema/model authorization expressions and parameter metadata (or enforce equivalent checks) before exposing it.
This issue also appears in the following locations of the same file:
- line 73
- line 120
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4120056849
##########
common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java:
##########
@@ -0,0 +1,206 @@
+/*
+ * 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 org.apache.gravitino.dto.semantic;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/** DTO for a schema-scoped Semantic Model. */
+@EqualsAndHashCode
+@ToString
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({"name", "comment", "definition", "properties", "audit"})
+public class SemanticModelDTO implements SemanticModel {
+
+ @JsonProperty("name")
+ private String name;
+
+ @Nullable
+ @JsonProperty("comment")
+ private String comment;
+
+ @JsonProperty("definition")
+ private SemanticModelDefinitionDTO definition;
+
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ private SemanticModelDTO() {}
+
+ private SemanticModelDTO(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinitionDTO definition,
+ @Nullable Map<String, String> properties,
+ AuditDTO audit) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = immutableProperties(properties);
+ this.audit = audit;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ @Nullable
+ public String comment() {
+ return comment;
+ }
+
+ /**
+ * Returns whether this DTO contains a Semantic Model definition.
+ *
+ * @return {@code true} if the definition is present, otherwise {@code false}.
+ */
+ public boolean hasDefinition() {
+ return definition != null;
+ }
+
+ @Override
+ public SemanticModelDefinition definition() {
+ Preconditions.checkArgument(definition != null, "definition must not be null");
+ return definition.toDefinition();
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return immutableProperties(properties);
+ }
+
+ @Override
+ public AuditDTO auditInfo() {
+ return audit;
+ }
+
+ /**
+ * Creates a builder for a Semantic Model DTO.
+ *
+ * @return A new builder.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for {@link SemanticModelDTO}. */
+ public static final class Builder {
+
+ private String name;
+ @Nullable private String comment;
+ private SemanticModelDefinitionDTO definition;
+ @Nullable private Map<String, String> properties;
+ private AuditDTO audit;
+
+ private Builder() {}
+
+ /**
+ * Sets the Semantic Model name.
+ *
+ * @param name The Semantic Model name.
+ * @return This builder.
+ */
+ public Builder withName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model comment.
+ *
+ * @param comment The comment, or {@code null} if it is not set.
+ * @return This builder.
+ */
+ public Builder withComment(@Nullable String comment) {
+ this.comment = comment;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model definition.
+ *
+ * @param definition The complete definition DTO.
+ * @return This builder.
+ */
+ public Builder withDefinition(SemanticModelDefinitionDTO definition) {
+ this.definition = definition;
+ return this;
+ }
+
+ /**
+ * Sets the Gravitino-specific Semantic Model properties.
+ *
+ * @param properties The properties, or {@code null} if none are set.
+ * @return This builder.
+ */
+ public Builder withProperties(@Nullable Map<String, String> properties) {
+ this.properties = properties;
+ return this;
+ }
+
+ /**
+ * Sets the Semantic Model audit information.
+ *
+ * @param audit The audit information.
+ * @return This builder.
+ */
+ public Builder withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return this;
+ }
+
+ /**
+ * Builds a Semantic Model DTO.
+ *
+ * @return The Semantic Model DTO.
+ * @throws IllegalArgumentException If a required field is missing.
+ */
+ public SemanticModelDTO build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be null or empty");
+ Preconditions.checkArgument(definition != null, "definition cannot be null");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+
+ return new SemanticModelDTO(name, comment, definition, properties, audit);
Review Comment:
The shallow build-time validation is intentional, but the two downstream effects are slightly different from described. The Java client’s `GenericSemanticModel` constructor immediately calls `semanticModel.definition()`, so an invalid nested response fails before the client operation returns rather than at an arbitrary later accessor. Also, `SemanticModelDefinitionDTO` copies its arrays in the constructor and returns defensive copies from its array getters; `testDefinitionAndPropertiesAreDefensive` covers mutation of the original datasets array. Storing the DTO directly therefore removes the conversion round trip without exposing mutable array state. No additional change is needed here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4120084787
##########
server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java:
##########
@@ -0,0 +1,495 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.ErrorConstants;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.semantic.DatasetDTO;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.exceptions.MetalakeNotInUseException;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dialects;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+/** Tests the Semantic Model create/load REST resource and its error mappings. */
+public class TestSemanticModelOperations extends BaseOperationsTest {
+
+ private static final String VND_V1_JSON = "application/vnd.gravitino.v1+json";
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+ @Override
+ public HttpServletRequest get() {
+ return mock(HttpServletRequest.class);
+ }
+ }
+
+ private final SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class);
+ private final String metalake = "semantic_model_metalake";
+ private final String catalog = "semantic_model_catalog";
+ private final String schema = "semantic_model_schema";
+ private final Namespace namespace = NamespaceUtil.ofSemanticModel(metalake, catalog, schema);
+
+ /** {@inheritDoc} */
+ @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(SemanticModelOperations.class);
+ resourceConfig.register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(dispatcher).to(SemanticModelDispatcher.class).ranked(2);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+ return resourceConfig;
+ }
+
+ @BeforeEach
+ void resetDispatcher() {
+ reset(dispatcher);
+ }
+
+ @Test
+ void testLoadSemanticModelReturnsCompleteDefinitionWithoutWrites() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ SemanticModel semanticModel = semanticModel("sales", "Sales definitions");
+ when(dispatcher.loadSemanticModel(ident)).thenReturn(semanticModel);
+
+ Response response = get(semanticModelPath() + "/sales");
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ SemanticModelResponse body = response.readEntity(SemanticModelResponse.class);
+ body.validate();
+ Assertions.assertEquals("sales", body.getSemanticModel().name());
+ Assertions.assertEquals("Sales definitions", body.getSemanticModel().comment());
+ Assertions.assertEquals(semanticModel.definition(), body.getSemanticModel().definition());
+ Assertions.assertEquals("orders", body.getSemanticModel().definition().datasets()[0].name());
+ Assertions.assertEquals(
+ "order_total", body.getSemanticModel().definition().metrics()[0].name());
+ Assertions.assertEquals(
+ "acme", body.getSemanticModel().definition().customExtensions()[0].vendorName());
+ Assertions.assertEquals(Map.of("domain", "sales"), body.getSemanticModel().properties());
+ Assertions.assertEquals("tester", body.getSemanticModel().auditInfo().creator());
+ verify(dispatcher).loadSemanticModel(ident);
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testLoadSemanticModelNotFound() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ doThrow(new NoSuchSemanticModelException("sales does not exist"))
+ .when(dispatcher)
+ .loadSemanticModel(ident);
+
+ assertError(
+ get(semanticModelPath() + "/sales"),
+ Response.Status.NOT_FOUND,
+ ErrorConstants.NOT_FOUND_CODE,
+ NoSuchSemanticModelException.class.getSimpleName(),
+ "sales does not exist");
+ }
+
+ @Test
+ void testLoadSemanticModelNotInUse() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ doThrow(new MetalakeNotInUseException("metalake is not in use"))
+ .when(dispatcher)
+ .loadSemanticModel(ident);
+
+ assertError(
+ get(semanticModelPath() + "/sales"),
+ Response.Status.CONFLICT,
+ ErrorConstants.NOT_IN_USE_CODE,
+ MetalakeNotInUseException.class.getSimpleName(),
+ "metalake is not in use");
+ }
Review Comment:
The mapping is implemented in the shared `SemanticModelExceptionHandler`, and the existing load test exercises the exact `NotInUseException` branch with a concrete subclass. The create error cases already verify that create exceptions reach the same handler. Since the dispatcher is mocked here, adding a create-side `CatalogNotInUseException` case would not exercise the Core catalog/schema path and would only repeat the same mapping assertion, so I’ll keep the focused regression test as-is.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12607] feat(server): Add Semantic Model create and load REST APIs [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on code in PR #12625:
URL: https://github.com/apache/gravitino/pull/12625#discussion_r4118928636
##########
server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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 org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.responses.SemanticModelResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST create and load operations for schema-scoped Semantic Models. */
+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models")
+public class SemanticModelOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SemanticModelOperations.class);
+
+ private final SemanticModelDispatcher dispatcher;
+
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates Semantic Model REST operations.
+ *
+ * @param dispatcher The Semantic Model dispatcher.
+ */
+ @Inject
+ public SemanticModelOperations(SemanticModelDispatcher dispatcher) {
+ this.dispatcher = dispatcher;
+ }
+
+ /**
+ * Creates a Semantic Model.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param request The structured Semantic Model create request.
+ * @return A response containing the created Semantic Model.
+ */
+ @POST
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "create-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "create-semantic-model", absolute = true)
+ public Response createSemanticModel(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ SemanticModelCreateRequest request) {
+ String name = request == null ? "" : request.getName();
+ LOG.info(
+ "Received create Semantic Model request: {}.{}.{}.{}", metalake, catalog, schema, name);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ if (request == null) {
+ throw new IllegalArgumentException("Request body must not be null");
+ }
+ request.validate();
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, request.getName());
+ SemanticModel semanticModel =
+ dispatcher.createSemanticModel(
+ ident, request.getComment(), request.toDefinition(), request.getProperties());
Review Comment:
Removed the validation-only `toDefinition()` call from `SemanticModelCreateRequest.validate()`. The REST resource now converts the definition once, stores the result locally, and passes that instance to the dispatcher.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org