Skip to content

Commit 59d07fa

Browse files
authored
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.
1 parent 3bb3e0b commit 59d07fa

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

src/data/impl/LedgerCacheFile.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ LedgerCacheFile::write(DataView dataView)
115115
auto const hash = file.hash();
116116
file.write(hash.data(), decltype(hash)::bytes);
117117

118+
// flush internal buffer explicitly before renaming
119+
if (auto const expectedSuccess = file.close(); not expectedSuccess.has_value()) {
120+
return expectedSuccess;
121+
}
122+
118123
try {
119124
std::filesystem::rename(newFilePath, path_);
120125
} catch (std::exception const& e) {

src/data/impl/OutputFile.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
#include <cstddef>
2525
#include <cstring>
26+
#include <expected>
2627
#include <ios>
2728
#include <string>
2829
#include <utility>
@@ -59,4 +60,14 @@ OutputFile::hash() const
5960
return std::move(sum).finalize();
6061
}
6162

63+
std::expected<void, std::string>
64+
OutputFile::close()
65+
{
66+
file_.close();
67+
if (not file_) {
68+
return std::unexpected{"Error closing cache file"};
69+
}
70+
return {};
71+
}
72+
6273
} // namespace data::impl

src/data/impl/OutputFile.hpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
#include <cstddef>
2727
#include <cstring>
28+
#include <expected>
2829
#include <fstream>
2930
#include <string>
3031

@@ -60,6 +61,9 @@ class OutputFile {
6061
ripple::uint256
6162
hash() const;
6263

64+
std::expected<void, std::string>
65+
close();
66+
6367
private:
6468
void
6569
writeToFile(char const* data, size_t size);

0 commit comments

Comments
 (0)