This is an automated email from the ASF dual-hosted git repository.

blue pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/main by this push:
     new 4c5208a423 API: Extend FileIO and add EncryptingFileIO. (#9592)
4c5208a423 is described below

commit 4c5208a42382a2888a76af85eb52b5d69eca6f7e
Author: Ryan Blue <[email protected]>
AuthorDate: Mon Feb 19 14:42:51 2024 -0800

    API: Extend FileIO and add EncryptingFileIO. (#9592)
---
 .../iceberg/encryption/EncryptingFileIO.java       | 214 +++++++++++++++++++++
 .../main/java/org/apache/iceberg/io/FileIO.java    |  28 +++
 .../java/org/apache/iceberg/ManifestFiles.java     |  40 ++--
 .../encryption/NativeEncryptionOutputFile.java     |  24 ++-
 .../encryption/StandardEncryptionManager.java      |   4 +
 .../java/org/apache/iceberg/io/ContentCache.java   | 162 +++++++---------
 .../iceberg/hadoop/TestCatalogUtilDropTable.java   |  42 ++--
 .../apache/iceberg/spark/source/BaseReader.java    |  23 +--
 8 files changed, 384 insertions(+), 153 deletions(-)

diff --git 
a/api/src/main/java/org/apache/iceberg/encryption/EncryptingFileIO.java 
b/api/src/main/java/org/apache/iceberg/encryption/EncryptingFileIO.java
new file mode 100644
index 0000000000..ea63b29754
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/encryption/EncryptingFileIO.java
@@ -0,0 +1,214 @@
+/*
+ * 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.encryption;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.Serializable;
+import java.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+
+public class EncryptingFileIO implements FileIO, Serializable {
+  public static EncryptingFileIO create(FileIO io, EncryptionManager em) {
+    if (io instanceof EncryptingFileIO) {
+      return (EncryptingFileIO) io;
+    }
+
+    return new EncryptingFileIO(io, em);
+  }
+
+  private final FileIO io;
+  private final EncryptionManager em;
+
+  EncryptingFileIO(FileIO io, EncryptionManager em) {
+    this.io = io;
+    this.em = em;
+  }
+
+  public Map<String, InputFile> bulkDecrypt(Iterable<? extends ContentFile<?>> 
files) {
+    Iterable<InputFile> decrypted = em.decrypt(Iterables.transform(files, 
this::wrap));
+
+    ImmutableMap.Builder<String, InputFile> builder = ImmutableMap.builder();
+    for (InputFile in : decrypted) {
+      builder.put(in.location(), in);
+    }
+
+    return builder.buildKeepingLast();
+  }
+
+  public EncryptionManager encryptionManager() {
+    return em;
+  }
+
+  @Override
+  public InputFile newInputFile(String path) {
+    return io.newInputFile(path);
+  }
+
+  @Override
+  public InputFile newInputFile(String path, long length) {
+    return io.newInputFile(path, length);
+  }
+
+  @Override
+  public InputFile newInputFile(DataFile file) {
+    return newInputFile((ContentFile<?>) file);
+  }
+
+  @Override
+  public InputFile newInputFile(DeleteFile file) {
+    return newInputFile((ContentFile<?>) file);
+  }
+
+  private InputFile newInputFile(ContentFile<?> file) {
+    if (file.keyMetadata() != null) {
+      return newDecryptingInputFile(
+          file.path().toString(), file.fileSizeInBytes(), file.keyMetadata());
+    } else {
+      return newInputFile(file.path().toString(), file.fileSizeInBytes());
+    }
+  }
+
+  @Override
+  public InputFile newInputFile(ManifestFile manifest) {
+    if (manifest.keyMetadata() != null) {
+      return newDecryptingInputFile(manifest.path(), manifest.length(), 
manifest.keyMetadata());
+    } else {
+      return newInputFile(manifest.path(), manifest.length());
+    }
+  }
+
+  public InputFile newDecryptingInputFile(String path, ByteBuffer buffer) {
+    return em.decrypt(wrap(io.newInputFile(path), buffer));
+  }
+
+  public InputFile newDecryptingInputFile(String path, long length, ByteBuffer 
buffer) {
+    // TODO: is the length correct for the encrypted file? It may be the 
length of the plaintext
+    // stream
+    return em.decrypt(wrap(io.newInputFile(path, length), buffer));
+  }
+
+  @Override
+  public OutputFile newOutputFile(String path) {
+    return io.newOutputFile(path);
+  }
+
+  public EncryptedOutputFile newEncryptingOutputFile(String path) {
+    OutputFile plainOutputFile = io.newOutputFile(path);
+    return em.encrypt(plainOutputFile);
+  }
+
+  @Override
+  public void deleteFile(String path) {
+    io.deleteFile(path);
+  }
+
+  @Override
+  public void close() {
+    io.close();
+
+    if (em instanceof Closeable) {
+      try {
+        ((Closeable) em).close();
+      } catch (IOException e) {
+        throw new UncheckedIOException("Failed to close encryption manager", 
e);
+      }
+    }
+  }
+
+  private SimpleEncryptedInputFile wrap(ContentFile<?> file) {
+    InputFile encryptedInputFile = io.newInputFile(file.path().toString(), 
file.fileSizeInBytes());
+    return new SimpleEncryptedInputFile(encryptedInputFile, 
toKeyMetadata(file.keyMetadata()));
+  }
+
+  private static SimpleEncryptedInputFile wrap(InputFile encryptedInputFile, 
ByteBuffer buffer) {
+    return new SimpleEncryptedInputFile(encryptedInputFile, 
toKeyMetadata(buffer));
+  }
+
+  private static EncryptionKeyMetadata toKeyMetadata(ByteBuffer buffer) {
+    return buffer != null ? new SimpleKeyMetadata(buffer) : 
EmptyKeyMetadata.get();
+  }
+
+  private static class SimpleEncryptedInputFile implements EncryptedInputFile {
+    private final InputFile encryptedInputFile;
+    private final EncryptionKeyMetadata keyMetadata;
+
+    private SimpleEncryptedInputFile(
+        InputFile encryptedInputFile, EncryptionKeyMetadata keyMetadata) {
+      this.encryptedInputFile = encryptedInputFile;
+      this.keyMetadata = keyMetadata;
+    }
+
+    @Override
+    public InputFile encryptedInputFile() {
+      return encryptedInputFile;
+    }
+
+    @Override
+    public EncryptionKeyMetadata keyMetadata() {
+      return keyMetadata;
+    }
+  }
+
+  private static class SimpleKeyMetadata implements EncryptionKeyMetadata {
+    private final ByteBuffer metadataBuffer;
+
+    private SimpleKeyMetadata(ByteBuffer metadataBuffer) {
+      this.metadataBuffer = metadataBuffer;
+    }
+
+    @Override
+    public ByteBuffer buffer() {
+      return metadataBuffer;
+    }
+
+    @Override
+    public EncryptionKeyMetadata copy() {
+      return new SimpleKeyMetadata(metadataBuffer.duplicate());
+    }
+  }
+
+  private static class EmptyKeyMetadata implements EncryptionKeyMetadata {
+    private static final EmptyKeyMetadata INSTANCE = new EmptyKeyMetadata();
+
+    private static EmptyKeyMetadata get() {
+      return INSTANCE;
+    }
+
+    @Override
+    public ByteBuffer buffer() {
+      return null;
+    }
+
+    @Override
+    public EncryptionKeyMetadata copy() {
+      return this;
+    }
+  }
+}
diff --git a/api/src/main/java/org/apache/iceberg/io/FileIO.java 
b/api/src/main/java/org/apache/iceberg/io/FileIO.java
index 928f09eb20..fc6a53367f 100644
--- a/api/src/main/java/org/apache/iceberg/io/FileIO.java
+++ b/api/src/main/java/org/apache/iceberg/io/FileIO.java
@@ -21,6 +21,10 @@ package org.apache.iceberg.io;
 import java.io.Closeable;
 import java.io.Serializable;
 import java.util.Map;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
 
 /**
  * Pluggable module for reading, writing, and deleting files.
@@ -42,6 +46,30 @@ public interface FileIO extends Serializable, Closeable {
     return newInputFile(path);
   }
 
+  default InputFile newInputFile(DataFile file) {
+    Preconditions.checkArgument(
+        file.keyMetadata() == null,
+        "Cannot decrypt data file: {} (use EncryptingFileIO)",
+        file.path());
+    return newInputFile(file.path().toString());
+  }
+
+  default InputFile newInputFile(DeleteFile file) {
+    Preconditions.checkArgument(
+        file.keyMetadata() == null,
+        "Cannot decrypt delete file: {} (use EncryptingFileIO)",
+        file.path());
+    return newInputFile(file.path().toString());
+  }
+
+  default InputFile newInputFile(ManifestFile manifest) {
+    Preconditions.checkArgument(
+        manifest.keyMetadata() == null,
+        "Cannot decrypt manifest: {} (use EncryptingFileIO)",
+        manifest.path());
+    return newInputFile(manifest.path());
+  }
+
   /** Get a {@link OutputFile} instance to write bytes to the file at the 
given path. */
   OutputFile newOutputFile(String path);
 
diff --git a/core/src/main/java/org/apache/iceberg/ManifestFiles.java 
b/core/src/main/java/org/apache/iceberg/ManifestFiles.java
index c23ab667a4..f7b1add6bd 100644
--- a/core/src/main/java/org/apache/iceberg/ManifestFiles.java
+++ b/core/src/main/java/org/apache/iceberg/ManifestFiles.java
@@ -126,7 +126,7 @@ public class ManifestFiles {
         manifest.content() == ManifestContent.DATA,
         "Cannot read a delete manifest with a ManifestReader: %s",
         manifest);
-    InputFile file = newInputFile(io, manifest.path(), manifest.length());
+    InputFile file = newInputFile(io, manifest);
     InheritableMetadata inheritableMetadata = 
InheritableMetadataFactory.fromManifest(manifest);
     return new ManifestReader<>(
         file, manifest.partitionSpecId(), specsById, inheritableMetadata, 
FileType.DATA_FILES);
@@ -181,7 +181,7 @@ public class ManifestFiles {
         manifest.content() == ManifestContent.DELETES,
         "Cannot read a data manifest with a DeleteManifestReader: %s",
         manifest);
-    InputFile file = newInputFile(io, manifest.path(), manifest.length());
+    InputFile file = newInputFile(io, manifest);
     InheritableMetadata inheritableMetadata = 
InheritableMetadataFactory.fromManifest(manifest);
     return new ManifestReader<>(
         file, manifest.partitionSpecId(), specsById, inheritableMetadata, 
FileType.DELETE_FILES);
@@ -345,34 +345,24 @@ public class ManifestFiles {
     return writer.toManifestFile();
   }
 
-  private static InputFile newInputFile(FileIO io, String path, long length) {
-    boolean enabled;
-
-    try {
-      enabled = cachingEnabled(io);
-    } catch (UnsupportedOperationException e) {
-      // There is an issue reading io.properties(). Disable caching.
-      enabled = false;
-    }
-
-    if (enabled) {
-      ContentCache cache = contentCache(io);
-      Preconditions.checkNotNull(
-          cache,
-          "ContentCache creation failed. Check that all manifest caching 
configurations has valid value.");
-      LOG.debug("FileIO-level cache stats: {}", CONTENT_CACHES.stats());
-      return cache.tryCache(io, path, length);
+  private static InputFile newInputFile(FileIO io, ManifestFile manifest) {
+    InputFile input = io.newInputFile(manifest);
+    if (cachingEnabled(io)) {
+      return contentCache(io).tryCache(input);
     }
 
-    // caching is not enable for this io or caught RuntimeException.
-    return io.newInputFile(path, length);
+    return input;
   }
 
   static boolean cachingEnabled(FileIO io) {
-    return PropertyUtil.propertyAsBoolean(
-        io.properties(),
-        CatalogProperties.IO_MANIFEST_CACHE_ENABLED,
-        CatalogProperties.IO_MANIFEST_CACHE_ENABLED_DEFAULT);
+    try {
+      return PropertyUtil.propertyAsBoolean(
+          io.properties(),
+          CatalogProperties.IO_MANIFEST_CACHE_ENABLED,
+          CatalogProperties.IO_MANIFEST_CACHE_ENABLED_DEFAULT);
+    } catch (UnsupportedOperationException e) {
+      return false;
+    }
   }
 
   static long cacheDurationMs(FileIO io) {
diff --git 
a/core/src/main/java/org/apache/iceberg/encryption/NativeEncryptionOutputFile.java
 
b/core/src/main/java/org/apache/iceberg/encryption/NativeEncryptionOutputFile.java
index 0d0d5da8a6..6d095252cb 100644
--- 
a/core/src/main/java/org/apache/iceberg/encryption/NativeEncryptionOutputFile.java
+++ 
b/core/src/main/java/org/apache/iceberg/encryption/NativeEncryptionOutputFile.java
@@ -18,13 +18,35 @@
  */
 package org.apache.iceberg.encryption;
 
+import org.apache.iceberg.io.InputFile;
 import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.PositionOutputStream;
 
 /** An {@link EncryptedOutputFile} that can be used for format-native 
encryption. */
-public interface NativeEncryptionOutputFile extends EncryptedOutputFile {
+public interface NativeEncryptionOutputFile extends EncryptedOutputFile, 
OutputFile {
   @Override
   NativeEncryptionKeyMetadata keyMetadata();
 
   /** An {@link OutputFile} instance for the underlying (plaintext) output 
stream. */
   OutputFile plainOutputFile();
+
+  @Override
+  default PositionOutputStream create() {
+    return encryptingOutputFile().create();
+  }
+
+  @Override
+  default PositionOutputStream createOrOverwrite() {
+    return encryptingOutputFile().createOrOverwrite();
+  }
+
+  @Override
+  default String location() {
+    return encryptingOutputFile().location();
+  }
+
+  @Override
+  default InputFile toInputFile() {
+    return encryptingOutputFile().toInputFile();
+  }
 }
diff --git 
a/core/src/main/java/org/apache/iceberg/encryption/StandardEncryptionManager.java
 
b/core/src/main/java/org/apache/iceberg/encryption/StandardEncryptionManager.java
index 185f4d6f81..119d2a5f9a 100644
--- 
a/core/src/main/java/org/apache/iceberg/encryption/StandardEncryptionManager.java
+++ 
b/core/src/main/java/org/apache/iceberg/encryption/StandardEncryptionManager.java
@@ -61,6 +61,10 @@ public class StandardEncryptionManager implements 
EncryptionManager {
   @Override
   public NativeEncryptionInputFile decrypt(EncryptedInputFile encrypted) {
     // this input file will lazily parse key metadata in case the file is not 
an AES GCM stream.
+    if (encrypted instanceof NativeEncryptionInputFile) {
+      return (NativeEncryptionInputFile) encrypted;
+    }
+
     return new StandardDecryptedInputFile(encrypted);
   }
 
diff --git a/core/src/main/java/org/apache/iceberg/io/ContentCache.java 
b/core/src/main/java/org/apache/iceberg/io/ContentCache.java
index c999f3f333..7942c69d5d 100644
--- a/core/src/main/java/org/apache/iceberg/io/ContentCache.java
+++ b/core/src/main/java/org/apache/iceberg/io/ContentCache.java
@@ -32,7 +32,6 @@ import java.util.function.Function;
 import org.apache.iceberg.exceptions.NotFoundException;
 import org.apache.iceberg.exceptions.ValidationException;
 import org.apache.iceberg.relocated.com.google.common.base.MoreObjects;
-import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -40,8 +39,8 @@ import org.slf4j.LoggerFactory;
 /**
  * Class that provides file-content caching during reading.
  *
- * <p>The file-content caching is initiated by calling {@link 
ContentCache#tryCache(FileIO, String,
- * long)}. Given a FileIO, a file location string, and file length that is 
within allowed limit,
+ * <p>The file-content caching is initiated by calling {@link 
ContentCache#tryCache(InputFile)}.
+ * Given a FileIO, a file location string, and file length that is within 
allowed limit,
  * ContentCache will return a {@link CachingInputFile} that is backed by the 
cache. Calling {@link
  * CachingInputFile#newStream()} will return a {@link ByteBufferInputStream} 
backed by list of
  * {@link ByteBuffer} from the cache if such file-content exist in the cache. 
If the file-content
@@ -56,7 +55,7 @@ public class ContentCache {
   private final long expireAfterAccessMs;
   private final long maxTotalBytes;
   private final long maxContentLength;
-  private final Cache<String, CacheEntry> cache;
+  private final Cache<String, FileContent> cache;
 
   /**
    * Constructor for ContentCache class.
@@ -86,11 +85,11 @@ public class ContentCache {
         builder
             .maximumWeight(maxTotalBytes)
             .weigher(
-                (Weigher<String, CacheEntry>)
+                (Weigher<String, FileContent>)
                     (key, value) -> (int) Math.min(value.length, 
Integer.MAX_VALUE))
             .softValues()
             .removalListener(
-                (location, cacheEntry, cause) ->
+                (location, fileContent, cause) ->
                     LOG.debug("Evicted {} from ContentCache ({})", location, 
cause))
             .recordStats()
             .build();
@@ -112,14 +111,24 @@ public class ContentCache {
     return cache.stats();
   }
 
-  public CacheEntry get(String key, Function<String, CacheEntry> 
mappingFunction) {
+  /** @deprecated will be removed in 1.7; use {@link #tryCache(InputFile)} 
instead */
+  @Deprecated
+  public CacheEntry get(String key, Function<String, FileContent> 
mappingFunction) {
     return cache.get(key, mappingFunction);
   }
 
+  /** @deprecated will be removed in 1.7; use {@link #tryCache(InputFile)} 
instead */
+  @Deprecated
   public CacheEntry getIfPresent(String location) {
     return cache.getIfPresent(location);
   }
 
+  /** @deprecated will be removed in 1.7; use {@link #tryCache(InputFile)} 
instead */
+  @Deprecated
+  public InputFile tryCache(FileIO io, String location, long length) {
+    return tryCache(io.newInputFile(location, length));
+  }
+
   /**
    * Try cache the file-content of file in the given location upon stream 
reading.
    *
@@ -127,17 +136,15 @@ public class ContentCache {
    * and no caching will be done for that file. Otherwise, this method will 
return a {@link
    * CachingInputFile} that serve file reads backed by ContentCache.
    *
-   * @param io a FileIO associated with the location.
-   * @param location URL/path of a file accessible by io.
-   * @param length the known length of such file.
+   * @param input an InputFile to cache
    * @return a {@link CachingInputFile} if length is within allowed limit. 
Otherwise, a regular
    *     {@link InputFile} for given location.
    */
-  public InputFile tryCache(FileIO io, String location, long length) {
-    if (length <= maxContentLength) {
-      return new CachingInputFile(this, io, location, length);
+  public InputFile tryCache(InputFile input) {
+    if (input.getLength() <= maxContentLength) {
+      return new CachingInputFile(this, input);
     }
-    return io.newInputFile(location, length);
+    return input;
   }
 
   public void invalidate(String key) {
@@ -166,11 +173,15 @@ public class ContentCache {
         .toString();
   }
 
-  private static class CacheEntry {
+  /** @deprecated will be removed in 1.7; use {@link FileContent} instead. */
+  @Deprecated
+  private static class CacheEntry {}
+
+  private static class FileContent extends CacheEntry {
     private final long length;
     private final List<ByteBuffer> buffers;
 
-    private CacheEntry(long length, List<ByteBuffer> buffers) {
+    private FileContent(long length, List<ByteBuffer> buffers) {
       this.length = length;
       this.buffers = buffers;
     }
@@ -187,34 +198,20 @@ public class ContentCache {
    */
   private static class CachingInputFile implements InputFile {
     private final ContentCache contentCache;
-    private final FileIO io;
-    private final String location;
-    private final long length;
-    private InputFile fallbackInputFile = null;
+    private final InputFile input;
 
-    private CachingInputFile(ContentCache cache, FileIO io, String location, 
long length) {
+    private CachingInputFile(ContentCache cache, InputFile input) {
       this.contentCache = cache;
-      this.io = io;
-      this.location = location;
-      this.length = length;
-    }
-
-    private InputFile wrappedInputFile() {
-      if (fallbackInputFile == null) {
-        fallbackInputFile = io.newInputFile(location, length);
-      }
-      return fallbackInputFile;
+      this.input = input;
     }
 
     @Override
     public long getLength() {
-      CacheEntry buf = contentCache.getIfPresent(location);
+      FileContent buf = contentCache.cache.getIfPresent(input.location());
       if (buf != null) {
         return buf.length;
-      } else if (fallbackInputFile != null) {
-        return fallbackInputFile.getLength();
       } else {
-        return length;
+        return input.getLength();
       }
     }
 
@@ -232,80 +229,63 @@ public class ContentCache {
     @Override
     public SeekableInputStream newStream() {
       try {
-        // read from cache if file length is less than or equal to maximum 
length allowed to
-        // cache.
-        if (getLength() <= contentCache.maxContentLength()) {
-          return cachedStream();
-        }
-
-        // fallback to non-caching input stream.
-        return wrappedInputFile().newStream();
+        return cachedStream();
       } catch (FileNotFoundException e) {
-        throw new NotFoundException(
-            e, "Failed to open input stream for file %s: %s", location, 
e.toString());
+        throw new NotFoundException(e, "Failed to open file: %s", 
input.location());
       } catch (IOException e) {
-        throw new UncheckedIOException(
-            String.format("Failed to open input stream for file %s: %s", 
location, e), e);
+        return input.newStream();
       }
     }
 
     @Override
     public String location() {
-      return location;
+      return input.location();
     }
 
     @Override
     public boolean exists() {
-      CacheEntry buf = contentCache.getIfPresent(location);
-      return buf != null || wrappedInputFile().exists();
-    }
-
-    private CacheEntry cacheEntry() {
-      long start = System.currentTimeMillis();
-      try (SeekableInputStream stream = wrappedInputFile().newStream()) {
-        long fileLength = getLength();
-        long totalBytesToRead = fileLength;
-        List<ByteBuffer> buffers = Lists.newArrayList();
-
-        while (totalBytesToRead > 0) {
-          // read the stream in 4MB chunk
-          int bytesToRead = (int) Math.min(BUFFER_CHUNK_SIZE, 
totalBytesToRead);
-          byte[] buf = new byte[bytesToRead];
-          int bytesRead = IOUtil.readRemaining(stream, buf, 0, bytesToRead);
-          totalBytesToRead -= bytesRead;
-
-          if (bytesRead < bytesToRead) {
-            // Read less than it should be, possibly hitting EOF. Abandon 
caching by throwing
-            // IOException and let the caller fallback to non-caching input 
file.
-            throw new IOException(
-                String.format(
-                    "Expected to read %d bytes, but only %d bytes read.",
-                    fileLength, fileLength - totalBytesToRead));
-          } else {
-            buffers.add(ByteBuffer.wrap(buf));
-          }
-        }
-
-        CacheEntry newEntry = new CacheEntry(fileLength, buffers);
-        LOG.debug("cacheEntry took {} ms for {}", (System.currentTimeMillis() 
- start), location);
-        return newEntry;
-      } catch (IOException ex) {
-        throw new UncheckedIOException(ex);
-      }
+      FileContent buf = contentCache.cache.getIfPresent(input.location());
+      return buf != null || input.exists();
     }
 
     private SeekableInputStream cachedStream() throws IOException {
       try {
-        CacheEntry entry = contentCache.get(location, k -> cacheEntry());
-        Preconditions.checkNotNull(
-            entry, "CacheEntry should not be null when there is no 
RuntimeException occurs");
-        LOG.debug("Cache stats: {}", contentCache.stats());
-        return ByteBufferInputStream.wrap(entry.buffers);
+        FileContent content = contentCache.cache.get(input.location(), k -> 
download(input));
+        return ByteBufferInputStream.wrap(content.buffers);
       } catch (UncheckedIOException ex) {
         throw ex.getCause();
-      } catch (RuntimeException ex) {
-        throw new IOException("Caught an error while reading from cache", ex);
       }
     }
   }
+
+  private static FileContent download(InputFile input) {
+    try (SeekableInputStream stream = input.newStream()) {
+      long fileLength = input.getLength();
+      long totalBytesToRead = fileLength;
+      List<ByteBuffer> buffers = Lists.newArrayList();
+
+      while (totalBytesToRead > 0) {
+        // read the stream in chunks
+        int bytesToRead = (int) Math.min(BUFFER_CHUNK_SIZE, totalBytesToRead);
+        byte[] buf = new byte[bytesToRead];
+        int bytesRead = IOUtil.readRemaining(stream, buf, 0, bytesToRead);
+        totalBytesToRead -= bytesRead;
+
+        if (bytesRead < bytesToRead) {
+          // Read less than it should be, possibly hitting EOF. Abandon 
caching by throwing
+          // IOException and let the caller fallback to non-caching input file.
+          throw new IOException(
+              String.format(
+                  "Failed to read %d bytes: %d bytes in stream",
+                  fileLength, fileLength - totalBytesToRead));
+        } else {
+          buffers.add(ByteBuffer.wrap(buf));
+        }
+      }
+
+      return new FileContent(fileLength, buffers);
+    } catch (IOException ex) {
+      throw new UncheckedIOException(ex);
+    }
+  }
 }
diff --git 
a/core/src/test/java/org/apache/iceberg/hadoop/TestCatalogUtilDropTable.java 
b/core/src/test/java/org/apache/iceberg/hadoop/TestCatalogUtilDropTable.java
index 9cb44b1341..e3d2b4d8db 100644
--- a/core/src/test/java/org/apache/iceberg/hadoop/TestCatalogUtilDropTable.java
+++ b/core/src/test/java/org/apache/iceberg/hadoop/TestCatalogUtilDropTable.java
@@ -28,6 +28,8 @@ import java.util.UUID;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
 import org.apache.iceberg.GenericBlobMetadata;
 import org.apache.iceberg.GenericStatisticsFile;
 import org.apache.iceberg.ImmutableGenericPartitionStatisticsFile;
@@ -90,13 +92,7 @@ public class TestCatalogUtilDropTable extends 
HadoopTableTestBase {
         .as("should have 1 partition stats file")
         .containsExactly(partitionStatisticsFile.path());
 
-    FileIO fileIO = Mockito.mock(FileIO.class);
-    Mockito.when(fileIO.newInputFile(Mockito.anyString()))
-        .thenAnswer(invocation -> 
table.io().newInputFile(invocation.getArgument(0)));
-    Mockito.when(fileIO.newInputFile(Mockito.anyString(), Mockito.anyLong()))
-        .thenAnswer(
-            invocation ->
-                table.io().newInputFile(invocation.getArgument(0), 
invocation.getArgument(1)));
+    FileIO fileIO = createMockFileIO(table.io());
 
     CatalogUtil.dropTableData(fileIO, tableMetadata);
     ArgumentCaptor<String> argumentCaptor = 
ArgumentCaptor.forClass(String.class);
@@ -141,14 +137,7 @@ public class TestCatalogUtilDropTable extends 
HadoopTableTestBase {
     TableMetadata tableMetadata = readMetadataVersion(3);
     Set<Snapshot> snapshotSet = Sets.newHashSet(table.snapshots());
 
-    FileIO fileIO = Mockito.mock(FileIO.class);
-    Mockito.when(fileIO.newInputFile(Mockito.anyString()))
-        .thenAnswer(invocation -> 
table.io().newInputFile(invocation.getArgument(0)));
-    Mockito.when(fileIO.newInputFile(Mockito.anyString(), Mockito.anyLong()))
-        .thenAnswer(
-            invocation ->
-                table.io().newInputFile(invocation.getArgument(0), 
invocation.getArgument(1)));
-    Mockito.doThrow(new 
RuntimeException()).when(fileIO).deleteFile(ArgumentMatchers.anyString());
+    FileIO fileIO = createMockFileIO(table.io());
 
     CatalogUtil.dropTableData(fileIO, tableMetadata);
     Mockito.verify(
@@ -176,9 +165,7 @@ public class TestCatalogUtilDropTable extends 
HadoopTableTestBase {
     Assertions.assertThat(manifestListLocations).as("should have 2 manifest 
lists").hasSize(2);
     Assertions.assertThat(metadataLocations).as("should have 4 metadata 
locations").hasSize(4);
 
-    FileIO fileIO = Mockito.mock(FileIO.class);
-    Mockito.when(fileIO.newInputFile(Mockito.anyString()))
-        .thenAnswer(invocation -> 
table.io().newInputFile(invocation.getArgument(0)));
+    FileIO fileIO = createMockFileIO(table.io());
 
     CatalogUtil.dropTableData(fileIO, tableMetadata);
     ArgumentCaptor<String> argumentCaptor = 
ArgumentCaptor.forClass(String.class);
@@ -201,6 +188,25 @@ public class TestCatalogUtilDropTable extends 
HadoopTableTestBase {
         .containsAll(metadataLocations);
   }
 
+  private static FileIO createMockFileIO(FileIO wrapped) {
+    FileIO mockIO = Mockito.mock(FileIO.class);
+
+    Mockito.when(mockIO.newInputFile(Mockito.anyString()))
+        .thenAnswer(invocation -> wrapped.newInputFile((String) 
invocation.getArgument(0)));
+    Mockito.when(mockIO.newInputFile(Mockito.anyString(), Mockito.anyLong()))
+        .thenAnswer(
+            invocation ->
+                wrapped.newInputFile(invocation.getArgument(0), 
invocation.getArgument(1)));
+    Mockito.when(mockIO.newInputFile(Mockito.any(ManifestFile.class)))
+        .thenAnswer(invocation -> wrapped.newInputFile((ManifestFile) 
invocation.getArgument(0)));
+    Mockito.when(mockIO.newInputFile(Mockito.any(DataFile.class)))
+        .thenAnswer(invocation -> wrapped.newInputFile((DataFile) 
invocation.getArgument(0)));
+    Mockito.when(mockIO.newInputFile(Mockito.any(DeleteFile.class)))
+        .thenAnswer(invocation -> wrapped.newInputFile((DeleteFile) 
invocation.getArgument(0)));
+
+    return mockIO;
+  }
+
   private static Set<String> manifestListLocations(Set<Snapshot> snapshotSet) {
     return 
snapshotSet.stream().map(Snapshot::manifestListLocation).collect(Collectors.toSet());
   }
diff --git 
a/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java
 
b/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java
index c2b3e7c2dc..f67171708b 100644
--- 
a/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java
+++ 
b/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java
@@ -46,14 +46,11 @@ import org.apache.iceberg.data.BaseDeleteLoader;
 import org.apache.iceberg.data.DeleteFilter;
 import org.apache.iceberg.data.DeleteLoader;
 import org.apache.iceberg.deletes.DeleteCounter;
-import org.apache.iceberg.encryption.EncryptedFiles;
-import org.apache.iceberg.encryption.EncryptedInputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
 import org.apache.iceberg.io.CloseableIterator;
 import org.apache.iceberg.io.InputFile;
 import org.apache.iceberg.mapping.NameMapping;
 import org.apache.iceberg.mapping.NameMappingParser;
-import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
-import org.apache.iceberg.relocated.com.google.common.collect.Maps;
 import org.apache.iceberg.spark.SparkExecutorCache;
 import org.apache.iceberg.spark.SparkSchemaUtil;
 import org.apache.iceberg.types.Type;
@@ -184,25 +181,15 @@ abstract class BaseReader<T, TaskT extends ScanTask> 
implements Closeable {
 
   private Map<String, InputFile> inputFiles() {
     if (lazyInputFiles == null) {
-      Stream<EncryptedInputFile> encryptedFiles =
-          
taskGroup.tasks().stream().flatMap(this::referencedFiles).map(this::toEncryptedInputFile);
-
-      // decrypt with the batch call to avoid multiple RPCs to a key server, 
if possible
-      Iterable<InputFile> decryptedFiles = 
table.encryption().decrypt(encryptedFiles::iterator);
-
-      Map<String, InputFile> files = 
Maps.newHashMapWithExpectedSize(taskGroup.tasks().size());
-      decryptedFiles.forEach(decrypted -> 
files.putIfAbsent(decrypted.location(), decrypted));
-      this.lazyInputFiles = ImmutableMap.copyOf(files);
+      this.lazyInputFiles =
+          EncryptingFileIO.create(table().io(), table().encryption())
+              .bulkDecrypt(
+                  () -> 
taskGroup.tasks().stream().flatMap(this::referencedFiles).iterator());
     }
 
     return lazyInputFiles;
   }
 
-  private EncryptedInputFile toEncryptedInputFile(ContentFile<?> file) {
-    InputFile inputFile = table.io().newInputFile(file.path().toString());
-    return EncryptedFiles.encryptedInput(inputFile, file.keyMetadata());
-  }
-
   protected Map<Integer, ?> constantsMap(ContentScanTask<?> task, Schema 
readSchema) {
     if (readSchema.findField(MetadataColumns.PARTITION_COLUMN_ID) != null) {
       StructType partitionType = Partitioning.partitionType(table);

Reply via email to