wgtmac commented on code in PR #875:
URL: https://github.com/apache/iceberg-cpp/pull/875#discussion_r4465938049


##########
src/iceberg/metadata_cache.h:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/// \file iceberg/metadata_cache.h
+/// \brief A bounded cache for immutable Iceberg metadata file content.
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for cached metadata file content.
+///
+/// The property names and defaults match Apache Iceberg Java's manifest 
content cache.
+/// The cache is disabled by default.
+struct ICEBERG_EXPORT MetadataCacheOptions {
+  inline static constexpr std::string_view kEnabled = 
"io.manifest.cache-enabled";
+  inline static constexpr std::string_view kExpirationIntervalMs =
+      "io.manifest.cache.expiration-interval-ms";
+  inline static constexpr std::string_view kMaxTotalBytes =
+      "io.manifest.cache.max-total-bytes";
+  inline static constexpr std::string_view kMaxContentLength =
+      "io.manifest.cache.max-content-length";
+
+  bool enabled = false;
+  /// Zero disables time-based expiration; positive values expire after last 
access.
+  int64_t expiration_interval_ms = 60 * 1000;
+  /// Maximum combined weight of cached entries.
+  size_t max_total_bytes = 100 * 1024 * 1024;
+  /// Files larger than this value are read without being cached.
+  size_t max_content_length = 8 * 1024 * 1024;
+
+  friend bool operator==(const MetadataCacheOptions&,
+                         const MetadataCacheOptions&) = default;
+
+  /// \brief Parse cache options from catalog/FileIO properties.
+  static Result<MetadataCacheOptions> FromProperties(
+      const std::unordered_map<std::string, std::string>& properties);
+};
+
+/// \brief Thread-safe, size-bounded cache of immutable metadata file bytes.
+///
+/// Entries expire after the configured interval since their last access and 
are evicted
+/// in least-recently-used order to enforce the total byte limit. Concurrent 
loads for
+/// the same location are coalesced. Load failures are not cached.
+class ICEBERG_EXPORT MetadataCache {
+ public:
+  using Content = std::shared_ptr<const std::string>;
+  using Loader = std::function<Result<Content>()>;
+
+  static Result<std::shared_ptr<MetadataCache>> Make(MetadataCacheOptions 
options);
+
+  ~MetadataCache();
+  MetadataCache(const MetadataCache&) = delete;
+  MetadataCache& operator=(const MetadataCache&) = delete;
+
+  const MetadataCacheOptions& options() const noexcept;
+
+  /// \brief Return cached content or invoke loader and cache its result when 
eligible.
+  Result<Content> Get(std::string location, std::optional<size_t> length, 
Loader loader);
+
+  /// \brief Return an unexpired cached entry without loading it.
+  Content GetIfPresent(std::string_view location);
+
+  /// \brief Invalidate one location, waiting for an in-progress load if 
necessary.
+  void Invalidate(std::string_view location);
+
+  /// \brief Invalidate all currently cached entries.
+  void Clear();
+
+  size_t size() const;

Review Comment:
   Please add simple docstring for both `size` and `total_bytes`.



##########
src/iceberg/metadata_cache.cc:
##########
@@ -0,0 +1,365 @@
+/*
+ * 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.
+ */
+
+#include "iceberg/metadata_cache.h"
+
+#include <algorithm>
+#include <chrono>
+#include <condition_variable>
+#include <limits>
+#include <list>
+#include <mutex>
+#include <utility>
+
+#include "iceberg/util/macros.h"
+#include "iceberg/util/string_util.h"
+
+namespace iceberg {
+
+namespace {
+
+template <typename T>
+Result<T> ParseNumberProperty(
+    const std::unordered_map<std::string, std::string>& properties, 
std::string_view key,
+    T default_value) {
+  auto it = properties.find(std::string(key));
+  if (it == properties.end()) {
+    return default_value;
+  }
+  auto value = StringUtils::ParseNumber<T>(it->second);
+  if (!value.has_value()) {
+    return InvalidArgument("Invalid numeric value '{}' for property '{}': {}", 
it->second,
+                           key, value.error().message);
+  }
+  return value;
+}
+
+}  // namespace
+
+Result<MetadataCacheOptions> MetadataCacheOptions::FromProperties(
+    const std::unordered_map<std::string, std::string>& properties) {
+  MetadataCacheOptions options;
+  if (auto it = properties.find(std::string(kEnabled)); it != 
properties.end()) {
+    options.enabled = StringUtils::ParseBoolean(it->second);
+  }
+
+  ICEBERG_ASSIGN_OR_RAISE(options.expiration_interval_ms,
+                          ParseNumberProperty(properties, 
kExpirationIntervalMs,
+                                              options.expiration_interval_ms));
+  ICEBERG_ASSIGN_OR_RAISE(
+      options.max_total_bytes,
+      ParseNumberProperty(properties, kMaxTotalBytes, 
options.max_total_bytes));
+  ICEBERG_ASSIGN_OR_RAISE(
+      options.max_content_length,
+      ParseNumberProperty(properties, kMaxContentLength, 
options.max_content_length));
+  return options;
+}
+
+class MetadataCache::Impl {
+ public:
+  using Clock = std::chrono::steady_clock;
+
+  explicit Impl(MetadataCacheOptions options) : options_(std::move(options)) {}
+
+  struct Entry {

Review Comment:
   It seems that we are reimplementing a LRU cache and it is similar to 
src/iceberg/catalog/rest/auth/auth_session_cache_internal.h and 
src/iceberg/util/cache_internal.h. It is not blocking that we should consider 
refactoring them into a shared implementation if possible as a followup.



##########
src/iceberg/metadata_cache.h:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/// \file iceberg/metadata_cache.h
+/// \brief A bounded cache for immutable Iceberg metadata file content.
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for cached metadata file content.
+///
+/// The property names and defaults match Apache Iceberg Java's manifest 
content cache.
+/// The cache is disabled by default.
+struct ICEBERG_EXPORT MetadataCacheOptions {
+  inline static constexpr std::string_view kEnabled = 
"io.manifest.cache-enabled";
+  inline static constexpr std::string_view kExpirationIntervalMs =
+      "io.manifest.cache.expiration-interval-ms";
+  inline static constexpr std::string_view kMaxTotalBytes =
+      "io.manifest.cache.max-total-bytes";
+  inline static constexpr std::string_view kMaxContentLength =
+      "io.manifest.cache.max-content-length";
+
+  bool enabled = false;
+  /// Zero disables time-based expiration; positive values expire after last 
access.
+  int64_t expiration_interval_ms = 60 * 1000;
+  /// Maximum combined weight of cached entries.
+  size_t max_total_bytes = 100 * 1024 * 1024;
+  /// Files larger than this value are read without being cached.
+  size_t max_content_length = 8 * 1024 * 1024;
+
+  friend bool operator==(const MetadataCacheOptions&,
+                         const MetadataCacheOptions&) = default;
+
+  /// \brief Parse cache options from catalog/FileIO properties.
+  static Result<MetadataCacheOptions> FromProperties(
+      const std::unordered_map<std::string, std::string>& properties);
+};
+
+/// \brief Thread-safe, size-bounded cache of immutable metadata file bytes.
+///
+/// Entries expire after the configured interval since their last access and 
are evicted
+/// in least-recently-used order to enforce the total byte limit. Concurrent 
loads for
+/// the same location are coalesced. Load failures are not cached.
+class ICEBERG_EXPORT MetadataCache {
+ public:
+  using Content = std::shared_ptr<const std::string>;
+  using Loader = std::function<Result<Content>()>;
+
+  static Result<std::shared_ptr<MetadataCache>> Make(MetadataCacheOptions 
options);
+
+  ~MetadataCache();
+  MetadataCache(const MetadataCache&) = delete;
+  MetadataCache& operator=(const MetadataCache&) = delete;
+
+  const MetadataCacheOptions& options() const noexcept;
+
+  /// \brief Return cached content or invoke loader and cache its result when 
eligible.
+  Result<Content> Get(std::string location, std::optional<size_t> length, 
Loader loader);

Review Comment:
   Should we use `std::string_view` for location which `GetIfPresent` exactly 
uses?



##########
src/iceberg/metadata_cache.h:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/// \file iceberg/metadata_cache.h
+/// \brief A bounded cache for immutable Iceberg metadata file content.
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for cached metadata file content.
+///
+/// The property names and defaults match Apache Iceberg Java's manifest 
content cache.
+/// The cache is disabled by default.
+struct ICEBERG_EXPORT MetadataCacheOptions {
+  inline static constexpr std::string_view kEnabled = 
"io.manifest.cache-enabled";
+  inline static constexpr std::string_view kExpirationIntervalMs =
+      "io.manifest.cache.expiration-interval-ms";
+  inline static constexpr std::string_view kMaxTotalBytes =
+      "io.manifest.cache.max-total-bytes";
+  inline static constexpr std::string_view kMaxContentLength =
+      "io.manifest.cache.max-content-length";
+
+  bool enabled = false;
+  /// Zero disables time-based expiration; positive values expire after last 
access.
+  int64_t expiration_interval_ms = 60 * 1000;
+  /// Maximum combined weight of cached entries.
+  size_t max_total_bytes = 100 * 1024 * 1024;
+  /// Files larger than this value are read without being cached.
+  size_t max_content_length = 8 * 1024 * 1024;
+
+  friend bool operator==(const MetadataCacheOptions&,
+                         const MetadataCacheOptions&) = default;
+
+  /// \brief Parse cache options from catalog/FileIO properties.
+  static Result<MetadataCacheOptions> FromProperties(
+      const std::unordered_map<std::string, std::string>& properties);
+};
+
+/// \brief Thread-safe, size-bounded cache of immutable metadata file bytes.
+///
+/// Entries expire after the configured interval since their last access and 
are evicted
+/// in least-recently-used order to enforce the total byte limit. Concurrent 
loads for
+/// the same location are coalesced. Load failures are not cached.
+class ICEBERG_EXPORT MetadataCache {
+ public:
+  using Content = std::shared_ptr<const std::string>;

Review Comment:
   Should we use `std::vector<std::byte>`?



##########
src/iceberg/file_io.h:
##########
@@ -181,6 +211,17 @@ class ICEBERG_EXPORT FileIO {
 
   /// \brief Return storage-credential support when implemented by this FileIO.
   virtual SupportsStorageCredentials* AsSupportsStorageCredentials() { return 
nullptr; }
+
+ private:
+  struct MetadataCacheState {
+    std::mutex mutex;
+    std::shared_ptr<MetadataCache> cache;
+  };
+
+  std::shared_ptr<MetadataCache> GetMetadataCache() const;
+
+  std::shared_ptr<MetadataCacheState> metadata_cache_state_ =

Review Comment:
   I'm hesitant to make the cache as a member variable of FileIO, which 
complicates the internal state but is not used in many cases. But I also think 
the Java pattern is not something we should follow. Perhaps we can investigate 
how other iceberg implementations deal with manifest cache and then think about 
our solution?
   



##########
src/iceberg/file_io.h:
##########
@@ -154,6 +157,33 @@ class ICEBERG_EXPORT FileIO {
   virtual Result<std::string> ReadFile(const std::string& file_location,
                                        std::optional<size_t> length);
 
+  /// \brief Create an input handle backed by the metadata content cache when 
enabled.
+  ///
+  /// This is intended for immutable Iceberg manifest lists and manifests. 
Data files
+  /// and table metadata JSON should use NewInputFile or ReadFile directly.
+  Result<std::unique_ptr<InputFile>> NewCachedInputFile(
+      std::string file_location, std::optional<size_t> length = std::nullopt);

Review Comment:
   Why pass by value? Should it be `const std::string&` or `std::string_view`?



##########
src/iceberg/metadata_cache.h:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/// \file iceberg/metadata_cache.h
+/// \brief A bounded cache for immutable Iceberg metadata file content.
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for cached metadata file content.
+///
+/// The property names and defaults match Apache Iceberg Java's manifest 
content cache.
+/// The cache is disabled by default.
+struct ICEBERG_EXPORT MetadataCacheOptions {
+  inline static constexpr std::string_view kEnabled = 
"io.manifest.cache-enabled";
+  inline static constexpr std::string_view kExpirationIntervalMs =
+      "io.manifest.cache.expiration-interval-ms";
+  inline static constexpr std::string_view kMaxTotalBytes =
+      "io.manifest.cache.max-total-bytes";
+  inline static constexpr std::string_view kMaxContentLength =
+      "io.manifest.cache.max-content-length";
+
+  bool enabled = false;
+  /// Zero disables time-based expiration; positive values expire after last 
access.
+  int64_t expiration_interval_ms = 60 * 1000;
+  /// Maximum combined weight of cached entries.
+  size_t max_total_bytes = 100 * 1024 * 1024;
+  /// Files larger than this value are read without being cached.
+  size_t max_content_length = 8 * 1024 * 1024;
+
+  friend bool operator==(const MetadataCacheOptions&,
+                         const MetadataCacheOptions&) = default;
+
+  /// \brief Parse cache options from catalog/FileIO properties.
+  static Result<MetadataCacheOptions> FromProperties(
+      const std::unordered_map<std::string, std::string>& properties);
+};
+
+/// \brief Thread-safe, size-bounded cache of immutable metadata file bytes.
+///
+/// Entries expire after the configured interval since their last access and 
are evicted
+/// in least-recently-used order to enforce the total byte limit. Concurrent 
loads for
+/// the same location are coalesced. Load failures are not cached.
+class ICEBERG_EXPORT MetadataCache {

Review Comment:
   For the naming, I think `MetadataCache` is not that precise. If we cannot 
find a better name, we can just follow Java to use `ContentCache` because it 
caches actually pure file content instead of concrete metadata.



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