552 lines
19 KiB
C++
552 lines
19 KiB
C++
#pragma once
|
|
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/System/Types.hpp>
|
|
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <functional>
|
|
#include <optional>
|
|
#include <span>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
#ifndef _WIN32
|
|
#include <fcntl.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
#if defined(__linux__)
|
|
#include <sys/random.h>
|
|
#endif
|
|
#endif
|
|
|
|
namespace Void::FileSystem
|
|
{
|
|
|
|
struct ReadFileOptions {
|
|
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
|
};
|
|
|
|
enum class ReplaceDurability {
|
|
atomic_visibility,
|
|
durable_sync,
|
|
};
|
|
|
|
enum class ReplacePhase {
|
|
validation,
|
|
create_stage,
|
|
write_stage,
|
|
sync_stage,
|
|
rename,
|
|
sync_parent,
|
|
};
|
|
|
|
struct ReplaceFailure {
|
|
Void::Result::Error error{};
|
|
ReplacePhase phase{ReplacePhase::validation};
|
|
bool visible_on_disk{false};
|
|
bool durability_unknown{false};
|
|
};
|
|
|
|
/// Optional test hook: return a POSIX errno to inject a failure at `phase`.
|
|
using ReplaceFaultHook = std::function<std::optional<int>(ReplacePhase phase)>;
|
|
|
|
struct ReplaceOptions {
|
|
ReplaceDurability durability{ReplaceDurability::durable_sync};
|
|
unsigned mode{0644};
|
|
ReplaceFaultHook fault_hook{};
|
|
};
|
|
|
|
namespace detail
|
|
{
|
|
|
|
[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept
|
|
{
|
|
static std::atomic<std::uint64_t> counter{0};
|
|
std::uint64_t rnd = 0;
|
|
#if defined(__linux__)
|
|
if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast<ssize_t>(sizeof(rnd))) {
|
|
return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12);
|
|
}
|
|
#endif
|
|
const auto now = static_cast<std::uint64_t>(
|
|
std::chrono::steady_clock::now().time_since_epoch().count());
|
|
return now ^ (counter.fetch_add(1, std::memory_order_relaxed) *
|
|
0x9e3779b97f4a7c15ULL);
|
|
}
|
|
|
|
#ifndef _WIN32
|
|
[[nodiscard]] inline int fsync_eintr(int fd) noexcept
|
|
{
|
|
for (;;) {
|
|
if (::fsync(fd) == 0) {
|
|
return 0;
|
|
}
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
return errno;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
} // namespace detail
|
|
|
|
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
|
read_file_bounded(const std::filesystem::path& path,
|
|
ReadFileOptions options = {})
|
|
{
|
|
#ifndef _WIN32
|
|
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::read_file: cannot open '{}'", path.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd guard{fd};
|
|
|
|
struct stat st {};
|
|
if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
|
|
const auto sz = static_cast<std::uint64_t>(st.st_size);
|
|
if (sz > options.max_bytes) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
|
|
path.string(),
|
|
sz,
|
|
options.max_bytes))};
|
|
}
|
|
}
|
|
|
|
std::string content;
|
|
std::array<char, 8192> buf{};
|
|
for (;;) {
|
|
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
|
if (n > 0) {
|
|
const auto un = static_cast<std::size_t>(n);
|
|
if (un > options.max_bytes - content.size()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
|
|
path.string(),
|
|
options.max_bytes))};
|
|
}
|
|
content.append(buf.data(), un);
|
|
} else if (n == 0) {
|
|
break;
|
|
} else {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"read_file: I/O error reading '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::read_file: I/O error reading '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
}
|
|
Void::Log::debug("FileSystem",
|
|
"read_file: '{}' ({} bytes)",
|
|
path.string(),
|
|
content.size());
|
|
return content;
|
|
#else
|
|
(void)path;
|
|
(void)options;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::read_file: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
/// Read the entire contents of a file as a string (bounded at 16 MiB default).
|
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
|
read_file(const std::filesystem::path& path)
|
|
{
|
|
return read_file_bounded(path, ReadFileOptions{});
|
|
}
|
|
|
|
/// Write `content` to `path`, overwriting any existing file (not crash-safe).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
write_file(const std::filesystem::path& path, std::string_view content)
|
|
{
|
|
#ifndef _WIN32
|
|
const int fd =
|
|
::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
|
|
if (fd < 0) {
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"write_file: cannot open '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::write_file: cannot open '{}'", path.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd guard{fd};
|
|
|
|
std::size_t off = 0;
|
|
while (off < content.size()) {
|
|
const ssize_t n =
|
|
::write(fd, content.data() + off, content.size() - off);
|
|
if (n < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"write_file: I/O error writing '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::write_file: I/O error writing '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
off += static_cast<std::size_t>(n);
|
|
}
|
|
return guard.close();
|
|
#else
|
|
(void)path;
|
|
(void)content;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::write_file: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
/// Atomically stage and replace `path`, distinguishing atomic visibility vs
|
|
/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir).
|
|
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
|
|
const std::filesystem::path& path,
|
|
std::span<const std::byte> bytes,
|
|
ReplaceOptions options = {})
|
|
{
|
|
#ifndef _WIN32
|
|
auto check_fault = [&](ReplacePhase phase,
|
|
bool visible,
|
|
bool unknown) -> std::optional<ReplaceFailure> {
|
|
if (options.fault_hook) {
|
|
if (const auto injected = options.fault_hook(phase)) {
|
|
return ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
unknown
|
|
? Void::System::SystemErrorCode::durability_unknown
|
|
: Void::System::map_errno_to_system_code(*injected),
|
|
std::format("FileSystem::replace_file: injected fault for '{}'",
|
|
path.string()),
|
|
*injected),
|
|
phase,
|
|
visible,
|
|
unknown};
|
|
}
|
|
}
|
|
return std::nullopt;
|
|
};
|
|
|
|
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
if (path.empty() || !path.has_filename()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: empty path or missing filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
const std::filesystem::path parent =
|
|
path.parent_path().empty() ? std::filesystem::path{"."}
|
|
: path.parent_path();
|
|
const std::string target_name = path.filename().string();
|
|
if (target_name == "." || target_name == "..") {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: invalid target filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
const int raw_dir_fd = ::open(
|
|
parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
|
if (raw_dir_fd < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: cannot open parent '{}'",
|
|
parent.string()),
|
|
err),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
Void::System::OwnedFd dir_fd{raw_dir_fd};
|
|
|
|
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::string tmp_name;
|
|
Void::System::OwnedFd tmp_fd;
|
|
int last_err = 0;
|
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
|
tmp_name = std::format(
|
|
".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy());
|
|
const int fd = ::openat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW |
|
|
O_CLOEXEC,
|
|
static_cast<mode_t>(options.mode));
|
|
if (fd >= 0) {
|
|
tmp_fd.reset(fd);
|
|
break;
|
|
}
|
|
last_err = errno;
|
|
if (last_err != EEXIST) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(last_err),
|
|
std::format(
|
|
"FileSystem::replace_file: cannot create temp in '{}'",
|
|
parent.string()),
|
|
last_err),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
if (!tmp_fd.valid()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::already_exists,
|
|
"FileSystem::replace_file: exhausted temp names",
|
|
last_err),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
bool cleanup_temp = true;
|
|
struct TempCleanup {
|
|
int dir_fd{-1};
|
|
const std::string* name{nullptr};
|
|
bool* active{nullptr};
|
|
~TempCleanup() noexcept
|
|
{
|
|
if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) {
|
|
(void)::unlinkat(dir_fd, name->c_str(), 0);
|
|
}
|
|
}
|
|
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp};
|
|
|
|
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::size_t off = 0;
|
|
while (off < bytes.size()) {
|
|
const ssize_t n =
|
|
::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off);
|
|
if (n < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: write failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
off += static_cast<std::size_t>(n);
|
|
}
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::sync_failed,
|
|
std::format(
|
|
"FileSystem::replace_file: stage fsync failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
|
|
if (auto closed = tmp_fd.close(); !closed.has_value()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
std::move(closed.error()),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
if (::renameat(
|
|
dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) !=
|
|
0) {
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: rename failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::rename,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
// Rename succeeded: target is now visible on disk; never unlink target!
|
|
cleanup_temp = false;
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::durability_unknown,
|
|
std::format(
|
|
"FileSystem::replace_file: parent dir fsync failed after rename for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_parent,
|
|
true,
|
|
true}};
|
|
}
|
|
}
|
|
|
|
Void::Log::debug("FileSystem",
|
|
"replace_file: '{}' committed ({} bytes)",
|
|
path.string(),
|
|
bytes.size());
|
|
return {};
|
|
#else
|
|
(void)path;
|
|
(void)bytes;
|
|
(void)options;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::replace_file: unsupported platform"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
#endif
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
|
|
const std::filesystem::path& path,
|
|
std::string_view content,
|
|
ReplaceOptions options = {})
|
|
{
|
|
const auto* ptr = reinterpret_cast<const std::byte*>(content.data());
|
|
return replace_file(path, std::span<const std::byte>{ptr, content.size()}, std::move(options));
|
|
}
|
|
|
|
/// Crash-safe write: stages content in a unique temp file and atomically
|
|
/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to
|
|
/// preserve 1.x atomic replacement behavior safely across concurrent writers.
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
atomic_write(const std::filesystem::path& path, std::string_view content)
|
|
{
|
|
auto res = replace_file(
|
|
path,
|
|
content,
|
|
ReplaceOptions{.durability = ReplaceDurability::atomic_visibility});
|
|
if (!res.has_value()) {
|
|
Void::Log::warn("FileSystem",
|
|
"atomic_write: failed for '{}': {}",
|
|
path.string(),
|
|
res.error().error.message());
|
|
return std::unexpected{std::move(res.error().error)};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
/// Create `path` as a directory, including any missing parents.
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
ensure_directory(const std::filesystem::path& path)
|
|
{
|
|
std::error_code ec;
|
|
if (std::filesystem::is_directory(path, ec)) {
|
|
return {};
|
|
}
|
|
std::filesystem::create_directories(path, ec);
|
|
if (ec) {
|
|
Void::Log::warn("FileSystem",
|
|
"ensure_directory: cannot create '{}': {}",
|
|
path.string(),
|
|
ec.message());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(ec.value()),
|
|
std::format("FileSystem::ensure_directory: cannot create '{}': {}",
|
|
path.string(),
|
|
ec.message()))};
|
|
}
|
|
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
|
|
return {};
|
|
}
|
|
|
|
/// Remove a file or directory (recursively for directories).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
remove_path(const std::filesystem::path& path)
|
|
{
|
|
std::error_code ec;
|
|
std::filesystem::remove_all(path, ec);
|
|
if (ec) {
|
|
Void::Log::warn("FileSystem",
|
|
"remove_path: cannot remove '{}': {}",
|
|
path.string(),
|
|
ec.message());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(ec.value()),
|
|
std::format("FileSystem::remove_path: cannot remove '{}': {}",
|
|
path.string(),
|
|
ec.message()))};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
} // namespace Void::FileSystem
|