World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#5872] feat(client): Add model management Java client API (#6003)
Jerry Shao0c516e26abcc
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.javaindex 20aa193198..560dae06d1 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java@@ -124,6 +124,18 @@ class DTOConverters {.withAudit((AuditDTO) catalog.auditInfo()).withRestClient(client).build();+ case MODEL:+ return GenericModelCatalog.builder()+ .withNamespace(namespace)+ .withName(catalog.name())+ .withType(catalog.type())+ .withProvider(catalog.provider())+ .withComment(catalog.comment())+ .withProperties(catalog.properties())+ .withAudit((AuditDTO) catalog.auditInfo())+ .withRestClient(client)+ .build();+default:throw new UnsupportedOperationException("Unsupported catalog type: " + catalog.type());}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.javaindex 776300a5a6..2fca9cde35 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java@@ -41,12 +41,16 @@ import org.apache.gravitino.exceptions.InUseException;import org.apache.gravitino.exceptions.MetalakeAlreadyExistsException;import org.apache.gravitino.exceptions.MetalakeInUseException;import org.apache.gravitino.exceptions.MetalakeNotInUseException;+import org.apache.gravitino.exceptions.ModelAlreadyExistsException;+import org.apache.gravitino.exceptions.ModelVersionAliasesAlreadyExistException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchCredentialException;import org.apache.gravitino.exceptions.NoSuchFilesetException;import org.apache.gravitino.exceptions.NoSuchGroupException;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;+import org.apache.gravitino.exceptions.NoSuchModelException;+import org.apache.gravitino.exceptions.NoSuchModelVersionException;import org.apache.gravitino.exceptions.NoSuchPartitionException;import org.apache.gravitino.exceptions.NoSuchRoleException;import org.apache.gravitino.exceptions.NoSuchSchemaException;@@ -220,6 +224,15 @@ public class ErrorHandlers {return OwnerErrorHandler.INSTANCE;}+ /**+ * Creates an error handler specific to Model operations.+ *+ * @return A Consumer representing the Model error handler.+ */+ public static Consumer<ErrorResponse> modelErrorHandler() {+ return ModelErrorHandler.INSTANCE;+ }+private ErrorHandlers() {}/**@@ -987,6 +1000,69 @@ public class ErrorHandlers {}}+ /** Error handler specific to Model operations. */+ @SuppressWarnings("FormatStringAnnotation")+ private static class ModelErrorHandler extends RestErrorHandler {++ private static final ModelErrorHandler INSTANCE = new ModelErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMsg = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ throw new IllegalArgumentException(errorMsg);++ case ErrorConstants.NOT_FOUND_CODE:+ if (errorResponse.getType().equals(NoSuchSchemaException.class.getSimpleName())) {+ throw new NoSuchSchemaException(errorMsg);+ } else if (errorResponse.getType().equals(NoSuchModelException.class.getSimpleName())) {+ throw new NoSuchModelException(errorMsg);+ } else if (errorResponse+ .getType()+ .equals(NoSuchModelVersionException.class.getSimpleName())) {+ throw new NoSuchModelVersionException(errorMsg);+ } else {+ throw new NotFoundException(errorMsg);+ }++ case ErrorConstants.ALREADY_EXISTS_CODE:+ if (errorResponse.getType().equals(ModelAlreadyExistsException.class.getSimpleName())) {+ throw new ModelAlreadyExistsException(errorMsg);+ } else if (errorResponse+ .getType()+ .equals(ModelVersionAliasesAlreadyExistException.class.getSimpleName())) {+ throw new ModelVersionAliasesAlreadyExistException(errorMsg);+ } else {+ throw new AlreadyExistsException(errorMsg);+ }++ case ErrorConstants.FORBIDDEN_CODE:+ throw new ForbiddenException(errorMsg);++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMsg);++ case ErrorConstants.NOT_IN_USE_CODE:+ if (errorResponse.getType().equals(CatalogNotInUseException.class.getSimpleName())) {+ throw new CatalogNotInUseException(errorMsg);++ } else if (errorResponse+ .getType()+ .equals(MetalakeNotInUseException.class.getSimpleName())) {+ throw new MetalakeNotInUseException(errorMsg);++ } else {+ throw new NotInUseException(errorMsg);+ }++ default:+ super.accept(errorResponse);+ }+ }+ }+/** Generic error handler for REST requests. */private static class RestErrorHandler extends ErrorHandler {private static final ErrorHandler INSTANCE = new RestErrorHandler();diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.javanew file mode 100644index 0000000000..2d356b712f--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java@@ -0,0 +1,89 @@+/*+ * 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.client;++import java.util.Map;+import org.apache.gravitino.Audit;+import org.apache.gravitino.authorization.SupportsRoles;+import org.apache.gravitino.dto.model.ModelDTO;+import org.apache.gravitino.model.Model;+import org.apache.gravitino.tag.SupportsTags;++/** Represents a generic model. */+class GenericModel implements Model {++ private final ModelDTO modelDTO;++ GenericModel(ModelDTO modelDTO) {+ this.modelDTO = modelDTO;+ }++ @Override+ public Audit auditInfo() {+ return modelDTO.auditInfo();+ }++ @Override+ public String name() {+ return modelDTO.name();+ }++ @Override+ public String comment() {+ return modelDTO.comment();+ }++ @Override+ public Map<String, String> properties() {+ return modelDTO.properties();+ }++ @Override+ public int latestVersion() {+ return modelDTO.latestVersion();+ }++ @Override+ public SupportsTags supportsTags() {+ throw new UnsupportedOperationException("Not supported yet.");+ }++ @Override+ public SupportsRoles supportsRoles() {+ throw new UnsupportedOperationException("Not supported yet.");+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof GenericModel)) {+ return false;+ }++ GenericModel that = (GenericModel) o;+ return modelDTO.equals(that.modelDTO);+ }++ @Override+ public int hashCode() {+ return modelDTO.hashCode();+ }+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelCatalog.javanew file mode 100644index 0000000000..9c1c4654d3--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelCatalog.java@@ -0,0 +1,330 @@+/*+ * 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.client;++import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Collections;+import java.util.Map;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.dto.CatalogDTO;+import org.apache.gravitino.dto.requests.ModelRegisterRequest;+import org.apache.gravitino.dto.requests.ModelVersionLinkRequest;+import org.apache.gravitino.dto.responses.BaseResponse;+import org.apache.gravitino.dto.responses.DropResponse;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.ModelResponse;+import org.apache.gravitino.dto.responses.ModelVersionListResponse;+import org.apache.gravitino.dto.responses.ModelVersionResponse;+import org.apache.gravitino.exceptions.ModelAlreadyExistsException;+import org.apache.gravitino.exceptions.ModelVersionAliasesAlreadyExistException;+import org.apache.gravitino.exceptions.NoSuchModelException;+import org.apache.gravitino.exceptions.NoSuchModelVersionException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.model.Model;+import org.apache.gravitino.model.ModelCatalog;+import org.apache.gravitino.model.ModelVersion;+import org.apache.gravitino.rest.RESTUtils;++class GenericModelCatalog extends BaseSchemaCatalog implements ModelCatalog {++ GenericModelCatalog(+ Namespace namespace,+ String catalogName,+ Catalog.Type catalogType,+ String provider,+ String comment,+ Map<String, String> properties,+ AuditDTO auditDTO,+ RESTClient restClient) {+ super(namespace, catalogName, catalogType, provider, comment, properties, auditDTO, restClient);+ }++ @Override+ public ModelCatalog asModelCatalog() {+ return this;+ }++ @Override+ public NameIdentifier[] listModels(Namespace namespace) throws NoSuchSchemaException {+ checkModelNamespace(namespace);++ Namespace modelFullNs = modelFullNamespace(namespace);+ EntityListResponse resp =+ restClient.get(+ formatModelRequestPath(modelFullNs),+ EntityListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return Arrays.stream(resp.identifiers())+ .map(id -> NameIdentifier.of(id.namespace().level(2), id.name()))+ .toArray(NameIdentifier[]::new);+ }++ @Override+ public Model getModel(NameIdentifier ident) throws NoSuchModelException {+ checkModelNameIdentifier(ident);++ Namespace modelFullNs = modelFullNamespace(ident.namespace());+ ModelResponse resp =+ restClient.get(+ formatModelRequestPath(modelFullNs) + "/" + RESTUtils.encodeString(ident.name()),+ ModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return new GenericModel(resp.getModel());+ }++ @Override+ public Model registerModel(NameIdentifier ident, String comment, Map<String, String> properties)+ throws NoSuchSchemaException, ModelAlreadyExistsException {+ checkModelNameIdentifier(ident);++ Namespace modelFullNs = modelFullNamespace(ident.namespace());+ ModelRegisterRequest req = new ModelRegisterRequest(ident.name(), comment, properties);+ req.validate();++ ModelResponse resp =+ restClient.post(+ formatModelRequestPath(modelFullNs),+ req,+ ModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());++ resp.validate();+ return new GenericModel(resp.getModel());+ }++ @Override+ public boolean deleteModel(NameIdentifier ident) {+ checkModelNameIdentifier(ident);++ Namespace modelFullNs = modelFullNamespace(ident.namespace());+ DropResponse resp =+ restClient.delete(+ formatModelRequestPath(modelFullNs) + "/" + RESTUtils.encodeString(ident.name()),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return resp.dropped();+ }++ @Override+ public int[] listModelVersions(NameIdentifier ident) throws NoSuchModelException {+ checkModelNameIdentifier(ident);++ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ ModelVersionListResponse resp =+ restClient.get(+ formatModelVersionRequestPath(modelFullIdent) + "/versions",+ ModelVersionListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return resp.getVersions();+ }++ @Override+ public ModelVersion getModelVersion(NameIdentifier ident, int version)+ throws NoSuchModelVersionException {+ checkModelNameIdentifier(ident);+ Preconditions.checkArgument(version >= 0, "Model version must be non-negative");++ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ ModelVersionResponse resp =+ restClient.get(+ formatModelVersionRequestPath(modelFullIdent) + "/versions/" + version,+ ModelVersionResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();+ return new GenericModelVersion(resp.getModelVersion());+ }++ @Override+ public ModelVersion getModelVersion(NameIdentifier ident, String alias)+ throws NoSuchModelVersionException {+ checkModelNameIdentifier(ident);+ Preconditions.checkArgument(StringUtils.isNotBlank(alias), "Model alias must be non-empty");++ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ ModelVersionResponse resp =+ restClient.get(+ formatModelVersionRequestPath(modelFullIdent)+ + "/aliases/"+ + RESTUtils.encodeString(alias),+ ModelVersionResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());++ resp.validate();+ return new GenericModelVersion(resp.getModelVersion());+ }++ @Override+ public void linkModelVersion(+ NameIdentifier ident,+ String uri,+ String[] aliases,+ String comment,+ Map<String, String> properties)+ throws NoSuchModelException, ModelVersionAliasesAlreadyExistException {+ checkModelNameIdentifier(ident);++ ModelVersionLinkRequest req = new ModelVersionLinkRequest(uri, aliases, comment, properties);+ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ BaseResponse resp =+ restClient.post(+ formatModelVersionRequestPath(modelFullIdent),+ req,+ BaseResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());++ resp.validate();+ }++ @Override+ public boolean deleteModelVersion(NameIdentifier ident, int version) {+ checkModelNameIdentifier(ident);+ Preconditions.checkArgument(version >= 0, "Model version must be non-negative");++ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ DropResponse resp =+ restClient.delete(+ formatModelVersionRequestPath(modelFullIdent) + "/versions/" + version,+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return resp.dropped();+ }++ @Override+ public boolean deleteModelVersion(NameIdentifier ident, String alias) {+ checkModelNameIdentifier(ident);+ Preconditions.checkArgument(StringUtils.isNotBlank(alias), "Model alias must be non-empty");++ NameIdentifier modelFullIdent = modelFullNameIdentifier(ident);+ DropResponse resp =+ restClient.delete(+ formatModelVersionRequestPath(modelFullIdent)+ + "/aliases/"+ + RESTUtils.encodeString(alias),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.modelErrorHandler());+ resp.validate();++ return resp.dropped();+ }++ /** @return A new builder instance for {@link GenericModelCatalog}. */+ public static Builder builder() {+ return new Builder();+ }++ private void checkModelNamespace(Namespace namespace) {+ Namespace.check(+ namespace != null && namespace.length() == 1,+ "Model namespace must be non-null and only have 1 level, the input namespace is ");+ }++ private void checkModelNameIdentifier(NameIdentifier ident) {+ NameIdentifier.check(ident != null, "Model name identifier must be non-null");+ NameIdentifier.check(+ StringUtils.isNotBlank(ident.name()), "Model name identifier must have a non-empty name");+ checkModelNamespace(ident.namespace());+ }++ private Namespace modelFullNamespace(Namespace modelNs) {+ return Namespace.of(catalogNamespace().level(0), name(), modelNs.level(0));+ }++ private NameIdentifier modelFullNameIdentifier(NameIdentifier modelIdent) {+ return NameIdentifier.of(modelFullNamespace(modelIdent.namespace()), modelIdent.name());+ }++ @VisibleForTesting+ static String formatModelRequestPath(Namespace modelNs) {+ Namespace schemaNs = Namespace.of(modelNs.level(0), modelNs.level(1));+ return new StringBuilder()+ .append(formatSchemaRequestPath(schemaNs))+ .append("/")+ .append(RESTUtils.encodeString(modelNs.level(2)))+ .append("/models")+ .toString();+ }++ @VisibleForTesting+ static String formatModelVersionRequestPath(NameIdentifier modelIdent) {+ return formatModelRequestPath(modelIdent.namespace())+ + "/"+ + RESTUtils.encodeString(modelIdent.name());+ }++ static class Builder extends CatalogDTO.Builder<Builder> {++ private RESTClient restClient;++ private Namespace namespace;++ private Builder() {}++ Builder withNamespace(Namespace namespace) {+ this.namespace = namespace;+ return this;+ }++ Builder withRestClient(RESTClient restClient) {+ this.restClient = restClient;+ return this;+ }++ @Override+ public GenericModelCatalog build() {+ Namespace.check(+ namespace != null && namespace.length() == 1,+ "Catalog namespace must be non-null and have 1 level, the input namespace is %s",+ namespace);+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not be blank");+ Preconditions.checkArgument(type != null, "type must not be null");+ Preconditions.checkArgument(StringUtils.isNotBlank(provider), "provider must not be blank");+ Preconditions.checkArgument(audit != null, "audit must not be null");+ Preconditions.checkArgument(restClient != null, "restClient must be set");++ return new GenericModelCatalog(+ namespace, name, type, provider, comment, properties, audit, restClient);+ }+ }+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelVersion.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelVersion.javanew file mode 100644index 0000000000..28b2d1e93e--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModelVersion.java@@ -0,0 +1,80 @@+/*+ * 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.client;++import java.util.Map;+import org.apache.gravitino.Audit;+import org.apache.gravitino.dto.model.ModelVersionDTO;+import org.apache.gravitino.model.ModelVersion;++class GenericModelVersion implements ModelVersion {++ private final ModelVersionDTO modelVersionDTO;++ GenericModelVersion(ModelVersionDTO modelVersionDTO) {+ this.modelVersionDTO = modelVersionDTO;+ }++ @Override+ public int version() {+ return modelVersionDTO.version();+ }++ @Override+ public String uri() {+ return modelVersionDTO.uri();+ }++ @Override+ public String comment() {+ return modelVersionDTO.comment();+ }++ @Override+ public String[] aliases() {+ return modelVersionDTO.aliases();+ }++ @Override+ public Map<String, String> properties() {+ return modelVersionDTO.properties();+ }++ @Override+ public Audit auditInfo() {+ return modelVersionDTO.auditInfo();+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof GenericModelVersion)) {+ return false;+ }+ GenericModelVersion that = (GenericModelVersion) o;+ return modelVersionDTO.equals(that.modelVersionDTO);+ }++ @Override+ public int hashCode() {+ return modelVersionDTO.hashCode();+ }+}diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericModelCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericModelCatalog.javanew file mode 100644index 0000000000..10e3ed678d--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericModelCatalog.java@@ -0,0 +1,546 @@+/*+ * 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.client;++import com.fasterxml.jackson.core.JsonProcessingException;+import java.time.Instant;+import java.util.Collections;+import java.util.Map;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.CatalogProvider;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.dto.CatalogDTO;+import org.apache.gravitino.dto.model.ModelDTO;+import org.apache.gravitino.dto.model.ModelVersionDTO;+import org.apache.gravitino.dto.requests.CatalogCreateRequest;+import org.apache.gravitino.dto.requests.ModelRegisterRequest;+import org.apache.gravitino.dto.requests.ModelVersionLinkRequest;+import org.apache.gravitino.dto.responses.BaseResponse;+import org.apache.gravitino.dto.responses.CatalogResponse;+import org.apache.gravitino.dto.responses.DropResponse;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.ErrorResponse;+import org.apache.gravitino.dto.responses.ModelResponse;+import org.apache.gravitino.dto.responses.ModelVersionListResponse;+import org.apache.gravitino.dto.responses.ModelVersionResponse;+import org.apache.gravitino.exceptions.ModelAlreadyExistsException;+import org.apache.gravitino.exceptions.ModelVersionAliasesAlreadyExistException;+import org.apache.gravitino.exceptions.NoSuchModelException;+import org.apache.gravitino.exceptions.NoSuchModelVersionException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.model.Model;+import org.apache.gravitino.model.ModelVersion;+import org.apache.hc.core5.http.HttpStatus;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++public class TestGenericModelCatalog extends TestBase {++ private static final String METALAKE_NAME = "metalake_for_model_test";++ private static final String CATALOG_NAME = "catalog_for_model_test";++ private static Catalog catalog;++ private static GravitinoMetalake metalake;++ @BeforeAll+ public static void setUp() throws Exception {+ TestBase.setUp();++ metalake = TestGravitinoMetalake.createMetalake(client, METALAKE_NAME);++ CatalogDTO mockCatalog =+ CatalogDTO.builder()+ .withName(CATALOG_NAME)+ .withType(Catalog.Type.MODEL)+ .withProvider(CatalogProvider.shortNameForManagedCatalog(Catalog.Type.MODEL))+ .withComment("comment")+ .withProperties(Collections.emptyMap())+ .withAudit(+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();++ CatalogCreateRequest request =+ new CatalogCreateRequest(+ CATALOG_NAME, Catalog.Type.MODEL, null, "comment", Collections.emptyMap());+ CatalogResponse resp = new CatalogResponse(mockCatalog);+ buildMockResource(+ Method.POST,+ "/api/metalakes/" + METALAKE_NAME + "/catalogs",+ request,+ resp,+ HttpStatus.SC_OK);++ catalog =+ metalake.createCatalog(CATALOG_NAME, Catalog.Type.MODEL, "comment", Collections.emptyMap());+ }++ @Test+ public void testListModels() throws JsonProcessingException {+ NameIdentifier modelId1 = NameIdentifier.of("schema1", "model1");+ NameIdentifier modelId2 = NameIdentifier.of("schema1", "model2");++ NameIdentifier resultModelId1 =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1");+ NameIdentifier resultModelId2 =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model2");++ String modelPath =+ withSlash(+ GenericModelCatalog.formatModelRequestPath(+ Namespace.of(METALAKE_NAME, CATALOG_NAME, "schema1")));++ EntityListResponse resp =+ new EntityListResponse(new NameIdentifier[] {resultModelId1, resultModelId2});+ buildMockResource(Method.GET, modelPath, null, resp, HttpStatus.SC_OK);++ NameIdentifier[] modelIds = catalog.asModelCatalog().listModels(modelId1.namespace());+ Assertions.assertEquals(2, modelIds.length);+ Assertions.assertEquals(modelId1, modelIds[0]);+ Assertions.assertEquals(modelId2, modelIds[1]);++ // Throw schema not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.GET, modelPath, null, errResp, HttpStatus.SC_NOT_FOUND);+ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () -> catalog.asModelCatalog().listModels(modelId1.namespace()),+ "schema not found");++ // Throw RuntimeException+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.GET, modelPath, null, errResp2, HttpStatus.SC_INTERNAL_SERVER_ERROR);+ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().listModels(modelId1.namespace()),+ "internal error");+ }++ @Test+ public void testGetModel() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelPath =+ withSlash(+ GenericModelCatalog.formatModelRequestPath(+ Namespace.of(METALAKE_NAME, CATALOG_NAME, "schema1"))+ + "/"+ + modelId.name());++ ModelDTO modelDTO = mockModelDTO("model1", 0, "model comment", Collections.emptyMap());+ ModelResponse resp = new ModelResponse(modelDTO);+ buildMockResource(Method.GET, modelPath, null, resp, HttpStatus.SC_OK);++ Model model = catalog.asModelCatalog().getModel(modelId);+ compareModel(modelDTO, model);++ // Throw model not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(NoSuchModelException.class.getSimpleName(), "model not found");+ buildMockResource(Method.GET, modelPath, null, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchModelException.class,+ () -> catalog.asModelCatalog().getModel(modelId),+ "model not found");++ // Throw RuntimeException+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.GET, modelPath, null, errResp2, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asModelCatalog().getModel(modelId), "internal error");+ }++ @Test+ public void testRegisterModel() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ ModelDTO modelDTO = mockModelDTO("model1", 0, "model comment", Collections.emptyMap());+ ModelResponse resp = new ModelResponse(modelDTO);+ ModelRegisterRequest request =+ new ModelRegisterRequest(modelId.name(), "model comment", Collections.emptyMap());++ String modelPath =+ withSlash(+ GenericModelCatalog.formatModelRequestPath(+ Namespace.of(METALAKE_NAME, CATALOG_NAME, "schema1")));+ buildMockResource(Method.POST, modelPath, request, resp, HttpStatus.SC_OK);++ Model model =+ catalog.asModelCatalog().registerModel(modelId, "model comment", Collections.emptyMap());+ compareModel(modelDTO, model);++ // Throw schema not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.POST, modelPath, request, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () ->+ catalog+ .asModelCatalog()+ .registerModel(modelId, "model comment", Collections.emptyMap()),+ "schema not found");++ // Throw model already exists exception+ ErrorResponse errResp2 =+ ErrorResponse.alreadyExists(+ ModelAlreadyExistsException.class.getSimpleName(), "model already exists");+ buildMockResource(Method.POST, modelPath, request, errResp2, HttpStatus.SC_CONFLICT);++ Assertions.assertThrows(+ ModelAlreadyExistsException.class,+ () ->+ catalog+ .asModelCatalog()+ .registerModel(modelId, "model comment", Collections.emptyMap()),+ "model already exists");++ // Throw RuntimeException+ ErrorResponse errResp3 = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.POST, modelPath, request, errResp3, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () ->+ catalog+ .asModelCatalog()+ .registerModel(modelId, "model comment", Collections.emptyMap()),+ "internal error");+ }++ @Test+ public void testDeleteModel() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelPath =+ withSlash(+ GenericModelCatalog.formatModelRequestPath(+ Namespace.of(METALAKE_NAME, CATALOG_NAME, "schema1"))+ + "/"+ + modelId.name());++ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, modelPath, null, resp, HttpStatus.SC_OK);++ Assertions.assertTrue(catalog.asModelCatalog().deleteModel(modelId));++ // Test RuntimeException+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(Method.DELETE, modelPath, null, errResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().deleteModel(modelId),+ "internal error");+ }++ @Test+ public void testListModelVersions() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1"))+ + "/versions");++ int[] expectedVersions = new int[] {0, 1, 2};+ ModelVersionListResponse resp = new ModelVersionListResponse(expectedVersions);+ buildMockResource(Method.GET, modelVersionPath, null, resp, HttpStatus.SC_OK);++ int[] versions = catalog.asModelCatalog().listModelVersions(modelId);+ Assertions.assertArrayEquals(expectedVersions, versions);++ // Throw model not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(NoSuchModelException.class.getSimpleName(), "model not found");+ buildMockResource(Method.GET, modelVersionPath, null, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchModelException.class,+ () -> catalog.asModelCatalog().listModelVersions(modelId),+ "model not found");++ // Throw RuntimeException+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.GET, modelVersionPath, null, errResp2, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().listModelVersions(modelId),+ "internal error");+ }++ @Test+ public void testGetModelVersion() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1"))+ + "/versions/0");++ ModelVersionDTO mockModelVersion =+ mockModelVersion(+ 0, "uri", new String[] {"alias1", "alias2"}, "comment", Collections.emptyMap());+ ModelVersionResponse resp = new ModelVersionResponse(mockModelVersion);+ buildMockResource(Method.GET, modelVersionPath, null, resp, HttpStatus.SC_OK);++ ModelVersion modelVersion = catalog.asModelCatalog().getModelVersion(modelId, 0);+ compareModelVersion(mockModelVersion, modelVersion);++ // Throw model version not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(+ NoSuchModelVersionException.class.getSimpleName(), "model version not found");+ buildMockResource(Method.GET, modelVersionPath, null, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchModelVersionException.class,+ () -> catalog.asModelCatalog().getModelVersion(modelId, 0),+ "model version not found");++ // Throw RuntimeException+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.GET, modelVersionPath, null, errResp2, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().getModelVersion(modelId, 0),+ "internal error");+ }++ @Test+ public void testGetModelVersionByAlias() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1"))+ + "/aliases/alias1");++ ModelVersionDTO mockModelVersion =+ mockModelVersion(+ 0, "uri", new String[] {"alias1", "alias2"}, "comment", Collections.emptyMap());+ ModelVersionResponse resp = new ModelVersionResponse(mockModelVersion);+ buildMockResource(Method.GET, modelVersionPath, null, resp, HttpStatus.SC_OK);++ ModelVersion modelVersion = catalog.asModelCatalog().getModelVersion(modelId, "alias1");+ compareModelVersion(mockModelVersion, modelVersion);++ // Throw model version not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(+ NoSuchModelVersionException.class.getSimpleName(), "model version not found");+ buildMockResource(Method.GET, modelVersionPath, null, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchModelVersionException.class,+ () -> catalog.asModelCatalog().getModelVersion(modelId, "alias1"),+ "model version not found");++ // Throw RuntimeException+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.GET, modelVersionPath, null, errResp2, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().getModelVersion(modelId, "alias1"),+ "internal error");+ }++ @Test+ public void testLinkModelVersion() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1")));++ ModelVersionLinkRequest request =+ new ModelVersionLinkRequest(+ "uri", new String[] {"alias1", "alias2"}, "comment", Collections.emptyMap());+ BaseResponse resp = new BaseResponse(0);+ buildMockResource(Method.POST, modelVersionPath, request, resp, HttpStatus.SC_OK);++ Assertions.assertDoesNotThrow(+ () ->+ catalog+ .asModelCatalog()+ .linkModelVersion(+ modelId,+ "uri",+ new String[] {"alias1", "alias2"},+ "comment",+ Collections.emptyMap()));++ // Throw model not found exception+ ErrorResponse errResp =+ ErrorResponse.notFound(NoSuchModelException.class.getSimpleName(), "model not found");+ buildMockResource(Method.POST, modelVersionPath, request, errResp, HttpStatus.SC_NOT_FOUND);++ Assertions.assertThrows(+ NoSuchModelException.class,+ () ->+ catalog+ .asModelCatalog()+ .linkModelVersion(+ modelId,+ "uri",+ new String[] {"alias1", "alias2"},+ "comment",+ Collections.emptyMap()),+ "model not found");++ // Throw ModelVersionAliasesAlreadyExistException+ ErrorResponse errResp2 =+ ErrorResponse.alreadyExists(+ ModelVersionAliasesAlreadyExistException.class.getSimpleName(),+ "model version already exists");+ buildMockResource(Method.POST, modelVersionPath, request, errResp2, HttpStatus.SC_CONFLICT);++ Assertions.assertThrows(+ ModelVersionAliasesAlreadyExistException.class,+ () ->+ catalog+ .asModelCatalog()+ .linkModelVersion(+ modelId,+ "uri",+ new String[] {"alias1", "alias2"},+ "comment",+ Collections.emptyMap()),+ "model version already exists");++ // Throw RuntimeException+ ErrorResponse errResp3 = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.POST, modelVersionPath, request, errResp3, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () ->+ catalog+ .asModelCatalog()+ .linkModelVersion(+ modelId,+ "uri",+ new String[] {"alias1", "alias2"},+ "comment",+ Collections.emptyMap()),+ "internal error");+ }++ @Test+ public void testDeleteModelVersion() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1"))+ + "/versions/0");++ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, modelVersionPath, null, resp, HttpStatus.SC_OK);++ Assertions.assertTrue(catalog.asModelCatalog().deleteModelVersion(modelId, 0));++ // Test RuntimeException+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.DELETE, modelVersionPath, null, errResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().deleteModelVersion(modelId, 0),+ "internal error");+ }++ @Test+ public void testDeleteModelVersionByAlias() throws JsonProcessingException {+ NameIdentifier modelId = NameIdentifier.of("schema1", "model1");+ String modelVersionPath =+ withSlash(+ GenericModelCatalog.formatModelVersionRequestPath(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "schema1", "model1"))+ + "/aliases/alias1");++ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, modelVersionPath, null, resp, HttpStatus.SC_OK);++ Assertions.assertTrue(catalog.asModelCatalog().deleteModelVersion(modelId, "alias1"));++ // Test RuntimeException+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.DELETE, modelVersionPath, null, errResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(+ RuntimeException.class,+ () -> catalog.asModelCatalog().deleteModelVersion(modelId, "alias1"),+ "internal error");+ }++ private ModelDTO mockModelDTO(+ String modelName, int latestVersion, String comment, Map<String, String> properties) {+ return ModelDTO.builder()+ .withName(modelName)+ .withLatestVersion(latestVersion)+ .withComment(comment)+ .withProperties(properties)+ .withAudit(AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ }++ private ModelVersionDTO mockModelVersion(+ int version, String uri, String[] aliases, String comment, Map<String, String> properties) {+ return ModelVersionDTO.builder()+ .withVersion(version)+ .withUri(uri)+ .withAliases(aliases)+ .withComment(comment)+ .withProperties(properties)+ .withAudit(AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ }++ private void compareModel(Model expect, Model result) {+ Assertions.assertEquals(expect.name(), result.name());+ Assertions.assertEquals(expect.latestVersion(), result.latestVersion());+ Assertions.assertEquals(expect.comment(), result.comment());+ Assertions.assertEquals(expect.properties(), result.properties());+ }++ private void compareModelVersion(ModelVersion expect, ModelVersion result) {+ Assertions.assertEquals(expect.version(), result.version());+ Assertions.assertEquals(expect.uri(), result.uri());+ Assertions.assertArrayEquals(expect.aliases(), result.aliases());+ Assertions.assertEquals(expect.comment(), result.comment());+ Assertions.assertEquals(expect.properties(), result.properties());+ }+}diff --git a/clients/client-python/gravitino/client/generic_model_catalog.py b/clients/client-python/gravitino/client/generic_model_catalog.pyindex c468f455db..6077b0b642 100644--- a/clients/client-python/gravitino/client/generic_model_catalog.py+++ b/clients/client-python/gravitino/client/generic_model_catalog.py@@ -258,7 +258,8 @@ class GenericModelCatalog(BaseSchemaCatalog):model_full_ident = self._model_full_identifier(model_ident)resp = self.rest_client.get(- f"{self._format_model_version_request_path(model_full_ident)}/aliases/{alias}",+ f"{self._format_model_version_request_path(model_full_ident)}/aliases/"+ f"{encode_string(alias)}",error_handler=MODEL_ERROR_HANDLER,)model_version_resp = ModelVersionResponse.from_json(@@ -349,7 +350,8 @@ class GenericModelCatalog(BaseSchemaCatalog):model_full_ident = self._model_full_identifier(model_ident)resp = self.rest_client.delete(- f"{self._format_model_version_request_path(model_full_ident)}/aliases/{alias}",+ f"{self._format_model_version_request_path(model_full_ident)}/aliases/"+ f"{encode_string(alias)}",error_handler=MODEL_ERROR_HANDLER,)drop_resp = DropResponse.from_json(resp.body, infer_missing=True)