MaxComputeExternalMetaCache.java

// 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.doris.datasource.maxcompute;

import org.apache.doris.catalog.Env;
import org.apache.doris.common.Config;
import org.apache.doris.datasource.CacheException;
import org.apache.doris.datasource.CatalogIf;
import org.apache.doris.datasource.ExternalCatalog;
import org.apache.doris.datasource.ExternalTable;
import org.apache.doris.datasource.SchemaCacheKey;
import org.apache.doris.datasource.SchemaCacheValue;
import org.apache.doris.datasource.TablePartitionValues;
import org.apache.doris.datasource.metacache.AbstractExternalMetaCache;
import org.apache.doris.datasource.metacache.CacheSpec;
import org.apache.doris.datasource.metacache.MetaCacheEntry;
import org.apache.doris.datasource.metacache.MetaCacheEntryDef;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;

/**
 * MaxCompute engine implementation of {@link AbstractExternalMetaCache}.
 *
 * <p>Registered entries:
 * <ul>
 *   <li>{@code metadata}: per-catalog {@link MaxComputeMetadataCache} stored under a fixed key</li>
 *   <li>{@code schema}: schema cache keyed by {@link SchemaCacheKey}</li>
 * </ul>
 *
 * <p>The metadata cache entry is a container for multiple inner caches (partition values,
 * table info and related objects). Database/table invalidation first delegates to that
 * container, then invalidates schema entries.
 *
 * <p>Partition-level invalidation currently follows table-level invalidation semantics.
 */
public class MaxComputeExternalMetaCache extends AbstractExternalMetaCache {
    public static final String ENGINE = "maxcompute";
    public static final String ENTRY_METADATA = "metadata";
    public static final String ENTRY_SCHEMA = "schema";
    private static final String METADATA_KEY = "__default__";
    private static final CacheSpec SCHEMA_CACHE_SPEC = CacheSpec.fromTtlValue(
            null, Config.external_cache_expire_time_seconds_after_access, Config.max_external_schema_cache_num);

    private final MetaCacheEntryDef<String, MaxComputeMetadataCache> metadataEntryDef;
    private final MetaCacheEntryDef<SchemaCacheKey, SchemaCacheValue> schemaEntryDef;

    public MaxComputeExternalMetaCache(ExecutorService refreshExecutor) {
        super(ENGINE, refreshExecutor);
        metadataEntryDef = MetaCacheEntryDef.of(
                ENTRY_METADATA,
                String.class,
                MaxComputeMetadataCache.class,
                ignored -> new MaxComputeMetadataCache(),
                DEFAULT_ENTRY_CACHE_SPEC);
        schemaEntryDef = MetaCacheEntryDef.of(
                ENTRY_SCHEMA,
                SchemaCacheKey.class,
                SchemaCacheValue.class,
                this::loadSchemaCacheValue,
                SCHEMA_CACHE_SPEC);
        registerMetaCacheEntryDef(metadataEntryDef);
        registerMetaCacheEntryDef(schemaEntryDef);
    }

    public MaxComputeMetadataCache getMaxComputeMetadataCache(long catalogId) {
        return metadataEntry(catalogId).get(METADATA_KEY);
    }

    public TablePartitionValues getCachedPartitionValues(long catalogId, MaxComputeCacheKey key,
            Function<? super MaxComputeCacheKey, ? extends TablePartitionValues> loader) {
        return getMaxComputeMetadataCache(catalogId).getCachedPartitionValues(key, loader);
    }

    public MaxComputeSchemaCacheValue getMaxComputeSchemaCacheValue(long catalogId, SchemaCacheKey key) {
        SchemaCacheValue schemaCacheValue = schemaEntry(catalogId).get(key);
        return (MaxComputeSchemaCacheValue) schemaCacheValue;
    }

    @Override
    public void invalidateCatalog(long catalogId) {
        MaxComputeMetadataCache metadataCache = metadataCacheIfPresent(catalogId);
        if (metadataCache != null) {
            metadataCache.cleanUp();
        }
        super.invalidateCatalog(catalogId);
    }

    @Override
    public void invalidateDb(long catalogId, String dbName) {
        MaxComputeMetadataCache metadataCache = metadataCacheIfPresent(catalogId);
        if (metadataCache != null) {
            metadataCache.cleanDatabaseCache(dbName);
        }
        schemaEntry(catalogId).invalidateIf(key -> key.getNameMapping().getLocalDbName().equals(dbName));
    }

    @Override
    public void invalidateTable(long catalogId, String dbName, String tableName) {
        MaxComputeMetadataCache metadataCache = metadataCacheIfPresent(catalogId);
        if (metadataCache != null) {
            metadataCache.cleanTableCache(dbName, tableName);
        }
        schemaEntry(catalogId).invalidateIf(key -> key.getNameMapping().getLocalDbName().equals(dbName)
                && key.getNameMapping().getLocalTblName().equals(tableName));
    }

    @Override
    public void invalidatePartitions(long catalogId, String dbName, String tableName, List<String> partitions) {
        invalidateTable(catalogId, dbName, tableName);
    }

    private MetaCacheEntry<String, MaxComputeMetadataCache> metadataEntry(long catalogId) {
        return entry(catalogId, metadataEntryDef);
    }

    private MetaCacheEntry<SchemaCacheKey, SchemaCacheValue> schemaEntry(long catalogId) {
        return entry(catalogId, schemaEntryDef);
    }

    private MaxComputeMetadataCache metadataCacheIfPresent(long catalogId) {
        try {
            return metadataEntry(catalogId).getIfPresent(METADATA_KEY);
        } catch (IllegalStateException e) {
            return null;
        }
    }

    private SchemaCacheValue loadSchemaCacheValue(SchemaCacheKey key) {
        ExternalTable dorisTable = findExternalTable(key);
        return dorisTable.initSchemaAndUpdateTime(key).orElseThrow(() ->
                new CacheException("failed to load maxcompute schema cache value for: %s.%s.%s",
                        null, key.getNameMapping().getCtlId(), key.getNameMapping().getLocalDbName(),
                        key.getNameMapping().getLocalTblName()));
    }

    @Override
    protected Map<String, String> catalogPropertyCompatibilityMap() {
        return Collections.singletonMap(
                ExternalCatalog.SCHEMA_CACHE_TTL_SECOND,
                "meta.cache." + ENGINE + "." + ENTRY_SCHEMA + ".ttl-second");
    }

    private ExternalTable findExternalTable(SchemaCacheKey key) {
        CatalogIf<?> catalog = Env.getCurrentEnv().getCatalogMgr().getCatalog(key.getNameMapping().getCtlId());
        if (!(catalog instanceof ExternalCatalog)) {
            throw new CacheException("catalog %s is not external when loading maxcompute schema cache",
                    null, key.getNameMapping().getCtlId());
        }
        ExternalCatalog externalCatalog = (ExternalCatalog) catalog;
        return externalCatalog.getDb(key.getNameMapping().getLocalDbName())
                .flatMap(db -> db.getTable(key.getNameMapping().getLocalTblName()))
                .orElseThrow(() -> new CacheException(
                        "table %s.%s.%s not found when loading maxcompute schema cache",
                        null, key.getNameMapping().getCtlId(), key.getNameMapping().getLocalDbName(),
                        key.getNameMapping().getLocalTblName()));
    }
}