singhpk234 commented on code in PR #4537:
URL: https://github.com/apache/iceberg/pull/4537#discussion_r850117735


##########
core/src/main/java/org/apache/iceberg/stats/FileMetadataParser.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.iceberg.stats;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.UncheckedIOException;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.util.JsonUtil;
+
+public final class FileMetadataParser {
+
+  private FileMetadataParser() {
+  }
+
+  private static final String BLOBS = "blobs";
+  private static final String PROPERTIES = "properties";
+
+  private static final String TYPE = "type";
+  private static final String COLUMNS = "columns";
+  private static final String OFFSET = "offset";
+  private static final String LENGTH = "length";
+  private static final String COMPRESSION_CODEC = "compression_codec";
+
+  public static String toJson(FileMetadata fileMetadata) {
+    try {
+      StringWriter writer = new StringWriter();
+      JsonGenerator generator = JsonUtil.factory().createGenerator(writer);
+      generator.useDefaultPrettyPrinter();
+      toJson(fileMetadata, generator);
+      generator.flush();
+      return writer.toString();
+    } catch (IOException e) {
+      throw new UncheckedIOException("Failed to write json for: " + 
fileMetadata, e);
+    }
+  }
+
+  public static FileMetadata fromJson(String json) {
+    try {
+      return fromJson(JsonUtil.mapper().readValue(json, JsonNode.class));
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+  }
+
+  public static FileMetadata fromJson(JsonNode json) {
+    return fileMetadataFromJson(json);
+  }
+
+  static void toJson(FileMetadata fileMetadata, JsonGenerator generator) 
throws IOException {
+    generator.writeStartObject();
+
+    generator.writeArrayFieldStart(BLOBS);
+    for (BlobMetadata blobMetadata : fileMetadata.blobs()) {
+      toJson(blobMetadata, generator);
+    }
+    generator.writeEndArray();
+
+    generator.writeObjectFieldStart(PROPERTIES);
+    for (Map.Entry<String, String> entry : 
fileMetadata.properties().entrySet()) {
+      generator.writeStringField(entry.getKey(), entry.getValue());
+    }
+    generator.writeEndObject();
+
+    generator.writeEndObject();

Review Comment:
   we are calling `writeEndObject` twice, is it intentional ? 



##########
core/src/main/java/org/apache/iceberg/stats/StatsWriter.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.iceberg.stats;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.PositionOutputStream;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+
+public class StatsWriter implements Closeable {
+
+  private final PositionOutputStream outputStream;
+
+  private final Map<String, String> properties = Maps.newHashMap();
+  private final List<BlobMetadata> blobs = Lists.newArrayList();
+  private boolean compressFooter = false; // TODO compress footer by default 
when LZ4 support is added
+
+  private boolean headerWritten;
+  private boolean finished;
+  private Optional<Integer> footerSize = Optional.empty();
+
+  public StatsWriter(OutputFile outputFile) {
+    Objects.requireNonNull(outputFile, "outputFile is null");
+    this.outputStream = outputFile.create();
+  }
+
+  public void addFileProperty(String name, String value) {
+    Objects.requireNonNull(name, "name is null");
+    Objects.requireNonNull(value, "value is null");
+
+    if (properties.putIfAbsent(name, value) != null) {
+      throw new IllegalStateException(String.format("Property '%s' already 
set", name));
+    }
+  }
+  public void append(
+      String type,
+      Set<Integer> columnsCovered,
+      ByteBuffer blobData,
+      Optional<StatsCompressionCodec> compression) throws IOException {
+    checkNotFinished();
+    writeHeaderIfNeeded();
+
+    Objects.requireNonNull(type, "type is null");
+    long fileOffset = outputStream.getPos();
+    ByteBuffer data;
+    data = compression.map(codec -> StatsFormat.compressBlob(codec, blobData))
+        .orElse(blobData);
+    int length = data.remaining();
+    Channels.newChannel(outputStream).write(data);
+    @Nullable String codecName = 
compression.map(StatsCompressionCodec::getCodecName).orElse(null);
+    blobs.add(new BlobMetadata(type, columnsCovered, fileOffset, length, 
codecName));
+  }
+
+  public void setCompressFooter(boolean compressFooter) {
+    this.compressFooter = compressFooter;
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (!finished) {
+      finish();
+    }
+
+    outputStream.close();
+  }
+
+  private void writeHeaderIfNeeded() throws IOException {
+    if (headerWritten) {
+      return;
+    }
+
+    outputStream.write(StatsFormat.getMagic());
+    headerWritten = true;
+  }
+
+  public void finish() throws IOException {
+    writeHeaderIfNeeded();
+    if (finished) {
+      throw new IllegalStateException("Already finished");
+    }

Review Comment:
   can call `checkNotFinished()`



##########
core/src/main/java/org/apache/iceberg/stats/StatsFormat.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.iceberg.stats;
+
+import io.airlift.compress.Compressor;
+import io.airlift.compress.zstd.ZstdCompressor;
+import io.airlift.compress.zstd.ZstdDecompressor;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+
+final class StatsFormat {
+  private StatsFormat() {
+  }
+
+  static final int CURRENT_FORMAT_VERSION = 1;
+
+  static final int MAGIC_AS_NUMBER_LE = new 
BigInteger(swap(getMagic())).intValueExact();
+
+  static final int SUPPORTED_FLAGS = 0b1;
+  static final int FLAG_COMPRESSED = 0b1;
+
+  static byte[] getMagic() {
+    return new byte[] {0x50, 0x46, 0x49, 0x53};
+  }
+
+  static void writeIntegerLittleEndian(OutputStream outputStream, int value) 
throws IOException {
+    outputStream.write(0xFF & value);
+    outputStream.write(0xFF & value >> 8);
+    outputStream.write(0xFF & value >> 16);
+    outputStream.write(0xFF & value >> 24);
+  }
+
+  static int readIntegerLittleEndian(byte[] data, int offset) {
+    return Byte.toUnsignedInt(data[offset]) |
+        (Byte.toUnsignedInt(data[offset + 1]) << 8) |
+        (Byte.toUnsignedInt(data[offset + 2]) << 16) |
+        (Byte.toUnsignedInt(data[offset + 3]) << 24);
+  }
+
+  static ByteBuffer compressFooterPayload(ByteBuffer payload) {
+    return compress(StatsCompressionCodec.LZ4, payload);
+  }
+
+  static byte[] decompressFooterPayload(byte[] footer, int offset, int length) 
{
+    return decompress(StatsCompressionCodec.LZ4, footer, offset, length);
+  }
+
+  static ByteBuffer compressBlob(StatsCompressionCodec codec, ByteBuffer data) 
{
+    return compress(codec, data);
+  }
+
+  static byte[] decompressBlob(StatsCompressionCodec codec, byte[] data, int 
dataOffset, int dataLength) {
+    return decompress(codec, data, dataOffset, dataLength);
+  }
+
+  private static ByteBuffer compress(StatsCompressionCodec codec, ByteBuffer 
input) {
+    Compressor compressor = getCompressor(codec);
+    ByteBuffer output = 
ByteBuffer.allocate(compressor.maxCompressedLength(input.remaining()));
+    compressor.compress(input,  output);
+    output.flip();
+    return output;
+  }
+
+  private static Compressor getCompressor(StatsCompressionCodec codec) {
+    switch (codec) {
+      case LZ4:
+        // TODO currently not supported
+        break;
+      case ZSTD:
+        return new ZstdCompressor();
+    }
+    throw new UnsupportedOperationException("Unsupported codec: " + codec);
+  }
+
+  private static byte[] decompress(StatsCompressionCodec codec, byte[] input, 
int inputOffset, int inputLength) {
+    switch (codec) {
+      case LZ4: {
+        // TODO requires LZ4 frame decompressor, e.g. 
https://github.com/airlift/aircompressor/pull/142
+        throw new UnsupportedOperationException("LZ4 is not supported yet");

Review Comment:
   can add a break here instead and let the exp in L#112 take care of throwing 
UnsupportedException, something done above.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to