fix: Flush buffers before renaming cache file (#2927)

If clio shuts itself down due to exceeding graceful period when cache is
saved and renamed but the buffers are not flushed, we may end up with a
corrupted cache file. Clio will detect corruption and will not load
corrupted cache file, but we could avoid it by explicitly flushing
ofstream buffer.
This commit is contained in:
Sergey Kuznetsov
2026-01-22 11:35:00 +00:00
committed by GitHub
parent 3bb3e0b9f9
commit 59d07fab64
3 changed files with 20 additions and 0 deletions

View File

@@ -115,6 +115,11 @@ LedgerCacheFile::write(DataView dataView)
auto const hash = file.hash();
file.write(hash.data(), decltype(hash)::bytes);
// flush internal buffer explicitly before renaming
if (auto const expectedSuccess = file.close(); not expectedSuccess.has_value()) {
return expectedSuccess;
}
try {
std::filesystem::rename(newFilePath, path_);
} catch (std::exception const& e) {

View File

@@ -23,6 +23,7 @@
#include <cstddef>
#include <cstring>
#include <expected>
#include <ios>
#include <string>
#include <utility>
@@ -59,4 +60,14 @@ OutputFile::hash() const
return std::move(sum).finalize();
}
std::expected<void, std::string>
OutputFile::close()
{
file_.close();
if (not file_) {
return std::unexpected{"Error closing cache file"};
}
return {};
}
} // namespace data::impl

View File

@@ -25,6 +25,7 @@
#include <cstddef>
#include <cstring>
#include <expected>
#include <fstream>
#include <string>
@@ -60,6 +61,9 @@ public:
ripple::uint256
hash() const;
std::expected<void, std::string>
close();
private:
void
writeToFile(char const* data, size_t size);