manuzhang commented on code in PR #1174: URL: https://github.com/apache/iceberg-cpp/pull/1174#discussion_r4756991016
########## src/iceberg/content_cache.cc: ########## @@ -0,0 +1,648 @@ +/* + * 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 <algorithm> +#include <atomic> +#include <cstring> +#include <format> +#include <list> +#include <mutex> +#include <shared_mutex> +#include <stdexcept> +#include <utility> + +#include "iceberg/content_cache_internal.h" +#include "iceberg/util/cache_internal.h" +#include "iceberg/util/error_util_internal.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/property_util.h" +#include "iceberg/util/string_util.h" + +namespace iceberg::internal { + +using CachedFiles = LruCache<std::string, MetadataContent, StringHash, StringEqual>; + +// Owned by the table. The registry guards files and position under its mutex. +// A position is valid while files is non-null. +struct ContentCacheRegistration { + using Entries = std::list<std::weak_ptr<ContentCacheRegistration>>; + Entries::iterator position; + std::shared_ptr<CachedFiles> files; + // Accessed under the per-table mutex. A miss needs no registry lock. + std::weak_ptr<CachedFiles> last_files; +}; + +// Adapters over one storage FileIO share mutation state. Each table still owns +// its own cached bytes. The registry mutex protects the number of bound caches. +struct ContentCacheStorage { + explicit ContentCacheStorage(FileIO* file_io) : io(file_io) {} + FileIO* const io; + size_t caches = 0; + std::shared_mutex mutex; + size_t active_writes = 0; + uint64_t finished_writes = 0; + uint64_t invalidations = 0; + std::atomic<bool> ever_cached = false; +}; + +class ContentCacheRegistry { + public: + explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {} + + ContentCacheStorage& Bind(FileIO* io) { + if (!io) { + throw std::invalid_argument("Content cache requires a storage FileIO"); + } + std::lock_guard lock(mutex_); + auto& storage = storage_.try_emplace(io, io).first->second; + ++storage.caches; + return storage; + } + + void Unbind(ContentCacheStorage& storage) { + std::lock_guard lock(mutex_); + if (--storage.caches == 0) { + storage_.erase(storage.io); + } + } + + bool IsActive(const ContentCacheRegistration& entry, + const std::shared_ptr<CachedFiles>& files, bool promote) { + std::lock_guard lock(mutex_); + if (entry.files != files) { + return false; + } + if (promote) { + entries_.splice(entries_.begin(), entries_, entry.position); + } + return true; + } + + std::shared_ptr<CachedFiles> GetOrCreate( + const std::shared_ptr<ContentCacheRegistration>& entry, size_t max_total_bytes) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry->files) { + entries_.splice(entries_.begin(), entries_, entry->position); + } else { + auto files = std::make_shared<CachedFiles>(static_cast<int64_t>(max_total_bytes)); + entry->position = entries_.emplace(entries_.begin(), entry); + entry->files = std::move(files); + if (std::cmp_greater(entries_.size(), capacity_)) { + evicted = PopLeastRecentlyUsed(); + } + } + return entry->files; + } + + void Erase(ContentCacheRegistration& entry) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry.files) { + entries_.erase(entry.position); + evicted = std::move(entry.files); + } + } + + int32_t SetCapacity(int32_t capacity) { + if (capacity <= 0) { + throw std::invalid_argument( + std::format("Global manifest cache limit must be positive, got {}", capacity)); + } + std::vector<std::shared_ptr<CachedFiles>> evicted; + std::lock_guard lock(mutex_); + if (std::cmp_greater(entries_.size(), capacity)) { + evicted.reserve(entries_.size() - static_cast<size_t>(capacity)); + while (std::cmp_greater(entries_.size(), capacity)) { + evicted.push_back(PopLeastRecentlyUsed()); + } + } + return std::exchange(capacity_, capacity); + } + + private: + // Transfer ownership to the caller so destruction happens after unlocking. + std::shared_ptr<CachedFiles> PopLeastRecentlyUsed() { + auto entry = entries_.back().lock(); + entries_.pop_back(); + return entry ? std::move(entry->files) : nullptr; + } + + std::mutex mutex_; + int32_t capacity_; + ContentCacheRegistration::Entries entries_; + std::unordered_map<const FileIO*, ContentCacheStorage> storage_; +}; + +namespace { + +// Match Iceberg Java's default for iceberg.io.manifest.cache.fileio-max. +constexpr int32_t kDefaultMaxTableCaches = 8; + +std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() { + // Handles keep the registry alive even when destroyed during static teardown. + static auto registry = std::make_shared<ContentCacheRegistry>(kDefaultMaxTableCaches); + return registry; +} + +Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t read_size, + std::string_view file_location) { + if (!std::in_range<size_t>(read_size)) { + return Invalid("File size {} for {} does not fit in size_t", read_size, + file_location); + } + + std::vector<std::byte> content(static_cast<size_t>(read_size)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open()); + auto read_status = stream->ReadFully(/*position=*/0, content); + ICEBERG_RETURN_UNEXPECTED( + FinishWithCloseStatus(std::move(read_status), stream->Close())); + return content; +} + +class SizedInputStream : public SeekableInputStream { + public: + explicit SizedInputStream(MetadataContent content) + : size_(content->size()), content_(std::move(content)) {} + SizedInputStream(std::unique_ptr<SeekableInputStream> input, size_t size) + : size_(size), input_(std::move(input)) {} + + Result<int64_t> Position() const override { + return input_ ? input_->Position() : Result<int64_t>(position_); + } + + Status Seek(int64_t position) override { Review Comment: Tests added. -- 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]
