World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#7177] feat(core): Add a Caffeine-based implementation for EntityCache (#7200)
Lord of Abyss711d276423f7
diff --git a/LICENSE.bin b/LICENSE.binindex 58f7d0793d..dc0d66c318 100644--- a/LICENSE.bin+++ b/LICENSE.bin@@ -376,6 +376,7 @@RomeJettisonAwaitility+ npgall concurrent-treesThis product bundles various third-party components also under theApache Software Foundation License 1.1diff --git a/core/build.gradle.kts b/core/build.gradle.ktsindex c5f92a6ed7..29948009fa 100644--- a/core/build.gradle.kts+++ b/core/build.gradle.kts@@ -16,6 +16,7 @@* specific language governing permissions and limitations* under the License.*/+import net.ltgt.gradle.errorprone.errorproneplugins {`maven-publish`id("java")@@ -34,6 +35,7 @@ dependencies {implementation(libs.commons.io)implementation(libs.commons.lang3)implementation(libs.commons.collections4)+ implementation(libs.concurrent.trees)implementation(libs.guava)implementation(libs.h2db)implementation(libs.mybatis)@@ -69,3 +71,9 @@ tasks.test {environment("GRAVITINO_HOME", project.rootDir.path + "/distribution/package")}}++tasks.withType<JavaCompile>().configureEach {+ if (name.contains("test", ignoreCase = true)) {+ options.errorprone?.excludedPaths?.set(".*/generated/.*")+ }+}diff --git a/core/src/main/java/org/apache/gravitino/Configs.java b/core/src/main/java/org/apache/gravitino/Configs.javaindex 6801434fe7..3449aecee4 100644--- a/core/src/main/java/org/apache/gravitino/Configs.java+++ b/core/src/main/java/org/apache/gravitino/Configs.java@@ -343,4 +343,50 @@ public class Configs {.stringConf().toSequence().createWithDefault(Collections.emptyList());++ // Whether to enable cache store+ public static final ConfigEntry<Boolean> CACHE_ENABLED =+ new ConfigBuilder("gravitino.cache.enabled")+ .doc("Whether to enable cache store.")+ .version(ConfigConstants.VERSION_0_10_0)+ .booleanConf()+ .createWithDefault(true);++ // Maximum number of entries in the cache+ public static final ConfigEntry<Integer> CACHE_MAX_ENTRIES =+ new ConfigBuilder("gravitino.cache.maxEntries")+ .doc("Maximum number of entries allowed in the cache.")+ .version(ConfigConstants.VERSION_0_10_0)+ .intConf()+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(10_000);++ // Cache entry expiration time+ public static final ConfigEntry<Long> CACHE_EXPIRATION_TIME =+ new ConfigBuilder("gravitino.cache.expireTimeInMs")+ .doc(+ "Time in milliseconds after which a cache entry expires. Default is 3,600,000 ms (1 hour).")+ .version(ConfigConstants.VERSION_0_10_0)+ .longConf()+ .checkValue(value -> value >= 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(3_600_000L);++ // Whether to enable cache statistics logging+ public static final ConfigEntry<Boolean> CACHE_STATS_ENABLED =+ new ConfigBuilder("gravitino.cache.enableStats")+ .doc(+ "Whether to enable cache statistics logging such as hit/miss count, load failures, and size.")+ .version(ConfigConstants.VERSION_0_10_0)+ .booleanConf()+ .createWithDefault(false);++ // Whether to enable weighted cache+ public static final ConfigEntry<Boolean> CACHE_WEIGHER_ENABLED =+ new ConfigBuilder("gravitino.cache.enableWeigher")+ .doc(+ "Whether to enable weighted cache eviction. "+ + "Entries are evicted based on weight instead of count.")+ .version(ConfigConstants.VERSION_0_10_0)+ .booleanConf()+ .createWithDefault(true);}diff --git a/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.javanew file mode 100644index 0000000000..37ceab2448--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java@@ -0,0 +1,162 @@+/*+ * 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;++import com.google.common.base.Preconditions;+import java.util.Collections;+import java.util.EnumMap;+import java.util.List;+import java.util.Map;+import org.apache.gravitino.Config;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.HasIdentifier;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.meta.BaseMetalake;+import org.apache.gravitino.meta.CatalogEntity;+import org.apache.gravitino.meta.ColumnEntity;+import org.apache.gravitino.meta.FilesetEntity;+import org.apache.gravitino.meta.ModelEntity;+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.storage.relational.RelationalEntityStore;++/**+ * An abstract class that provides a basic implementation for the {@link EntityCache} interface.+ * This class is abstract and cannot be instantiated directly, it is designed to be a base class for+ * other entity cache implementations.+ */+public abstract class BaseEntityCache implements EntityCache {+ private static final Map<Entity.EntityType, Class<?>> ENTITY_CLASS_MAP;+ // The entity store used by the cache, initialized through the constructor.+ protected final RelationalEntityStore entityStore;+ protected final Config cacheConfig;++ static {+ Map<Entity.EntityType, Class<?>> map = new EnumMap<>(Entity.EntityType.class);+ map.put(Entity.EntityType.METALAKE, BaseMetalake.class);+ map.put(Entity.EntityType.CATALOG, CatalogEntity.class);+ map.put(Entity.EntityType.SCHEMA, SchemaEntity.class);+ map.put(Entity.EntityType.TABLE, TableEntity.class);+ map.put(Entity.EntityType.FILESET, FilesetEntity.class);+ map.put(Entity.EntityType.MODEL, ModelEntity.class);+ map.put(Entity.EntityType.TOPIC, TopicEntity.class);+ map.put(Entity.EntityType.TAG, TagEntity.class);+ map.put(Entity.EntityType.MODEL_VERSION, ModelVersionEntity.class);+ map.put(Entity.EntityType.COLUMN, ColumnEntity.class);+ map.put(Entity.EntityType.USER, UserEntity.class);+ map.put(Entity.EntityType.GROUP, Entity.class);+ map.put(Entity.EntityType.ROLE, RoleEntity.class);+ ENTITY_CLASS_MAP = Collections.unmodifiableMap(map);+ }++ /**+ * Constructs a new {@link BaseEntityCache} instance.+ *+ * @param entityStore The entity store to be used by the cache.+ */+ public BaseEntityCache(Config config, EntityStore entityStore) {+ Preconditions.checkArgument(config != null, "Config must not be null");+ Preconditions.checkArgument(entityStore != null, "EntityStore must not be null");++ this.cacheConfig = config;+ this.entityStore = (RelationalEntityStore) entityStore;+ }++ /**+ * Returns the class of the entity based on its type.+ *+ * @param type The entity type+ * @return The class of the entity+ * @throws IllegalArgumentException if the entity type is not supported+ */+ @SuppressWarnings("unchecked")+ public static <E extends Entity & HasIdentifier> Class<E> getEntityClass(Entity.EntityType type) {+ Preconditions.checkArgument(type != null, "EntityType must not be null");++ Class<?> clazz = ENTITY_CLASS_MAP.get(type);+ Preconditions.checkArgument(clazz != null, "Unsupported EntityType: " + type);++ return (Class<E>) clazz;+ }++ /**+ * Returns the {@link NameIdentifier} of the entity based on its type.+ *+ * @param entity The {@link Entity} instance.+ * @return The {@link NameIdentifier} of the entity+ */+ protected static NameIdentifier getIdentFromEntity(Entity entity) {+ validateEntityHasIdentifier(entity);+ HasIdentifier hasIdentifier = (HasIdentifier) entity;++ return hasIdentifier.nameIdentifier();+ }++ /**+ * Checks if the entity is of type {@link HasIdentifier}.+ *+ * @param entity The {@link Entity} instance to check.+ */+ protected static void validateEntityHasIdentifier(Entity entity) {+ Preconditions.checkArgument(+ entity instanceof HasIdentifier, "Unsupported EntityType: " + entity.type());+ }++ /**+ * Converts a list of entities to a new list with the target entity type.+ *+ * @param entities Thr original list of entities.+ * @return A list of converted entities.+ * @param <E> The type of the entities in the new list.+ */+ @SuppressWarnings("unchecked")+ protected static <E extends Entity & HasIdentifier> List<E> convertEntity(List<Entity> entities) {+ entities.forEach(BaseEntityCache::validateEntityHasIdentifier);++ return (List<E>) (List<? extends Entity>) entities;+ }++ /**+ * Converts an entity to a new one.+ *+ * @param entity The original entity.+ * @return A new entity.+ * @param <E> The type of the new entity.+ */+ @SuppressWarnings("unchecked")+ protected static <E extends Entity & HasIdentifier> E convertEntity(Entity entity) {+ validateEntityHasIdentifier(entity);++ return (E) entity;+ }++ /**+ * Removes an expired entity from the data cache.+ *+ * @param key The expired entity key to remove.+ */+ protected abstract void invalidateExpiredItem(EntityCacheKey key);+}diff --git a/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.javanew file mode 100644index 0000000000..c002bf64fe--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java@@ -0,0 +1,558 @@+/*+ * 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;++import com.github.benmanes.caffeine.cache.Cache;+import com.github.benmanes.caffeine.cache.Caffeine;+import com.github.benmanes.caffeine.cache.RemovalCause;+import com.github.benmanes.caffeine.cache.stats.CacheStats;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import com.google.common.collect.Lists;+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;+import com.googlecode.concurrenttrees.radix.RadixTree;+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;+import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import java.util.concurrent.ArrayBlockingQueue;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.locks.ReentrantLock;+import java.util.function.Supplier;+import java.util.stream.Collectors;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.HasIdentifier;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.SupportsRelationOperations;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/** This class implements the {@link EntityCache} using Caffeine. */+public class CaffeineEntityCache extends BaseEntityCache {+ private static final int CACHE_CLEANUP_CORE_THREADS = 1;+ private static final int CACHE_CLEANUP_MAX_THREADS = 1;+ private static final int CACHE_CLEANUP_QUEUE_CAPACITY = 100;+ private static final int CACHE_MONITOR_PERIOD_MINUTES = 5;+ private static final int CACHE_MONITOR_INITIAL_DELAY_MINUTES = 0;+ private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());+ private static volatile CaffeineEntityCache INSTANCE;+ private final ReentrantLock opLock = new ReentrantLock();++ /** Cache part */+ private final Cache<EntityCacheKey, List<Entity>> cacheData;++ /** Index part */+ private RadixTree<EntityCacheKey> cacheIndex;++ private ScheduledExecutorService scheduler;++ @VisibleForTesting+ static void resetForTest() {+ INSTANCE = null;+ }++ /**+ * Returns the instance of {@link CaffeineEntityCache} based on the cache configuration and entity+ * store.+ *+ * @param cacheConfig The cache configuration+ * @param entityStore The entity store to load entities from the database+ * @return The instance of {@link CaffeineEntityCache}+ */+ public static CaffeineEntityCache getInstance(Config cacheConfig, EntityStore entityStore) {+ if (INSTANCE == null) {+ synchronized (CaffeineEntityCache.class) {+ if (INSTANCE == null) {+ INSTANCE = new CaffeineEntityCache(cacheConfig, entityStore);+ }+ }+ }+ return INSTANCE;+ }++ /**+ * Constructs a new {@link CaffeineEntityCache}.+ *+ * @param cacheConfig the cache configuration+ * @param entityStore The entity store to load entities from the database+ */+ private CaffeineEntityCache(Config cacheConfig, EntityStore entityStore) {+ super(cacheConfig, entityStore);+ this.cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());++ ThreadPoolExecutor cleanupExec = buildCleanupExecutor();+ Caffeine<EntityCacheKey, List<Entity>> cacheDataBuilder = newBaseBuilder(cacheConfig);++ cacheDataBuilder+ .executor(cleanupExec)+ .removalListener(+ (key, value, cause) -> {+ if (cause == RemovalCause.EXPLICIT || cause == RemovalCause.REPLACED) {+ return;+ }+ try {+ invalidateExpiredItem(key);+ } catch (Throwable t) {+ LOG.error(+ "Failed to remove entity key={} value={} from cache asynchronously, cause={}",+ key,+ value,+ cause,+ t);+ }+ });++ this.cacheData = cacheDataBuilder.build();++ if (cacheConfig.get(Configs.CACHE_STATS_ENABLED)) {+ this.scheduler = Executors.newSingleThreadScheduledExecutor();+ startCacheStatsMonitor();+ }+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> List<E> getOrLoad(+ NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relType)+ throws IOException {+ checkArguments(ident, type, relType);++ // Executes a thread-safe operation: attempts to load the entity from the cache,+ // falls back to the underlying store if not present, and updates the cache.+ // If an error occurs during loading, the exception will be propagated.+ return withLockAndThrow(+ () -> {+ EntityCacheKey entityCacheKey = EntityCacheKey.of(ident, type, relType);+ List<Entity> entitiesFromCache = cacheData.getIfPresent(entityCacheKey);++ if (entitiesFromCache != null) {+ return convertEntity(entitiesFromCache);+ }++ List<E> entities = entityStore.listEntitiesByRelation(relType, ident, type);+ syncEntitiesToCache(+ entityCacheKey, entities.stream().map(e -> (Entity) e).collect(Collectors.toList()));++ return entities;+ });+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> E getOrLoad(+ NameIdentifier ident, Entity.EntityType type) throws IOException {+ checkArguments(ident, type);++ // Executes a thread-safe operation: attempts to load the entity from the cache,+ // falls back to the underlying store if not present, and updates the cache.+ // If an error occurs during loading, the exception will be propagated.+ return withLockAndThrow(+ () -> {+ EntityCacheKey entityCacheKey = EntityCacheKey.of(ident, type);+ List<Entity> entitiesFromCache = cacheData.getIfPresent(entityCacheKey);++ if (entitiesFromCache != null) {+ return convertEntity(entitiesFromCache.get(0));+ }++ E entityFromStore = entityStore.get(ident, type, getEntityClass(type));+ syncEntitiesToCache(entityCacheKey, Lists.newArrayList(entityFromStore));++ return entityFromStore;+ });+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> Optional<List<E>> getIfPresent(+ SupportsRelationOperations.Type relType,+ NameIdentifier nameIdentifier,+ Entity.EntityType identType) {+ checkArguments(nameIdentifier, identType, relType);++ return withLock(+ () -> {+ List<Entity> entitiesFromCache =+ cacheData.getIfPresent(EntityCacheKey.of(nameIdentifier, identType, relType));+ return Optional.ofNullable(entitiesFromCache).map(BaseEntityCache::convertEntity);+ });+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> Optional<E> getIfPresent(+ NameIdentifier ident, Entity.EntityType type) {+ checkArguments(ident, type);++ return withLock(+ () -> {+ List<Entity> entitiesFromCache = cacheData.getIfPresent(EntityCacheKey.of(ident, type));++ return Optional.ofNullable(entitiesFromCache)+ .filter(l -> !l.isEmpty())+ .map(entities -> convertEntity(entities.get(0)));+ });+ }++ /** {@inheritDoc} */+ @Override+ public boolean invalidate(+ NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relType) {+ checkArguments(ident, type, relType);++ return withLock(+ () -> {+ boolean existed = contains(ident, type, relType);+ if (existed) {+ invalidateEntities(ident);+ }++ return existed;+ });+ }++ /** {@inheritDoc} */+ @Override+ public boolean invalidate(NameIdentifier ident, Entity.EntityType type) {+ checkArguments(ident, type);++ return withLock(+ () -> {+ boolean existed = contains(ident, type);+ if (existed) {+ invalidateEntities(ident);+ }++ return existed;+ });+ }++ /** {@inheritDoc} */+ @Override+ public boolean contains(+ NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relType) {+ checkArguments(ident, type, relType);++ return withLock(() -> cacheData.getIfPresent(EntityCacheKey.of(ident, type, relType)) != null);+ }++ /** {@inheritDoc} */+ @Override+ public boolean contains(NameIdentifier ident, Entity.EntityType type) {+ checkArguments(ident, type);++ return withLock(() -> cacheData.getIfPresent(EntityCacheKey.of(ident, type)) != null);+ }++ /** {@inheritDoc} */+ @Override+ public long size() {+ return cacheData.estimatedSize();+ }++ /** {@inheritDoc} */+ @Override+ public void clear() {+ withLock(+ () -> {+ cacheData.invalidateAll();+ cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());+ });+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> void put(+ NameIdentifier ident,+ Entity.EntityType type,+ SupportsRelationOperations.Type relType,+ List<E> entities) {+ checkArguments(ident, type, relType);+ Preconditions.checkArgument(entities != null, "Entities cannot be null");++ syncEntitiesToCache(+ EntityCacheKey.of(ident, type, relType),+ entities.stream().map(e -> (Entity) e).collect(Collectors.toList()));+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Entity & HasIdentifier> void put(E entity) {+ Preconditions.checkArgument(entity != null, "Entity cannot be null");++ withLock(+ () -> {+ NameIdentifier identifier = getIdentFromEntity(entity);+ EntityCacheKey entityCacheKey = EntityCacheKey.of(identifier, entity.type());+ syncEntitiesToCache(entityCacheKey, Lists.newArrayList(entity));+ });+ }++ /** {@inheritDoc} */+ @Override+ public <E extends Exception> void withCacheLock(ThrowingRunnable<E> action) throws E {+ Preconditions.checkArgument(action != null, "Action cannot be null");++ withLockAndThrow(action);+ }++ /** {@inheritDoc} */+ @Override+ public <E, T extends Exception> E withCacheLock(ThrowingSupplier<E, T> action) throws T {+ Preconditions.checkArgument(action != null, "Action cannot be null");++ return withLockAndThrow(action);+ }++ /**+ * Removes the expired entity from the cache. This method is a hook method for the Cache, when an+ * entry expires, it will call this method.+ *+ * @param key The key of the expired entity+ */+ @Override+ protected void invalidateExpiredItem(EntityCacheKey key) {+ withLock(+ () -> {+ cacheIndex.remove(key.toString());+ });+ }++ /**+ * Syncs the entities to the cache, if entities is too big and can not put to the cache, then it+ * will be removed from the cache and cacheIndex will not be updated.+ *+ * @param key The key of the entities.+ * @param newEntities The new entities to sync to the cache.+ */+ private void syncEntitiesToCache(EntityCacheKey key, List<Entity> newEntities) {+ List<Entity> existingEntities = cacheData.getIfPresent(key);++ if (existingEntities != null && key.relationType() != null) {+ List<Entity> merged = new ArrayList<>(existingEntities);+ merged.addAll(newEntities);++ cacheData.put(key, merged);+ } else {+ cacheData.put(key, newEntities);+ }++ if (cacheData.policy().getIfPresentQuietly(key) != null) {+ cacheIndex.put(key.toString(), key);+ }+ }++ /**+ * Returns a new instance of Caffeine cache builder.+ *+ * @param cacheConfig The cache configuration+ * @param <KEY> The key type+ * @param <VALUE> The value type+ * @return The new instance of Caffeine cache builder+ */+ @SuppressWarnings("unchecked")+ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {+ Caffeine<Object, Object> builder = Caffeine.newBuilder();++ if (cacheConfig.get(Configs.CACHE_WEIGHER_ENABLED)) {+ builder.maximumWeight(EntityCacheWeigher.getMaxWeight());+ builder.weigher(EntityCacheWeigher.getInstance());+ } else {+ builder.maximumSize(cacheConfig.get(Configs.CACHE_MAX_ENTRIES));+ }++ if (cacheConfig.get(Configs.CACHE_EXPIRATION_TIME) > 0) {+ builder.expireAfterWrite(+ cacheConfig.get(Configs.CACHE_EXPIRATION_TIME), TimeUnit.MILLISECONDS);+ }++ if (cacheConfig.get(Configs.CACHE_STATS_ENABLED)) {+ builder.recordStats();+ }++ return (Caffeine<KEY, VALUE>) builder;+ }++ /**+ * Invalidates the entities by the given cache key.+ *+ * @param identifier The identifier of the entity to invalidate+ */+ private void invalidateEntities(NameIdentifier identifier) {+ Iterable<EntityCacheKey> entityKeysToRemove =+ cacheIndex.getValuesForKeysStartingWith(identifier.toString());++ cacheData.invalidateAll(entityKeysToRemove);+ entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));+ }++ /**+ * Runs the given action with the lock.+ *+ * @param action The action to run with the lock+ */+ private void withLock(Runnable action) {+ try {+ opLock.lockInterruptibly();+ try {+ action.run();+ } finally {+ opLock.unlock();+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("Thread was interrupted while waiting for lock", e);+ }+ }++ /**+ * Runs the given action with the lock and returns the result.+ *+ * @param action The action to run with the lock+ * @return The result of the action+ * @param <T> The type of the result+ */+ private <T> T withLock(Supplier<T> action) {+ try {+ opLock.lockInterruptibly();+ try {+ return action.get();+ } finally {+ opLock.unlock();+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("Thread was interrupted while waiting for lock", e);+ }+ }++ /**+ * Runs the given action with the lock and throws the exception if it occurs.+ *+ * @param action The action to run with the lock+ * @param <T> The type of the result+ * @return The result of the action+ * @throws IOException If an exception occurs during the action+ */+ private <T, E extends Exception> T withLockAndThrow(ThrowingSupplier<T, E> action) throws E {+ try {+ opLock.lockInterruptibly();+ try {+ return action.get();+ } finally {+ opLock.unlock();+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("Thread was interrupted while waiting for lock", e);+ }+ }++ /**+ * Runs the given action with the lock and throws the exception if it occurs.+ *+ * @param action The action to run with the lock+ * @param <E> The type of the exception+ * @throws E If an exception occurs during the action+ */+ private <E extends Exception> void withLockAndThrow(ThrowingRunnable<E> action) throws E {+ try {+ opLock.lockInterruptibly();+ try {+ action.run();+ } finally {+ opLock.unlock();+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("Thread was interrupted while waiting for lock", e);+ }+ }++ /**+ * Builds the cleanup executor.+ *+ * @return The cleanup executor+ */+ private ThreadPoolExecutor buildCleanupExecutor() {+ return new ThreadPoolExecutor(+ CACHE_CLEANUP_CORE_THREADS,+ CACHE_CLEANUP_MAX_THREADS,+ 0L,+ TimeUnit.MILLISECONDS,+ new ArrayBlockingQueue<>(CACHE_CLEANUP_QUEUE_CAPACITY),+ r -> {+ Thread t = new Thread(r, "CaffeineEntityCache-Cleanup");+ t.setDaemon(true);+ return t;+ },+ new ThreadPoolExecutor.CallerRunsPolicy());+ }++ /** Starts the cache stats monitor. */+ private void startCacheStatsMonitor() {+ scheduler.scheduleAtFixedRate(+ () -> {+ CacheStats stats = cacheData.stats();+ LOG.info(+ "[Cache Stats] hitRate={}, hitCount={}, missCount={}, loadSuccess={}, loadFailure={}, evictions={}",+ String.format("%.4f", stats.hitRate()),+ stats.hitCount(),+ stats.missCount(),+ stats.loadSuccessCount(),+ stats.loadFailureCount(),+ stats.evictionCount());+ },+ CACHE_MONITOR_INITIAL_DELAY_MINUTES,+ CACHE_MONITOR_PERIOD_MINUTES,+ TimeUnit.MINUTES);+ }++ /**+ * Checks the arguments for the methods. All arguments must not be null.+ *+ * @param ident The identifier of the entity to check+ * @param type The type of the entity to check+ * @param relType The relation type of the entity to check+ */+ private void checkArguments(+ NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relType) {+ checkArguments(ident, type);+ Preconditions.checkArgument(relType != null, "relType cannot be null");+ }++ /**+ * Checks the arguments for the methods. All arguments must not be null.+ *+ * @param ident The identifier of the entity to check+ * @param type The type of the entity to check+ */+ private void checkArguments(NameIdentifier ident, Entity.EntityType type) {+ Preconditions.checkArgument(ident != null, "NameIdentifier cannot be null");+ Preconditions.checkArgument(type != null, "EntityType cannot be null");+ }+}diff --git a/core/src/main/java/org/apache/gravitino/cache/EntityCacheWeigher.java b/core/src/main/java/org/apache/gravitino/cache/EntityCacheWeigher.javanew file mode 100644index 0000000000..8fe8c5e255--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/cache/EntityCacheWeigher.java@@ -0,0 +1,121 @@+/*+ * 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;++import com.github.benmanes.caffeine.cache.Weigher;+import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableMap;+import java.util.List;+import java.util.Map;+import lombok.NonNull;+import org.apache.gravitino.Entity;+import org.checkerframework.checker.index.qual.NonNegative;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * A {@link Weigher} implementation that calculates the weight of an entity based on its type. The+ * weight is calculated as follows:+ *+ * <ul>+ * <li>Metalake: 100+ * <li>Catalog: 75+ * <li>Schema: 50+ * <li>Other: 15+ * </ul>+ */+public class EntityCacheWeigher implements Weigher<EntityCacheKey, List<Entity>> {+ public static final int METALAKE_WEIGHT = 100;+ public static final int CATALOG_WEIGHT = 75;+ public static final int SCHEMA_WEIGHT = 50;+ public static final int OTHER_WEIGHT = 15;+ private static final Logger LOG = LoggerFactory.getLogger(EntityCacheWeigher.class.getName());+ private static final EntityCacheWeigher INSTANCE = new EntityCacheWeigher();+ private static final Map<Entity.EntityType, Integer> ENTITY_WEIGHTS =+ ImmutableMap.of(+ Entity.EntityType.METALAKE, METALAKE_WEIGHT,+ Entity.EntityType.CATALOG, CATALOG_WEIGHT,+ Entity.EntityType.SCHEMA, SCHEMA_WEIGHT);+ public static long MAX_WEIGHT =+ 2 * (METALAKE_WEIGHT * 10 + CATALOG_WEIGHT * (10 * 200) + SCHEMA_WEIGHT * (10 * 200 * 1000));++ private EntityCacheWeigher() {}++ /**+ * Returns the maximum weight that can be stored in the cache.+ *+ * <p>The total weight is estimated based on the expected number of entities:+ *+ * <ul>+ * <li>~10 Metalakes per Gravitino instance+ * <li>~200 Catalogs per Metalake+ * <li>~1000 Schemas per Catalog+ * </ul>+ *+ * <p>The total estimated entity count is:+ *+ * <pre>+ * 10 * METALAKE_WEIGHT+ * + (10 * 200) * CATALOG_WEIGHT+ * + (10 * 200 * 1000) * SCHEMA_WEIGHT+ * </pre>+ *+ * <p>To provide headroom and avoid early eviction, the result is multiplied by 2:+ *+ * <pre>+ * total = 2 * (10 * METALAKE_WEIGHT + 2000 * CATALOG_WEIGHT + 2_000_000 * SCHEMA_WEIGHT)+ * </pre>+ *+ * @return The maximum weight that can be stored in the cache.+ */+ public static long getMaxWeight() {+ return MAX_WEIGHT;+ }++ /**+ * Returns the singleton instance of the {@link EntityCacheWeigher}.+ *+ * @return the singleton instance of the {@link EntityCacheWeigher}.+ */+ public static EntityCacheWeigher getInstance() {+ return INSTANCE;+ }++ /** {@inheritDoc} */+ @Override+ public @NonNegative int weigh(+ @NonNull EntityCacheKey storeEntityCacheKey, @NonNull List<Entity> entities) {+ int weight = 0;+ for (Entity entity : entities) {+ weight += calculateWeight(entity.type());+ }++ if (weight > getMaxWeight()) {+ LOG.warn("Entity group exceeds max weight: {}", weight);+ }++ return weight;+ }++ private int calculateWeight(Entity.EntityType entityType) {+ Preconditions.checkArgument(entityType != null, "entityType cannot be null");+ return ENTITY_WEIGHTS.getOrDefault(entityType, OTHER_WEIGHT);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/cache/SupportsRelationEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/SupportsRelationEntityCache.javaindex 7f5616a550..42db55ca1f 100644--- a/core/src/main/java/org/apache/gravitino/cache/SupportsRelationEntityCache.java+++ b/core/src/main/java/org/apache/gravitino/cache/SupportsRelationEntityCache.java@@ -88,13 +88,17 @@ public interface SupportsRelationEntityCache {NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relType);/**- * Puts a relation between two entities into the cache.+ * Puts a list of related entities into the cache.*- * @param srcEntity The source entity- * @param destEntity The destination entity- * @param relType The relation type- * @param <E> The class of the entities+ * @param ident The name identifier of the entity to cache the related entities for+ * @param type The type of the entity to cache the related entities for+ * @param relType The relation type to cache the related entities for+ * @param entities The list of related entities to cache+ * @param <E> The class of the related entities*/<E extends Entity & HasIdentifier> void put(- E srcEntity, E destEntity, SupportsRelationOperations.Type relType);+ NameIdentifier ident,+ Entity.EntityType type,+ SupportsRelationOperations.Type relType,+ List<E> entities);}diff --git a/core/src/test/java/org/apache/gravitino/cache/TestCacheConfig.java b/core/src/test/java/org/apache/gravitino/cache/TestCacheConfig.javanew file mode 100644index 0000000000..4316b777f5--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/cache/TestCacheConfig.java@@ -0,0 +1,49 @@+/*+ * 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;++import com.google.common.collect.Lists;+import java.util.ArrayList;+import java.util.Optional;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestCacheConfig {+ @Test+ void testDefaultCacheConfig() {+ Config config = new Config(false) {};+ Assertions.assertFalse(config.get(Configs.CACHE_STATS_ENABLED));+ Assertions.assertTrue(config.get(Configs.CACHE_ENABLED));+ Assertions.assertTrue(config.get(Configs.CACHE_WEIGHER_ENABLED));+ Assertions.assertEquals(10_000, config.get(Configs.CACHE_MAX_ENTRIES));+ Assertions.assertEquals(3_600_000L, config.get(Configs.CACHE_EXPIRATION_TIME));+ Assertions.assertEquals(200_302_000L, EntityCacheWeigher.getMaxWeight());+ }++ @Test+ void test() {+ ArrayList<Integer> list = Lists.newArrayList();+ Optional<Integer> i =+ Optional.ofNullable(list).filter(entities -> !entities.isEmpty()).map(l -> l.get(0));+ Assertions.assertFalse(i.isPresent());+ }+}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex a157bb13d0..77d1ebf3dd 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -119,6 +119,7 @@ hudi = "0.15.0"google-auth = "1.28.0"aliyun-credentials = "0.3.12"openlineage = "1.29.0"+concurrent-trees = "2.6.0"[libraries]aws-iam = { group = "software.amazon.awssdk", name = "iam", version.ref = "awssdk" }@@ -282,6 +283,8 @@ aliyun-credentials-sdk = { group='com.aliyun', name='credentials-java', version.flinkjdbc = {group='org.apache.flink',name='flink-connector-jdbc', version.ref='flinkjdbc'}openlineage-java= { group = "io.openlineage", name = "openlineage-java", version.ref = "openlineage" }+concurrent-trees = { group = "com.googlecode.concurrent-trees", name = "concurrent-trees", version.ref = "concurrent-trees" }+[bundles]log4j = ["slf4j-api", "log4j-slf4j2-impl", "log4j-api", "log4j-core", "log4j-12-api", "log4j-layout-template-json"]jetty = ["jetty-server", "jetty-servlet", "jetty-webapp", "jetty-servlets"]