Caideyipi commented on code in PR #16425: URL: https://github.com/apache/iotdb/pull/16425#discussion_r2357277962
########## iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/cache/schema/DeviceSchemaCache.java: ########## @@ -0,0 +1,335 @@ +/* + * 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.iotdb.db.queryengine.plan.analyze.cache.schema; + +import org.apache.iotdb.commons.exception.IllegalPathException; +import org.apache.iotdb.commons.path.PartialPath; +import org.apache.iotdb.commons.path.PathPatternUtil; +import org.apache.iotdb.commons.service.metric.MetricService; +import org.apache.iotdb.db.conf.IoTDBConfig; +import org.apache.iotdb.db.conf.IoTDBDescriptor; +import org.apache.iotdb.db.queryengine.common.schematree.DeviceSchemaInfo; +import org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.IDualKeyCache; +import org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.impl.DualKeyCacheBuilder; +import org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.impl.DualKeyCachePolicy; + +import org.apache.tsfile.common.constant.TsFileConstant; +import org.apache.tsfile.file.metadata.IDeviceID; +import org.apache.tsfile.read.TimeValuePair; +import org.apache.tsfile.utils.RamUsageEstimator; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.concurrent.ThreadSafe; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Predicate; +import java.util.function.ToIntFunction; + +/** + * The {@link DeviceSchemaCache} caches some of the devices and their: measurement info / template + * info. The last value of one device is also cached here. + */ +@ThreadSafe +public class DeviceSchemaCache { + + private static final IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig(); + private static final Logger logger = LoggerFactory.getLogger(DeviceSchemaCache.class); + + /** + * Leading_Segment, {@link IDeviceID}, Map{@literal <}Measurement, Schema{@literal + * >}/templateInfo{@literal >} + * + * <p>The segment is used to: + * + * <p>1. Keep abreast of the newer versions. + * + * <p>2. Optimize the speed in invalidation by databases for most scenarios. + */ + private final IDualKeyCache<String, PartialPath, DeviceCacheEntry> dualKeyCache; + + private final Map<String, String> databasePool = new ConcurrentHashMap<>(); + + private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(false); + + DeviceSchemaCache() { + dualKeyCache = + new DualKeyCacheBuilder<String, PartialPath, DeviceCacheEntry>() + .cacheEvictionPolicy( + DualKeyCachePolicy.valueOf(config.getDataNodeSchemaCacheEvictionPolicy())) + .memoryCapacity(config.getAllocateMemoryForSchemaCache()) + .firstKeySizeComputer(segment -> (int) RamUsageEstimator.sizeOf(segment)) + .secondKeySizeComputer(PartialPath::estimateSize) + .valueSizeComputer(DeviceCacheEntry::estimateSize) + .build(); + MetricService.getInstance().addMetricSet(new DataNodeSchemaCacheMetrics(this)); + } + + /////////////////////////////// Last Cache /////////////////////////////// + + /** + * Get the last {@link TimeValuePair} of a measurement, the measurement shall never be "time". + * + * @param device {@link IDeviceID} + * @param measurement the measurement to get + * @return {@code null} iff cache miss, {@link DeviceLastCache#EMPTY_TIME_VALUE_PAIR} iff cache + * hit but result is {@code null}, and the result value otherwise. + */ + public TimeValuePair getLastEntry(final PartialPath device, final String measurement) { + final DeviceCacheEntry entry = dualKeyCache.get(getLeadingSegment(device), device); + return Objects.nonNull(entry) ? entry.getTimeValuePair(measurement) : null; + } + + /** + * Invalidate the last cache of one device. + * + * @param device IDeviceID + */ + public void invalidateDeviceLastCache(final PartialPath device) { + dualKeyCache.update( + getLeadingSegment(device), device, null, entry -> -entry.invalidateLastCache(), false); + } + + /////////////////////////////// Tree model /////////////////////////////// + + public void putDeviceSchema(final String database, final DeviceSchemaInfo deviceSchemaInfo) { + final PartialPath devicePath = deviceSchemaInfo.getDevicePath(); + final String previousDatabase = databasePool.putIfAbsent(database, database); + + dualKeyCache.update( + getLeadingSegment(devicePath), + devicePath, + new DeviceCacheEntry(), + entry -> + entry.setDeviceSchema( + Objects.nonNull(previousDatabase) ? previousDatabase : database, deviceSchemaInfo), + true); + } + + public IDeviceSchema getDeviceSchema(final PartialPath device) { + final DeviceCacheEntry entry = dualKeyCache.get(getLeadingSegment(device), device); + return Objects.nonNull(entry) ? entry.getDeviceSchema() : null; + } + + void updateLastCache( + final String database, + final PartialPath device, + final String[] measurements, + final @Nullable TimeValuePair[] timeValuePairs, + final boolean isAligned, + final IMeasurementSchema[] measurementSchemas, + final boolean initOrInvalidate) { + final String previousDatabase = databasePool.putIfAbsent(database, database); + final String database2Use = Objects.nonNull(previousDatabase) ? previousDatabase : database; + Review Comment: Does "putIfAbsent" have any differences? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
