hongzhi-gao commented on code in PR #19244:
URL: https://github.com/apache/iotdb/pull/19244#discussion_r4562000809


##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogCompression.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.consensus.iot.logdispatcher;
+
+import org.apache.iotdb.consensus.i18n.IoTConsensusMessages;
+import org.apache.iotdb.consensus.iot.thrift.TLogBufferCompression;
+import org.apache.iotdb.consensus.iot.thrift.TLogCompressionType;
+import org.apache.iotdb.consensus.iot.thrift.TLogEntry;
+import org.apache.iotdb.consensus.iot.thrift.TSyncLogEntriesReq;
+
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdException;
+import org.apache.tsfile.compress.ICompressor;
+import org.apache.tsfile.compress.IUnCompressor;
+import org.apache.tsfile.file.metadata.enums.CompressionType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.zip.CRC32C;
+
+/** Wire-only encoding: the original batch and its buffer positions remain 
available for retries. */
+public final class LogCompression {
+  // Conservative allowance for the additional Thrift descriptor and list 
field on the wire.
+  private static final int DESCRIPTOR_BYTES = 32;
+  private static final ICompressor LZ4 = 
ICompressor.getCompressor(CompressionType.LZ4);
+  private static final ICompressor SNAPPY = 
ICompressor.getCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor LZ4_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.LZ4);
+  private static final IUnCompressor SNAPPY_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor ZSTD_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.ZSTD);
+
+  private LogCompression() {}
+
+  /** Accounts for arrays throughout the async attempt, including synchronous 
send failure. */
+  public static final class EncodedRequest implements AutoCloseable {
+    private TSyncLogEntriesReq request;
+    private final AtomicLong reserved;
+    private final long rawBytes;
+    private long encodedBytes;
+    private boolean memoryLimited;
+
+    private EncodedRequest(
+        TSyncLogEntriesReq request, long reserved, long rawBytes, boolean 
memoryLimited) {
+      this.request = request;
+      this.reserved = new AtomicLong(reserved);
+      this.rawBytes = rawBytes;
+      this.encodedBytes = rawBytes;
+      this.memoryLimited = memoryLimited;
+    }
+
+    public long getRawBytes() {
+      return rawBytes;
+    }
+
+    public long getEncodedBytes() {
+      return encodedBytes;
+    }
+
+    public boolean isMemoryLimited() {
+      return memoryLimited;
+    }
+
+    public TSyncLogEntriesReq getRequest() {
+      return request;
+    }
+
+    private void retain(long bytes) {
+      long released = reserved.getAndSet(bytes) - bytes;
+      if (released > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(released);
+    }
+
+    @Override
+    public void close() {
+      long bytes = reserved.getAndSet(0);
+      if (bytes > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(bytes);
+    }
+  }
+
+  public static EncodedRequest compress(
+      TSyncLogEntriesReq original, TLogCompressionType codec, int minSize, int 
maxDecodedBytes)
+      throws IOException {
+    long buffers = 0, rawSize = 0;
+    boolean hasEligibleBuffer = false;
+    for (TLogEntry entry : original.getLogEntries()) {
+      for (ByteBuffer buffer : entry.getData()) {
+        int size = buffer.remaining();
+        rawSize += size;
+        if (size >= minSize && size > 0) {
+          hasEligibleBuffer = true;
+        }
+        buffers++;
+      }
+    }
+    // Preserve the original path for oversized legal entries and when scratch 
memory is scarce.
+    if (codec == TLogCompressionType.NONE || !hasEligibleBuffer || rawSize > 
maxDecodedBytes)
+      return new EncodedRequest(original, 0, rawSize, false);
+    // Charge descriptor/list/entry overhead first, then one block's working 
arrays at a time.
+    // Retain only actual compact outputs between blocks, not a whole-batch 
worst-case estimate.
+    long budget = buffers * 256 + original.getLogEntriesSize() * 128L;
+    if 
(!IoTConsensusMemoryManager.getInstance().reserveLogCompression(budget)) {
+      return new EncodedRequest(original, 0, rawSize, true);
+    }
+    EncodedRequest result = new EncodedRequest(original, budget, rawSize, 
false);
+    try {
+      List<TLogEntry> entries = new ArrayList<>(original.getLogEntriesSize());
+      long retained = 0;
+      boolean changed = false;
+      for (TLogEntry entry : original.getLogEntries()) {
+        List<ByteBuffer> data = new ArrayList<>(entry.getDataSize());
+        List<TLogBufferCompression> info = new 
ArrayList<>(entry.getDataSize());
+        long raw = 0, wire = 0, arrays = 0;
+        boolean compressed = false;
+        for (ByteBuffer buffer : entry.getData()) {
+          int size = buffer.remaining();
+          raw += size;
+          ByteBuffer encoded = buffer;
+          TLogCompressionType actualCodec = TLogCompressionType.NONE;
+          if (size >= minSize && size > 0) {
+            // Includes an optional input copy, codec-bound output and compact 
output, with
+            // allowance for array headers and codec bounds on very small 
buffers.
+            long workspace = 4L * size + 256;
+            long before = result.reserved.get();
+            if 
(IoTConsensusMemoryManager.getInstance().reserveLogCompression(workspace)) {
+              result.reserved.addAndGet(workspace);
+              byte[] input = buffer.hasArray() ? buffer.array() : 
bytes(buffer);
+              int offset = buffer.hasArray() ? buffer.arrayOffset() + 
buffer.position() : 0;
+              int bound =
+                  codec == TLogCompressionType.ZSTD
+                      ? (int) Zstd.compressBound(size)
+                      : compressor(codec).getMaxBytesForCompression(size);
+              byte[] output = new byte[bound];
+              int length =
+                  codec == TLogCompressionType.ZSTD
+                      ? (int)
+                          Zstd.compressByteArray(output, 0, output.length, 
input, offset, size, 1)
+                      : compressor(codec).compress(input, offset, size, 
output);
+              if (length < 0) throw invalid(Failure.CODEC, size, length);
+              if ((long) length + DESCRIPTOR_BYTES < size) {

Review Comment:
   Renamed the variables to compressedLength and uncompressedLength. There is 
already an internal 4 KiB threshold: buffers smaller than this are sent 
uncompressed. For buffers at or above the threshold, the compressed result is 
sent only if it still saves space after accounting for metadata; otherwise, the 
original uncompressed data is sent.



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