Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#12151] improvement(core): complete cached entity change-log coverage (#12374)

Qi Yubb6b039ccf1d
diff --git a/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
index 0ff75c94f8..e23c53b81d 100644
--- a/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
@@ -45,15 +45,12 @@ public abstract class BaseEntityCache implements EntityCache {
* SupportsEntityStoreCache#put(Entity)} for the contract. New entity types are excluded by
* default until their invalidation behavior has been validated.
*
- * <p>{@code USER}, {@code GROUP} and {@code ROLE} are materialized with relation-derived data
- * joined in at load time: a role carries its securable objects, and a user/group carries its role
- * names. A mutation on the entity itself invalidates its own key through the write path, but this
- * embedded data also goes stale through a mutation on a different entity. For example, deleting
- * or renaming a securable object changes a role's materialized form, and deleting or renaming a
- * role changes a user's/group's role names. Such a mutation touches neither this entity's own key
- * nor any hierarchy ancestor of it, so neither the write-path invalidation nor a prefix cascade
- * over the entity hierarchy would evict it. Caching them would therefore serve stale
- * authorization data.
+ * <p>Only self-contained entities are cacheable: a stale copy of one is at worst cosmetically old
+ * (an old comment, property, or job status), never a wrong pointer, and each can be invalidated
+ * with a single one-to-one key drop. Every other type is read straight from the store.
+ * User/group/role embed relation-derived data that a per-node cache cannot invalidate;
+ * model/model version and function carry a load-bearing pointer that would be silently wrong if
+ * served stale.
*/
private static final Set<Entity.EntityType> CACHEABLE_TYPES =
Sets.immutableEnumSet(
@@ -61,19 +58,12 @@ public abstract class BaseEntityCache implements EntityCache {
Entity.EntityType.CATALOG,
Entity.EntityType.SCHEMA,
Entity.EntityType.TABLE,
+ Entity.EntityType.TOPIC,
Entity.EntityType.VIEW,
- Entity.EntityType.COLUMN,
Entity.EntityType.FILESET,
- Entity.EntityType.TOPIC,
Entity.EntityType.TAG,
- Entity.EntityType.MODEL,
- Entity.EntityType.MODEL_VERSION,
Entity.EntityType.POLICY,
- Entity.EntityType.TABLE_STATISTIC,
- Entity.EntityType.JOB_TEMPLATE,
- Entity.EntityType.JOB,
- Entity.EntityType.AUDIT,
- Entity.EntityType.FUNCTION);
+ Entity.EntityType.JOB);
protected final Config cacheConfig;
@@ -88,6 +78,18 @@ public abstract class BaseEntityCache implements EntityCache {
this.cacheConfig = config;
}
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Defaults to {@link Coherence#LOCAL_PER_NODE}: an in-memory, per-node cache whose changes
+ * must be propagated to the other nodes. A shared implementation must override this to return
+ * {@link Coherence#SHARED}.
+ */
+ @Override
+ public Coherence coherence() {
+ return Coherence.LOCAL_PER_NODE;
+ }
+
/**
* Returns whether entities of the given type may be cached.
*
diff --git a/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java
index 71e2592f4c..2f79394dbc 100644
--- a/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java
@@ -30,7 +30,6 @@ import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
import com.googlecode.concurrenttrees.radix.RadixTree;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import java.util.List;
-import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
@@ -43,7 +42,6 @@ import org.apache.gravitino.Configs;
import org.apache.gravitino.Entity;
import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.meta.ModelVersionEntity;
import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -57,10 +55,10 @@ import org.slf4j.LoggerFactory;
* schemas and tables under it).
*
* <p>Relation query results are NOT cached by this implementation; relation and list operations
- * always fall back to the {@code EntityStore}. Entity types whose materialized form embeds
- * relation-derived data ({@code USER}, {@code GROUP}, {@code ROLE}) are excluded from caching
- * entirely by {@link BaseEntityCache#put}, because without relation tracking their entries could
- * not be invalidated when the referenced entities change.
+ * always fall back to the {@code EntityStore}. Only the self-contained metadata objects listed in
+ * {@link BaseEntityCache#isCacheable} are cached; every other type (user/group/role, model/model
+ * version, function, job template, and any type not in that allowlist) is read straight from the
+ * {@code EntityStore}.
*/
public class CaffeineEntityCache extends BaseEntityCache {
private static final int CACHE_CLEANUP_CORE_THREADS = 1;
@@ -228,13 +226,9 @@ public class CaffeineEntityCache extends BaseEntityCache {
/** {@inheritDoc} */
@Override
public <E extends Entity & HasIdentifier> void invalidateOnKeyChange(E entity) {
- // Invalidate the cache if inserting the entity may affect related cache keys.
- // For example, inserting a model version changes the latest version of the model,
- // so the corresponding model cache entry should be invalidated.
- if (Objects.requireNonNull(entity.type()) == Entity.EntityType.MODEL_VERSION) {
- NameIdentifier modelIdent = ((ModelVersionEntity) entity).modelIdentifier();
- invalidate(modelIdent, Entity.EntityType.MODEL);
- }
+ // Every cacheable entity is self-contained (see BaseEntityCache#isCacheable), so inserting one
+ // never requires invalidating a different key. Kept for the SPI contract; implementations that
+ // cache derived entries can override this.
}
/** {@inheritDoc} */
diff --git a/core/src/main/java/org/apache/gravitino/cache/Coherence.java b/core/src/main/java/org/apache/gravitino/cache/Coherence.java
new file mode 100644
index 0000000000..151eb63901
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/cache/Coherence.java
@@ -0,0 +1,45 @@
+/*
+ * 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.cache;
+
+/**
+ * Describes how an {@link EntityCache} implementation stays coherent across a multi-node Gravitino
+ * cluster. The write path reads this marker to decide whether a change made on one node must be
+ * propagated to the other nodes.
+ */
+public enum Coherence {
+ /** The implementation does not retain entries, so it needs no coherence mechanism. */
+ NONE,
+
+ /**
+ * Each node keeps its own copy of the cache, so a change made on one node does not clear the
+ * copies held by the other nodes. To stay correct across a cluster the write path must publish
+ * the change (via the {@code entity_change_log}) so every other node's poller invalidates its own
+ * copy. The default {@code caffeine} cache is {@code LOCAL_PER_NODE}.
+ */
+ LOCAL_PER_NODE,
+
+ /**
+ * A single copy is shared by the whole cluster, so a write clears it once and every node observes
+ * the change immediately. There is nothing per-node to propagate. The {@code redis} cache is
+ * {@code SHARED}.
+ */
+ SHARED
+}
diff --git a/core/src/main/java/org/apache/gravitino/cache/EntityCache.java b/core/src/main/java/org/apache/gravitino/cache/EntityCache.java
index 0ea458bf36..98d46f15b8 100644
--- a/core/src/main/java/org/apache/gravitino/cache/EntityCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/EntityCache.java
@@ -28,6 +28,14 @@ package org.apache.gravitino.cache;
* this SPI; relation and list operations always fall back to the {@code EntityStore}.
*/
public interface EntityCache extends SupportsEntityStoreCache {
+ /**
+ * Returns how this cache stays coherent across a multi-node cluster. The write path uses this to
+ * decide whether a local change must be propagated to the other nodes (see {@link Coherence}).
+ *
+ * @return the {@link Coherence} model of this cache
+ */
+ Coherence coherence();
+
/**
* Clears all entries from the cache, including data and index, resetting it to an empty state.
*/
diff --git a/core/src/main/java/org/apache/gravitino/cache/NoOpsCache.java b/core/src/main/java/org/apache/gravitino/cache/NoOpsCache.java
index 8a8aab9956..c581f6f51f 100644
--- a/core/src/main/java/org/apache/gravitino/cache/NoOpsCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/NoOpsCache.java
@@ -37,6 +37,12 @@ public class NoOpsCache extends BaseEntityCache {
super(config);
}
+ /** {@inheritDoc} */
+ @Override
+ public Coherence coherence() {
+ return Coherence.NONE;
+ }
+
/** {@inheritDoc} */
@Override
protected void invalidateExpiredItem(EntityCacheKey key) {
diff --git a/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java b/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
index dce181822e..a6eb72d11a 100644
--- a/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
@@ -68,12 +68,11 @@ public interface SupportsEntityStoreCache {
* invalidation path covers, so it must remain non-cacheable until its invalidation behavior has
* been validated. Implementations extending {@link BaseEntityCache} get this check for free.
*
- * <p>{@code USER}, {@code GROUP} and {@code ROLE} are deliberately excluded because they are
- * materialized with relation-derived data joined in at load time (a role carries its securable
- * objects, and a user/group carries its role names). That embedded data goes stale through
- * mutations on other entities that touch neither this entity's own key nor any of its hierarchy
- * ancestors. Since no invalidation path covers them, caching them serves stale authorization
- * data.
+ * <p>Only self-contained entities are approved. User/group/role are deliberately excluded because
+ * they contain relation-derived data whose source can change through another entity. Model/model
+ * version and function are also excluded because they carry load-bearing pointers that must not
+ * be served stale. Other unapproved and newly introduced entity types go straight to the store
+ * until their invalidation behavior has been validated.
*
* <p>Implementations must also invoke {@link #invalidateOnKeyChange(Entity)} for every entity,
* including non-cacheable ones, since a non-cacheable entity may still invalidate a cacheable
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
index 9d7443ca88..9aa3c843c6 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
@@ -24,6 +24,7 @@ import java.util.Optional;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.storage.relational.EntityChangeLogListener;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -116,11 +117,17 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
return Optional.empty();
}
- String[] names = change.getFullName().split("\\.");
- if (names.length != 2) {
+ NameIdentifier ident;
+ try {
+ ident = EntityChangeLogNameIdentifierCodec.decode(change.getFullName());
+ } catch (IllegalArgumentException e) {
LOG.warn("Invalid catalog full name in entity change log: {}", change.getFullName());
return Optional.empty();
}
- return Optional.of(NameIdentifier.of(names[0], names[1]));
+ if (ident.namespace().length() != 1) {
+ LOG.warn("Invalid catalog full name in entity change log: {}", change.getFullName());
+ return Optional.empty();
+ }
+ return Optional.of(ident);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java
new file mode 100644
index 0000000000..587292c6d2
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java
@@ -0,0 +1,131 @@
+/*
+ * 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;
+
+import com.google.common.base.Preconditions;
+import java.util.List;
+import java.util.Locale;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.cache.EntityCache;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Keeps a per-node {@link EntityCache} coherent across a multi-node cluster by replaying {@code
+ * entity_change_log} rows written by other nodes.
+ *
+ * <p>Every ALTER/DROP row is replayed as a direct {@link EntityCache#invalidate(NameIdentifier,
+ * EntityType)} for exactly the changed entity key. Because the cache indexes its keys by identifier
+ * prefix, invalidating a container (for example a schema) cascades to its cached children on the
+ * local node through that forward prefix scan; no reverse index is involved.
+ *
+ * <p>This listener is registered only for a {@link
+ * org.apache.gravitino.cache.Coherence#LOCAL_PER_NODE} cache: a shared cache has a single
+ * cluster-wide copy and nothing per-node to invalidate. It is called <em>synchronously</em> on the
+ * poller thread, so it performs only fast, in-memory, idempotent invalidations.
+ *
+ * <p>The two failure modes of a replayed row are handled separately, because they mean different
+ * things:
+ *
+ * <ul>
+ * <li>A <b>malformed row</b> (unknown entity type, undecodable full name) names no entity, so
+ * there is nothing to invalidate. It is logged and skipped, and the rest of the batch still
+ * applies.
+ * <li>A <b>failed invalidation</b> means this node may now serve stale metadata indefinitely. The
+ * whole cache is cleared instead, which is strictly stronger than the invalidation that
+ * failed and only costs a cold-cache penalty, since the cache is derived state. If even the
+ * clear fails the exception propagates, and {@link EntityChangeLogPoller} retries the batch
+ * and ultimately applies its configured listener failure action.
+ * </ul>
+ */
+public class EntityCacheChangeLogListener implements EntityChangeLogListener {
+
+ private static final Logger LOG = LoggerFactory.getLogger(EntityCacheChangeLogListener.class);
+
+ private final EntityCache cache;
+
+ /**
+ * Creates a listener that invalidates the given entity store cache.
+ *
+ * @param cache the per-node entity store cache to keep coherent
+ */
+ public EntityCacheChangeLogListener(EntityCache cache) {
+ Preconditions.checkArgument(cache != null, "cache cannot be null");
+ this.cache = cache;
+ }
+
+ @Override
+ public void onEntityChange(List<EntityChangeRecord> changes) {
+ for (EntityChangeRecord change : changes) {
+ EntityType type = entityType(change);
+ NameIdentifier ident = identifier(change);
+ if (type == null || ident == null) {
+ // Already logged by the parsing helpers. A row that names no entity cannot invalidate
+ // anything, so skipping it leaves no stale entry behind.
+ continue;
+ }
+
+ try {
+ LOG.debug("Invalidating entity cache due to entity change log: {} ({})", ident, type);
+ cache.invalidate(ident, type);
+ } catch (RuntimeException e) {
+ // Dropping a single invalidation would leave this node serving that entity stale until it
+ // expires. Clearing the whole cache is the safe superset, and it also covers the rest of
+ // this batch, so there is nothing left to replay.
+ LOG.error(
+ "Failed to invalidate {} ({}) from the entity change log, clearing the local entity "
+ + "cache to stay coherent",
+ ident,
+ type,
+ e);
+ cache.clear();
+ return;
+ }
+ }
+ }
+
+ private EntityType entityType(EntityChangeRecord change) {
+ if (change.getEntityType() == null) {
+ LOG.warn("Invalid entity type in entity change log: null");
+ return null;
+ }
+ try {
+ return EntityType.valueOf(change.getEntityType().toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e) {
+ LOG.warn("Unknown entity type in entity change log: {}", change.getEntityType());
+ return null;
+ }
+ }
+
+ private NameIdentifier identifier(EntityChangeRecord change) {
+ String fullName = change.getFullName();
+ if (fullName == null || fullName.isEmpty()) {
+ LOG.warn("Invalid full name in entity change log: {}", fullName);
+ return null;
+ }
+ try {
+ return EntityChangeLogNameIdentifierCodec.decode(fullName);
+ } catch (IllegalArgumentException e) {
+ LOG.warn("Undecodable full name in entity change log: {}", fullName, e);
+ return null;
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java
new file mode 100644
index 0000000000..d457d67608
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java
@@ -0,0 +1,115 @@
+/*
+ * 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;
+
+import java.util.Arrays;
+import org.apache.gravitino.NameIdentifier;
+
+/** Losslessly encodes entity identifiers in the change log while retaining legacy readability. */
+public final class EntityChangeLogNameIdentifierCodec {
+
+ private static final String ENCODED_PREFIX = "gravitino:v1:";
+
+ private EntityChangeLogNameIdentifierCodec() {}
+
+ /**
+ * Encodes an identifier for the {@code entity_full_name} change-log column.
+ *
+ * <p>Identifiers without ambiguous dots retain their historical dot-joined representation, so
+ * older nodes can continue consuming ordinary names during a rolling upgrade. Identifiers whose
+ * segments contain dots use a length-prefixed representation.
+ *
+ * @param ident identifier to encode
+ * @return encoded identifier
+ */
+ public static String encode(NameIdentifier ident) {
+ String legacyValue = ident.toString();
+ String[] levels = levels(ident);
+ boolean requiresEncoding =
+ legacyValue.startsWith(ENCODED_PREFIX)
+ || Arrays.stream(levels).anyMatch(level -> level.indexOf('.') >= 0);
+ if (!requiresEncoding) {
+ return legacyValue;
+ }
+
+ StringBuilder encoded = new StringBuilder(ENCODED_PREFIX).append(levels.length).append(':');
+ for (String level : levels) {
+ encoded.append(level.length()).append(':').append(level);
+ }
+ return encoded.toString();
+ }
+
+ /**
+ * Decodes an identifier read from the {@code entity_full_name} change-log column.
+ *
+ * @param encoded encoded identifier
+ * @return decoded identifier
+ * @throws IllegalArgumentException if the encoded value is malformed
+ */
+ public static NameIdentifier decode(String encoded) {
+ if (encoded == null || encoded.isEmpty()) {
+ throw new IllegalArgumentException("Cannot decode a null or empty entity identifier");
+ }
+ if (!encoded.startsWith(ENCODED_PREFIX)) {
+ return NameIdentifier.parse(encoded);
+ }
+
+ int offset = ENCODED_PREFIX.length();
+ int separator = encoded.indexOf(':', offset);
+ int levelCount = parseLength(encoded, offset, separator);
+ if (levelCount <= 0) {
+ throw new IllegalArgumentException("Entity identifier must contain at least one level");
+ }
+
+ String[] levels = new String[levelCount];
+ offset = separator + 1;
+ for (int index = 0; index < levelCount; index++) {
+ separator = encoded.indexOf(':', offset);
+ int levelLength = parseLength(encoded, offset, separator);
+ offset = separator + 1;
+ if (levelLength <= 0 || levelLength > encoded.length() - offset) {
+ throw new IllegalArgumentException("Invalid entity identifier level length");
+ }
+ levels[index] = encoded.substring(offset, offset + levelLength);
+ offset += levelLength;
+ }
+ if (offset != encoded.length()) {
+ throw new IllegalArgumentException("Unexpected trailing data in entity identifier");
+ }
+ return NameIdentifier.of(levels);
+ }
+
+ private static String[] levels(NameIdentifier ident) {
+ String[] namespace = ident.namespace().levels();
+ String[] levels = Arrays.copyOf(namespace, namespace.length + 1);
+ levels[namespace.length] = ident.name();
+ return levels;
+ }
+
+ private static int parseLength(String encoded, int offset, int separator) {
+ if (separator <= offset) {
+ throw new IllegalArgumentException("Missing entity identifier length");
+ }
+ try {
+ return Integer.parseInt(encoded.substring(offset, separator));
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid entity identifier length", e);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index c87edc0c38..70a0cbdf8f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -47,6 +47,7 @@ import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.UnsupportedEntityTypeException;
import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.cache.BaseEntityCache;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -69,6 +70,8 @@ import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterFactory;
import org.apache.gravitino.storage.relational.database.H2Database;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.service.CatalogMetaService;
import org.apache.gravitino.storage.relational.service.FilesetMetaService;
import org.apache.gravitino.storage.relational.service.FunctionMetaService;
@@ -91,7 +94,9 @@ import org.apache.gravitino.storage.relational.service.TopicMetaService;
import org.apache.gravitino.storage.relational.service.UserMetaService;
import org.apache.gravitino.storage.relational.service.ViewMetaService;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.NameIdentifierUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -183,52 +188,27 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
@Override
public <E extends Entity & HasIdentifier> void insert(E e, boolean overwritten)
throws EntityAlreadyExistsException, IOException {
- if (e instanceof BaseMetalake) {
- MetalakeMetaService.getInstance().insertMetalake((BaseMetalake) e, overwritten);
- } else if (e instanceof CatalogEntity) {
- CatalogMetaService.getInstance().insertCatalog((CatalogEntity) e, overwritten);
- } else if (e instanceof SchemaEntity) {
- SchemaMetaService.getInstance().insertSchema((SchemaEntity) e, overwritten);
- } else if (e instanceof TableEntity) {
- TableMetaService.getInstance().insertTable((TableEntity) e, overwritten);
- } else if (e instanceof FilesetEntity) {
- FilesetMetaService.getInstance().insertFileset((FilesetEntity) e, overwritten);
- } else if (e instanceof TopicEntity) {
- TopicMetaService.getInstance().insertTopic((TopicEntity) e, overwritten);
- } else if (e instanceof UserEntity) {
- UserMetaService.getInstance().insertUser((UserEntity) e, overwritten);
- } else if (e instanceof RoleEntity) {
- RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);
- } else if (e instanceof GroupEntity) {
- GroupMetaService.getInstance().insertGroup((GroupEntity) e, overwritten);
- } else if (e instanceof TagEntity) {
- TagMetaService.getInstance().insertTag((TagEntity) e, overwritten);
- } else if (e instanceof ModelEntity) {
- ModelMetaService.getInstance().insertModel((ModelEntity) e, overwritten);
- } else if (e instanceof ModelVersionEntity) {
- if (overwritten) {
- LOG.warn(
- "'overwritten' is not supported for model version meta, ignoring this flag and "
- + "inserting the new model version.");
+ if (!overwritten || !BaseEntityCache.isCacheable(e.type())) {
+ insertEntity(e, overwritten);
+ return;
+ }
+
+ boolean transactionOwner = !SessionUtils.isInTransaction();
+ if (transactionOwner) {
+ SessionUtils.beginTransaction();
+ }
+ boolean committed = false;
+ try {
+ insertEntity(e, true);
+ insertEntityChange(e.nameIdentifier(), e.type(), OperateType.ALTER);
+ if (transactionOwner) {
+ SessionUtils.commitTransaction();
+ }
+ committed = true;
+ } finally {
+ if (transactionOwner && !committed) {
+ SessionUtils.rollbackTransaction();
}
- ModelVersionMetaService.getInstance().insertModelVersion((ModelVersionEntity) e);
- } else if (e instanceof FunctionEntity) {
- FunctionMetaService.getInstance().insertFunction((FunctionEntity) e, overwritten);
- } else if (e instanceof PolicyEntity) {
- PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
- } else if (e instanceof JobTemplateEntity) {
- JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);
- } else if (e instanceof JobEntity) {
- JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);
- } else if (e instanceof ViewEntity) {
- ViewMetaService.getInstance().insertView((ViewEntity) e, overwritten);
- } else if (e instanceof GenericEntity) {
- GenericEntity genericEntity = (GenericEntity) e;
- throw new UnsupportedEntityTypeException(
- "Unsupported entity type: %s for insert operation", genericEntity.type());
- } else {
- throw new UnsupportedEntityTypeException(
- "Unsupported entity type: %s for insert operation", e.getClass());
}
}
@@ -236,42 +216,27 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
public <E extends Entity & HasIdentifier> E update(
NameIdentifier ident, Entity.EntityType entityType, Function<E, E> updater)
throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
- switch (entityType) {
- case METALAKE:
- return (E) MetalakeMetaService.getInstance().updateMetalake(ident, updater);
- case CATALOG:
- return (E) CatalogMetaService.getInstance().updateCatalog(ident, updater);
- case SCHEMA:
- return (E) SchemaMetaService.getInstance().updateSchema(ident, updater);
- case TABLE:
- return (E) TableMetaService.getInstance().updateTable(ident, updater);
- case FILESET:
- return (E) FilesetMetaService.getInstance().updateFileset(ident, updater);
- case TOPIC:
- return (E) TopicMetaService.getInstance().updateTopic(ident, updater);
- case USER:
- return (E) UserMetaService.getInstance().updateUser(ident, updater);
- case GROUP:
- return (E) GroupMetaService.getInstance().updateGroup(ident, updater);
- case ROLE:
- return (E) RoleMetaService.getInstance().updateRole(ident, updater);
- case TAG:
- return (E) TagMetaService.getInstance().updateTag(ident, updater);
- case MODEL:
- return (E) ModelMetaService.getInstance().updateModel(ident, updater);
- case MODEL_VERSION:
- return (E) ModelVersionMetaService.getInstance().updateModelVersion(ident, updater);
- case FUNCTION:
- return (E) FunctionMetaService.getInstance().updateFunction(ident, updater);
- case POLICY:
- return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
- case JOB_TEMPLATE:
- return (E) JobTemplateMetaService.getInstance().updateJobTemplate(ident, updater);
- case VIEW:
- return (E) ViewMetaService.getInstance().updateView(ident, updater);
- default:
- throw new UnsupportedEntityTypeException(
- "Unsupported entity type: %s for update operation", entityType);
+ if (!BaseEntityCache.isCacheable(entityType)) {
+ return updateEntity(ident, entityType, updater);
+ }
+
+ boolean transactionOwner = !SessionUtils.isInTransaction();
+ if (transactionOwner) {
+ SessionUtils.beginTransaction();
+ }
+ boolean committed = false;
+ try {
+ E updatedEntity = updateEntity(ident, entityType, updater);
+ insertEntityChange(ident, entityType, OperateType.ALTER);
+ if (transactionOwner) {
+ SessionUtils.commitTransaction();
+ }
+ committed = true;
+ return updatedEntity;
+ } finally {
+ if (transactionOwner && !committed) {
+ SessionUtils.rollbackTransaction();
+ }
}
}
@@ -470,44 +435,29 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
@Override
public boolean delete(NameIdentifier ident, Entity.EntityType entityType, boolean cascade)
throws IOException {
- switch (entityType) {
- case METALAKE:
- return MetalakeMetaService.getInstance().deleteMetalake(ident, cascade);
- case CATALOG:
- return CatalogMetaService.getInstance().deleteCatalog(ident, cascade);
- case SCHEMA:
- return SchemaMetaService.getInstance().deleteSchema(ident, cascade);
- case TABLE:
- return TableMetaService.getInstance().deleteTable(ident);
- case FILESET:
- return FilesetMetaService.getInstance().deleteFileset(ident);
- case TOPIC:
- return TopicMetaService.getInstance().deleteTopic(ident);
- case USER:
- return UserMetaService.getInstance().deleteUser(ident);
- case GROUP:
- return GroupMetaService.getInstance().deleteGroup(ident);
- case ROLE:
- return RoleMetaService.getInstance().deleteRole(ident);
- case TAG:
- return TagMetaService.getInstance().deleteTag(ident);
- case MODEL:
- return ModelMetaService.getInstance().deleteModel(ident);
- case MODEL_VERSION:
- return ModelVersionMetaService.getInstance().deleteModelVersion(ident);
- case FUNCTION:
- return FunctionMetaService.getInstance().deleteFunction(ident);
- case POLICY:
- return PolicyMetaService.getInstance().deletePolicy(ident);
- case JOB_TEMPLATE:
- return JobTemplateMetaService.getInstance().deleteJobTemplate(ident);
- case JOB:
- return JobMetaService.getInstance().deleteJob(ident);
- case VIEW:
- return ViewMetaService.getInstance().deleteView(ident);
- default:
- throw new UnsupportedEntityTypeException(
- "Unsupported entity type: %s for delete operation", entityType);
+ if (!BaseEntityCache.isCacheable(entityType)) {
+ return deleteEntity(ident, entityType, cascade);
+ }
+
+ boolean transactionOwner = !SessionUtils.isInTransaction();
+ if (transactionOwner) {
+ SessionUtils.beginTransaction();
+ }
+ boolean committed = false;
+ try {
+ boolean deleted = deleteEntity(ident, entityType, cascade);
+ if (deleted) {
+ insertEntityChange(ident, entityType, OperateType.DROP);
+ }
+ if (transactionOwner) {
+ SessionUtils.commitTransaction();
+ }
+ committed = true;
+ return deleted;
+ } finally {
+ if (transactionOwner && !committed) {
+ SessionUtils.rollbackTransaction();
+ }
}
}
@@ -1007,6 +957,154 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
}
}
+ private <E extends Entity & HasIdentifier> void insertEntity(E e, boolean overwritten)
+ throws EntityAlreadyExistsException, IOException {
+ if (e instanceof BaseMetalake) {
+ MetalakeMetaService.getInstance().insertMetalake((BaseMetalake) e, overwritten);
+ } else if (e instanceof CatalogEntity) {
+ CatalogMetaService.getInstance().insertCatalog((CatalogEntity) e, overwritten);
+ } else if (e instanceof SchemaEntity) {
+ SchemaMetaService.getInstance().insertSchema((SchemaEntity) e, overwritten);
+ } else if (e instanceof TableEntity) {
+ TableMetaService.getInstance().insertTable((TableEntity) e, overwritten);
+ } else if (e instanceof FilesetEntity) {
+ FilesetMetaService.getInstance().insertFileset((FilesetEntity) e, overwritten);
+ } else if (e instanceof TopicEntity) {
+ TopicMetaService.getInstance().insertTopic((TopicEntity) e, overwritten);
+ } else if (e instanceof UserEntity) {
+ UserMetaService.getInstance().insertUser((UserEntity) e, overwritten);
+ } else if (e instanceof RoleEntity) {
+ RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);
+ } else if (e instanceof GroupEntity) {
+ GroupMetaService.getInstance().insertGroup((GroupEntity) e, overwritten);
+ } else if (e instanceof TagEntity) {
+ TagMetaService.getInstance().insertTag((TagEntity) e, overwritten);
+ } else if (e instanceof ModelEntity) {
+ ModelMetaService.getInstance().insertModel((ModelEntity) e, overwritten);
+ } else if (e instanceof ModelVersionEntity) {
+ if (overwritten) {
+ LOG.warn(
+ "'overwritten' is not supported for model version meta, ignoring this flag and "
+ + "inserting the new model version.");
+ }
+ ModelVersionMetaService.getInstance().insertModelVersion((ModelVersionEntity) e);
+ } else if (e instanceof FunctionEntity) {
+ FunctionMetaService.getInstance().insertFunction((FunctionEntity) e, overwritten);
+ } else if (e instanceof PolicyEntity) {
+ PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
+ } else if (e instanceof JobTemplateEntity) {
+ JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);
+ } else if (e instanceof JobEntity) {
+ JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);
+ } else if (e instanceof ViewEntity) {
+ ViewMetaService.getInstance().insertView((ViewEntity) e, overwritten);
+ } else if (e instanceof GenericEntity) {
+ GenericEntity genericEntity = (GenericEntity) e;
+ throw new UnsupportedEntityTypeException(
+ "Unsupported entity type: %s for insert operation", genericEntity.type());
+ } else {
+ throw new UnsupportedEntityTypeException(
+ "Unsupported entity type: %s for insert operation", e.getClass());
+ }
+ }
+
+ private <E extends Entity & HasIdentifier> E updateEntity(
+ NameIdentifier ident, Entity.EntityType entityType, Function<E, E> updater)
+ throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+ switch (entityType) {
+ case METALAKE:
+ return (E) MetalakeMetaService.getInstance().updateMetalake(ident, updater);
+ case CATALOG:
+ return (E) CatalogMetaService.getInstance().updateCatalog(ident, updater);
+ case SCHEMA:
+ return (E) SchemaMetaService.getInstance().updateSchema(ident, updater);
+ case TABLE:
+ return (E) TableMetaService.getInstance().updateTable(ident, updater);
+ case FILESET:
+ return (E) FilesetMetaService.getInstance().updateFileset(ident, updater);
+ case TOPIC:
+ return (E) TopicMetaService.getInstance().updateTopic(ident, updater);
+ case USER:
+ return (E) UserMetaService.getInstance().updateUser(ident, updater);
+ case GROUP:
+ return (E) GroupMetaService.getInstance().updateGroup(ident, updater);
+ case ROLE:
+ return (E) RoleMetaService.getInstance().updateRole(ident, updater);
+ case TAG:
+ return (E) TagMetaService.getInstance().updateTag(ident, updater);
+ case MODEL:
+ return (E) ModelMetaService.getInstance().updateModel(ident, updater);
+ case MODEL_VERSION:
+ return (E) ModelVersionMetaService.getInstance().updateModelVersion(ident, updater);
+ case FUNCTION:
+ return (E) FunctionMetaService.getInstance().updateFunction(ident, updater);
+ case POLICY:
+ return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
+ case JOB_TEMPLATE:
+ return (E) JobTemplateMetaService.getInstance().updateJobTemplate(ident, updater);
+ case VIEW:
+ return (E) ViewMetaService.getInstance().updateView(ident, updater);
+ default:
+ throw new UnsupportedEntityTypeException(
+ "Unsupported entity type: %s for update operation", entityType);
+ }
+ }
+
+ private boolean deleteEntity(NameIdentifier ident, Entity.EntityType entityType, boolean cascade)
+ throws IOException {
+ switch (entityType) {
+ case METALAKE:
+ return MetalakeMetaService.getInstance().deleteMetalake(ident, cascade);
+ case CATALOG:
+ return CatalogMetaService.getInstance().deleteCatalog(ident, cascade);
+ case SCHEMA:
+ return SchemaMetaService.getInstance().deleteSchema(ident, cascade);
+ case TABLE:
+ return TableMetaService.getInstance().deleteTable(ident);
+ case FILESET:
+ return FilesetMetaService.getInstance().deleteFileset(ident);
+ case TOPIC:
+ return TopicMetaService.getInstance().deleteTopic(ident);
+ case USER:
+ return UserMetaService.getInstance().deleteUser(ident);
+ case GROUP:
+ return GroupMetaService.getInstance().deleteGroup(ident);
+ case ROLE:
+ return RoleMetaService.getInstance().deleteRole(ident);
+ case TAG:
+ return TagMetaService.getInstance().deleteTag(ident);
+ case MODEL:
+ return ModelMetaService.getInstance().deleteModel(ident);
+ case MODEL_VERSION:
+ return ModelVersionMetaService.getInstance().deleteModelVersion(ident);
+ case FUNCTION:
+ return FunctionMetaService.getInstance().deleteFunction(ident);
+ case POLICY:
+ return PolicyMetaService.getInstance().deletePolicy(ident);
+ case JOB_TEMPLATE:
+ return JobTemplateMetaService.getInstance().deleteJobTemplate(ident);
+ case JOB:
+ return JobMetaService.getInstance().deleteJob(ident);
+ case VIEW:
+ return ViewMetaService.getInstance().deleteView(ident);
+ default:
+ throw new UnsupportedEntityTypeException(
+ "Unsupported entity type: %s for delete operation", entityType);
+ }
+ }
+
+ private static void insertEntityChange(
+ NameIdentifier ident, Entity.EntityType entityType, OperateType operateType) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ NameIdentifierUtil.getMetalake(ident),
+ entityType.name(),
+ EntityChangeLogNameIdentifierCodec.encode(ident),
+ operateType));
+ }
+
/** Start JDBC database if necessary. For example, start the H2 database if the backend is H2. */
private static JDBCDatabase startJDBCDatabaseIfNecessary(Config config) {
String jdbcUrl = config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
index 333e88b024..6700b83ec1 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
@@ -50,6 +50,7 @@ import org.apache.gravitino.SupportsIdOperations;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.cache.CacheFactory;
import org.apache.gravitino.cache.CachedEntityIdResolver;
+import org.apache.gravitino.cache.Coherence;
import org.apache.gravitino.cache.EntityCache;
import org.apache.gravitino.cache.EntityCacheKey;
import org.apache.gravitino.cache.NoOpsCache;
@@ -80,6 +81,10 @@ public class RelationalEntityStore
private EntityChangeLogCleaner entityChangeLogCleaner;
private EntityCache cache;
+ // Non-null only for a LOCAL_PER_NODE cache, which needs cross-node invalidation. SHARED and NONE
+ // caches have no per-node copy to invalidate, so no listener is registered.
+ @Nullable private EntityCacheChangeLogListener entityCacheChangeLogListener;
+
@VisibleForTesting
public EntityCache getCache() {
return cache;
@@ -115,10 +120,29 @@ public class RelationalEntityStore
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_RETENTION_SECS)),
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)),
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)));
+
+ registerCacheChangeLogListener();
+
this.entityChangeLogPoller.start();
this.entityChangeLogCleaner.start();
}
+ /**
+ * The coherence gate: a {@link Coherence#LOCAL_PER_NODE} cache keeps its own copy per node, so
+ * changes made on other nodes must be replayed here through the change log. {@link
+ * Coherence#SHARED} and {@link Coherence#NONE} caches have nothing per-node to invalidate, so no
+ * listener is registered.
+ */
+ @VisibleForTesting
+ void registerCacheChangeLogListener() {
+ if (cache.coherence() != Coherence.LOCAL_PER_NODE) {
+ return;
+ }
+
+ this.entityCacheChangeLogListener = new EntityCacheChangeLogListener(cache);
+ this.entityChangeLogPoller.registerListener(entityCacheChangeLogListener);
+ }
+
private RelationalBackend createRelationalEntityBackend(Config config) {
String backendName = config.get(ENTITY_RELATIONAL_STORE);
String className =
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
index a85e1b85ba..9f63b9189f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
@@ -39,7 +39,6 @@ import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.helper.CatalogIds;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -58,7 +57,6 @@ import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.po.CatalogPO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -222,10 +220,6 @@ public class CatalogMetaService {
newEntity.id(),
oldCatalogEntity.id());
- String metalakeName = identifier.namespace().level(0);
- String oldFullName =
- NameIdentifierUtil.ofCatalog(metalakeName, oldCatalogEntity.name()).toString();
-
AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -237,19 +231,7 @@ public class CatalogMetaService {
mapper.updateCatalogMeta(
POConverters.updateCatalogPOWithVersion(
oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
- oldCatalogPO))),
- () -> {
- if (updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.CATALOG.name(),
- oldFullName,
- OperateType.ALTER));
- }
- });
+ oldCatalogPO))));
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.CATALOG, newEntity.nameIdentifier().toString());
@@ -271,7 +253,6 @@ public class CatalogMetaService {
String catalogName = identifier.name();
long catalogId = EntityIdService.getEntityId(identifier, Entity.EntityType.CATALOG);
- String metalakeName = identifier.namespace().level(0);
if (cascade) {
SessionUtils.doMultipleWithCommit(
@@ -344,20 +325,8 @@ public class CatalogMetaService {
mapper -> mapper.softDeleteStatisticsByCatalogId(catalogId)),
() ->
SessionUtils.doWithoutCommit(
- ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasByCatalogId(catalogId)),
- // Only one CATALOG DROP record is written here; the cache layer performs prefix
- // eviction on '<metalake>.<catalog>.*', covering all descendants automatically.
- // Writing per-child DROP rows would multiply changelog volume without benefit.
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.CATALOG.name(),
- NameIdentifierUtil.ofCatalog(metalakeName, catalogName).toString(),
- OperateType.DROP));
- });
+ ViewMetaMapper.class,
+ mapper -> mapper.softDeleteViewMetasByCatalogId(catalogId)));
} else {
List<SchemaEntity> schemaEntities =
SchemaMetaService.getInstance()
@@ -399,17 +368,7 @@ public class CatalogMetaService {
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- catalogId, MetadataObject.Type.CATALOG.name())),
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.CATALOG.name(),
- NameIdentifierUtil.ofCatalog(metalakeName, catalogName).toString(),
- OperateType.DROP));
- });
+ catalogId, MetadataObject.Type.CATALOG.name())));
}
return true;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
index 9c1f677b4b..4dbcadbe38 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
@@ -37,7 +37,6 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.metrics.Monitored;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
@@ -47,7 +46,6 @@ import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.FilesetMaxVersionPO;
import org.apache.gravitino.storage.relational.po.FilesetPO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -210,14 +208,6 @@ public class FilesetMetaService {
newEntity.id(),
oldFilesetEntity.id());
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- String oldFullName =
- NameIdentifierUtil.ofFileset(metalakeName, catalogName, schemaName, oldFilesetEntity.name())
- .toString();
- boolean isRenamed = !Objects.equals(oldFilesetEntity.name(), newEntity.name());
-
Integer updateResult;
try {
boolean checkNeedUpdateVersion =
@@ -245,18 +235,6 @@ public class FilesetMetaService {
if (metaUpdateCountRef[0] == 0) {
throw new RuntimeException("Failed to update the entity: " + identifier);
}
- },
- () -> {
- if (isRenamed && metaUpdateCountRef[0] > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.FILESET.name(),
- oldFullName,
- OperateType.ALTER));
- }
});
updateResult = 1;
} catch (RuntimeException re) {
@@ -277,19 +255,7 @@ public class FilesetMetaService {
metaUpdateCountRef[0] =
SessionUtils.getWithoutCommit(
FilesetMetaMapper.class,
- mapper -> mapper.updateFilesetMeta(newFilesetPO, oldFilesetPO)),
- () -> {
- if (isRenamed && metaUpdateCountRef[0] > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.FILESET.name(),
- oldFullName,
- OperateType.ALTER));
- }
- });
+ mapper -> mapper.updateFilesetMeta(newFilesetPO, oldFilesetPO)));
updateResult = metaUpdateCountRef[0];
}
} catch (RuntimeException re) {
@@ -312,13 +278,6 @@ public class FilesetMetaService {
FilesetPO filesetPO = getFilesetPOByIdentifier(identifier);
Long filesetId = filesetPO.getFilesetId();
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- String filesetFullName =
- NameIdentifierUtil.ofFileset(metalakeName, catalogName, schemaName, identifier.name())
- .toString();
-
// We should delete meta and version info
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
@@ -356,18 +315,6 @@ public class FilesetMetaService {
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
filesetId, MetadataObject.Type.FILESET.name()));
}
- },
- () -> {
- if (deleteResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.FILESET.name(),
- filesetFullName,
- OperateType.DROP));
- }
});
return deleteResult.get() > 0;
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.java
index 607dab00c1..ba810a6130 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
@@ -37,7 +37,6 @@ import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -66,7 +65,6 @@ import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;
import org.apache.gravitino.storage.relational.mapper.UserRoleRelMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.po.MetalakePO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -177,9 +175,6 @@ public class MetalakeMetaService {
MetalakePO newMetalakePO =
POConverters.updateMetalakePOWithVersion(oldMetalakePO, newMetalakeEntity);
- String oldFullName = oldMetalakeEntity.name();
- boolean isRenamed = !Objects.equals(oldMetalakeEntity.name(), newMetalakeEntity.name());
-
AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -187,19 +182,7 @@ public class MetalakeMetaService {
updateResult.set(
SessionUtils.getWithoutCommit(
MetalakeMetaMapper.class,
- mapper -> mapper.updateMetalakeMeta(newMetalakePO, oldMetalakePO))),
- () -> {
- if (isRenamed && updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- oldMetalakeEntity.name(),
- Entity.EntityType.METALAKE.name(),
- oldFullName,
- OperateType.ALTER));
- }
- });
+ mapper -> mapper.updateMetalakeMeta(newMetalakePO, oldMetalakePO))));
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.METALAKE, newMetalakeEntity.nameIdentifier().toString());
@@ -333,17 +316,7 @@ public class MetalakeMetaService {
() ->
SessionUtils.doWithoutCommit(
ViewMetaMapper.class,
- mapper -> mapper.softDeleteViewMetasByMetalakeId(metalakeId)),
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- ident.name(),
- Entity.EntityType.METALAKE.name(),
- ident.name(),
- OperateType.DROP));
- });
+ mapper -> mapper.softDeleteViewMetasByMetalakeId(metalakeId)));
} else {
List<CatalogEntity> catalogEntities =
CatalogMetaService.getInstance()
@@ -404,17 +377,7 @@ public class MetalakeMetaService {
() ->
SessionUtils.doWithoutCommit(
JobMetaMapper.class,
- mapper -> mapper.softDeleteJobMetasByMetalakeId(metalakeId)),
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- ident.name(),
- Entity.EntityType.METALAKE.name(),
- ident.name(),
- OperateType.DROP));
- });
+ mapper -> mapper.softDeleteJobMetasByMetalakeId(metalakeId)));
}
}
return true;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
index d492371024..838a17fdef 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
@@ -39,6 +39,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
@@ -129,7 +130,8 @@ public class ModelMetaService {
String catalogName = ident.namespace().level(1);
String schemaName = ident.namespace().level(2);
String modelFullName =
- NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, ident.name()).toString();
+ EntityChangeLogNameIdentifierCodec.encode(
+ NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, ident.name()));
AtomicInteger modelDeletedCount = new AtomicInteger();
SessionUtils.doMultipleWithCommit(
@@ -373,8 +375,9 @@ public class ModelMetaService {
String catalogName = identifier.namespace().level(1);
String schemaName = identifier.namespace().level(2);
String oldFullName =
- NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, oldModelEntity.name())
- .toString();
+ EntityChangeLogNameIdentifierCodec.encode(
+ NameIdentifierUtil.ofModel(
+ metalakeName, catalogName, schemaName, oldModelEntity.name()));
boolean isRenamed = !Objects.equals(oldModelEntity.name(), newEntity.name());
AtomicInteger updateResult = new AtomicInteger(0);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
index 39d820b42d..898687f80f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
@@ -49,7 +49,6 @@ import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.relational.helper.SchemaIds;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -68,7 +67,6 @@ import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.po.SchemaPO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -221,12 +219,6 @@ public class SchemaMetaService {
newEntity.id(),
oldSchemaEntity.id());
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String oldFullName =
- NameIdentifierUtil.ofSchema(metalakeName, catalogName, oldSchemaEntity.name()).toString();
- boolean isRenamed = !Objects.equals(oldSchemaEntity.name(), newEntity.name());
-
AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -238,19 +230,7 @@ public class SchemaMetaService {
ops.updatePO(
mapper,
POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
- oldSchemaPO))),
- () -> {
- if (isRenamed && updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.SCHEMA.name(),
- oldFullName,
- OperateType.ALTER));
- }
- });
+ oldSchemaPO))));
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.SCHEMA, newEntity.nameIdentifier().toString());
@@ -273,10 +253,6 @@ public class SchemaMetaService {
String schemaName = identifier.name();
SchemaPO schemaPO = getSchemaPOByIdentifier(identifier);
Long schemaId = schemaPO.getSchemaId();
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaFullName =
- NameIdentifierUtil.ofSchema(metalakeName, catalogName, schemaName).toString();
if (cascade) {
// For HierarchicalSchema, deleting `A:B` must also cascade into all descendant schemas
@@ -353,17 +329,8 @@ public class SchemaMetaService {
mapper -> mapper.softDeleteStatisticsBySchemaIds(schemaIds)),
() ->
SessionUtils.doWithoutCommit(
- ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasBySchemaIds(schemaIds)),
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.SCHEMA.name(),
- schemaFullName,
- OperateType.DROP));
- });
+ ViewMetaMapper.class,
+ mapper -> mapper.softDeleteViewMetasBySchemaIds(schemaIds)));
} else {
List<TableEntity> tableEntities =
TableMetaService.getInstance()
@@ -444,17 +411,7 @@ public class SchemaMetaService {
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- schemaId, MetadataObject.Type.SCHEMA.name())),
- () -> {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.SCHEMA.name(),
- schemaFullName,
- OperateType.DROP));
- });
+ schemaId, MetadataObject.Type.SCHEMA.name())));
}
return true;
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
index 17ee0d5c3b..15a61bdd9f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
@@ -37,7 +37,6 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.metrics.Monitored;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
@@ -47,7 +46,6 @@ import org.apache.gravitino.storage.relational.mapper.TableVersionMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.ColumnPO;
import org.apache.gravitino.storage.relational.po.TablePO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -193,15 +191,6 @@ public class TableMetaService {
TablePO newTablePO =
POConverters.updateTablePOWithVersionAndSchemaId(oldTablePO, newTableEntity, newSchemaId);
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- String oldFullName =
- NameIdentifierUtil.ofTable(metalakeName, catalogName, schemaName, oldTableEntity.name())
- .toString();
- boolean isFullNameChanged =
- isSchemaChanged || !Objects.equals(oldTableEntity.name(), newTableEntity.name());
-
final AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -223,18 +212,6 @@ public class TableMetaService {
TableColumnMetaService.getInstance()
.updateColumnPOsFromTableDiff(oldTableEntity, newTableEntity, newTablePO);
}
- },
- () -> {
- if (isFullNameChanged && updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.TABLE.name(),
- oldFullName,
- OperateType.ALTER));
- }
});
} catch (RuntimeException re) {
@@ -254,13 +231,6 @@ public class TableMetaService {
public boolean deleteTable(NameIdentifier identifier) {
TablePO tablePO = getTablePOByIdentifier(identifier);
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- String tableFullName =
- NameIdentifierUtil.ofTable(metalakeName, catalogName, schemaName, identifier.name())
- .toString();
-
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
@@ -302,18 +272,6 @@ public class TableMetaService {
mapper.softDeleteTableVersionByTableIdAndVersion(
tablePO.getTableId(), tablePO.getCurrentVersion()));
}
- },
- () -> {
- if (deleteResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.TABLE.name(),
- tableFullName,
- OperateType.DROP));
- }
});
return deleteResult.get() > 0;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
index 85bc2dbbe0..d5618842d0 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
@@ -37,7 +37,6 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.metrics.Monitored;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
@@ -45,7 +44,6 @@ import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.po.TopicPO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -113,14 +111,6 @@ public class TopicMetaService {
newEntity.id(),
oldTopicEntity.id());
- String metalakeName = ident.namespace().level(0);
- String catalogName = ident.namespace().level(1);
- String schemaName = ident.namespace().level(2);
- String oldFullName =
- NameIdentifierUtil.ofTopic(metalakeName, catalogName, schemaName, oldTopicEntity.name())
- .toString();
- boolean isRenamed = !Objects.equals(oldTopicEntity.name(), newEntity.name());
-
AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -131,19 +121,7 @@ public class TopicMetaService {
mapper ->
mapper.updateTopicMeta(
POConverters.updateTopicPOWithVersion(oldTopicPO, newEntity),
- oldTopicPO))),
- () -> {
- if (isRenamed && updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.TOPIC.name(),
- oldFullName,
- OperateType.ALTER));
- }
- });
+ oldTopicPO))));
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.TOPIC, newEntity.nameIdentifier().toString());
@@ -293,13 +271,6 @@ public class TopicMetaService {
TopicPO topicPO = getTopicPOByIdentifier(identifier);
Long topicId = topicPO.getTopicId();
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- String topicFullName =
- NameIdentifierUtil.ofTopic(metalakeName, catalogName, schemaName, identifier.name())
- .toString();
-
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
@@ -333,18 +304,6 @@ public class TopicMetaService {
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
topicId, MetadataObject.Type.TOPIC.name()));
}
- },
- () -> {
- if (deleteResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.TOPIC.name(),
- topicFullName,
- OperateType.DROP));
- }
});
return deleteResult.get() > 0;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
index a305e05645..d676b6bf08 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
@@ -38,14 +38,12 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.metrics.Monitored;
-import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;
import org.apache.gravitino.storage.relational.po.ViewPO;
-import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -145,14 +143,6 @@ public class ViewMetaService {
AtomicInteger updateResult = new AtomicInteger(0);
try {
ViewPO newViewPO = updateViewPO(oldViewPO, newEntity);
- String metalakeName = ident.namespace().level(0);
- String catalogName = ident.namespace().level(1);
- String schemaName = ident.namespace().level(2);
- String oldFullName =
- NameIdentifierUtil.ofView(metalakeName, catalogName, schemaName, oldViewPO.getViewName())
- .toString();
- boolean isRenamed = !Objects.equals(oldViewPO.getViewName(), newViewPO.getViewName());
-
SessionUtils.doMultipleWithCommit(
() ->
SessionUtils.doWithoutCommit(
@@ -165,18 +155,6 @@ public class ViewMetaService {
if (updateResult.get() == 0) {
throw new RuntimeException("Failed to update the entity: " + ident);
}
- },
- () -> {
- if (isRenamed && updateResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.VIEW.name(),
- oldFullName,
- OperateType.ALTER));
- }
});
return newEntity;
} catch (RuntimeException re) {
@@ -194,13 +172,7 @@ public class ViewMetaService {
baseMetricName = "deleteViewByIdentifier")
public boolean deleteView(NameIdentifier ident) {
ViewPO viewPO = getViewPOByIdentifier(ident);
- String metalakeName = ident.namespace().level(0);
- String catalogName = ident.namespace().level(1);
- String schemaName = ident.namespace().level(2);
- String viewFullName =
- NameIdentifierUtil.ofView(metalakeName, catalogName, schemaName, viewPO.getViewName())
- .toString();
- return deleteView(viewPO.getViewId(), metalakeName, viewFullName);
+ return deleteView(viewPO.getViewId());
}
@Monitored(
@@ -224,7 +196,7 @@ public class ViewMetaService {
return ops;
}
- private boolean deleteView(Long viewId, String metalakeName, String viewFullName) {
+ private boolean deleteView(Long viewId) {
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
@@ -252,18 +224,6 @@ public class ViewMetaService {
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
viewId, MetadataObject.Type.VIEW.name()));
}
- },
- () -> {
- if (deleteResult.get() > 0) {
- SessionUtils.doWithoutCommit(
- EntityChangeLogMapper.class,
- mapper ->
- mapper.insertEntityChange(
- metalakeName,
- Entity.EntityType.VIEW.name(),
- viewFullName,
- OperateType.DROP));
- }
});
return deleteResult.get() > 0;
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessions.java b/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessions.java
index 03d6608a65..48a10324b5 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessions.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessions.java
@@ -103,6 +103,15 @@ public final class SqlSessions {
return getSqlSession().getMapper(className);
}
+ /**
+ * Returns whether the current thread already owns an open SQL session.
+ *
+ * @return {@code true} when an SQL session is active on the current thread
+ */
+ public static boolean hasActiveSession() {
+ return sessions.get() != null;
+ }
+
private static void handleSessionClose(boolean commit, boolean rollback) {
SqlSession sqlSession = sessions.get();
if (sqlSession == null) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java
index 8a36bc1add..54539355bb 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java
@@ -111,6 +111,15 @@ public class SessionUtils {
SqlSessions.getSqlSession();
}
+ /**
+ * Returns whether the current thread is already participating in a transaction.
+ *
+ * @return {@code true} when the current thread has an active transaction
+ */
+ public static boolean isInTransaction() {
+ return SqlSessions.hasActiveSession();
+ }
+
public static void commitTransaction() {
SqlSessions.commitAndCloseSqlSession();
}
diff --git a/core/src/test/java/org/apache/gravitino/cache/TestBaseEntityCache.java b/core/src/test/java/org/apache/gravitino/cache/TestBaseEntityCache.java
index 89da218569..e2e04deaf9 100644
--- a/core/src/test/java/org/apache/gravitino/cache/TestBaseEntityCache.java
+++ b/core/src/test/java/org/apache/gravitino/cache/TestBaseEntityCache.java
@@ -47,19 +47,12 @@ public class TestBaseEntityCache {
Entity.EntityType.CATALOG,
Entity.EntityType.SCHEMA,
Entity.EntityType.TABLE,
+ Entity.EntityType.TOPIC,
Entity.EntityType.VIEW,
- Entity.EntityType.COLUMN,
Entity.EntityType.FILESET,
- Entity.EntityType.TOPIC,
Entity.EntityType.TAG,
- Entity.EntityType.MODEL,
- Entity.EntityType.MODEL_VERSION,
Entity.EntityType.POLICY,
- Entity.EntityType.TABLE_STATISTIC,
- Entity.EntityType.JOB_TEMPLATE,
- Entity.EntityType.JOB,
- Entity.EntityType.AUDIT,
- Entity.EntityType.FUNCTION);
+ Entity.EntityType.JOB);
private RecordingCache cache;
diff --git a/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java b/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java
index d30228e5d9..ce277811ca 100644
--- a/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java
+++ b/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java
@@ -34,6 +34,7 @@ import org.apache.gravitino.meta.ModelVersionEntity;
import org.apache.gravitino.meta.RoleEntity;
import org.apache.gravitino.meta.SchemaEntity;
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.utils.HierarchicalSchemaUtil;
@@ -143,11 +144,8 @@ public class TestCaffeineEntityCacheInvalidation {
}
@Test
- void testPutModelVersionInvalidatesModel() {
+ void testModelAndModelVersionAreNotCached() {
ModelEntity model = TestUtil.getTestModelEntity(1L, "model1", Namespace.of("m1", "c1", "s1"));
- cache.put(model);
- Assertions.assertTrue(cache.contains(model.nameIdentifier(), Entity.EntityType.MODEL));
-
ModelVersionEntity version =
TestUtil.getTestModelVersionEntity(
model.nameIdentifier(),
@@ -156,11 +154,27 @@ public class TestCaffeineEntityCacheInvalidation {
ImmutableMap.of(),
"cmt",
ImmutableList.of());
+
+ cache.put(model);
cache.put(version);
+ // Model and model version carry a load-bearing pointer (a version URI, the latest version), so
+ // they are not cached; reads go straight to the store.
+ Assertions.assertEquals(0, cache.size());
Assertions.assertFalse(cache.contains(model.nameIdentifier(), Entity.EntityType.MODEL));
}
+ @Test
+ void testTagIsCached() {
+ TagEntity tag = TestUtil.getTestTagEntity();
+
+ cache.put(tag);
+
+ Assertions.assertTrue(cache.contains(tag.nameIdentifier(), Entity.EntityType.TAG));
+ Assertions.assertEquals(
+ tag, cache.getIfPresent(tag.nameIdentifier(), Entity.EntityType.TAG).orElse(null));
+ }
+
@Test
void testGetIfPresentReturnsCachedEntity() {
CatalogEntity catalog =
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
index 410dcd5829..4ec22ccd58 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
@@ -28,6 +28,7 @@ import com.github.benmanes.caffeine.cache.Cache;
import java.util.List;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.junit.jupiter.api.Assertions;
@@ -86,6 +87,20 @@ public class TestCatalogChangeLogListener {
verify(catalogCache, never()).invalidate(any());
}
+ @Test
+ @SuppressWarnings("unchecked")
+ void testInvalidatesCatalogWithDotsInsideNameLevels() {
+ CatalogManager catalogManager = mock(CatalogManager.class);
+ Cache<NameIdentifier, CatalogWrapper> catalogCache = mock(Cache.class);
+ NameIdentifier ident = NameIdentifier.of("meta.lake", "cat.alog");
+ when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
+
+ CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
+ listener.onEntityChange(List.of(change(1L, EntityChangeLogNameIdentifierCodec.encode(ident))));
+
+ verify(catalogCache).invalidate(ident);
+ }
+
private static EntityChangeRecord change(long id, String fullName) {
return new EntityChangeRecord(id, "metalake", "CATALOG", fullName, OperateType.ALTER, 0L);
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageChangeLog.java b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageChangeLog.java
new file mode 100644
index 0000000000..f21f49d9b7
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageChangeLog.java
@@ -0,0 +1,229 @@
+/*
+ * 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;
+
+import java.time.Instant;
+import java.util.List;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.EntityStoreFactory;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mockito;
+
+/** Tests entity change logs through the relational {@link EntityStore}. */
+@Tag("gravitino-docker-test")
+public class TestEntityStorageChangeLog extends AbstractEntityStorageTest {
+ private static final String METALAKE_NAME = "metalake_for_entity_store_change_log_test";
+ private static final String CATALOG_NAME = "catalog_for_entity_store_change_log_test";
+ private static final String SCHEMA_NAME = "schema_for_entity_store_change_log_test";
+
+ @ParameterizedTest
+ @MethodSource("storageProvider")
+ void testMutationChangeLogLifecycle(String type, boolean enableCache) throws Exception {
+ Config config = Mockito.mock(Config.class);
+ init(type, config);
+ Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(enableCache);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+ BaseMetalake metalake =
+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, auditInfo);
+ CatalogEntity catalog =
+ createCatalog(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofCatalog(METALAKE_NAME),
+ CATALOG_NAME,
+ auditInfo);
+ SchemaEntity schema =
+ createSchemaEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofSchema(METALAKE_NAME, CATALOG_NAME),
+ SCHEMA_NAME,
+ auditInfo);
+ TableEntity table =
+ createTableEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofTable(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "table",
+ auditInfo);
+
+ long maxIdBeforeCreate = maxEntityChangeId();
+ store.put(metalake, false);
+ store.put(catalog, false);
+ store.put(schema, false);
+ store.put(table, false);
+ Assertions.assertEquals(maxIdBeforeCreate, maxEntityChangeId());
+
+ CatalogEntity updatedCatalog =
+ CatalogEntity.builder()
+ .withId(catalog.id())
+ .withNamespace(catalog.namespace())
+ .withName(catalog.name())
+ .withType(catalog.getType())
+ .withProvider(catalog.getProvider())
+ .withComment("updated comment")
+ .withProperties(catalog.getProperties())
+ .withAuditInfo(auditInfo)
+ .build();
+ long maxIdBeforeAlter = maxEntityChangeId();
+ store.update(
+ catalog.nameIdentifier(),
+ CatalogEntity.class,
+ Entity.EntityType.CATALOG,
+ entity -> updatedCatalog);
+ assertEntityChange(
+ maxIdBeforeAlter,
+ Entity.EntityType.CATALOG,
+ NameIdentifierUtil.ofCatalog(METALAKE_NAME, CATALOG_NAME).toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforeOverwrite = maxEntityChangeId();
+ store.put(table, true);
+ assertEntityChange(
+ maxIdBeforeOverwrite,
+ Entity.EntityType.TABLE,
+ NameIdentifierUtil.ofTable(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, table.name())
+ .toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforeTableDrop = maxEntityChangeId();
+ Assertions.assertTrue(store.delete(table.nameIdentifier(), Entity.EntityType.TABLE, false));
+ assertEntityChange(
+ maxIdBeforeTableDrop,
+ Entity.EntityType.TABLE,
+ table.nameIdentifier().toString(),
+ OperateType.DROP);
+
+ SchemaEntity renamedSchema =
+ createSchemaEntity(schema.id(), schema.namespace(), SCHEMA_NAME + "_renamed", auditInfo);
+ long maxIdBeforeRename = maxEntityChangeId();
+ store.update(
+ schema.nameIdentifier(),
+ SchemaEntity.class,
+ Entity.EntityType.SCHEMA,
+ entity -> renamedSchema);
+ assertEntityChange(
+ maxIdBeforeRename,
+ Entity.EntityType.SCHEMA,
+ schema.nameIdentifier().toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforeSchemaDrop = maxEntityChangeId();
+ Assertions.assertTrue(
+ store.delete(renamedSchema.nameIdentifier(), Entity.EntityType.SCHEMA, false));
+ assertEntityChange(
+ maxIdBeforeSchemaDrop,
+ Entity.EntityType.SCHEMA,
+ renamedSchema.nameIdentifier().toString(),
+ OperateType.DROP);
+ destroy(type);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("storageProvider")
+ void testCascadeDropWritesOnlyRootChangeLog(String type, boolean enableCache) throws Exception {
+ Config config = Mockito.mock(Config.class);
+ init(type, config);
+ Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(enableCache);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+ BaseMetalake metalake =
+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, auditInfo);
+ CatalogEntity catalog =
+ createCatalog(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofCatalog(METALAKE_NAME),
+ CATALOG_NAME,
+ auditInfo);
+ SchemaEntity schema =
+ createSchemaEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofSchema(METALAKE_NAME, CATALOG_NAME),
+ SCHEMA_NAME,
+ auditInfo);
+ TableEntity table =
+ createTableEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofTable(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "table",
+ auditInfo);
+
+ store.put(metalake, false);
+ store.put(catalog, false);
+ store.put(schema, false);
+ store.put(table, false);
+
+ long maxIdBeforeDrop = maxEntityChangeId();
+ Assertions.assertTrue(store.delete(schema.nameIdentifier(), Entity.EntityType.SCHEMA, true));
+ assertEntityChange(
+ maxIdBeforeDrop,
+ Entity.EntityType.SCHEMA,
+ schema.nameIdentifier().toString(),
+ OperateType.DROP);
+ Assertions.assertFalse(store.exists(table.nameIdentifier(), Entity.EntityType.TABLE));
+ destroy(type);
+ }
+ }
+
+ private static long maxEntityChangeId() {
+ return SessionUtils.doWithCommitAndFetchResult(
+ EntityChangeLogMapper.class, EntityChangeLogMapper::selectMaxChangeId);
+ }
+
+ private static List<EntityChangeRecord> listEntityChanges(long lastConsumedId) {
+ return SessionUtils.doWithCommitAndFetchResult(
+ EntityChangeLogMapper.class, mapper -> mapper.selectEntityChanges(lastConsumedId, 100));
+ }
+
+ private static void assertEntityChange(
+ long lastConsumedId, Entity.EntityType entityType, String fullName, OperateType operateType) {
+ List<EntityChangeRecord> entityChanges = listEntityChanges(lastConsumedId);
+ Assertions.assertEquals(1, entityChanges.size());
+ EntityChangeRecord entityChange = entityChanges.get(0);
+ Assertions.assertEquals(METALAKE_NAME, entityChange.getMetalakeName());
+ Assertions.assertEquals(entityType.name(), entityChange.getEntityType());
+ Assertions.assertEquals(fullName, entityChange.getFullName());
+ Assertions.assertEquals(operateType, entityChange.getOperateType());
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheChangeLogListener.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheChangeLogListener.java
new file mode 100644
index 0000000000..7e8a4e07e5
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheChangeLogListener.java
@@ -0,0 +1,231 @@
+/*
+ * 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;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.util.List;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.cache.CaffeineEntityCache;
+import org.apache.gravitino.cache.Coherence;
+import org.apache.gravitino.cache.EntityCache;
+import org.apache.gravitino.cache.NoOpsCache;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.utils.TestUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests {@link EntityCacheChangeLogListener}: parsing, dispatch, hierarchical cascade. */
+public class TestEntityCacheChangeLogListener {
+
+ private static EntityChangeRecord record(
+ EntityType type, String fullName, OperateType operateType) {
+ return new EntityChangeRecord(
+ 1L, "metalake", type == null ? null : type.name(), fullName, operateType, 0L);
+ }
+
+ @Test
+ void testDropInvalidatesExactlyTheChangedKey() {
+ CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {});
+ CatalogEntity catalog =
+ TestUtil.getTestCatalogEntity(1L, "catalog1", Namespace.of("metalake"), "hive", "cmt");
+ SchemaEntity schema =
+ TestUtil.getTestSchemaEntity(2L, "schema1", Namespace.of("metalake", "catalog1"), "cmt");
+ cache.put(catalog);
+ cache.put(schema);
+
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+ listener.onEntityChange(
+ List.of(record(EntityType.SCHEMA, schema.nameIdentifier().toString(), OperateType.DROP)));
+
+ Assertions.assertFalse(cache.contains(schema.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertTrue(cache.contains(catalog.nameIdentifier(), EntityType.CATALOG));
+ }
+
+ @Test
+ void testContainerDropCascadesToChildrenButKeepsSiblings() {
+ CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {});
+ CatalogEntity catalog =
+ TestUtil.getTestCatalogEntity(1L, "catalog1", Namespace.of("metalake"), "hive", "cmt");
+ SchemaEntity schema1 =
+ TestUtil.getTestSchemaEntity(2L, "schema1", Namespace.of("metalake", "catalog1"), "cmt");
+ TableEntity table1 =
+ TestUtil.getTestTableEntity(3L, "table1", Namespace.of("metalake", "catalog1", "schema1"));
+ SchemaEntity schema2 =
+ TestUtil.getTestSchemaEntity(4L, "schema2", Namespace.of("metalake", "catalog1"), "cmt");
+ cache.put(catalog);
+ cache.put(schema1);
+ cache.put(table1);
+ cache.put(schema2);
+ Assertions.assertEquals(4, cache.size());
+
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+ listener.onEntityChange(
+ List.of(record(EntityType.SCHEMA, schema1.nameIdentifier().toString(), OperateType.DROP)));
+
+ // schema1 and its child table1 are dropped through the forward prefix scan ...
+ Assertions.assertFalse(cache.contains(schema1.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertFalse(cache.contains(table1.nameIdentifier(), EntityType.TABLE));
+ // ... while the sibling schema2 and the parent catalog stay cached.
+ Assertions.assertTrue(cache.contains(schema2.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertTrue(cache.contains(catalog.nameIdentifier(), EntityType.CATALOG));
+ }
+
+ @Test
+ void testAlterInvalidatesTagKey() {
+ CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {});
+ TagEntity tag = TestUtil.getTestTagEntity(1L, "tag1", Namespace.of("m1"), "comment");
+ cache.put(tag);
+
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+ listener.onEntityChange(
+ List.of(record(EntityType.TAG, tag.nameIdentifier().toString(), OperateType.ALTER)));
+
+ Assertions.assertFalse(cache.contains(tag.nameIdentifier(), EntityType.TAG));
+ }
+
+ @Test
+ void testInvalidatesIdentifierWithDotsInsideLevels() {
+ EntityCache cache = mock(EntityCache.class);
+ NameIdentifier ident = NameIdentifier.of("meta.lake", "cat.alog", "sche.ma", "tab.le");
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+
+ listener.onEntityChange(
+ List.of(
+ record(
+ EntityType.TABLE,
+ EntityChangeLogNameIdentifierCodec.encode(ident),
+ OperateType.ALTER)));
+
+ verify(cache).invalidate(ident, EntityType.TABLE);
+ }
+
+ @Test
+ void testReplaysEveryCacheableTypeAsInvalidate() {
+ EntityCache cache = mock(EntityCache.class);
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+
+ listener.onEntityChange(
+ List.of(
+ record(EntityType.CATALOG, "m1.cat1", OperateType.ALTER),
+ record(EntityType.SCHEMA, "m1.cat1.sch1", OperateType.DROP),
+ record(EntityType.TABLE, "m1.cat1.sch1.tbl1", OperateType.DROP),
+ record(EntityType.TAG, "m1.system.tag.tag1", OperateType.ALTER),
+ record(EntityType.POLICY, "m1.system.policy.p1", OperateType.DROP),
+ record(EntityType.JOB, "m1.system.job.job-1", OperateType.ALTER)));
+
+ verify(cache).invalidate(NameIdentifier.of("m1", "cat1"), EntityType.CATALOG);
+ verify(cache).invalidate(NameIdentifier.of("m1", "cat1", "sch1"), EntityType.SCHEMA);
+ verify(cache).invalidate(NameIdentifier.of("m1", "cat1", "sch1", "tbl1"), EntityType.TABLE);
+ verify(cache).invalidate(NameIdentifier.of("m1", "system", "tag", "tag1"), EntityType.TAG);
+ verify(cache).invalidate(NameIdentifier.of("m1", "system", "policy", "p1"), EntityType.POLICY);
+ verify(cache).invalidate(NameIdentifier.of("m1", "system", "job", "job-1"), EntityType.JOB);
+ }
+
+ @Test
+ void testSkipsMalformedRowsAndContinues() {
+ EntityCache cache = mock(EntityCache.class);
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+
+ listener.onEntityChange(
+ List.of(
+ record(null, "m1.cat1", OperateType.ALTER),
+ record(EntityType.CATALOG, null, OperateType.ALTER),
+ new EntityChangeRecord(1L, "m1", "NOT_A_TYPE", "m1.x", OperateType.ALTER, 0L),
+ record(EntityType.CATALOG, "m1.cat_ok", OperateType.ALTER)));
+
+ // Only the single well-formed row is applied.
+ verify(cache, times(1)).invalidate(any(NameIdentifier.class), any(EntityType.class));
+ verify(cache).invalidate(NameIdentifier.of("m1", "cat_ok"), EntityType.CATALOG);
+ }
+
+ @Test
+ void testUndecodableFullNameIsSkippedWithoutClearingTheCache() {
+ EntityCache cache = mock(EntityCache.class);
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+
+ listener.onEntityChange(
+ List.of(
+ // Claims two levels but only carries one, so the codec rejects it.
+ record(EntityType.TABLE, "gravitino:v1:2:3:abc", OperateType.ALTER),
+ record(EntityType.CATALOG, "m1.cat_ok", OperateType.ALTER)));
+
+ // A row that names no entity leaves nothing stale behind, so the batch keeps going and the
+ // cache is not cleared.
+ verify(cache, times(1)).invalidate(any(NameIdentifier.class), any(EntityType.class));
+ verify(cache).invalidate(NameIdentifier.of("m1", "cat_ok"), EntityType.CATALOG);
+ verify(cache, never()).clear();
+ }
+
+ @Test
+ void testFailedInvalidationClearsTheWholeCache() {
+ EntityCache cache = mock(EntityCache.class);
+ NameIdentifier failing = NameIdentifier.of("m1", "boom");
+ doThrow(new RuntimeException("boom")).when(cache).invalidate(failing, EntityType.CATALOG);
+
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+ listener.onEntityChange(
+ List.of(
+ record(EntityType.CATALOG, "m1.boom", OperateType.DROP),
+ record(EntityType.CATALOG, "m1.ok", OperateType.DROP)));
+
+ // The clear is a superset of every invalidation in this batch, so the remaining row is not
+ // replayed and no entry can survive stale.
+ verify(cache).clear();
+ verify(cache, never()).invalidate(NameIdentifier.of("m1", "ok"), EntityType.CATALOG);
+ }
+
+ @Test
+ void testFailedClearPropagatesToThePoller() {
+ EntityCache cache = mock(EntityCache.class);
+ NameIdentifier failing = NameIdentifier.of("m1", "boom");
+ doThrow(new RuntimeException("boom")).when(cache).invalidate(failing, EntityType.CATALOG);
+ doThrow(new IllegalStateException("cache is broken")).when(cache).clear();
+
+ EntityCacheChangeLogListener listener = new EntityCacheChangeLogListener(cache);
+
+ // The listener cannot heal itself, so the poller must see the failure and apply its own
+ // retry / failure-action policy instead of the batch being silently dropped.
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ listener.onEntityChange(
+ List.of(record(EntityType.CATALOG, "m1.boom", OperateType.DROP))));
+ }
+
+ @Test
+ void testCacheCoherenceModes() {
+ Assertions.assertEquals(
+ Coherence.LOCAL_PER_NODE, new CaffeineEntityCache(new Config() {}).coherence());
+ Assertions.assertEquals(Coherence.NONE, new NoOpsCache(new Config() {}).coherence());
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheCrossNodeInvalidation.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheCrossNodeInvalidation.java
new file mode 100644
index 0000000000..9f75ec105d
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityCacheCrossNodeInvalidation.java
@@ -0,0 +1,124 @@
+/*
+ * 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;
+
+import java.io.IOException;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.cache.CaffeineEntityCache;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+/**
+ * End-to-end test of the caffeine cross-node invalidation chain: a write on one node emits an
+ * {@code entity_change_log} row, and a second node's poller replays it into that node's own {@link
+ * CaffeineEntityCache}. "Node A" is the shared {@link #backend}; "node B" is a separate cache kept
+ * fresh by an {@link EntityCacheChangeLogListener} on its own {@link EntityChangeLogPoller}.
+ */
+public class TestEntityCacheCrossNodeInvalidation extends TestJDBCBackend {
+
+ private static final String METALAKE = "metalake_cross_node";
+ private static final String CATALOG = "catalog_cross_node";
+ private static final String SCHEMA = "schema_cross_node";
+
+ // A large poll interval so the background scheduler never fires during the test; the test drives
+ // node B's poll explicitly via pollChanges().
+ private EntityChangeLogPoller newIdlePoller(CaffeineEntityCache nodeBCache) {
+ EntityChangeLogPoller poller =
+ new EntityChangeLogPoller(
+ 3600,
+ 0,
+ EntityChangeLogPoller.ListenerFailureAction.EXIT,
+ () -> Assertions.fail("The entity cache listener must not exhaust its retries"));
+ poller.registerListener(new EntityCacheChangeLogListener(nodeBCache));
+ // start() seeds the cursor with the current DB tail, modelling a node whose cache is already
+ // warm: only changes written after this point are replayed.
+ poller.start();
+ return poller;
+ }
+
+ @TestTemplate
+ void testAlterOnNodeAIsReflectedOnNodeBAfterOnePoll() throws IOException {
+ createParentEntities(METALAKE, CATALOG, SCHEMA, AUDIT_INFO);
+ Namespace namespace = Namespace.of(METALAKE, CATALOG, SCHEMA);
+ TableEntity table =
+ createTableEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "table1", AUDIT_INFO);
+ backend.insert(table, false);
+
+ // Node B has already read and cached the table.
+ CaffeineEntityCache nodeBCache = new CaffeineEntityCache(new Config() {});
+ nodeBCache.put(table);
+ Assertions.assertTrue(nodeBCache.contains(table.nameIdentifier(), EntityType.TABLE));
+
+ EntityChangeLogPoller nodeBPoller = newIdlePoller(nodeBCache);
+ try {
+ // Node A renames the table, which emits an ALTER row in the shared change log.
+ backend.update(
+ table.nameIdentifier(),
+ EntityType.TABLE,
+ entity -> createTableEntity(table.id(), namespace, "table2", AUDIT_INFO));
+
+ // Before node B polls, it still serves the stale copy.
+ Assertions.assertTrue(nodeBCache.contains(table.nameIdentifier(), EntityType.TABLE));
+
+ // One poll later, node B has dropped the stale key.
+ nodeBPoller.pollChanges();
+ Assertions.assertFalse(nodeBCache.contains(table.nameIdentifier(), EntityType.TABLE));
+ } finally {
+ nodeBPoller.close();
+ }
+ }
+
+ @TestTemplate
+ void testSchemaDropOnNodeAClearsChildTablesOnNodeB() throws IOException {
+ createParentEntities(METALAKE, CATALOG, SCHEMA, AUDIT_INFO);
+ Namespace tableNamespace = Namespace.of(METALAKE, CATALOG, SCHEMA);
+ SchemaEntity schema =
+ backend.get(NameIdentifierUtil.ofSchema(METALAKE, CATALOG, SCHEMA), EntityType.SCHEMA);
+ TableEntity table =
+ createTableEntity(
+ RandomIdGenerator.INSTANCE.nextId(), tableNamespace, "table1", AUDIT_INFO);
+ backend.insert(table, false);
+
+ // Node B has cached both the schema and its child table.
+ CaffeineEntityCache nodeBCache = new CaffeineEntityCache(new Config() {});
+ nodeBCache.put(schema);
+ nodeBCache.put(table);
+ Assertions.assertEquals(2, nodeBCache.size());
+
+ EntityChangeLogPoller nodeBPoller = newIdlePoller(nodeBCache);
+ try {
+ // Node A drops the schema with cascade, emitting a single SCHEMA DROP row.
+ Assertions.assertTrue(backend.delete(schema.nameIdentifier(), EntityType.SCHEMA, true));
+
+ nodeBPoller.pollChanges();
+
+ // The schema drop cascades to its cached child table on node B via the forward prefix scan.
+ Assertions.assertFalse(nodeBCache.contains(schema.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertFalse(nodeBCache.contains(table.nameIdentifier(), EntityType.TABLE));
+ } finally {
+ nodeBPoller.close();
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogNameIdentifierCodec.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogNameIdentifierCodec.java
new file mode 100644
index 0000000000..b7e03a42ff
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogNameIdentifierCodec.java
@@ -0,0 +1,66 @@
+/*
+ * 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;
+
+import org.apache.gravitino.NameIdentifier;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests lossless and backward-compatible entity change-log identifier encoding. */
+public class TestEntityChangeLogNameIdentifierCodec {
+
+ @Test
+ void testKeepsLegacyEncodingForUnambiguousNames() {
+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "table");
+
+ String encoded = EntityChangeLogNameIdentifierCodec.encode(ident);
+
+ Assertions.assertEquals(ident.toString(), encoded);
+ Assertions.assertEquals(ident, EntityChangeLogNameIdentifierCodec.decode(encoded));
+ }
+
+ @Test
+ void testRoundTripsDotsInsideEveryLevel() {
+ NameIdentifier ident = NameIdentifier.of("meta.lake", "cat.alog", "sche.ma", "tab.le");
+
+ String encoded = EntityChangeLogNameIdentifierCodec.encode(ident);
+
+ Assertions.assertNotEquals(ident.toString(), encoded);
+ Assertions.assertEquals(ident, EntityChangeLogNameIdentifierCodec.decode(encoded));
+ }
+
+ @Test
+ void testEscapesLegacyValueThatStartsWithCodecPrefix() {
+ NameIdentifier ident = NameIdentifier.of("gravitino:v1:metalake");
+
+ String encoded = EntityChangeLogNameIdentifierCodec.encode(ident);
+
+ Assertions.assertEquals(ident, EntityChangeLogNameIdentifierCodec.decode(encoded));
+ }
+
+ @Test
+ void testRejectsMalformedEncodedValue() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> EntityChangeLogNameIdentifierCodec.decode("gravitino:v1:2:1:a"));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> EntityChangeLogNameIdentifierCodec.decode("gravitino:v1:1:x:a"));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
index 2aca05b3c1..3d7e38e9ac 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
@@ -34,6 +34,8 @@ import org.apache.gravitino.RelationEdgeTarget;
import org.apache.gravitino.RelationQuery;
import org.apache.gravitino.RelationUpdate;
import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.cache.Coherence;
+import org.apache.gravitino.cache.EntityCache;
import org.apache.gravitino.cache.NoOpsCache;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.junit.jupiter.api.Assertions;
@@ -299,4 +301,55 @@ public class TestRelationalEntityStore {
IllegalArgumentException.class, () -> store.updateEntityRelations(update));
Mockito.verifyNoInteractions(backend);
}
+
+ @Test
+ void testLocalPerNodeCacheRegistersChangeLogListener() throws IllegalAccessException {
+ EntityChangeLogPoller poller = givenCacheWithCoherence(Coherence.LOCAL_PER_NODE);
+
+ store.registerCacheChangeLogListener();
+
+ // A per-node cache holds its own copy, so it must replay changes made on the other nodes.
+ EntityCacheChangeLogListener listener =
+ (EntityCacheChangeLogListener)
+ FieldUtils.readField(store, "entityCacheChangeLogListener", true);
+ Assertions.assertNotNull(listener);
+ Mockito.verify(poller).registerListener(listener);
+ }
+
+ @Test
+ void testSharedCacheDoesNotRegisterChangeLogListener() throws IllegalAccessException {
+ EntityChangeLogPoller poller = givenCacheWithCoherence(Coherence.SHARED);
+
+ store.registerCacheChangeLogListener();
+
+ // A shared cache has a single cluster-wide copy, so there is nothing per-node to invalidate.
+ Assertions.assertNull(FieldUtils.readField(store, "entityCacheChangeLogListener", true));
+ Mockito.verify(poller, Mockito.never()).registerListener(Mockito.any());
+ }
+
+ @Test
+ void testCacheDisabledDoesNotRegisterChangeLogListener() throws IllegalAccessException {
+ EntityChangeLogPoller poller = givenCacheWithCoherence(Coherence.NONE);
+
+ store.registerCacheChangeLogListener();
+
+ // Nothing is cached, so there is nothing to invalidate either.
+ Assertions.assertNull(FieldUtils.readField(store, "entityCacheChangeLogListener", true));
+ Mockito.verify(poller, Mockito.never()).registerListener(Mockito.any());
+ }
+
+ /**
+ * Installs a cache reporting the given coherence mode plus a mock poller, and returns the poller
+ * so the caller can assert on listener registration.
+ */
+ private EntityChangeLogPoller givenCacheWithCoherence(Coherence coherence)
+ throws IllegalAccessException {
+ EntityCache cache = Mockito.mock(EntityCache.class);
+ Mockito.when(cache.coherence()).thenReturn(coherence);
+ EntityChangeLogPoller poller = Mockito.mock(EntityChangeLogPoller.class);
+
+ FieldUtils.writeField(store, "cache", cache, true);
+ FieldUtils.writeField(store, "entityChangeLogPoller", poller, true);
+ return poller;
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java
index f58c6b9da3..8611b77db5 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java
@@ -18,28 +18,45 @@
*/
package org.apache.gravitino.storage.relational.service;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.job.JobHandle;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.JobEntity;
+import org.apache.gravitino.meta.JobTemplateEntity;
import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
@@ -64,20 +81,25 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
Entity.EntityType entityType,
String fullName,
OperateType operateType) {
- Assertions.assertTrue(
+ long matchingChanges =
listEntityChanges(lastConsumedId).stream()
- .anyMatch(
- record ->
- record.getMetalakeName().equals(metalakeName)
- && record.getEntityType().equals(entityType.name())
- && record.getFullName().equals(fullName)
- && record.getOperateType() == operateType),
- String.format("Missing %s %s changelog for %s", entityType, operateType, fullName));
+ .filter(change -> metalakeName.equals(change.getMetalakeName()))
+ .filter(change -> entityType.name().equals(change.getEntityType()))
+ .filter(change -> fullName.equals(change.getFullName()))
+ .filter(change -> operateType == change.getOperateType())
+ .count();
+ Assertions.assertEquals(
+ 1,
+ matchingChanges,
+ String.format(
+ "Expected exactly one %s %s changelog for %s", entityType, operateType, fullName));
}
@TestTemplate
void testMetalakeChangeLogOnRenameAndDrop() throws IOException {
+ long maxIdBeforeCreate = maxEntityChangeId();
BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ Assertions.assertEquals(maxIdBeforeCreate, maxEntityChangeId());
long maxIdBeforeRename = maxEntityChangeId();
BaseMetalake renamedMetalake =
@@ -96,7 +118,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeDrop = maxEntityChangeId();
Assertions.assertTrue(
- MetalakeMetaService.getInstance().deleteMetalake(renamedMetalake.nameIdentifier(), false));
+ backend.delete(renamedMetalake.nameIdentifier(), Entity.EntityType.METALAKE, false));
assertEntityChange(
maxIdBeforeDrop,
renamedMetalake.name(),
@@ -109,7 +131,9 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
void testCatalogAndSchemaChangeLogOnRenameAndDrop() throws IOException {
createAndInsertMakeLake(METALAKE_NAME);
+ long maxIdBeforeCatalogCreate = maxEntityChangeId();
CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);
+ Assertions.assertEquals(maxIdBeforeCatalogCreate, maxEntityChangeId());
long maxIdBeforeCatalogAlter = maxEntityChangeId();
CatalogEntity alteredCatalog =
backend.update(
@@ -153,7 +177,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeCatalogDrop = maxEntityChangeId();
Assertions.assertTrue(
- CatalogMetaService.getInstance().deleteCatalog(renamedCatalog.nameIdentifier(), false));
+ backend.delete(renamedCatalog.nameIdentifier(), Entity.EntityType.CATALOG, false));
assertEntityChange(
maxIdBeforeCatalogDrop,
METALAKE_NAME,
@@ -162,7 +186,9 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
OperateType.DROP);
CatalogEntity schemaCatalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME + "_schema");
+ long maxIdBeforeSchemaCreate = maxEntityChangeId();
SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, schemaCatalog.name(), SCHEMA_NAME);
+ Assertions.assertEquals(maxIdBeforeSchemaCreate, maxEntityChangeId());
long maxIdBeforeSchemaRename = maxEntityChangeId();
SchemaEntity renamedSchema =
backend.update(
@@ -180,7 +206,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeSchemaDrop = maxEntityChangeId();
Assertions.assertTrue(
- SchemaMetaService.getInstance().deleteSchema(renamedSchema.nameIdentifier(), false));
+ backend.delete(renamedSchema.nameIdentifier(), Entity.EntityType.SCHEMA, false));
assertEntityChange(
maxIdBeforeSchemaDrop,
METALAKE_NAME,
@@ -190,6 +216,73 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
OperateType.DROP);
}
+ @TestTemplate
+ void testEntityAndChangeLogRollbackTogether() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);
+ long maxIdBeforeUpdate = maxEntityChangeId();
+
+ SessionUtils.beginTransaction();
+ try {
+ backend.update(
+ catalog.nameIdentifier(),
+ Entity.EntityType.CATALOG,
+ entity ->
+ createCatalog(
+ catalog.id(), catalog.namespace(), CATALOG_NAME + "_rolled_back", AUDIT_INFO));
+ } finally {
+ SessionUtils.rollbackTransaction();
+ }
+
+ CatalogEntity persistedCatalog =
+ backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);
+ Assertions.assertEquals(CATALOG_NAME, persistedCatalog.name());
+ Assertions.assertEquals(maxIdBeforeUpdate, maxEntityChangeId());
+ }
+
+ @TestTemplate
+ void testEntityUpdateRollsBackWhenChangeLogInsertFails() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);
+ long maxIdBeforeUpdate = maxEntityChangeId();
+
+ // Take the change-log table away so that the entity row is updated first and the change-log
+ // insert then fails inside the same transaction. This is the only ordering the rollback in
+ // JDBCBackend#update protects against, and the caller owns no outer transaction here.
+ renameTable("entity_change_log", "entity_change_log_bak");
+ try {
+ Assertions.assertThrows(
+ Exception.class,
+ () ->
+ backend.update(
+ catalog.nameIdentifier(),
+ Entity.EntityType.CATALOG,
+ entity ->
+ createCatalog(
+ catalog.id(),
+ catalog.namespace(),
+ CATALOG_NAME + "_rolled_back",
+ AUDIT_INFO)));
+ } finally {
+ renameTable("entity_change_log_bak", "entity_change_log");
+ }
+
+ // The entity mutation must not survive a failed change-log write.
+ CatalogEntity persistedCatalog =
+ backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);
+ Assertions.assertEquals(CATALOG_NAME, persistedCatalog.name());
+ Assertions.assertEquals(maxIdBeforeUpdate, maxEntityChangeId());
+ }
+
+ private void renameTable(String from, String to) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute(String.format("ALTER TABLE %s RENAME TO %s", from, to));
+ }
+ }
+
@TestTemplate
void testLeafEntityChangeLogOnRenameAndDrop() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
@@ -197,14 +290,16 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
TableEntity table =
createTableEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "table1", AUDIT_INFO);
+ long maxIdBeforeTableCreate = maxEntityChangeId();
backend.insert(table, false);
+ Assertions.assertEquals(maxIdBeforeTableCreate, maxEntityChangeId());
long maxIdBeforeTableRename = maxEntityChangeId();
TableEntity renamedTable =
- TableMetaService.getInstance()
- .updateTable(
- table.nameIdentifier(),
- entity ->
- createTableEntity(table.id(), table.namespace(), "table2", table.auditInfo()));
+ backend.update(
+ table.nameIdentifier(),
+ Entity.EntityType.TABLE,
+ entity ->
+ createTableEntity(table.id(), table.namespace(), "table2", table.auditInfo()));
assertEntityChange(
maxIdBeforeTableRename,
METALAKE_NAME,
@@ -214,7 +309,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeTableDrop = maxEntityChangeId();
Assertions.assertTrue(
- TableMetaService.getInstance().deleteTable(renamedTable.nameIdentifier()));
+ backend.delete(renamedTable.nameIdentifier(), Entity.EntityType.TABLE, false));
assertEntityChange(
maxIdBeforeTableDrop,
METALAKE_NAME,
@@ -228,7 +323,9 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
NamespaceUtil.ofTopic(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
"topic1",
AUDIT_INFO);
+ long maxIdBeforeTopicCreate = maxEntityChangeId();
backend.insert(topic, false);
+ Assertions.assertEquals(maxIdBeforeTopicCreate, maxEntityChangeId());
long maxIdBeforeTopicRename = maxEntityChangeId();
TopicEntity renamedTopic =
backend.update(
@@ -244,7 +341,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeTopicDrop = maxEntityChangeId();
Assertions.assertTrue(
- TopicMetaService.getInstance().deleteTopic(renamedTopic.nameIdentifier()));
+ backend.delete(renamedTopic.nameIdentifier(), Entity.EntityType.TOPIC, false));
assertEntityChange(
maxIdBeforeTopicDrop,
METALAKE_NAME,
@@ -257,21 +354,23 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
RandomIdGenerator.INSTANCE.nextId(),
NamespaceUtil.ofView(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
"view1");
- ViewMetaService.getInstance().insertView(view, false);
+ long maxIdBeforeViewCreate = maxEntityChangeId();
+ backend.insert(view, false);
+ Assertions.assertEquals(maxIdBeforeViewCreate, maxEntityChangeId());
long maxIdBeforeViewRename = maxEntityChangeId();
ViewEntity renamedView =
- ViewMetaService.getInstance()
- .updateView(
- view.nameIdentifier(),
- entity ->
- ViewEntity.builder()
- .withId(view.id())
- .withName("view2")
- .withNamespace(view.namespace())
- .withColumns(view.columns())
- .withRepresentations(view.representations())
- .withAuditInfo(view.auditInfo())
- .build());
+ backend.update(
+ view.nameIdentifier(),
+ Entity.EntityType.VIEW,
+ entity ->
+ ViewEntity.builder()
+ .withId(view.id())
+ .withName("view2")
+ .withNamespace(view.namespace())
+ .withColumns(view.columns())
+ .withRepresentations(view.representations())
+ .withAuditInfo(view.auditInfo())
+ .build());
assertEntityChange(
maxIdBeforeViewRename,
METALAKE_NAME,
@@ -280,7 +379,8 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
OperateType.ALTER);
long maxIdBeforeViewDrop = maxEntityChangeId();
- Assertions.assertTrue(ViewMetaService.getInstance().deleteView(renamedView.nameIdentifier()));
+ Assertions.assertTrue(
+ backend.delete(renamedView.nameIdentifier(), Entity.EntityType.VIEW, false));
assertEntityChange(
maxIdBeforeViewDrop,
METALAKE_NAME,
@@ -294,14 +394,16 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
NamespaceUtil.ofFileset(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
"fileset1",
AUDIT_INFO);
- FilesetMetaService.getInstance().insertFileset(fileset, false);
+ long maxIdBeforeFilesetCreate = maxEntityChangeId();
+ backend.insert(fileset, false);
+ Assertions.assertEquals(maxIdBeforeFilesetCreate, maxEntityChangeId());
long maxIdBeforeFilesetRename = maxEntityChangeId();
FilesetEntity renamedFileset =
- FilesetMetaService.getInstance()
- .updateFileset(
- fileset.nameIdentifier(),
- entity ->
- createFilesetEntity(fileset.id(), fileset.namespace(), "fileset2", AUDIT_INFO));
+ backend.update(
+ fileset.nameIdentifier(),
+ Entity.EntityType.FILESET,
+ entity ->
+ createFilesetEntity(fileset.id(), fileset.namespace(), "fileset2", AUDIT_INFO));
assertEntityChange(
maxIdBeforeFilesetRename,
METALAKE_NAME,
@@ -312,7 +414,7 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
long maxIdBeforeFilesetDrop = maxEntityChangeId();
Assertions.assertTrue(
- FilesetMetaService.getInstance().deleteFileset(renamedFileset.nameIdentifier()));
+ backend.delete(renamedFileset.nameIdentifier(), Entity.EntityType.FILESET, false));
assertEntityChange(
maxIdBeforeFilesetDrop,
METALAKE_NAME,
@@ -362,4 +464,210 @@ public class TestEntityChangeLogService extends TestJDBCBackend {
NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "model2").toString(),
OperateType.DROP);
}
+
+ @TestTemplate
+ void testModelChangeLogEncodesNameLevelsContainingDots() throws IOException {
+ String dottedSchema = "schema.with.dot";
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, dottedSchema, AUDIT_INFO);
+
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofModel(METALAKE_NAME, CATALOG_NAME, dottedSchema),
+ "model1",
+ "model comment",
+ 0,
+ Map.of("k1", "v1"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+
+ // Readers decode() every full_name, so the writer must encode() it. Asserting on the encoded
+ // form (not toString()) is what pins the round trip: a raw "ml.cat.schema.with.dot.model1"
+ // decodes to a six-level identifier under a schema named "schema", not this model.
+ long maxIdBeforeModelRename = maxEntityChangeId();
+ ModelEntity renamedModel =
+ ModelMetaService.getInstance()
+ .updateModel(
+ model.nameIdentifier(),
+ entity ->
+ createModelEntity(
+ model.id(),
+ model.namespace(),
+ "model2",
+ model.comment(),
+ model.latestVersion(),
+ model.properties(),
+ AUDIT_INFO));
+ assertEntityChange(
+ maxIdBeforeModelRename,
+ METALAKE_NAME,
+ Entity.EntityType.MODEL,
+ EntityChangeLogNameIdentifierCodec.encode(
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, dottedSchema, "model1")),
+ OperateType.ALTER);
+
+ long maxIdBeforeModelDrop = maxEntityChangeId();
+ Assertions.assertTrue(
+ ModelMetaService.getInstance().deleteModel(renamedModel.nameIdentifier()));
+ assertEntityChange(
+ maxIdBeforeModelDrop,
+ METALAKE_NAME,
+ Entity.EntityType.MODEL,
+ EntityChangeLogNameIdentifierCodec.encode(
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, dottedSchema, "model2")),
+ OperateType.DROP);
+ }
+
+ @TestTemplate
+ void testTagChangeLogOnAlterAndDrop() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ long maxIdBeforeCreate = maxEntityChangeId();
+ TagEntity tag = createAndInsertTagEntity("tag1", "tag comment", METALAKE_NAME);
+ Assertions.assertEquals(maxIdBeforeCreate, maxEntityChangeId());
+
+ long maxIdBeforeTagAlter = maxEntityChangeId();
+ backend.update(
+ tag.nameIdentifier(),
+ Entity.EntityType.TAG,
+ entity ->
+ TagEntity.builder()
+ .withId(tag.id())
+ .withName(tag.name())
+ .withNamespace(tag.namespace())
+ .withComment("tag comment updated")
+ .withProperties(ImmutableMap.of())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ assertEntityChange(
+ maxIdBeforeTagAlter,
+ METALAKE_NAME,
+ Entity.EntityType.TAG,
+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1").toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforeTagDrop = maxEntityChangeId();
+ Assertions.assertTrue(backend.delete(tag.nameIdentifier(), Entity.EntityType.TAG, false));
+ assertEntityChange(
+ maxIdBeforeTagDrop,
+ METALAKE_NAME,
+ Entity.EntityType.TAG,
+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1").toString(),
+ OperateType.DROP);
+ }
+
+ @TestTemplate
+ void testDottedNameUsesLosslessChangeLogEncoding() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ TagEntity tag = createAndInsertTagEntity("tag.with.dot", "tag comment", METALAKE_NAME);
+ long maxIdBeforeAlter = maxEntityChangeId();
+
+ backend.update(
+ tag.nameIdentifier(),
+ Entity.EntityType.TAG,
+ entity ->
+ TagEntity.builder()
+ .withId(tag.id())
+ .withName(tag.name())
+ .withNamespace(tag.namespace())
+ .withComment("updated comment")
+ .withProperties(ImmutableMap.of())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+
+ String encoded = EntityChangeLogNameIdentifierCodec.encode(tag.nameIdentifier());
+ assertEntityChange(
+ maxIdBeforeAlter, METALAKE_NAME, Entity.EntityType.TAG, encoded, OperateType.ALTER);
+ Assertions.assertEquals(
+ tag.nameIdentifier(), EntityChangeLogNameIdentifierCodec.decode(encoded));
+ }
+
+ @TestTemplate
+ void testPolicyChangeLogOnAlterAndDrop() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ PolicyContent content =
+ PolicyContents.custom(
+ ImmutableMap.of("field1", 1), ImmutableSet.of(MetadataObject.Type.TABLE), null);
+ long maxIdBeforeCreate = maxEntityChangeId();
+ PolicyEntity policy =
+ createAndInsertPolicyEntity("policy1", "policy comment", content, METALAKE_NAME);
+ Assertions.assertEquals(maxIdBeforeCreate, maxEntityChangeId());
+
+ long maxIdBeforePolicyAlter = maxEntityChangeId();
+ backend.update(
+ policy.nameIdentifier(),
+ Entity.EntityType.POLICY,
+ entity ->
+ PolicyEntity.builder()
+ .withId(policy.id())
+ .withName(policy.name())
+ .withNamespace(policy.namespace())
+ .withPolicyType(Policy.BuiltInType.CUSTOM)
+ .withComment("policy comment updated")
+ .withEnabled(true)
+ .withContent(content)
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ assertEntityChange(
+ maxIdBeforePolicyAlter,
+ METALAKE_NAME,
+ Entity.EntityType.POLICY,
+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1").toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforePolicyDrop = maxEntityChangeId();
+ Assertions.assertTrue(backend.delete(policy.nameIdentifier(), Entity.EntityType.POLICY, false));
+ assertEntityChange(
+ maxIdBeforePolicyDrop,
+ METALAKE_NAME,
+ Entity.EntityType.POLICY,
+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1").toString(),
+ OperateType.DROP);
+ }
+
+ @TestTemplate
+ void testJobChangeLogOnOverwriteAndDrop() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ JobTemplateEntity jobTemplate =
+ TestJobTemplateMetaService.newShellJobTemplateEntity(
+ "job_template_for_change_log", "comment", METALAKE_NAME);
+ JobTemplateMetaService.getInstance().insertJobTemplate(jobTemplate, false);
+
+ JobEntity job =
+ TestJobTemplateMetaService.newJobEntity(
+ jobTemplate.name(), JobHandle.Status.QUEUED, METALAKE_NAME);
+
+ // A plain insert (create) must not emit a change-log row: list bypasses the cache and there is
+ // no negative caching.
+ long maxIdBeforeCreate = maxEntityChangeId();
+ backend.insert(job, false);
+ Assertions.assertEquals(maxIdBeforeCreate, maxEntityChangeId());
+
+ // An overwrite is an in-place status update, so it emits an ALTER row.
+ long maxIdBeforeOverwrite = maxEntityChangeId();
+ JobEntity runningJob =
+ JobEntity.builder()
+ .withId(job.id())
+ .withJobExecutionId(job.jobExecutionId())
+ .withNamespace(job.namespace())
+ .withJobTemplateName(job.jobTemplateName())
+ .withStatus(JobHandle.Status.STARTED)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ backend.insert(runningJob, true);
+ assertEntityChange(
+ maxIdBeforeOverwrite,
+ METALAKE_NAME,
+ Entity.EntityType.JOB,
+ job.nameIdentifier().toString(),
+ OperateType.ALTER);
+
+ long maxIdBeforeJobDrop = maxEntityChangeId();
+ Assertions.assertTrue(backend.delete(job.nameIdentifier(), Entity.EntityType.JOB, false));
+ assertEntityChange(
+ maxIdBeforeJobDrop,
+ METALAKE_NAME,
+ Entity.EntityType.JOB,
+ job.nameIdentifier().toString(),
+ OperateType.DROP);
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
index 08d874f295..a795168a5d 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
@@ -203,7 +203,7 @@ public class TestTableMetaService extends TestJDBCBackend {
.withColumns(List.of(column1))
.withAuditInfo(AUDIT_INFO)
.build();
- TableMetaService.getInstance().insertTable(createdTable, false);
+ backend.insert(createdTable, false);
// test update table without changing schema name
long maxIdBeforeRename = maxEntityChangeId();
@@ -216,7 +216,7 @@ public class TestTableMetaService extends TestJDBCBackend {
.withAuditInfo(AUDIT_INFO)
.build();
Function<TableEntity, TableEntity> updater = oldTable -> updatedTable;
- TableMetaService.getInstance().updateTable(createdTable.nameIdentifier(), updater);
+ backend.update(createdTable.nameIdentifier(), Entity.EntityType.TABLE, updater);
TableEntity retrievedTable =
TableMetaService.getInstance().getTableByIdentifier(updatedTable.nameIdentifier());
@@ -254,9 +254,7 @@ public class TestTableMetaService extends TestJDBCBackend {
Exception e =
Assertions.assertThrows(
NoSuchEntityException.class,
- () ->
- TableMetaService.getInstance()
- .updateTable(updatedTable.nameIdentifier(), updater2));
+ () -> backend.update(updatedTable.nameIdentifier(), Entity.EntityType.TABLE, updater2));
Assertions.assertTrue(e.getMessage().contains(newSchemaName));
// test update table with changing schema name to an existing schema
@@ -277,8 +275,7 @@ public class TestTableMetaService extends TestJDBCBackend {
.withColumns(updatedTable.columns())
.withAuditInfo(AUDIT_INFO)
.build();
- TableMetaService.getInstance()
- .updateTable(updatedTable.nameIdentifier(), oldTable -> movedTable);
+ backend.update(updatedTable.nameIdentifier(), Entity.EntityType.TABLE, oldTable -> movedTable);
Assertions.assertTrue(
listEntityChanges(maxIdBeforeSchemaMove).stream()
.anyMatch(
@@ -293,7 +290,7 @@ public class TestTableMetaService extends TestJDBCBackend {
.toString())
&& record.getOperateType() == OperateType.ALTER));
- TableMetaService.getInstance().updateTable(movedTable.nameIdentifier(), updater2);
+ backend.update(movedTable.nameIdentifier(), Entity.EntityType.TABLE, updater2);
TableEntity retrievedTable2 =
TableMetaService.getInstance().getTableByIdentifier(updatedTable2.nameIdentifier());
@@ -305,7 +302,7 @@ public class TestTableMetaService extends TestJDBCBackend {
long maxIdBeforeDelete = maxEntityChangeId();
Assertions.assertTrue(
- TableMetaService.getInstance().deleteTable(updatedTable2.nameIdentifier()));
+ backend.delete(updatedTable2.nameIdentifier(), Entity.EntityType.TABLE, false));
Assertions.assertTrue(
listEntityChanges(maxIdBeforeDelete).stream()
.anyMatch(
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java b/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java
index 5bdf6a6312..fd93824d10 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java
@@ -30,9 +30,11 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
@@ -137,10 +139,13 @@ public class TestSqlSession {
@Test
public void testOpenAndCloseSqlSession() {
+ assertFalse(SqlSessions.hasActiveSession());
SqlSession session = SqlSessions.getSqlSession();
assertNotNull(session);
+ assertTrue(SqlSessions.hasActiveSession());
assertEquals(1, SqlSessions.getSessionCount());
SqlSessions.closeSqlSession();
+ assertFalse(SqlSessions.hasActiveSession());
assertNull(SqlSessions.getSessions().get());
assertEquals(0, SqlSessions.getSessionCount());
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestSessionUtils.java b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestSessionUtils.java
index f3e7fc7d27..cc7c4dfde7 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestSessionUtils.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestSessionUtils.java
@@ -20,6 +20,7 @@
package org.apache.gravitino.storage.relational.utils;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
@@ -29,6 +30,16 @@ import org.mockito.MockedStatic;
public class TestSessionUtils {
+ @Test
+ public void testIsInTransactionDelegatesToSqlSessions() {
+ try (MockedStatic<SqlSessions> mockedSqlSessions = mockStatic(SqlSessions.class)) {
+ mockedSqlSessions.when(SqlSessions::hasActiveSession).thenReturn(true);
+
+ assertTrue(SessionUtils.isInTransaction());
+ mockedSqlSessions.verify(SqlSessions::hasActiveSession);
+ }
+ }
+
@Test
public void testDoWithCommitShouldRollbackOnAssertionError() {
Object mapper = new Object();
diff --git a/design-docs/gravitino-entity-cache-multinode-design.md b/design-docs/gravitino-entity-cache-multinode-design.md
index 9fc735219a..714d8ecb03 100644
--- a/design-docs/gravitino-entity-cache-multinode-design.md
+++ b/design-docs/gravitino-entity-cache-multinode-design.md
@@ -130,7 +130,7 @@ Dropping relations leaves the entity keys. But not every entity key is truly one
So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
-**Conclusion: cache the self-contained metadata objects** — metalake, catalog, schema, table, topic, view, fileset, plus tag, policy, and the job entity. A stale read of any of these is at worst cosmetic (an old comment, property, or job status), never a wrong pointer, so a per-node cache can serve them and refresh them across nodes through the change log. The first seven already emit change-log rows; tag, policy, and job do not emit one yet, so this work adds an emit point for them (a small writer-side change). Model, model version, and function are different because each holds a load-bearing pointer, so a per-node cache (caffeine) does not cache them — they read straight from the DB; a shared cache (redis) caches them since it has no staleness window. The [Consistency](#consistency) section works this out per alter and lists the handling per type. Every entity a per-node cache serves is then either self-contained and one-to-one or has its pointer resolved fresh, so cross-node invalidation stays precise with no reverse lookups.
+**Conclusion: cache the self-contained metadata objects** — metalake, catalog, schema, table, topic, view, fileset, plus tag, policy, and the job entity. A stale read of any of these is at worst cosmetic (an old comment, property, or job status), never a wrong pointer, so a per-node cache can serve them and refresh them across nodes through the change log. All invalidating mutations of these cacheable types emit change-log rows from the common entity-store boundary. Model, model version, and function are different because each holds a load-bearing pointer, so a per-node cache (caffeine) does not cache them — they read straight from the DB; a shared cache (redis) caches them since it has no staleness window. The [Consistency](#consistency) section works this out per alter and lists the handling per type. Every entity a per-node cache serves is then either self-contained and one-to-one or has its pointer resolved fresh, so cross-node invalidation stays precise with no reverse lookups.
The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
@@ -221,21 +221,25 @@ With only self-contained metadata objects cached, "entity X changed" names exact
- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
-Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. `full_name` retains the legacy dot-joined form for ordinary identifiers and uses a versioned, length-prefixed encoding when a name segment contains a dot, so consumers can reconstruct every `NameIdentifier` without ambiguity. The entity-store mutation boundary writes rows for all cacheable entity types, and the entity store cache is a **third consumer** of the same poller.
### Writer side
-Most cached objects **already write** an ALTER/DROP row to `entity_change_log` today, so the writer side is almost unchanged — no new columns and no new operate type. The one addition is a change-log row for **tag and policy**, which are cached but do not emit one yet:
+The writer policy is centralized in `JDBCBackend`, after dispatch to the type-specific MetaService. This avoids fragmented coverage in which some services emitted only on rename or drop while ordinary alters, overwrite/import paths, enable/disable operations, and repair updates were missed. No new column or operate type is required:
-| Change | Cached? | Writes a change-log row |
-| ----------------------------------------------------- | ------- | ------------------------------------- |
-| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
-| tag / policy / job ALTER/DROP | yes | **add a new emit point** (none today) |
-| user / group / role ALTER/DROP | no | not needed (not cached) |
-| model / model version / function ALTER/DROP | no | not needed (not cached) |
-| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+| Entity-store mutation | Cached? | Change-log action |
+| ----------------------------------------------------- | ------- | -------------------------------------------------------- |
+| create (`insert` with `overwritten = false`) | yes | none; there is no negative caching and `list` skips cache |
+| overwrite/import (`insert` with `overwritten = true`) | yes | `ALTER` for the entity key |
+| update, including enable/disable and repair | yes | `ALTER` for the identifier passed to `update` |
+| rename | yes | `ALTER` for the old identifier only |
+| successful drop | yes | `DROP` for the dropped identifier |
+| cascade drop | yes | one `DROP` for the root; prefix invalidation clears descendants |
+| failed mutation or rollback | yes | none |
+| mutation of a non-cacheable type | no | no cache-specific row |
+| relation change (grant, set owner, attach tag/policy) | no | none; relations are not cached |
-The existing structural rows are written in the same transaction as the entity write; the new tag/policy rows must be written the same way, in the same transaction as the tag/policy write.
+The entity mutation and its cache change-log row are enclosed by the same outer transaction. A MetaService failure, a change-log failure, or a caller rollback therefore leaves neither side committed. The cacheability allowlist is also the writer policy, so adding a new cacheable type cannot silently omit its standard overwrite, update, and drop events.
### Reader side
@@ -251,7 +255,7 @@ Dropping a container (for example a schema) must also drop its cached children.
### A third consumer of the existing feed
-The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same ALTER/DROP rows — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
### Consistency
@@ -315,8 +319,8 @@ We do **not** need a per-entity version check on the cache: for a point read, ch
| schema | own data (connector for external catalogs); safe | cache + change-log invalidation | cache |
| table, view, topic | real metadata comes from the connector; cache holds only id/audit; safe | cache + change-log invalidation | cache |
| fileset | own data; storage location is immutable | cache + change-log invalidation | cache |
-| tag, policy | self-contained; a stale read is only cosmetic (old comment/property) | cache + change-log invalidation (add the emit point — see writer side) | cache |
-| job | self-contained operational entity; a stale read is only an old job status | cache + change-log invalidation (add the emit point — see writer side) | cache |
+| tag, policy | self-contained; a stale read is only cosmetic (old comment/property) | cache + change-log invalidation | cache |
+| job | self-contained operational entity; a stale read is only an old job status | cache + change-log invalidation | cache |
| model, model version | carries a load-bearing pointer (a version's URI, the latest version) that would be wrong if stale | **not cached — read from the DB** (revisit if it gets hot) | cache |
| function | the cached value *is* the code that runs, so a stale copy would run the wrong code | **not cached — read from the DB** (revisit if it gets hot) | cache |
| user, group, role | derived fields (`roleNames`, `securableObjects`) need a reverse lookup | not cached | not cached |
@@ -409,7 +413,7 @@ Both are chosen through the same SPI, so a user picks by environment with a sing
| Phase | Deliverable | Why |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
-| 1 | cache self-contained metadata objects (incl. tag/policy/job); drop relation, user/group/role, model, and function caching; add the entity store `EntityChangeLogListener` and a change-log emit point for tag/policy/job (other structural rows already exist) — `caffeine` | multi-node works, no schema change, new emits (tag/policy/job) |
+| 1 | cache self-contained metadata objects (incl. tag/policy/job); drop relation, user/group/role, model, and function caching; add the entity store `EntityChangeLogListener`; centralize cache mutation events for every cacheable type — `caffeine` | multi-node works, no schema change, complete mutation coverage |
| 2 | `redis` `SHARED` implementation behind the same SPI | strong consistency, reuse user's Redis |
| 3 | (later, if metrics show hot relation reads) add precise relation caching back, per relation type | heavy tag/policy workloads |
@@ -418,7 +422,8 @@ Both are chosen through the same SPI, so a user picks by environment with a sing
| Area | Check |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Multi-node — caffeine | node A runs ALTER/DROP on table / schema / catalog; node B serves the fresh entity within one poll interval |
-| Tag / policy cross-node | after the new emit point is added, an ALTER/DROP of a tag or policy on node A is reflected on node B within one poll interval |
+| Mutation-event coverage | create emits nothing; overwrite/update/rename/successful drop emit exactly one row for every cacheable type; rename keeps only the old key; entity and row roll back together |
+| Tag / policy cross-node | an ALTER/DROP of a tag or policy on node A is reflected on node B within one poll interval |
| Hierarchical drop | dropping a schema drops the schema's cached child tables on the other node(s), and leaves a sibling schema alone (forward prefix scan) |
| Shared feed | the entity store cache, the catalog cache, and the jcasbin id-mapping cache all act on the same structural rows; adding the entity store consumer does not change the others |
| Not cached (caffeine) | get user / group / role / model / model version / function return correct data straight from the DB; authorization is unaffected |
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index 05039ccd48..4eb0d46fc9 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -614,7 +614,7 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_name` VARCHAR(128) NOT NULL COMMENT 'metalake name',
`entity_type` VARCHAR(32) NOT NULL COMMENT 'METALAKE | CATALOG | SCHEMA | TABLE | FILESET | TOPIC | MODEL | VIEW',
- `entity_full_name` VARCHAR(512) NOT NULL COMMENT 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.',
+ `entity_full_name` VARCHAR(512) NOT NULL COMMENT 'Encoded full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.',
`operate_type` TINYINT UNSIGNED NOT NULL COMMENT 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.',
`created_at` BIGINT NOT NULL COMMENT 'timestamp of the change in millis',
PRIMARY KEY (`id`),
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index 5defbd4faf..7c5935016d 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -601,7 +601,7 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_name` VARCHAR(128) NOT NULL COMMENT 'metalake name',
`entity_type` VARCHAR(32) NOT NULL COMMENT 'METALAKE | CATALOG | SCHEMA | TABLE | FILESET | TOPIC | MODEL | VIEW',
- `entity_full_name` VARCHAR(512) NOT NULL COMMENT 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.',
+ `entity_full_name` VARCHAR(512) NOT NULL COMMENT 'Encoded full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.',
`operate_type` TINYINT UNSIGNED NOT NULL COMMENT 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.',
`created_at` BIGINT NOT NULL COMMENT 'timestamp of the change in millis',
PRIMARY KEY (`id`),
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index cbc05204e8..6f602d5fd4 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1064,7 +1064,7 @@ COMMENT ON TABLE entity_change_log IS 'Append-only log of entity structural chan
COMMENT ON COLUMN entity_change_log.id IS 'auto increment id';
COMMENT ON COLUMN entity_change_log.metalake_name IS 'metalake name';
COMMENT ON COLUMN entity_change_log.entity_type IS 'METALAKE | CATALOG | SCHEMA | TABLE | FILESET | TOPIC | MODEL | VIEW';
-COMMENT ON COLUMN entity_change_log.entity_full_name IS 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.';
+COMMENT ON COLUMN entity_change_log.entity_full_name IS 'Encoded full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.';
COMMENT ON COLUMN entity_change_log.operate_type IS 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.';
COMMENT ON COLUMN entity_change_log.created_at IS 'timestamp of the change in millis';
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
index 352dfcb8fd..06dcf80f1b 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.server.authorization.jcasbin;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
@@ -33,8 +34,10 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.cache.GravitinoCache;
import org.apache.gravitino.storage.relational.EntityChangeLogListener;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.po.auth.ChangedOwnerInfo;
import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;
@@ -56,6 +59,21 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
private static final Logger LOG = LoggerFactory.getLogger(JcasbinChangeListener.class);
+ /**
+ * Entity types that are cacheable in the entity store — and therefore emitted into {@code
+ * entity_change_log} — but that live in a virtual namespace ({@code
+ * <metalake>.system.<kind>.<name>}) instead of under a catalog. Their change-log identifier has
+ * more levels than {@link MetadataObjects#of} accepts for the matching type, and the JCasbin
+ * {@code metadataIdCache} never keys on them, so they are dropped before any mapping is
+ * attempted.
+ */
+ private static final Set<MetadataObject.Type> VIRTUAL_NAMESPACE_TYPES =
+ ImmutableSet.of(
+ MetadataObject.Type.TAG,
+ MetadataObject.Type.POLICY,
+ MetadataObject.Type.JOB,
+ MetadataObject.Type.JOB_TEMPLATE);
+
private final GravitinoCache<String, Long> metadataIdCache;
private final GravitinoCache<Long, Optional<OwnerInfo>> ownerRelCache;
private final long pollIntervalSecs;
@@ -201,11 +219,16 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
* Invalidates the affected {@code metadataIdCache} keys from an entity-change batch.
*
* <p><b>Contract with the writer side:</b> {@code entity_change_log.full_name} must be the
- * <i>pre-mutation</i> name (the name that consumers currently have cached). The writers in {@code
- * SchemaMetaService} / {@code TableMetaService} / etc. emit {@code oldFullName} on rename and the
- * current name on drop, so the cacheKey we build here resolves to the entry a peer node would
- * have populated under that name. If a future change starts emitting the new post-rename name,
- * this invalidation will silently miss and stale entries will only clear via LRU eviction.
+ * <i>pre-mutation</i> name (the name that consumers currently have cached). {@code JDBCBackend}
+ * emits the pre-mutation identifier on update and the current name on drop, so the cacheKey we
+ * build here resolves to the entry a peer node would have populated under that name. If a future
+ * change starts emitting the new post-rename name, this invalidation will silently miss and stale
+ * entries will only clear via LRU eviction.
+ *
+ * <p><b>Poison-row tolerance:</b> a record this listener cannot map is logged and skipped rather
+ * than propagated. The poller treats a listener throw as a batch failure and, after exhausting
+ * retries, its default action is to stop the server — so one unmappable row must never be able to
+ * take the node down.
*
* <p>The {@code synchronized} modifier is defensive — see the note on {@link #pollOwnerChanges()}
* for the rationale. The single-threaded scheduler already prevents overlapping runs in
@@ -228,8 +251,23 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
continue;
}
- MetadataObject mdObj = metadataObjectFromChangeLog(metalake, fullName, mdType);
- String cacheKey = JcasbinAuthorizationCacheKeys.metadataIdCacheKey(metalake, mdObj);
+ if (VIRTUAL_NAMESPACE_TYPES.contains(mdType)) {
+ continue;
+ }
+
+ String cacheKey;
+ try {
+ MetadataObject mdObj = metadataObjectFromChangeLog(metalake, fullName, mdType);
+ cacheKey = JcasbinAuthorizationCacheKeys.metadataIdCacheKey(metalake, mdObj);
+ } catch (RuntimeException e) {
+ LOG.warn(
+ "Skipping unmappable entity change log record: metalake={}, type={}, fullName={}",
+ metalake,
+ entityType,
+ fullName,
+ e);
+ continue;
+ }
if (JcasbinAuthorizationCacheKeys.hasNestedMetadataObjects(mdType)) {
addCoalescedPrefix(containerPrefixes, cacheKey);
@@ -258,7 +296,9 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
@VisibleForTesting
static MetadataObject metadataObjectFromChangeLog(
String metalake, String fullName, MetadataObject.Type type) {
- List<String> names = new ArrayList<>(Arrays.asList(fullName.split("\\.")));
+ NameIdentifier ident = EntityChangeLogNameIdentifierCodec.decode(fullName);
+ List<String> names = new ArrayList<>(Arrays.asList(ident.namespace().levels()));
+ names.add(ident.name());
if (type != MetadataObject.Type.METALAKE
&& !names.isEmpty()
&& Objects.equals(names.get(0), metalake)) {
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
index 6bd330fc4c..2315405c63 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
@@ -24,7 +24,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.cache.GravitinoCache;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
@@ -81,6 +83,20 @@ public class TestJcasbinChangePoller {
JcasbinAuthorizationCacheKeys.metadataIdCacheKey("ml1", metalake));
}
+ @Test
+ void testChangeLogFullNamePreservesDotsInsideNameLevels() {
+ NameIdentifier ident =
+ NameIdentifier.of("ml1", "cat.with.dot", "schema.with.dot", "table.with.dot");
+
+ MetadataObject metadataObject =
+ JcasbinChangeListener.metadataObjectFromChangeLog(
+ "ml1", EntityChangeLogNameIdentifierCodec.encode(ident), MetadataObject.Type.TABLE);
+
+ Assertions.assertEquals("cat.with.dot.schema.with.dot", metadataObject.parent());
+ Assertions.assertEquals("table.with.dot", metadataObject.name());
+ Assertions.assertEquals(MetadataObject.Type.TABLE, metadataObject.type());
+ }
+
@Test
void testPollEntityChangesCoalescesContainerPrefixes() {
RecordingCache<String, Long> metadataIdCache = new RecordingCache<>();
@@ -102,6 +118,54 @@ public class TestJcasbinChangePoller {
Assertions.assertEquals(List.of(), metadataIdCache.invalidatedKeys);
}
+ @Test
+ void testVirtualNamespaceTypesAreSkippedWithoutFailingTheBatch() {
+ RecordingCache<String, Long> metadataIdCache = new RecordingCache<>();
+ RecordingCache<Long, Optional<OwnerInfo>> ownerRelCache = new RecordingCache<>();
+
+ JcasbinChangeListener poller = new JcasbinChangeListener(metadataIdCache, ownerRelCache, 1);
+
+ // TAG/POLICY/JOB live in a virtual namespace, so their change-log full name has more levels
+ // than MetadataObjects.of() accepts. They must be skipped, not blow up the whole batch.
+ Assertions.assertDoesNotThrow(
+ () ->
+ poller.onEntityChange(
+ List.of(
+ change(1L, MetadataObject.Type.TAG, "ml1.system.tag.pii"),
+ change(2L, MetadataObject.Type.POLICY, "ml1.system.policy.retention"),
+ change(3L, MetadataObject.Type.JOB, "ml1.system.job.job1"),
+ change(4L, MetadataObject.Type.TABLE, "ml1.cat1.sch1.tbl1"))));
+
+ // The one mappable record in the batch is still applied.
+ Assertions.assertEquals(
+ List.of(key("ml1", "CATALOG", "cat1", "SCHEMA", "sch1", "TABLE", "tbl1", "")),
+ metadataIdCache.invalidatedPrefixes);
+ Assertions.assertEquals(List.of(), metadataIdCache.invalidatedKeys);
+ }
+
+ @Test
+ void testUnmappableRecordDoesNotFailTheBatch() {
+ RecordingCache<String, Long> metadataIdCache = new RecordingCache<>();
+ RecordingCache<Long, Optional<OwnerInfo>> ownerRelCache = new RecordingCache<>();
+
+ JcasbinChangeListener poller = new JcasbinChangeListener(metadataIdCache, ownerRelCache, 1);
+
+ // A record whose full name cannot be turned into a MetadataObject of the declared type must be
+ // logged and skipped; a poison row must never take the node down via the poller's EXIT action.
+ Assertions.assertDoesNotThrow(
+ () ->
+ poller.onEntityChange(
+ List.of(
+ change(1L, MetadataObject.Type.TABLE, "ml1.cat1"),
+ change(2L, MetadataObject.Type.TABLE, "gravitino:v1:9:1:a"),
+ change(3L, MetadataObject.Type.TABLE, "ml1.cat1.sch1.tbl1"))));
+
+ Assertions.assertEquals(
+ List.of(key("ml1", "CATALOG", "cat1", "SCHEMA", "sch1", "TABLE", "tbl1", "")),
+ metadataIdCache.invalidatedPrefixes);
+ Assertions.assertEquals(List.of(), metadataIdCache.invalidatedKeys);
+ }
+
@Test
void testPollCursorAdvancementIsSynchronized() throws NoSuchMethodException {
Method pollOwnerChanges = JcasbinChangeListener.class.getDeclaredMethod("pollOwnerChanges");