flyrain commented on code in PR #4961: URL: https://github.com/apache/polaris/pull/4961#discussion_r3555294385
########## extensions/semantic-models/src/main/java/org/apache/polaris/service/catalog/semanticmodel/SemanticModelCatalog.java: ########## @@ -0,0 +1,349 @@ +/* + * 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.polaris.service.catalog.semanticmodel; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.polaris.core.context.CallContext; +import org.apache.polaris.core.entity.CatalogEntity; +import org.apache.polaris.core.entity.PolarisBaseEntity; +import org.apache.polaris.core.entity.PolarisEntity; +import org.apache.polaris.core.entity.PolarisEntitySubType; +import org.apache.polaris.core.entity.PolarisEntityType; +import org.apache.polaris.core.persistence.PolarisMetaStoreManager; +import org.apache.polaris.core.persistence.PolarisResolvedPathWrapper; +import org.apache.polaris.core.persistence.dao.entity.EntityResult; +import org.apache.polaris.core.persistence.dao.entity.ListEntitiesResult; +import org.apache.polaris.core.persistence.pagination.PageToken; +import org.apache.polaris.core.persistence.resolver.PolarisResolutionManifestCatalogView; +import org.apache.polaris.core.persistence.resolver.ResolvedPathKey; +import org.apache.polaris.core.semantic.SemanticModelEntity; +import org.apache.polaris.core.semantic.exceptions.NoSuchSemanticModelException; +import org.apache.polaris.core.semantic.exceptions.SemanticModelVersionMismatchException; +import org.apache.polaris.service.catalog.semanticmodel.types.ListSemanticModelsResponse; +import org.apache.polaris.service.catalog.semanticmodel.types.LoadSemanticModelResponse; +import org.apache.polaris.service.catalog.semanticmodel.types.SemanticModelDocument; +import org.apache.polaris.service.catalog.semanticmodel.types.SemanticModelIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Core create/list/load/update/drop logic for OSI semantic models. Mirrors {@link + * org.apache.polaris.service.catalog.policy.PolicyCatalog}: the OSI document body is stored inside + * the entity {@code properties} map, writes resolve every {@code dataset.source} to a {@code + * TABLE_LIKE} entity in the current catalog, and updates use optimistic concurrency on the entity + * version. Document schema validation is a separate concern (see {@link + * SemanticDocumentValidator}). + */ +public class SemanticModelCatalog { + private static final Logger LOGGER = LoggerFactory.getLogger(SemanticModelCatalog.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final CallContext callContext; + private final PolarisResolutionManifestCatalogView resolvedEntityView; + private final CatalogEntity catalogEntity; + private final long catalogId; + private final PolarisMetaStoreManager metaStoreManager; + + public SemanticModelCatalog( + PolarisMetaStoreManager metaStoreManager, + CallContext callContext, + PolarisResolutionManifestCatalogView resolvedEntityView) { + this.callContext = callContext; + this.resolvedEntityView = resolvedEntityView; + this.catalogEntity = resolvedEntityView.getResolvedCatalogEntity(); + this.catalogId = catalogEntity.getId(); + this.metaStoreManager = metaStoreManager; + } + + public LoadSemanticModelResponse createSemanticModel( + SemanticModelIdentifier identifier, SemanticModelDocument document) { + Namespace namespace = toNamespace(identifier); + PolarisResolvedPathWrapper resolvedParent = + resolvedEntityView.getResolvedPath(ResolvedPathKey.ofNamespace(namespace)); + if (resolvedParent == null) { + // Illegal state because the namespace should've already been in the static resolution set. + throw new IllegalStateException( + String.format("Failed to fetch resolved parent for semantic model '%s'", identifier)); + } + List<PolarisEntity> catalogPath = resolvedParent.getRawFullPath(); + + PolarisResolvedPathWrapper existing = + resolvedEntityView.getPassthroughResolvedPath( + ResolvedPathKey.ofSemanticModel(namespace, identifier.getName()), + PolarisEntitySubType.NULL_SUBTYPE); + if (existing != null && existing.getRawLeafEntity() != null) { + throw new AlreadyExistsException("Semantic model already exists: %s", identifier.getName()); + } + + // Parse the document and resolve its source tables before persisting. + validateDocumentAndSources(document); + + SemanticModelEntity entity = + new SemanticModelEntity.Builder(namespace, identifier.getName()) + .setCatalogId(catalogId) + .setParentId(resolvedParent.getRawLeafEntity().getId()) + .setSpecVersion(document.getVersion()) + .setContent(document.getSemanticModel()) + .setId( + metaStoreManager.generateNewEntityId(callContext.getPolarisCallContext()).getId()) + .setCreateTimestamp(System.currentTimeMillis()) + .build(); + + EntityResult res = + metaStoreManager.createEntityIfNotExists( + callContext.getPolarisCallContext(), PolarisEntity.toCoreList(catalogPath), entity); + if (!res.isSuccess()) { + switch (res.getReturnStatus()) { + case ENTITY_ALREADY_EXISTS -> + throw new AlreadyExistsException( + "Semantic model already exists: %s", identifier.getName()); + default -> + throw new IllegalStateException( + String.format( + "Unknown error status for identifier %s: %s with extraInfo: %s", + identifier, res.getReturnStatus(), res.getExtraInformation())); + } + } + + SemanticModelEntity result = SemanticModelEntity.of(res.getEntity()); + LOGGER.debug("Created semantic model entity {} with identifier {}", result, identifier); + return toLoadResponse(result); + } + + public ListSemanticModelsResponse listSemanticModels(Namespace namespace, PageToken pageToken) { + PolarisResolvedPathWrapper resolvedEntities = + resolvedEntityView.getResolvedPath(ResolvedPathKey.ofNamespace(namespace)); + if (resolvedEntities == null) { + throw new IllegalStateException( + String.format("Failed to fetch resolved namespace '%s'", namespace)); + } + List<PolarisEntity> catalogPath = resolvedEntities.getRawFullPath(); + + ListEntitiesResult result = + metaStoreManager.listEntities( + callContext.getPolarisCallContext(), + PolarisEntity.toCoreList(catalogPath), + PolarisEntityType.SEMANTIC_MODEL, + PolarisEntitySubType.NULL_SUBTYPE, + pageToken); + if (!result.isSuccess()) { + throw new IllegalStateException("Failed to list semantic models in namespace: " + namespace); + } + + // LinkedHashSet keeps the page order stable in the serialized response. + Set<SemanticModelIdentifier> identifiers = + result.getEntities().stream() + .map( + record -> + SemanticModelIdentifier.builder() + .setNamespace(List.of(namespace.levels())) + .setName(record.getName()) + .build()) + .collect(Collectors.toCollection(LinkedHashSet::new)); + return ListSemanticModelsResponse.builder() + .setIdentifiers(identifiers) + .setNextPageToken(result.getPage().encodedResponseToken()) + .build(); + } + + public LoadSemanticModelResponse loadSemanticModel(SemanticModelIdentifier identifier) { + return toLoadResponse(resolveModelOrThrow(identifier)); + } + + public LoadSemanticModelResponse updateSemanticModel( + SemanticModelIdentifier identifier, SemanticModelDocument document, String expectedVersion) { + PolarisResolvedPathWrapper resolvedPath = resolveModelPathOrThrow(identifier); + SemanticModelEntity current = SemanticModelEntity.of(resolvedPath.getRawLeafEntity()); + + String currentVersion = Integer.toString(current.getEntityVersion()); + if (!currentVersion.equals(expectedVersion)) { + throw new SemanticModelVersionMismatchException( + String.format( + "Semantic model version mismatch. Given version is %s, current version is %s", + expectedVersion, currentVersion)); + } + + validateDocumentAndSources(document); + + SemanticModelEntity newEntity = + new SemanticModelEntity.Builder(current) + .setSpecVersion(document.getVersion()) + .setContent(document.getSemanticModel()) + .build(); + + List<PolarisEntity> catalogPath = resolvedPath.getRawParentPath(); + SemanticModelEntity updated = + Optional.ofNullable( + metaStoreManager + .updateEntityPropertiesIfNotChanged( + callContext.getPolarisCallContext(), + PolarisEntity.toCoreList(catalogPath), + newEntity) + .getEntity()) + .map(SemanticModelEntity::of) + .orElse(null); + if (updated == null) { + // Lost the optimistic-concurrency race with a concurrent writer. + throw new SemanticModelVersionMismatchException( + String.format( + "Semantic model %s was modified concurrently; retry after reloading", + identifier.getName())); + } + + return toLoadResponse(updated); + } + + public void dropSemanticModel(SemanticModelIdentifier identifier) { + PolarisResolvedPathWrapper resolvedPath = resolveModelPathOrThrow(identifier); + List<PolarisEntity> catalogPath = resolvedPath.getRawParentPath(); + PolarisBaseEntity entity = resolvedPath.getRawLeafEntity(); + + var result = + metaStoreManager.dropEntityIfExists( + callContext.getPolarisCallContext(), + PolarisEntity.toCoreList(catalogPath), + entity, + java.util.Map.of(), + false); + if (!result.isSuccess()) { + throw new IllegalStateException( + String.format( + "Failed to drop semantic model %s error status: %s with extraInfo: %s", + identifier, result.getReturnStatus(), result.getExtraInformation())); Review Comment: Good question! The persistence layer implementation is not supposed to leak any sensitive information. It's kind of a convention, please check the other use cases, like https://github.com/apache/polaris/blob/main/runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/LocalIcebergCatalog.java#L541-L541 -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
