World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13906] feat(core): derive a policy-to-role record from access control content (#13957)
Bharath Krishna7f8f19b730d4
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelMapper.javanew file mode 100644index 0000000000..8d0b15da0d--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelMapper.java@@ -0,0 +1,110 @@+/*+ * 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.storage.relational.mapper;++import java.util.List;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;+import org.apache.ibatis.annotations.DeleteProvider;+import org.apache.ibatis.annotations.InsertProvider;+import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.SelectProvider;+import org.apache.ibatis.annotations.UpdateProvider;++/** MyBatis mapper for the policy-to-role references derived from policy content. */+public interface PolicyRoleRelMapper {+ /** The policy-to-role reference table name. */+ String POLICY_ROLE_RELATION_TABLE_NAME = "policy_role_relation_meta";++ /**+ * Lists the active role references of one policy.+ *+ * @param policyId The policy ID.+ * @return The active references, ordered by role name.+ */+ @SelectProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "listByPolicyId")+ List<PolicyRoleRelPO> listByPolicyId(@Param("policyId") Long policyId);++ /**+ * Lists the active references to one role name in a metalake.+ *+ * @param metalakeName The metalake name.+ * @param roleName The role name.+ * @return The active references, ordered by policy name.+ */+ @SelectProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "listByRoleName")+ List<PolicyRoleRelPO> listByRoleName(+ @Param("metalakeName") String metalakeName, @Param("roleName") String roleName);++ /**+ * Inserts a reference.+ *+ * @param relation The reference to insert.+ * @return The number of inserted rows.+ */+ @InsertProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "insert")+ int insert(@Param("relation") PolicyRoleRelPO relation);++ /**+ * Removes one active reference the content no longer names.+ *+ * <p>The row is deleted rather than soft-deleted. A superseded reference has no reader: the+ * record is derived, carries no audit info, and the content of every policy version is kept in+ * the policy version table. Leaving no tombstone also keeps the table's uniqueness over (policy,+ * role, deleted_at) free of the deletion timestamp, which two removals of one role can otherwise+ * share.+ *+ * <p>A row's version never changes after it is written; the only update to these rows is the soft+ * delete, which this statement excludes through {@code deleted_at = 0}. Writers to one policy are+ * serialised by the policy row they lock first.+ *+ * @param relation The observed reference and version.+ * @return The number of deleted rows.+ */+ @DeleteProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "deleteByIdAndVersion")+ int deleteByIdAndVersion(@Param("relation") PolicyRoleRelPO relation);++ /**+ * Soft-deletes every active reference of a policy.+ *+ * @param policyId The policy ID.+ * @return The number of affected rows.+ */+ @UpdateProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "softDeleteByPolicyId")+ int softDeleteByPolicyId(@Param("policyId") Long policyId);++ /**+ * Soft-deletes active references in a metalake.+ *+ * @param metalakeId The metalake ID.+ * @return The number of affected rows.+ */+ @UpdateProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "softDeleteByMetalakeId")+ int softDeleteByMetalakeId(@Param("metalakeId") Long metalakeId);++ /**+ * Physically deletes expired reference rows.+ *+ * @param legacyTimeline The exclusive deletion timestamp upper bound.+ * @param limit The maximum number of rows to delete.+ * @return The number of deleted rows.+ */+ @DeleteProvider(type = PolicyRoleRelSQLProviderFactory.class, method = "deleteByLegacyTimeline")+ int deleteByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelSQLProviderFactory.javanew file mode 100644index 0000000000..d6cd3fbc67--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyRoleRelSQLProviderFactory.java@@ -0,0 +1,91 @@+/*+ * 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.storage.relational.mapper;++import com.google.common.collect.ImmutableMap;+import java.util.Map;+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;+import org.apache.gravitino.storage.relational.mapper.provider.base.PolicyRoleRelBaseSQLProvider;+import org.apache.gravitino.storage.relational.mapper.provider.postgresql.PolicyRoleRelPostgreSQLProvider;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.annotations.Param;++/** Selects the policy-to-role reference SQL provider for the active JDBC backend. */+public class PolicyRoleRelSQLProviderFactory {++ private static final Map<JDBCBackendType, PolicyRoleRelBaseSQLProvider> PROVIDERS =+ ImmutableMap.of(+ JDBCBackendType.MYSQL, new PolicyRoleRelMySQLProvider(),+ JDBCBackendType.H2, new PolicyRoleRelH2Provider(),+ JDBCBackendType.POSTGRESQL, new PolicyRoleRelPostgreSQLProvider());++ /**+ * @return The SQL provider for the active backend.+ */+ public static PolicyRoleRelBaseSQLProvider getProvider() {+ String databaseId =+ SqlSessionFactoryHelper.getInstance()+ .getSqlSessionFactory()+ .getConfiguration()+ .getDatabaseId();+ return PROVIDERS.get(JDBCBackendType.fromString(databaseId));+ }++ /** Delegates a policy-anchored list query. */+ public static String listByPolicyId(@Param("policyId") Long policyId) {+ return getProvider().listByPolicyId(policyId);+ }++ /** Delegates a role-anchored list query. */+ public static String listByRoleName(+ @Param("metalakeName") String metalakeName, @Param("roleName") String roleName) {+ return getProvider().listByRoleName(metalakeName, roleName);+ }++ /** Delegates an insert operation. */+ public static String insert(@Param("relation") PolicyRoleRelPO relation) {+ return getProvider().insert(relation);+ }++ /** Delegates the removal of a superseded reference. */+ public static String deleteByIdAndVersion(@Param("relation") PolicyRoleRelPO relation) {+ return getProvider().deleteByIdAndVersion(relation);+ }++ /** Delegates policy deletion cleanup. */+ public static String softDeleteByPolicyId(@Param("policyId") Long policyId) {+ return getProvider().softDeleteByPolicyId(policyId);+ }++ /** Delegates metalake deletion cleanup. */+ public static String softDeleteByMetalakeId(@Param("metalakeId") Long metalakeId) {+ return getProvider().softDeleteByMetalakeId(metalakeId);+ }++ /** Delegates expired reference cleanup. */+ public static String deleteByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return getProvider().deleteByLegacyTimeline(legacyTimeline, limit);+ }++ static class PolicyRoleRelMySQLProvider extends PolicyRoleRelBaseSQLProvider {}++ static class PolicyRoleRelH2Provider extends PolicyRoleRelBaseSQLProvider {}+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.javaindex cd7914c040..b7fa109b37 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java@@ -40,6 +40,7 @@ import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;import org.apache.gravitino.storage.relational.mapper.OrphanedMetadataObjectRelationMapper;import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper;import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;@@ -86,6 +87,7 @@ public class DefaultMapperPackageProvider implements MapperPackageProvider {ModelVersionMetaMapper.class,OrphanedMetadataObjectRelationMapper.class,OwnerMetaMapper.class,+ PolicyRoleRelMapper.class,PolicyTagRelMapper.class,PolicyMetaMapper.class,PolicyVersionMapper.class,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyRoleRelBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyRoleRelBaseSQLProvider.javanew file mode 100644index 0000000000..63a7db2159--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyRoleRelBaseSQLProvider.java@@ -0,0 +1,125 @@+/*+ * 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.storage.relational.mapper.provider.base;++import static org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper.POLICY_ROLE_RELATION_TABLE_NAME;++import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;+import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;+import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;+import org.apache.ibatis.annotations.Param;++/** Base SQL provider for policy-to-role references. */+public class PolicyRoleRelBaseSQLProvider {++ /** Returns SQL for listing the role references of one policy. */+ public String listByPolicyId(@Param("policyId") Long policyId) {+ return selectColumns()+ + joins()+ + " WHERE prr.policy_id = #{policyId}"+ + activePredicates()+ + " ORDER BY prr.role_name";+ }++ /** Returns SQL for listing the policies that reference one role name. */+ public String listByRoleName(+ @Param("metalakeName") String metalakeName, @Param("roleName") String roleName) {+ return selectColumns()+ + joins()+ + " WHERE pm.metalake_id IN (SELECT mm.metalake_id FROM "+ + MetalakeMetaMapper.TABLE_NAME+ + " mm WHERE mm.metalake_name = #{metalakeName} AND mm.deleted_at = 0)"+ + " AND prr.role_name = #{roleName}"+ + activePredicates()+ + " ORDER BY pm.policy_name";+ }++ /** Returns SQL for inserting one reference. */+ public String insert(@Param("relation") PolicyRoleRelPO relation) {+ return "INSERT INTO "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " (policy_id, role_name, current_version, last_version, deleted_at)"+ + " VALUES (#{relation.policyId}, #{relation.roleName},"+ + " #{relation.currentVersion}, #{relation.lastVersion}, #{relation.deletedAt})";+ }++ /** Returns SQL for deleting one superseded reference. */+ public String deleteByIdAndVersion(@Param("relation") PolicyRoleRelPO relation) {+ return "DELETE FROM "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " WHERE id = #{relation.id} AND current_version = #{relation.currentVersion}"+ + " AND deleted_at = 0";+ }++ /** Returns SQL for soft-deleting references when a metalake is deleted. */+ public String softDeleteByMetalakeId(@Param("metalakeId") Long metalakeId) {+ return "UPDATE "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " SET deleted_at = "+ + deletedAtNowExpression()+ + " WHERE EXISTS (SELECT * FROM "+ + PolicyMetaMapper.POLICY_META_TABLE_NAME+ + " pm WHERE pm.metalake_id = #{metalakeId} AND pm.policy_id = "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + ".policy_id)"+ + " AND deleted_at = 0";+ }++ /** Returns SQL for soft-deleting references when a policy is deleted. */+ public String softDeleteByPolicyId(@Param("policyId") Long policyId) {+ return "UPDATE "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " SET deleted_at = "+ + deletedAtNowExpression()+ + " WHERE policy_id = #{policyId} AND deleted_at = 0";+ }++ /** Returns SQL for physically deleting expired reference rows. */+ public String deleteByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return "DELETE FROM "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";+ }++ /** Returns the database expression for the current epoch-millisecond timestamp. */+ protected String deletedAtNowExpression() {+ return DatabaseTimeSQL.MYSQL;+ }++ private String selectColumns() {+ return "SELECT prr.id AS id, prr.policy_id AS policyId, pm.policy_name AS policyName,"+ + " prr.role_name AS roleName,"+ + " prr.current_version AS currentVersion, prr.last_version AS lastVersion,"+ + " prr.deleted_at AS deletedAt";+ }++ private String joins() {+ return " FROM "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " prr JOIN "+ + PolicyMetaMapper.POLICY_META_TABLE_NAME+ + " pm ON prr.policy_id = pm.policy_id";+ }++ private String activePredicates() {+ return " AND prr.deleted_at = 0 AND pm.deleted_at = 0";+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyRoleRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyRoleRelPostgreSQLProvider.javanew file mode 100644index 0000000000..6b5689d8b5--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyRoleRelPostgreSQLProvider.java@@ -0,0 +1,44 @@+/*+ * 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.storage.relational.mapper.provider.postgresql;++import static org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper.POLICY_ROLE_RELATION_TABLE_NAME;++import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;+import org.apache.gravitino.storage.relational.mapper.provider.base.PolicyRoleRelBaseSQLProvider;+import org.apache.ibatis.annotations.Param;++/** PostgreSQL SQL provider for policy-to-role references. */+public class PolicyRoleRelPostgreSQLProvider extends PolicyRoleRelBaseSQLProvider {++ @Override+ public String deleteByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return "DELETE FROM "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " WHERE id IN (SELECT id FROM "+ + POLICY_ROLE_RELATION_TABLE_NAME+ + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";+ }++ @Override+ protected String deletedAtNowExpression() {+ return DatabaseTimeSQL.POSTGRESQL;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyRoleRelPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyRoleRelPO.javanew file mode 100644index 0000000000..6dac9f85cb--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyRoleRelPO.java@@ -0,0 +1,125 @@+/*+ * 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.storage.relational.po;++import com.google.common.base.Objects;+import com.google.common.base.Preconditions;+import lombok.Getter;++/** Persistent object for a policy-to-role reference row derived from policy content. */+@Getter+public class PolicyRoleRelPO {+ private Long id;+ private Long policyId;+ private String policyName;+ private String roleName;+ private Long currentVersion;+ private Long lastVersion;+ private Long deletedAt;++ /**+ * @return A builder for a policy-to-role reference persistent object.+ */+ public static Builder builder() {+ return new Builder();+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof PolicyRoleRelPO)) {+ return false;+ }+ PolicyRoleRelPO that = (PolicyRoleRelPO) o;+ return Objects.equal(id, that.id)+ && Objects.equal(policyId, that.policyId)+ && Objects.equal(policyName, that.policyName)+ && Objects.equal(roleName, that.roleName)+ && Objects.equal(currentVersion, that.currentVersion)+ && Objects.equal(lastVersion, that.lastVersion)+ && Objects.equal(deletedAt, that.deletedAt);+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(+ id, policyId, policyName, roleName, currentVersion, lastVersion, deletedAt);+ }++ /** Builder for {@link PolicyRoleRelPO}. */+ public static class Builder {+ private final PolicyRoleRelPO relation;++ private Builder() {+ relation = new PolicyRoleRelPO();+ }++ /** Sets the relation row ID. */+ public Builder withId(Long id) {+ relation.id = id;+ return this;+ }++ /** Sets the policy ID. */+ public Builder withPolicyId(Long policyId) {+ relation.policyId = policyId;+ return this;+ }++ /** Sets the referenced role name. */+ public Builder withRoleName(String roleName) {+ relation.roleName = roleName;+ return this;+ }++ /** Sets the current version. */+ public Builder withCurrentVersion(Long currentVersion) {+ relation.currentVersion = currentVersion;+ return this;+ }++ /** Sets the last version. */+ public Builder withLastVersion(Long lastVersion) {+ relation.lastVersion = lastVersion;+ return this;+ }++ /** Sets the deletion timestamp. */+ public Builder withDeletedAt(Long deletedAt) {+ relation.deletedAt = deletedAt;+ return this;+ }++ /**+ * Builds the persistent object.+ *+ * @return The persistent object.+ */+ public PolicyRoleRelPO build() {+ Preconditions.checkArgument(relation.policyId != null, "Policy id is required");+ Preconditions.checkArgument(relation.roleName != null, "Role name is required");+ Preconditions.checkArgument(relation.currentVersion != null, "Current version is required");+ Preconditions.checkArgument(relation.lastVersion != null, "Last version is required");+ Preconditions.checkArgument(relation.deletedAt != null, "Deleted at is required");+ return relation;+ }+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.javaindex 3de63af5fb..8d33120db3 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java@@ -51,6 +51,7 @@ import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapperimport org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper;import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;@@ -308,6 +309,10 @@ public class MetalakeMetaService {SessionUtils.doWithoutCommit(PolicyMetaMapper.class,mapper -> mapper.softDeletePolicyMetasByMetalakeId(metalakeId)),+ // Must follow the policy delete, which waits for an in-flight policy update to commit.+ () ->+ SessionUtils.doWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.softDeleteByMetalakeId(metalakeId)),() ->SessionUtils.doWithoutCommit(PolicyVersionMapper.class,@@ -432,6 +437,10 @@ public class MetalakeMetaService {SessionUtils.doWithoutCommit(PolicyMetaMapper.class,mapper -> mapper.softDeletePolicyMetasByMetalakeId(metalakeId)),+ // Must follow the policy delete, which waits for an in-flight policy update to commit.+ () ->+ SessionUtils.doWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.softDeleteByMetalakeId(metalakeId)),() ->SessionUtils.doWithoutCommit(PolicyVersionMapper.class,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.javaindex c223c39139..31288efbec 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java@@ -29,6 +29,7 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;+import java.util.Set;import java.util.function.Function;import java.util.stream.Collectors;import javax.annotation.Nullable;@@ -51,6 +52,7 @@ import org.apache.gravitino.storage.relational.EntityChangeLogWriter;import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;import org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper;import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;@@ -59,6 +61,7 @@ import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapperimport org.apache.gravitino.storage.relational.po.MetalakePO;import org.apache.gravitino.storage.relational.po.PolicyMaxVersionPO;import org.apache.gravitino.storage.relational.po.PolicyPO;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;import org.apache.gravitino.storage.relational.po.PolicyTagRelPO;import org.apache.gravitino.storage.relational.po.TagPO;import org.apache.gravitino.storage.relational.po.cache.OperateType;@@ -182,6 +185,7 @@ public class PolicyMetaService {() -> beforeUpdate(updatedPolicyEntity),() -> updatePolicyRootWithVersion(ident, oldPolicyPO, newPolicyPO),() -> insertPolicyVersionIfAllocated(oldPolicyPO, newPolicyPO),+ () -> updateRoleRelationsWithoutCommit(newPolicyPO.getPolicyId(), updatedPolicyEntity),() -> afterUpdate(updatedPolicyEntity));} catch (RuntimeException re) {ExceptionUtils.checkSQLException(@@ -231,6 +235,9 @@ public class PolicyMetaService {() ->SessionUtils.doWithoutCommit(PolicyTagRelMapper.class, mapper -> mapper.softDeleteByPolicyId(policyId)),+ () ->+ SessionUtils.doWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.softDeleteByPolicyId(policyId)),() ->SessionUtils.doWithoutCommit(TagMetadataObjectRelMapper.class,@@ -270,7 +277,12 @@ public class PolicyMetaService {PolicyVersionMapper.class,mapper -> mapper.deletePolicyVersionsByLegacyTimeline(legacyTimeline, limit));- return policyDeletedCount + policyVersionDeletedCount;+ int roleRelationDeletedCount =+ SessionUtils.doWithCommitAndFetchResult(+ PolicyRoleRelMapper.class,+ mapper -> mapper.deleteByLegacyTimeline(legacyTimeline, limit));++ return policyDeletedCount + policyVersionDeletedCount + roleRelationDeletedCount;}@Monitored(@@ -375,8 +387,17 @@ public class PolicyMetaService {}/**- * Writes the policy row and its content snapshot without committing, and fires the matching- * lifecycle hooks around the DML.+ * Writes the policy row, its content snapshot, and the role references derived from that content.+ */+ private void insertPolicyWithoutCommit(+ PolicyEntity policyEntity, PolicyPO initializedPolicyPO, boolean overwritten) {+ long policyId = writePolicyRowWithoutCommit(policyEntity, initializedPolicyPO, overwritten);+ updateRoleRelationsWithoutCommit(policyId, policyEntity);+ }++ /**+ * Writes the policy row and its content snapshot, returns the ID the row ended up with, and fires+ * the matching lifecycle hooks around the DML.** <p>A plain create (or an overwrite that finds no row) uses persist hooks. An overwrite that* replaces an existing row uses update hooks and passes the entity as stored — including the@@ -392,14 +413,14 @@ public class PolicyMetaService {* Such a row keeps the primary key, so the insert is rejected as an already-existing policy,* which is the honest answer: the snapshots and relations of the deleted policy are gone with it.*/- private void insertPolicyWithoutCommit(+ private long writePolicyRowWithoutCommit(PolicyEntity policyEntity, PolicyPO initializedPolicyPO, boolean overwritten) {if (!overwritten) {beforePersist(policyEntity);insertNewPolicyWithoutCommit(initializedPolicyPO);createHiddenTagWithoutCommit(policyEntity, initializedPolicyPO);afterPersist(policyEntity);- return;+ return initializedPolicyPO.getPolicyId();}PolicyPO existingPolicyPO = findAndLockPolicyForOverwrite(initializedPolicyPO);@@ -416,7 +437,7 @@ public class PolicyMetaService {insertNewPolicyWithoutCommit(initializedPolicyPO);createHiddenTagWithoutCommit(policyEntity, initializedPolicyPO);afterPersist(policyEntity);- return;+ return initializedPolicyPO.getPolicyId();}PolicyPO replacementPolicyPO =@@ -429,6 +450,70 @@ public class PolicyMetaService {updatePolicyRootWithVersion(observedIdentifier, existingPolicyPO, replacementPolicyPO);insertPolicyVersionIfAllocated(existingPolicyPO, replacementPolicyPO);afterUpdate(storedPolicy);+ return replacementPolicyPO.getPolicyId();+ }++ /**+ * Brings the role references derived from a policy's content in line with that content.+ *+ * <p>The references are written only here and never by a caller, so {@code content} stays the one+ * authority on which roles a policy names.+ *+ * <p>Only the difference is written: a reference the content still names keeps its row, so a+ * policy edit that leaves {@code applicableRoles} alone writes no reference rows at all.+ *+ * <p>A reference the content drops is deleted rather than soft-deleted, so no edit leaves a+ * tombstone behind. Removing a role, naming it again, and removing it once more therefore cannot+ * collide on the table's uniqueness over (policy, role, deleted_at), which the two removals would+ * otherwise share whenever they read the same millisecond from the database clock.+ */+ private void updateRoleRelationsWithoutCommit(long policyId, PolicyEntity policyEntity) {+ List<PolicyRoleRelPO> desired = POConverters.initializePolicyRoleRelPOs(policyId, policyEntity);+ List<PolicyRoleRelPO> current =+ SessionUtils.getWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.listByPolicyId(policyId));++ Set<String> desiredRoles =+ desired.stream().map(PolicyRoleRelPO::getRoleName).collect(Collectors.toSet());+ Set<String> currentRoles =+ current.stream().map(PolicyRoleRelPO::getRoleName).collect(Collectors.toSet());++ for (PolicyRoleRelPO superseded : current) {+ if (desiredRoles.contains(superseded.getRoleName())) {+ continue;+ }+ // A zero-row delete means the reference is already gone, which is the intended end state.+ SessionUtils.doWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.deleteByIdAndVersion(superseded));+ }++ for (PolicyRoleRelPO added : desired) {+ if (currentRoles.contains(added.getRoleName())) {+ continue;+ }+ try {+ SessionUtils.doWithoutCommit(PolicyRoleRelMapper.class, mapper -> mapper.insert(added));+ } catch (RuntimeException re) {+ // Only names the backend treats as equal can collide here, e.g. "analyst" and "analyst " on+ // MySQL. Report the role, not "policy already exists". The SQL error is logged, not set as+ // the cause: the caller's handler searches causes for a duplicate key and would report that+ // again.+ if (ExceptionUtils.isDuplicateKey(re)) {+ LOG.warn(+ "Failed to write the reference to role {} for policy {} (id {})",+ added.getRoleName(),+ policyEntity.nameIdentifier(),+ policyId,+ re);+ throw new IllegalArgumentException(+ String.format(+ "The content of policy %s names the role %s more than once; on this backend"+ + " those names identify the same role",+ policyEntity.name(), added.getRoleName()));+ }+ throw re;+ }+ }}/**diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.javaindex e46d525324..5b6907877c 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java@@ -21,10 +21,12 @@ package org.apache.gravitino.storage.relational.utils;import com.fasterxml.jackson.core.JsonProcessingException;import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableList;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import java.time.Instant;import java.util.Collections;+import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Objects;@@ -33,6 +35,8 @@ import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Audit;import org.apache.gravitino.Catalog;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityFieldLimits;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -64,6 +68,7 @@ import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;+import org.apache.gravitino.policy.AccessControlContent;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.rel.Column;@@ -84,6 +89,7 @@ import org.apache.gravitino.storage.relational.po.ModelVersionAliasRelPO;import org.apache.gravitino.storage.relational.po.ModelVersionPO;import org.apache.gravitino.storage.relational.po.OwnerRelPO;import org.apache.gravitino.storage.relational.po.PolicyPO;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;import org.apache.gravitino.storage.relational.po.PolicyVersionPO;import org.apache.gravitino.storage.relational.po.RolePO;import org.apache.gravitino.storage.relational.po.SchemaPO;@@ -1637,6 +1643,50 @@ public class POConverters {}}+ /**+ * Builds the role reference rows derived from a policy's content.+ *+ * <p>Only access control content names roles, so every other policy type yields no rows. Exact+ * duplicate names in the content collapse to one row. Names that differ as strings but compare+ * equal under the backend's collation, such as "analyst" and "analyst " on MySQL, are not+ * collapsed here; the insert rejects them as naming one role twice, the same way the role table+ * would.+ *+ * <p>A role name longer than the role table allows is rejected here rather than left to the+ * database, so every backend reports it the same way and none can store a shortened name.+ *+ * @param policyId the ID of the policy row the references belong to+ * @param policyEntity the policy being written+ * @return the references the content currently names+ * @throws IllegalArgumentException if a role name is longer than a role name can be+ */+ public static List<PolicyRoleRelPO> initializePolicyRoleRelPOs(+ Long policyId, PolicyEntity policyEntity) {+ PolicyContent content = policyEntity.content();+ if (!(content instanceof AccessControlContent)) {+ return ImmutableList.of();+ }++ ImmutableList.Builder<PolicyRoleRelPO> relations = ImmutableList.builder();+ for (String roleName :+ new LinkedHashSet<>(((AccessControlContent) content).applicableRoles())) {+ EntityFieldLimits.checkMaxLength(+ roleName,+ EntityFieldLimits.MAX_NAME_LENGTH,+ "applicable role name",+ Entity.EntityType.POLICY);+ relations.add(+ PolicyRoleRelPO.builder()+ .withPolicyId(policyId)+ .withRoleName(roleName)+ .withCurrentVersion(INIT_VERSION)+ .withLastVersion(INIT_VERSION)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build());+ }+ return relations.build();+ }+public static OwnerRelPO initializeOwnerRelPOsWithVersion(Long metalakeId,String ownerType,diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.javanew file mode 100644index 0000000000..ae2f981ad3--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java@@ -0,0 +1,540 @@+/*+ * 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.storage.relational.service;++import java.io.IOException;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;+import java.util.stream.Collectors;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;+import org.apache.gravitino.EntityFieldLimits;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.authorization.AuthorizationUtils;+import org.apache.gravitino.authorization.Privilege;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.meta.CatalogEntity;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.meta.RoleEntity;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.session.SqlSessions;+import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.apache.gravitino.utils.NamespaceUtil;+import org.apache.ibatis.session.SqlSession;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.TestTemplate;++/** Tests the policy-to-role references derived from access control policy content. */+public class TestPolicyRoleRelService extends TestJDBCBackend {++ private static final String METALAKE = "policy_role_relation_metalake";++ @TestTemplate+ public void testReferencesFollowPolicyContent() throws IOException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));+ backend.insert(policy, false);++ Assertions.assertEquals(Arrays.asList("analyst", "auditor"), rolesOf(policy.id()));+ Assertions.assertEquals(Collections.singletonList("reader"), policiesReferencing("analyst"));+ Long auditorRowId = referenceTo(policy.id(), "auditor").getId();++ backend.update(+ policy.nameIdentifier(),+ Entity.EntityType.POLICY,+ entity -> withRoles(policy, Arrays.asList("auditor", "steward")));++ Assertions.assertEquals(Arrays.asList("auditor", "steward"), rolesOf(policy.id()));+ Assertions.assertEquals(Collections.emptyList(), policiesReferencing("analyst"));+ // A reference the content still names is left alone rather than rewritten.+ Assertions.assertEquals(auditorRowId, referenceTo(policy.id(), "auditor").getId());+ }++ @TestTemplate+ public void testOverwriteAttachesReferencesToTheSurvivingPolicyRow() throws IOException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity original = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(original, false);++ PolicyEntity replacement = accessControlPolicy("reader", Collections.singletonList("auditor"));+ backend.insert(replacement, true);++ // An overwrite keeps the row the name already pointed at, so the references follow that ID.+ Assertions.assertEquals(Collections.singletonList("auditor"), rolesOf(original.id()));+ Assertions.assertEquals(Collections.emptyList(), rolesOf(replacement.id()));+ Assertions.assertEquals(Collections.singletonList("reader"), policiesReferencing("auditor"));+ Assertions.assertEquals(Collections.emptyList(), policiesReferencing("analyst"));+ }++ @TestTemplate+ public void testFailedPolicyWriteLeavesNoReferences() throws IOException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);++ PolicyEntity duplicate = accessControlPolicy("reader", Collections.singletonList("steward"));+ Assertions.assertThrows(+ EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false));++ Assertions.assertEquals(Collections.emptyList(), policiesReferencing("steward"));+ Assertions.assertEquals(Collections.singletonList("reader"), policiesReferencing("analyst"));+ }++ @TestTemplate+ public void testFailedReferenceWriteRollsBackThePolicy() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ String oversizedRoleName = "r".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);+ PolicyEntity policy =+ accessControlPolicy("reader", Collections.singletonList(oversizedRoleName));++ IllegalArgumentException failure =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> backend.insert(policy, false));+ Assertions.assertTrue(+ failure.getMessage().contains("must not exceed " + EntityFieldLimits.MAX_NAME_LENGTH),+ failure.getMessage());++ Assertions.assertEquals(+ 0L, count("SELECT COUNT(*) FROM policy_meta WHERE policy_id = ?", policy.id()));+ Assertions.assertEquals(+ 0L, count("SELECT COUNT(*) FROM policy_version_info WHERE policy_id = ?", policy.id()));+ Assertions.assertEquals(+ 0L,+ count("SELECT COUNT(*) FROM policy_role_relation_meta WHERE policy_id = ?", policy.id()));+ }++ @TestTemplate+ public void testRoleNameAtTheLengthLimitIsAccepted() throws IOException {+ createAndInsertMakeLake(METALAKE);+ String longestRoleName = "r".repeat(EntityFieldLimits.MAX_NAME_LENGTH);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList(longestRoleName));+ backend.insert(policy, false);++ Assertions.assertEquals(Collections.singletonList(longestRoleName), rolesOf(policy.id()));+ }++ @TestTemplate+ public void testFailedReferenceUpdateKeepsThePreviousPolicy() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);+ String versionsOfPolicy = "SELECT COUNT(*) FROM policy_version_info WHERE policy_id = ?";+ long versionsBefore = count(versionsOfPolicy, policy.id());++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ backend.update(+ policy.nameIdentifier(),+ Entity.EntityType.POLICY,+ entity ->+ withRoles(+ policy,+ Arrays.asList(+ "auditor", "r".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1)))));++ PolicyEntity stored = backend.get(policy.nameIdentifier(), Entity.EntityType.POLICY);+ Assertions.assertEquals(policy.content(), stored.content());+ Assertions.assertEquals(versionsBefore, count(versionsOfPolicy, policy.id()));+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));+ }++ @TestTemplate+ public void testDuplicateRoleNamesCollapseToOneReference() throws IOException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "analyst"));+ backend.insert(policy, false);++ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));+ }++ @TestTemplate+ public void testReferenceEqualityFollowsTheRoleTable() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ CatalogEntity catalog = createAndInsertCatalog(METALAKE, "policy_role_equality_catalog");++ // Ask the authoritative table whether these two names are one role or two, rather than+ // assuming: MySQL compares role names ignoring trailing spaces, PostgreSQL and H2 do not.+ backend.insert(role(catalog, "analyst"), false);+ boolean roleTableSeesTwoRoles;+ try {+ backend.insert(role(catalog, "analyst "), false);+ roleTableSeesTwoRoles = true;+ } catch (EntityAlreadyExistsException sameRoleTwice) {+ roleTableSeesTwoRoles = false;+ }++ PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "analyst "));+ if (roleTableSeesTwoRoles) {+ backend.insert(policy, false);+ Assertions.assertEquals(Arrays.asList("analyst", "analyst "), rolesOf(policy.id()));+ } else {+ // One role named twice. The write fails against the role that collided, not the policy name.+ IllegalArgumentException failure =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> backend.insert(policy, false));+ Assertions.assertTrue(failure.getMessage().contains("analyst"), failure.getMessage());+ Assertions.assertEquals(0L, activeReferenceCount(policy.id()));+ }+ }++ @TestTemplate+ public void testPolicyWithoutAccessControlContentReferencesNoRoles() throws IOException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(METALAKE),+ "compaction",+ AUDIT_INFO);+ backend.insert(policy, false);++ Assertions.assertEquals(Collections.emptyList(), rolesOf(policy.id()));+ }++ @TestTemplate+ public void testPolicyDeleteClearsReferences() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);++ Assertions.assertTrue(backend.delete(policy.nameIdentifier(), Entity.EntityType.POLICY, false));++ Assertions.assertEquals(0L, activeReferenceCount(policy.id()));+ }++ @TestTemplate+ public void testMetalakeDeleteClearsOnlyItsOwnReferences() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ String otherMetalake = METALAKE + "_other";+ createAndInsertMakeLake(otherMetalake);++ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);+ PolicyEntity otherPolicy =+ accessControlPolicy(otherMetalake, "reader", Collections.singletonList("analyst"));+ backend.insert(otherPolicy, false);++ Assertions.assertTrue(+ backend.delete(NameIdentifier.of(METALAKE), Entity.EntityType.METALAKE, true));++ Assertions.assertEquals(0L, activeReferenceCount(policy.id()));+ Assertions.assertEquals(1L, activeReferenceCount(otherPolicy.id()));+ }++ @TestTemplate+ public void testRoleLookupStaysInItsMetalake() throws IOException {+ createAndInsertMakeLake(METALAKE);+ String otherMetalake = METALAKE + "_other";+ createAndInsertMakeLake(otherMetalake);+ backend.insert(accessControlPolicy("reader", Collections.singletonList("analyst")), false);+ backend.insert(+ accessControlPolicy(otherMetalake, "writer", Collections.singletonList("analyst")), false);++ Assertions.assertEquals(+ Collections.singletonList("reader"), policiesReferencing(METALAKE, "analyst"));+ Assertions.assertEquals(+ Collections.singletonList("writer"), policiesReferencing(otherMetalake, "analyst"));++ Assertions.assertTrue(+ backend.delete(NameIdentifier.of(METALAKE), Entity.EntityType.METALAKE, true));++ Assertions.assertEquals(Collections.emptyList(), policiesReferencing(METALAKE, "analyst"));+ Assertions.assertEquals(+ Collections.singletonList("writer"), policiesReferencing(otherMetalake, "analyst"));+ }++ @TestTemplate+ public void testMetalakeDeleteClearsReferencesOfAnInFlightPolicyUpdate() throws Exception {+ assertMetalakeDeleteClearsReferenceAddedWhileWaiting(true);+ }++ @TestTemplate+ public void testNonCascadeMetalakeDeleteClearsReferencesOfAnInFlightPolicyUpdate()+ throws Exception {+ assertMetalakeDeleteClearsReferenceAddedWhileWaiting(false);+ }++ /**+ * Covers an update that read the policy before the metalake was deleted and writes after the+ * delete committed. It must fail as not found, leave the policy deleted, and write no reference.+ */+ @TestTemplate+ public void testUpdateReadBeforeMetalakeDeleteFailsWithoutReferences() throws Exception {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);++ // The updater callback runs after the update read the policy and before its write transaction+ // opens, so the delete commits in between.+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ backend.update(+ policy.nameIdentifier(),+ Entity.EntityType.POLICY,+ entity -> {+ deleteMetalakeOnAnotherThread();+ return withRoles(policy, Arrays.asList("analyst", "auditor"));+ }));++ Assertions.assertEquals(+ 0L,+ count(+ "SELECT COUNT(*) FROM policy_meta WHERE policy_id = ? AND deleted_at = 0",+ policy.id()));+ Assertions.assertEquals(0L, activeReferenceCount(policy.id()));+ }++ @TestTemplate+ public void testSupersededReferencesLeaveNoTombstone() throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));+ backend.insert(policy, false);++ // Remove a role, name it again, and remove it once more. Each removal takes the row out+ // rather than stamping it, so neither leaves a tombstone the next one could collide with,+ // whatever the database clock reads.+ for (List<String> roles :+ Arrays.asList(+ Collections.singletonList("auditor"),+ Arrays.asList("analyst", "auditor"),+ Collections.singletonList("auditor"))) {+ backend.update(+ policy.nameIdentifier(), Entity.EntityType.POLICY, entity -> withRoles(policy, roles));+ Assertions.assertEquals(0L, softDeletedReferenceCount());+ }++ Assertions.assertEquals(Collections.singletonList("auditor"), rolesOf(policy.id()));+ }++ @TestTemplate+ public void testLegacyCleanupRemovesOnlyReferencesOfDeletedPolicies()+ throws IOException, SQLException {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity deleted = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));+ PolicyEntity live = accessControlPolicy("writer", Collections.singletonList("analyst"));+ backend.insert(deleted, false);+ backend.insert(live, false);++ // A policy delete soft-deletes its references, so legacy cleanup has rows to collect.+ backend.delete(deleted.nameIdentifier(), Entity.EntityType.POLICY, false);+ Assertions.assertEquals(2L, softDeletedReferenceCount());++ // A cutoff past every timestamp avoids comparing the JVM clock with the database clock. A limit+ // of one stops the first run at its LIMIT, which PostgreSQL writes differently.+ PolicyMetaService service = PolicyMetaService.getInstance();+ service.deletePolicyAndVersionMetasByLegacyTimeline(Long.MAX_VALUE, 1);+ Assertions.assertEquals(1L, softDeletedReferenceCount());++ // The next run has room for every row, and must still leave the live policy's reference alone.+ service.deletePolicyAndVersionMetasByLegacyTimeline(Long.MAX_VALUE, 10);+ Assertions.assertEquals(0L, softDeletedReferenceCount());+ Assertions.assertEquals(1L, activeReferenceCount(live.id()));+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(live.id()));+ }++ /**+ * Holds a policy row the way an in-flight update does, waits until the metalake delete is blocked+ * on that row, and only then lets the update add a reference and commit.+ *+ * <p>The delete clears that reference only if its reference cleanup runs after the policy delete+ * it was blocked on. With the cleanup ordered first, it has already run by the time the update+ * commits, and the new reference is left active.+ */+ private void assertMetalakeDeleteClearsReferenceAddedWhileWaiting(boolean cascade)+ throws Exception {+ createAndInsertMakeLake(METALAKE);+ PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));+ backend.insert(policy, false);++ Throwable deleteFailure =+ new TransactionLockWaits(backendType)+ .whileTransactionHeld(+ () -> lockPolicyRow(policy.id()),+ () ->+ backend.delete(+ NameIdentifier.of(METALAKE), Entity.EntityType.METALAKE, cascade),+ () ->+ backend.update(+ policy.nameIdentifier(),+ Entity.EntityType.POLICY,+ entity -> withRoles(policy, Arrays.asList("analyst", "auditor"))),+ true);++ Assertions.assertNull(deleteFailure);+ Assertions.assertEquals(0L, activeReferenceCount(policy.id()));+ }++ /** Deletes the metalake without cascade on another thread and waits for it to finish. */+ private void deleteMetalakeOnAnotherThread() {+ ExecutorService executor = Executors.newSingleThreadExecutor();+ try {+ Assertions.assertTrue(+ executor+ .submit(+ () ->+ backend.delete(+ NameIdentifier.of(METALAKE), Entity.EntityType.METALAKE, false))+ .get(30, TimeUnit.SECONDS));+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("Interrupted while waiting for the metalake delete", e);+ } catch (ExecutionException | TimeoutException e) {+ throw new IllegalStateException("The metalake delete did not finish", e);+ } finally {+ executor.shutdownNow();+ }+ }++ /** Takes the policy row lock in the current transaction, which an update holds until commit. */+ private void lockPolicyRow(long policyId) throws SQLException {+ SqlSession session = SqlSessions.getSqlSession();+ try (PreparedStatement lock =+ session+ .getConnection()+ .prepareStatement("SELECT policy_id FROM policy_meta WHERE policy_id = ? FOR UPDATE")) {+ lock.setLong(1, policyId);+ lock.executeQuery().close();+ } finally {+ SqlSessions.closeSqlSession();+ }+ }++ private RoleEntity role(CatalogEntity catalog, String name) {+ return createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(METALAKE),+ name,+ AUDIT_INFO,+ catalog.name());+ }++ private PolicyEntity accessControlPolicy(String name, List<String> roles) {+ return accessControlPolicy(METALAKE, name, roles);+ }++ private PolicyEntity accessControlPolicy(String metalake, String name, List<String> roles) {+ return PolicyEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withNamespace(NamespaceUtil.ofPolicy(metalake))+ .withName(name)+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)+ .withComment("")+ .withEnabled(true)+ .withContent(+ PolicyContents.accessControl(+ Collections.singletonList(Privilege.Name.SELECT_TABLE), roles))+ .withAuditInfo(AUDIT_INFO)+ .build();+ }++ private static PolicyEntity withRoles(PolicyEntity policy, List<String> roles) {+ return PolicyEntity.builder()+ .withId(policy.id())+ .withNamespace(policy.namespace())+ .withName(policy.name())+ .withPolicyType(policy.policyType())+ .withComment(policy.comment())+ .withEnabled(policy.enabled())+ .withContent(+ PolicyContents.accessControl(+ Collections.singletonList(Privilege.Name.SELECT_TABLE), roles))+ .withAuditInfo(AUDIT_INFO)+ .build();+ }++ private List<String> rolesOf(long policyId) {+ return SessionUtils.getWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.listByPolicyId(policyId))+ .stream()+ .map(PolicyRoleRelPO::getRoleName)+ .collect(Collectors.toList());+ }++ private List<String> policiesReferencing(String roleName) {+ return policiesReferencing(METALAKE, roleName);+ }++ private List<String> policiesReferencing(String metalake, String roleName) {+ return SessionUtils.getWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.listByRoleName(metalake, roleName))+ .stream()+ .map(PolicyRoleRelPO::getPolicyName)+ .collect(Collectors.toList());+ }++ private PolicyRoleRelPO referenceTo(long policyId, String roleName) {+ return SessionUtils.getWithoutCommit(+ PolicyRoleRelMapper.class, mapper -> mapper.listByPolicyId(policyId))+ .stream()+ .filter(reference -> roleName.equals(reference.getRoleName()))+ .findFirst()+ .orElseThrow(() -> new AssertionError("No reference to role " + roleName));+ }++ private long softDeletedReferenceCount() throws SQLException {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement = connection.createStatement();+ ResultSet resultSet =+ statement.executeQuery(+ "SELECT COUNT(*) FROM policy_role_relation_meta WHERE deleted_at > 0")) {+ Assertions.assertTrue(resultSet.next());+ return resultSet.getLong(1);+ }+ }++ private long activeReferenceCount(long policyId) throws SQLException {+ return count(+ "SELECT COUNT(*) FROM policy_role_relation_meta WHERE policy_id = ? AND deleted_at = 0",+ policyId);+ }++ private long count(String sql, long policyId) throws SQLException {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ PreparedStatement statement = connection.prepareStatement(sql)) {+ statement.setLong(1, policyId);+ try (ResultSet resultSet = statement.executeQuery()) {+ Assertions.assertTrue(resultSet.next());+ return resultSet.getLong(1);+ }+ }+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMembershipWrites.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMembershipWrites.javaindex eae6773ddf..d2ab3f0ed5 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMembershipWrites.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMembershipWrites.java@@ -19,7 +19,6 @@package org.apache.gravitino.storage.relational.service;-import static org.awaitility.Awaitility.await;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNull;@@ -27,9 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;-import java.sql.Connection;import java.sql.ResultSet;-import java.sql.SQLException;import java.sql.Statement;import java.util.HashSet;import java.util.List;@@ -55,7 +52,6 @@ import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;import org.apache.gravitino.storage.relational.mapper.UserRoleRelMapper;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;-import org.apache.gravitino.storage.relational.session.SqlSessions;import org.apache.gravitino.storage.relational.utils.SessionUtils;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;@@ -306,18 +302,19 @@ class TestRoleMembershipWrites extends TestJDBCBackend {long groupId = RandomIdGenerator.INSTANCE.nextId();insertPrincipal(false, userId, List.of(), false);insertPrincipal(true, groupId, List.of(), false);+ TransactionLockWaits lockWaits = lockWaits();ExecutorService executor = Executors.newSingleThreadExecutor();CompletableFuture<Long> started = new CompletableFuture<>();SessionUtils.beginTransaction();try {- long holderId = prepareTransaction();+ long holderId = lockWaits.prepareTransaction();updatePrincipal(false, List.of(role), () -> {});Future<Throwable> grant =- submitTransaction(+ lockWaits.submitTransaction(executor, started, () -> updatePrincipal(true, List.of(role), () -> {}));long contenderId = started.get(10, TimeUnit.SECONDS);if ("h2".equalsIgnoreCase(backendType)) {- awaitBlockedBy(grant, contenderId, holderId);+ lockWaits.awaitBlockedBy(grant, contenderId, holderId);} else {// Independent principals can commit grants while the first transaction still holds its// shared locks on the metalake and role.@@ -634,128 +631,10 @@ class TestRoleMembershipWrites extends TestJDBCBackend {private Throwable whileTransactionHeld(Executable holder, Executable contender, Executable beforeCompletion, boolean commitHolder)throws Exception {- ExecutorService executor = Executors.newSingleThreadExecutor();- CompletableFuture<Long> started = new CompletableFuture<>();- SessionUtils.beginTransaction();- try {- long holderId = prepareTransaction();- Assertions.assertDoesNotThrow(holder);- Future<Throwable> result = submitTransaction(executor, started, contender);- awaitBlockedBy(result, started.get(10, TimeUnit.SECONDS), holderId);- Assertions.assertDoesNotThrow(beforeCompletion);- if (commitHolder) {- SessionUtils.commitTransaction();- } else {- SessionUtils.rollbackTransaction();- }- return result.get(10, TimeUnit.SECONDS);- } finally {- SessionUtils.rollbackTransaction();- executor.shutdownNow();- assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));- }+ return lockWaits().whileTransactionHeld(holder, contender, beforeCompletion, commitHolder);}- private Future<Throwable> submitTransaction(- ExecutorService executor, CompletableFuture<Long> started, Executable operation) {- return executor.submit(- () -> {- SessionUtils.beginTransaction();- try {- started.complete(prepareTransaction());- operation.execute();- SessionUtils.commitTransaction();- return null;- } catch (Throwable failure) {- started.completeExceptionally(failure);- return failure;- } finally {- SessionUtils.rollbackTransaction();- }- });- }-- private long prepareTransaction() throws SQLException {- SqlSession session = SqlSessions.getSqlSession();- try (Statement statement = session.getConnection().createStatement()) {- String sessionIdQuery;- switch (backendType) {- case "h2":- // Keep the engine timeout above the test's lock-observation deadline.- statement.execute("SET LOCK_TIMEOUT 30000");- sessionIdQuery = "SELECT SESSION_ID()";- break;- case "mysql":- statement.execute("SET SESSION innodb_lock_wait_timeout = 30");- sessionIdQuery = "SELECT CONNECTION_ID()";- break;- case "postgresql":- statement.execute("SET LOCAL lock_timeout = '30s'");- sessionIdQuery = "SELECT pg_backend_pid()";- break;- default:- throw new IllegalStateException("Unsupported backend: " + backendType);- }- try (ResultSet rows = statement.executeQuery(sessionIdQuery)) {- assertTrue(rows.next());- return rows.getLong(1);- }- } finally {- SqlSessions.closeSqlSession();- }- }-- private void awaitBlockedBy(Future<Throwable> result, long contenderId, long holderId)- throws Exception {- String query;- switch (backendType) {- case "h2":- query =- "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS WHERE SESSION_ID = "- + contenderId- + " AND BLOCKER_ID = "- + holderId;- break;- case "mysql":- query =- "SELECT COUNT(*) FROM performance_schema.data_lock_waits w"- + " JOIN performance_schema.threads r ON r.THREAD_ID = w.REQUESTING_THREAD_ID"- + " JOIN performance_schema.threads b ON b.THREAD_ID = w.BLOCKING_THREAD_ID"- + " WHERE r.PROCESSLIST_ID = "- + contenderId- + " AND b.PROCESSLIST_ID = "- + holderId;- break;- case "postgresql":- query =- "SELECT COUNT(*) FROM unnest(pg_blocking_pids("- + contenderId- + ")) AS blocker(pid) WHERE pid = "- + holderId;- break;- default:- throw new IllegalStateException("Unsupported backend: " + backendType);- }- // Observe the actual waiter/blocker pair. A slow thread or connection checkout alone cannot- // satisfy this assertion, and an unexpectedly completed operation fails immediately.- try (SqlSession observer =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {- Connection connection = observer.getConnection();- await()- .pollInSameThread()- .atMost(10, TimeUnit.SECONDS)- .pollInterval(10, TimeUnit.MILLISECONDS)- .until(- () -> {- if (result.isDone()) {- throw new AssertionError(- "Operation completed without waiting for the holder", result.get());- }- try (Statement statement = connection.createStatement();- ResultSet rows = statement.executeQuery(query)) {- return rows.next() && rows.getLong(1) > 0;- }- });- }+ private TransactionLockWaits lockWaits() {+ return new TransactionLockWaits(backendType);}}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.javanew file mode 100644index 0000000000..bb526dab56--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java@@ -0,0 +1,210 @@+/*+ * 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.storage.relational.service;++import static org.awaitility.Awaitility.await;++import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.session.SqlSessions;+import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.apache.ibatis.session.SqlSession;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.function.Executable;++/**+ * Runs one transaction while another holds a lock it needs, and waits until the database itself+ * reports that wait. Tests use it to order two transactions at a lock without relying on sleeps.+ */+final class TransactionLockWaits {++ private static final long TIMEOUT_SECONDS = 10;++ private final String backendType;++ TransactionLockWaits(String backendType) {+ this.backendType = backendType;+ }++ /**+ * Runs {@code holder} in a transaction on the calling thread, starts {@code contender} in its own+ * transaction on another thread, and waits until the contender is blocked on the holder. Then it+ * runs {@code beforeCompletion} in the holder's transaction and commits or rolls it back.+ *+ * @param holder the work that takes the lock in the holding transaction+ * @param contender the work that must wait for that lock+ * @param beforeCompletion more work for the holding transaction once the contender is waiting+ * @param commitHolder whether to commit the holding transaction rather than roll it back+ * @return the contender's failure, or null if its transaction committed+ * @throws Exception if the contender does not wait, or the holder fails+ */+ Throwable whileTransactionHeld(+ Executable holder, Executable contender, Executable beforeCompletion, boolean commitHolder)+ throws Exception {+ ExecutorService executor = Executors.newSingleThreadExecutor();+ CompletableFuture<Long> started = new CompletableFuture<>();+ SessionUtils.beginTransaction();+ try {+ long holderId = prepareTransaction();+ Assertions.assertDoesNotThrow(holder);+ Future<Throwable> result = submitTransaction(executor, started, contender);+ awaitBlockedBy(result, started.get(TIMEOUT_SECONDS, TimeUnit.SECONDS), holderId);+ Assertions.assertDoesNotThrow(beforeCompletion);+ if (commitHolder) {+ SessionUtils.commitTransaction();+ } else {+ SessionUtils.rollbackTransaction();+ }+ return result.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);+ } finally {+ SessionUtils.rollbackTransaction();+ executor.shutdownNow();+ Assertions.assertTrue(executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS));+ }+ }++ /**+ * Runs {@code operation} in its own transaction on {@code executor}.+ *+ * @param executor the executor that runs the transaction+ * @param started completed with the transaction's session ID once it has begun+ * @param operation the work to run in the transaction+ * @return the operation's failure, or null if its transaction committed+ */+ Future<Throwable> submitTransaction(+ ExecutorService executor, CompletableFuture<Long> started, Executable operation) {+ return executor.submit(+ () -> {+ SessionUtils.beginTransaction();+ try {+ started.complete(prepareTransaction());+ operation.execute();+ SessionUtils.commitTransaction();+ return null;+ } catch (Throwable failure) {+ started.completeExceptionally(failure);+ return failure;+ } finally {+ SessionUtils.rollbackTransaction();+ }+ });+ }++ /**+ * Sets the current transaction's lock timeout above the wait deadline and returns its session ID.+ *+ * @return the database session ID of the current transaction+ * @throws SQLException if the session cannot be configured+ */+ long prepareTransaction() throws SQLException {+ SqlSession session = SqlSessions.getSqlSession();+ try (Statement statement = session.getConnection().createStatement()) {+ String sessionIdQuery;+ switch (backendType) {+ case "h2":+ // Keep the engine timeout above the test's lock-observation deadline.+ statement.execute("SET LOCK_TIMEOUT 30000");+ sessionIdQuery = "SELECT SESSION_ID()";+ break;+ case "mysql":+ statement.execute("SET SESSION innodb_lock_wait_timeout = 30");+ sessionIdQuery = "SELECT CONNECTION_ID()";+ break;+ case "postgresql":+ statement.execute("SET LOCAL lock_timeout = '30s'");+ sessionIdQuery = "SELECT pg_backend_pid()";+ break;+ default:+ throw new IllegalStateException("Unsupported backend: " + backendType);+ }+ try (ResultSet rows = statement.executeQuery(sessionIdQuery)) {+ Assertions.assertTrue(rows.next());+ return rows.getLong(1);+ }+ } finally {+ SqlSessions.closeSqlSession();+ }+ }++ /**+ * Waits until the database reports the contender waiting on a lock the holder owns.+ *+ * @param result the contender's pending result+ * @param contenderId the contender's database session ID+ * @param holderId the holder's database session ID+ * @throws Exception if the contender finishes without waiting, or never waits in time+ */+ void awaitBlockedBy(Future<Throwable> result, long contenderId, long holderId) throws Exception {+ String query = blockedByQuery(contenderId, holderId);+ // Observe the actual waiter/blocker pair. A slow thread or connection checkout alone cannot+ // satisfy this assertion, and an unexpectedly completed operation fails immediately.+ try (SqlSession observer =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {+ Connection connection = observer.getConnection();+ await()+ .pollInSameThread()+ .atMost(TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .pollInterval(10, TimeUnit.MILLISECONDS)+ .until(+ () -> {+ if (result.isDone()) {+ throw new AssertionError(+ "Operation completed without waiting for the holder", result.get());+ }+ try (Statement statement = connection.createStatement();+ ResultSet rows = statement.executeQuery(query)) {+ return rows.next() && rows.getLong(1) > 0;+ }+ });+ }+ }++ private String blockedByQuery(long contenderId, long holderId) {+ switch (backendType) {+ case "h2":+ return "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS WHERE SESSION_ID = "+ + contenderId+ + " AND BLOCKER_ID = "+ + holderId;+ case "mysql":+ return "SELECT COUNT(*) FROM performance_schema.data_lock_waits w"+ + " JOIN performance_schema.threads r ON r.THREAD_ID = w.REQUESTING_THREAD_ID"+ + " JOIN performance_schema.threads b ON b.THREAD_ID = w.BLOCKING_THREAD_ID"+ + " WHERE r.PROCESSLIST_ID = "+ + contenderId+ + " AND b.PROCESSLIST_ID = "+ + holderId;+ case "postgresql":+ return "SELECT COUNT(*) FROM unnest(pg_blocking_pids("+ + contenderId+ + ")) AS blocker(pid) WHERE pid = "+ + holderId;+ default:+ throw new IllegalStateException("Unsupported backend: " + backendType);+ }+ }+}diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sqlindex b64f3ba8e8..65e385d9cd 100644--- a/scripts/h2/schema-2.0.0-h2.sql+++ b/scripts/h2/schema-2.0.0-h2.sql@@ -442,6 +442,18 @@ CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (KEY `idx_policy_tag_relation_meta_live` (`tag_id`, `deleted_at`)) ENGINE=InnoDB;+CREATE TABLE IF NOT EXISTS `policy_role_relation_meta` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name referenced by the policy content',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy role relation deleted at',+ PRIMARY KEY (`id`),+ UNIQUE KEY `policy_role_relation_meta_uk_pid_rn_del` (`policy_id`, `role_name`, `deleted_at`),+ KEY `policy_role_relation_meta_idx_role_name` (`role_name`)+) ENGINE=InnoDB;+CREATE TABLE IF NOT EXISTS `statistic_meta` (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',`statistic_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'statistic id',diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sqlindex a01f377f9f..30d84691d0 100644--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql@@ -94,6 +94,18 @@ CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (KEY `policy_tag_relation_meta_idx_tag_id` (`tag_id`)) ENGINE=InnoDB;+CREATE TABLE IF NOT EXISTS `policy_role_relation_meta` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name referenced by the policy content',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy role relation deleted at',+ PRIMARY KEY (`id`),+ UNIQUE KEY `policy_role_relation_meta_uk_pid_rn_del` (`policy_id`, `role_name`, `deleted_at`),+ KEY `policy_role_relation_meta_idx_role_name` (`role_name`)+) ENGINE=InnoDB;+ALTER TABLE `job_run_meta` ADD COLUMN IF NOT EXISTS `runtime_job_template` CLOB DEFAULT NULL COMMENT 'job run runtime job template' AFTER `job_finished_at`;CREATE TABLE IF NOT EXISTS `semantic_model_meta` (diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sqlindex 3403c8c1b4..2f5f2e93a2 100644--- a/scripts/mysql/schema-2.0.0-mysql.sql+++ b/scripts/mysql/schema-2.0.0-mysql.sql@@ -433,6 +433,18 @@ CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (KEY `idx_policy_tag_relation_meta_live` (`tag_id`, `deleted_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy tag relation';+CREATE TABLE IF NOT EXISTS `policy_role_relation_meta` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name referenced by the policy content',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy role relation deleted at',+ PRIMARY KEY (`id`),+ UNIQUE KEY `policy_role_relation_meta_uk_pid_rn_del` (`policy_id`, `role_name`, `deleted_at`),+ KEY `policy_role_relation_meta_idx_role_name` (`role_name`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy role relation';+CREATE TABLE IF NOT EXISTS `statistic_meta` (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',`statistic_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'statistic id',diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sqlindex 2f6e568c68..1cedda7f78 100644--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql@@ -571,6 +571,18 @@ CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (KEY `policy_tag_relation_meta_idx_tag_id` (`tag_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy tag relation';+CREATE TABLE IF NOT EXISTS `policy_role_relation_meta` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name referenced by the policy content',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy role relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy role relation deleted at',+ PRIMARY KEY (`id`),+ UNIQUE KEY `policy_role_relation_meta_uk_pid_rn_del` (`policy_id`, `role_name`, `deleted_at`),+ KEY `policy_role_relation_meta_idx_role_name` (`role_name`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy role relation';+SET @ddl = IF(EXISTS(SELECT 1 FROM information_schema.columnsWHERE table_schema = DATABASE() AND table_name = 'job_run_meta' AND column_name = 'runtime_job_template'),'SELECT 1',diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sqlindex 94df6f911b..93b3bfdf6d 100644--- a/scripts/postgresql/schema-2.0.0-postgresql.sql+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql@@ -767,6 +767,26 @@ COMMENT ON COLUMN policy_tag_relation_meta.current_version IS 'policy tag relatiCOMMENT ON COLUMN policy_tag_relation_meta.last_version IS 'policy tag relation last version';COMMENT ON COLUMN policy_tag_relation_meta.deleted_at IS 'policy tag relation deleted at';+CREATE TABLE IF NOT EXISTS policy_role_relation_meta (+ id BIGSERIAL NOT NULL,+ policy_id BIGINT NOT NULL,+ role_name VARCHAR(128) NOT NULL,+ current_version INT NOT NULL DEFAULT 1,+ last_version INT NOT NULL DEFAULT 1,+ deleted_at BIGINT NOT NULL DEFAULT 0,+ PRIMARY KEY (id),+ UNIQUE (policy_id, role_name, deleted_at)+);++CREATE INDEX IF NOT EXISTS policy_role_relation_meta_idx_role_name ON policy_role_relation_meta (role_name);+COMMENT ON TABLE policy_role_relation_meta IS 'policy role relation';+COMMENT ON COLUMN policy_role_relation_meta.id IS 'auto increment id';+COMMENT ON COLUMN policy_role_relation_meta.policy_id IS 'policy id';+COMMENT ON COLUMN policy_role_relation_meta.role_name IS 'role name referenced by the policy content';+COMMENT ON COLUMN policy_role_relation_meta.current_version IS 'policy role relation current version';+COMMENT ON COLUMN policy_role_relation_meta.last_version IS 'policy role relation last version';+COMMENT ON COLUMN policy_role_relation_meta.deleted_at IS 'policy role relation deleted at';+CREATE TABLE IF NOT EXISTS statistic_meta (id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,statistic_id BIGINT NOT NULL,diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sqlindex b29b9719b1..66587f9d18 100644--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql@@ -107,6 +107,26 @@ COMMENT ON COLUMN policy_tag_relation_meta.current_version IS 'policy tag relatiCOMMENT ON COLUMN policy_tag_relation_meta.last_version IS 'policy tag relation last version';COMMENT ON COLUMN policy_tag_relation_meta.deleted_at IS 'policy tag relation deleted at';+CREATE TABLE IF NOT EXISTS policy_role_relation_meta (+ id BIGSERIAL NOT NULL,+ policy_id BIGINT NOT NULL,+ role_name VARCHAR(128) NOT NULL,+ current_version INT NOT NULL DEFAULT 1,+ last_version INT NOT NULL DEFAULT 1,+ deleted_at BIGINT NOT NULL DEFAULT 0,+ PRIMARY KEY (id),+ UNIQUE (policy_id, role_name, deleted_at)+);++CREATE INDEX IF NOT EXISTS policy_role_relation_meta_idx_role_name ON policy_role_relation_meta (role_name);+COMMENT ON TABLE policy_role_relation_meta IS 'policy role relation';+COMMENT ON COLUMN policy_role_relation_meta.id IS 'auto increment id';+COMMENT ON COLUMN policy_role_relation_meta.policy_id IS 'policy id';+COMMENT ON COLUMN policy_role_relation_meta.role_name IS 'role name referenced by the policy content';+COMMENT ON COLUMN policy_role_relation_meta.current_version IS 'policy role relation current version';+COMMENT ON COLUMN policy_role_relation_meta.last_version IS 'policy role relation last version';+COMMENT ON COLUMN policy_role_relation_meta.deleted_at IS 'policy role relation deleted at';+ALTER TABLE job_run_meta ADD COLUMN IF NOT EXISTS runtime_job_template TEXT DEFAULT NULL;COMMENT ON COLUMN job_run_meta.runtime_job_template IS 'job run runtime job template';