JackieTien97 commented on code in PR #17169:
URL: https://github.com/apache/iotdb/pull/17169#discussion_r2938673635


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/utils/tableDiskUsageCache/TableDiskUsageCache.java:
##########
@@ -0,0 +1,511 @@
+/*
+ * 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.storageengine.dataregion.utils.tableDiskUsageCache;
+
+import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.commons.concurrent.ThreadName;
+import org.apache.iotdb.commons.utils.TestOnly;
+import org.apache.iotdb.db.storageengine.StorageEngine;
+import org.apache.iotdb.db.storageengine.dataregion.DataRegion;
+import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileID;
+import 
org.apache.iotdb.db.storageengine.dataregion.utils.tableDiskUsageCache.object.EmptyObjectTableSizeCacheReader;
+import 
org.apache.iotdb.db.storageengine.dataregion.utils.tableDiskUsageCache.object.IObjectTableSizeCacheReader;
+import 
org.apache.iotdb.db.storageengine.dataregion.utils.tableDiskUsageCache.tsfile.TsFileTableDiskUsageCacheWriter;
+import 
org.apache.iotdb.db.storageengine.dataregion.utils.tableDiskUsageCache.tsfile.TsFileTableSizeCacheReader;
+
+import org.apache.tsfile.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public class TableDiskUsageCache {
+  protected static final Logger LOGGER = 
LoggerFactory.getLogger(TableDiskUsageCache.class);
+  protected final BlockingQueue<Operation> queue = new 
LinkedBlockingQueue<>(1000);
+  // regionId -> writer mapping
+  protected final Map<Integer, DataRegionTableSizeCacheWriter> writerMap = new 
HashMap<>();
+  protected ScheduledExecutorService scheduledExecutorService;
+  private int processedOperationCountSinceLastPeriodicCheck = 0;
+  protected volatile boolean failedToRecover = false;
+  private volatile boolean stop = false;
+
+  protected TableDiskUsageCache() {
+    scheduledExecutorService =
+        IoTDBThreadPoolFactory.newSingleThreadScheduledExecutor(
+            ThreadName.FILE_TIME_INDEX_RECORD.getName());
+    scheduledExecutorService.submit(this::run);
+  }
+
+  protected void run() {
+    try {
+      while (!stop) {
+        try {
+          for (DataRegionTableSizeCacheWriter writer : writerMap.values()) {
+            syncTsFileTableSizeCacheIfNecessary(writer);
+            persistPendingObjectDeltasIfNecessary(writer);
+          }
+          Operation operation = queue.poll(1, TimeUnit.SECONDS);
+          if (operation != null) {
+            operation.apply(this);
+            processedOperationCountSinceLastPeriodicCheck++;
+          }
+          if (operation == null || 
processedOperationCountSinceLastPeriodicCheck % 1000 == 0) {
+            performPeriodicMaintenance();
+          }
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+          return;
+        } catch (Exception e) {
+          LOGGER.error("Meet exception when apply TableDiskUsageCache 
operation.", e);
+        }
+      }
+    } finally {
+      writerMap.values().forEach(DataRegionTableSizeCacheWriter::close);
+    }
+  }
+
+  private void performPeriodicMaintenance() {
+    checkAndMayCloseIdleWriter();
+    compactIfNecessary(TimeUnit.SECONDS.toMillis(1));
+    processedOperationCountSinceLastPeriodicCheck = 0;
+  }
+
+  /**
+   * Any unrecoverable error in a single writer will mark the whole 
TableDiskUsageCache as failed
+   * and disable further operations.
+   */
+  protected void failedToRecover(Exception e) {
+    failedToRecover = true;
+    LOGGER.error("Failed to recover TableDiskUsageCache", e);
+  }
+
+  protected void 
syncTsFileTableSizeCacheIfNecessary(DataRegionTableSizeCacheWriter writer) {
+    try {
+      writer.tsFileCacheWriter.syncIfNecessary();
+    } catch (IOException e) {
+      LOGGER.warn("Failed to sync tsfile table size cache.", e);
+    }
+  }
+
+  // Hook for subclasses to persist pending object table size deltas. No-op by 
default.
+  protected void 
persistPendingObjectDeltasIfNecessary(DataRegionTableSizeCacheWriter writer) {}
+
+  protected void compactIfNecessary(long maxRunTime) {
+    if (!StorageEngine.getInstance().isReadyForReadAndWrite()) {
+      return;
+    }
+    long startTime = System.currentTimeMillis();
+    for (DataRegionTableSizeCacheWriter writer : writerMap.values()) {
+      if (System.currentTimeMillis() - startTime > maxRunTime) {
+        break;
+      }
+      if (writer.getActiveReaderNum() > 0) {
+        continue;
+      }
+      writer.compactIfNecessary();
+    }
+  }
+
+  protected void checkAndMayCloseIdleWriter() {
+    for (DataRegionTableSizeCacheWriter writer : writerMap.values()) {
+      writer.closeIfIdle();
+    }
+  }
+
+  public void write(String database, TsFileID tsFileID, Map<String, Long> 
tableSizeMap) {
+    if (tableSizeMap == null || tableSizeMap.isEmpty()) {
+      // tree model
+      return;
+    }
+    addOperationToQueue(new WriteOperation(database, tsFileID, tableSizeMap));
+  }
+
+  public void write(String database, TsFileID originTsFileID, TsFileID 
newTsFileID) {
+    addOperationToQueue(new ReplaceTsFileOperation(database, originTsFileID, 
newTsFileID));
+  }
+
+  public void writeObjectDelta(
+      String database, int regionId, long timePartition, String table, long 
size, int num) {
+    throw new UnsupportedOperationException("writeObjectDelta");
+  }
+
+  public CompletableFuture<Pair<TsFileTableSizeCacheReader, 
IObjectTableSizeCacheReader>> startRead(
+      DataRegion dataRegion, boolean readTsFileCache, boolean 
readObjectFileCache) {
+    StartReadOperation operation =
+        new StartReadOperation(dataRegion, readTsFileCache, 
readObjectFileCache);
+    if (!addOperationToQueue(operation)) {
+      operation.future.complete(
+          new Pair<>(
+              new TsFileTableSizeCacheReader(0, null, 0, null, 
dataRegion.getDataRegionId()),
+              new EmptyObjectTableSizeCacheReader()));
+    }
+    return operation.future;
+  }
+
+  public void endRead(DataRegion dataRegion) {
+    EndReadOperation operation = new EndReadOperation(dataRegion);
+    addOperationToQueue(operation);
+  }
+
+  public void registerRegion(DataRegion region) {
+    RegisterRegionOperation operation = new RegisterRegionOperation(region);
+    if (!region.isTableModel()) {
+      return;
+    }
+    addOperationToQueue(operation);

Review Comment:
    Thread.currentThread().interrupt(); and stop state should be handled 
differently.



-- 
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]

Reply via email to