feat(System): harden OwnedFd/Child process spawn, full-duplex bounds, durable replace_file, safe TempFile/TempDir, and SystemOnly consumer (M-SYSTEM-01, M-SYSTEM-02, M-SYSTEM-05)

This commit is contained in:
faumaray committed 2026-11-24 14:32:05 +03:00
1 parent 3f67b1ecb7
commit fcdbc063b2
14 files changed
+3538 -890

No files matched your search

+105 -84
View File
@@ -1,5 +1,7 @@
#pragma once
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstdint>
#include <optional>
@@ -12,113 +14,132 @@
#include <unistd.h>
#endif
// Generic, app-agnostic process/system resource queries. Used to feed monitors
// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully
// supported; other platforms return nullopt / 0 so callers degrade gracefully.
namespace Void::SystemInfo
{
// ── memory ──────────────────────────────────────────────────────────────
/// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
/// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
#if defined(__linux__)
// /proc/self/statm: "size resident shared text lib data dt" in pages.
std::ifstream statm{"/proc/self/statm"};
std::uint64_t total_pages = 0, resident_pages = 0;
if (statm >> total_pages >> resident_pages) {
const long page = ::sysconf(_SC_PAGESIZE);
if (page > 0) {
return resident_pages * static_cast<std::uint64_t>(page);
}
}
return std::nullopt;
std::ifstream statm{"/proc/self/statm"};
std::uint64_t total_pages = 0, resident_pages = 0;
if (statm >> total_pages >> resident_pages) {
const long page = ::sysconf(_SC_PAGESIZE);
if (page > 0) {
return resident_pages * static_cast<std::uint64_t>(page);
}
}
return std::nullopt;
#else
return std::nullopt;
return std::nullopt;
#endif
}
}
struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work
};
struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work
};
/// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory()
{
/// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory()
{
#if defined(__linux__)
struct ::sysinfo info{};
if (::sysinfo(&info) != 0) {
return std::nullopt;
}
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit;
// freeram excludes reclaimable cache/buffers, so this is conservative.
m.available =
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
return m;
struct ::sysinfo info{};
if (::sysinfo(&info) != 0) {
return std::nullopt;
}
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit;
m.available =
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
return m;
#else
return std::nullopt;
return std::nullopt;
#endif
}
}
// ── CPU ─────────────────────────────────────────────────────────────────
struct CpuSample {
double ratio{0.0};
bool valid{false};
};
/// Samples this process's CPU usage between successive calls. usage()
/// returns the fraction of a single core consumed since the previous
/// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on
/// multi-core workloads). The first call establishes the baseline and
/// returns 0.
class CpuSampler
{
public:
/// Samples this process's CPU usage between successive calls.
/// `sample()` explicitly distinguishes real 0.0 from unavailable sampling.
class CpuSampler
{
public:
explicit CpuSampler(
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance())
: clock_(clock != nullptr ? clock
: &Void::Time::SystemMonotonicClock::instance())
{
reset();
}
CpuSampler() { reset(); }
void reset()
{
wall_ = std::chrono::steady_clock::now();
void reset()
{
wall_ = clock_->now();
baseline_valid_ = false;
#if defined(__linux__)
struct ::tms t{};
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1))
? 0
: (t.tms_utime + t.tms_stime);
struct ::tms t{};
if (::times(&t) != static_cast<::clock_t>(-1)) {
last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
#endif
}
}
[[nodiscard]] double usage()
{
const auto now = std::chrono::steady_clock::now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
[[nodiscard]] CpuSample sample(
const Void::Time::MonotonicClock* override_clock = nullptr)
{
const Void::Time::MonotonicClock* active =
(override_clock != nullptr) ? override_clock : clock_;
const auto now = active->now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
#if defined(__linux__)
const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{};
if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) ||
wall.count() <= 0.0) {
return 0.0;
}
const std::int64_t ticks = t.tms_utime + t.tms_stime;
const double cpu_seconds =
static_cast<double>(ticks - last_ticks_) /
static_cast<double>(hz);
last_ticks_ = ticks;
return cpu_seconds / wall.count();
const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{};
if (!baseline_valid_ || hz <= 0 ||
::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) {
if (::times(&t) != static_cast<::clock_t>(-1)) {
last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
return CpuSample{0.0, false};
}
const std::int64_t ticks = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
const std::int64_t delta_ticks =
(ticks >= last_ticks_) ? (ticks - last_ticks_) : 0;
last_ticks_ = ticks;
const double cpu_seconds =
static_cast<double>(delta_ticks) / static_cast<double>(hz);
return CpuSample{cpu_seconds / wall.count(), true};
#else
return 0.0;
(void)wall;
return CpuSample{0.0, false};
#endif
}
}
private:
[[nodiscard]] double usage()
{
const auto s = sample();
return s.valid ? s.ratio : 0.0;
}
std::chrono::steady_clock::time_point wall_;
private:
const Void::Time::MonotonicClock* clock_;
Void::Time::MonotonicClock::time_point wall_{};
bool baseline_valid_{false};
#if defined(__linux__)
std::int64_t last_ticks_ = 0;
std::int64_t last_ticks_{0};
#endif
};
};
} // namespace Void::SystemInfo
+531 -124
View File
@@ -1,144 +1,551 @@
#pragma once
#include <Void/Log/Log.hpp>
#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 <fstream>
#include <ios>
#include <iterator>
#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
{
/// Read the entire contents of a file as a string.
///
/// Failure modes wrapped in `Result`:
/// - File does not exist
/// - File cannot be opened (permissions, etc.)
/// - I/O error during read
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file(const std::filesystem::path& path)
{
std::ifstream f{path, std::ios::binary};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::read_file: cannot open '{}'", path.string()));
}
std::string content{std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>()};
if (f.bad()) {
Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::read_file: I/O error reading '{}'",
path.string()));
}
Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(),
content.size());
return Void::Result::ok(std::move(content));
}
/// Write `content` to `path`, overwriting any existing file.
///
/// This is NOT crash-safe — a process killed mid-write may leave a
/// truncated file. Use `atomic_write` when you need durability.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
write_file(const std::filesystem::path& path, std::string_view content)
{
std::ofstream f{path, std::ios::binary | std::ios::trunc};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::write_file: cannot open '{}'", path.string()));
}
f.write(content.data(), static_cast<std::streamsize>(content.size()));
f.flush();
if (!f.good()) {
Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::write_file: I/O error writing '{}'",
path.string()));
}
return {};
}
struct ReadFileOptions {
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
};
/// Crash-safe write: stage `content` in a sibling `.tmp` file, then
/// atomically rename onto `path`. The rename is atomic on POSIX
/// within the same filesystem; std::filesystem::rename uses the
/// platform-appropriate primitive (`ReplaceFileW` on Windows).
///
/// Note: this does NOT fsync the staged file before rename. A
/// process or kernel crash between write and rename may leave the
/// `.tmp` file behind, but the original `path` is never corrupted.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_write(const std::filesystem::path& path,
std::string_view content)
{
auto staging = path;
staging += ".tmp";
if (auto r = write_file(staging, content); !r) {
return r;
}
std::error_code ec;
std::filesystem::rename(staging, path, ec);
if (ec) {
std::error_code ignore;
std::filesystem::remove(staging, ignore);
Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}",
path.string(), ec.message());
return Void::Result::fail(std::format(
"FileSystem::atomic_write: rename failed for '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)",
path.string(), content.size());
return {};
}
enum class ReplaceDurability {
atomic_visibility,
durable_sync,
};
/// Create `path` as a directory, including any missing parents.
/// Succeeds (no-op) if `path` already exists as a directory.
[[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 Void::Result::fail(std::format(
"FileSystem::ensure_directory: cannot create '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
return {};
}
enum class ReplacePhase {
validation,
create_stage,
write_stage,
sync_stage,
rename,
sync_parent,
};
/// Remove a file or directory (recursively for directories).
/// Succeeds (no-op) if the path doesn't exist.
[[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 Void::Result::fail(
std::format("FileSystem::remove_path: cannot remove '{}': {}",
path.string(), ec.message()));
}
return {};
}
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
+182 -51
View File
@@ -2,72 +2,203 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <functional>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Process
{
/// Captured output from a completed subprocess.
struct Output {
int exit_code{0};
std::string out; ///< captured stdout
std::string err; ///< captured stderr
};
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL;
/// Live line callbacks for run_streaming(). Each fires (on the calling
/// thread, as output arrives) with one line of output, newline stripped.
/// Either may be left empty. The full output is still accumulated into the
/// returned Output.
struct StreamCallbacks {
std::function<void(std::string_view line)> on_stdout;
std::function<void(std::string_view line)> on_stderr;
};
/// Captured output from a completed subprocess.
struct Output {
int exit_code{0};
std::string out; ///< captured stdout
std::string err; ///< captured stderr
};
/// Run an executable synchronously, capturing stdout and stderr separately.
///
/// @param executable Path to the binary (searched via PATH when relative).
/// @param args Additional arguments passed after argv[0].
/// @param stdin_data Data written to the process's stdin before reading.
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
/// process receives SIGTERM and the call returns.
///
/// Returns an error only when process creation itself fails (pipe or fork
/// failure). A process that exits non-zero still yields a successful Result
/// with the appropriate exit_code. A process whose executable is not found
/// exits with code 127 (POSIX convention).
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Live line callbacks for run_streaming() and communicate_blocking().
struct StreamCallbacks {
std::function<void(std::string_view line)> on_stdout;
std::function<void(std::string_view line)> on_stderr;
};
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr
/// arrive, for progress reporting on long-running or streaming processes.
/// The complete output is still captured into the returned Output.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
enum class OverflowPolicy {
fail_and_terminate,
drain_and_truncate,
};
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
enum class EnvMode {
inherit,
allowlist,
explicit_only,
};
/// Replace the current process image while preserving its PID and inherited
/// environment. Returns only when the platform does not support re-exec or
/// exec fails.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
struct EnvironmentPolicy {
EnvMode mode{EnvMode::inherit};
std::vector<std::string> allowlist{};
std::vector<std::pair<std::string, std::string>> set_vars{};
std::vector<std::string> unset_keys{};
std::vector<std::string> redacted_keys{};
};
struct CaptureLimits {
std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes};
std::size_t max_stderr_bytes{kDefaultMaxStderrBytes};
std::size_t max_line_bytes{kDefaultMaxLineBytes};
std::size_t max_stdin_bytes{kDefaultMaxStdinBytes};
OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate};
};
struct SpawnOptions {
std::filesystem::path executable{};
std::vector<std::string> arguments{};
std::optional<std::filesystem::path> working_directory{};
EnvironmentPolicy environment{};
bool stdin_pipe{true};
bool stdout_pipe{true};
bool stderr_pipe{true};
bool search_path{true};
bool new_process_group{true};
std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}};
};
struct ExitStatus {
bool exited{false};
int code{-1};
int signal{0};
int raw_status{0};
};
struct CommunicateResult {
ExitStatus status{};
std::string out{};
std::string err{};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
};
class Child
{
public:
Child() noexcept = default;
Child(long long pid,
long long pgid,
bool owns_process_group,
Void::System::OwnedFd stdin_fd,
Void::System::OwnedFd stdout_fd,
Void::System::OwnedFd stderr_fd,
std::chrono::milliseconds kill_grace) noexcept;
~Child() noexcept;
Child(const Child&) = delete;
Child& operator=(const Child&) = delete;
Child(Child&& other) noexcept;
Child& operator=(Child&& other) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
[[nodiscard]] int stdin_fd() const noexcept;
[[nodiscard]] int stdout_fd() const noexcept;
[[nodiscard]] int stderr_fd() const noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept;
void close_stdin() noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_signal(int sig) noexcept;
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
[[nodiscard]] Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
try_wait();
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1});
private:
long long pid_{-1};
long long pgid_{-1};
bool owns_group_{false};
bool reaped_{true};
ExitStatus cached_status_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
CaptureLimits limits = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
const StreamCallbacks* callbacks = nullptr);
/// Run an executable synchronously, capturing stdout and stderr separately.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Replace the current process image while preserving its PID and inherited
/// environment.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
/// Replace the current process image with explicit open-descriptor cleanup policy.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments,
bool close_extra_fds);
} // namespace Void::Process
+133 -81
View File
@@ -1,9 +1,13 @@
#pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <system_error>
@@ -12,113 +16,161 @@
namespace Void::FileSystem
{
struct ListDirectoryOptions {
std::size_t max_entries{65536};
};
/// Return true if path exists (file, directory, or symlink).
[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept
{
std::error_code ec;
return std::filesystem::exists(path, ec);
std::error_code ec;
return std::filesystem::exists(path, ec);
}
/// Return the size of a regular file in bytes.
[[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error>
file_size(const std::filesystem::path& path)
file_size(const std::filesystem::path& path)
{
std::error_code ec;
auto sz = std::filesystem::file_size(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(),
ec.message());
return Void::Result::fail(
std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(), ec.message()));
}
return Void::Result::ok(sz);
std::error_code ec;
auto sz = std::filesystem::file_size(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"file_size: cannot stat '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(sz);
}
/// Return the last-write time of a path.
[[nodiscard]] inline Void::Result::
Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path)
Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path)
{
std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(),
ec.message());
return Void::Result::fail(
std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(), ec.message()));
}
return Void::Result::ok(t);
std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"last_modified: cannot stat '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(t);
}
/// List all entries in a directory (non-recursive, filesystem order).
/// List entries in a directory up to `options.max_entries`.
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory_bounded(const std::filesystem::path& path,
ListDirectoryOptions options = {})
{
std::error_code ec;
std::vector<std::filesystem::path> entries;
for (const auto& entry :
std::filesystem::directory_iterator{path, ec}) {
if (ec) {
break;
}
entries.push_back(entry.path());
}
if (ec) {
Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}",
path.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)",
path.string(), entries.size());
return Void::Result::ok(std::move(entries));
std::error_code ec;
std::vector<std::filesystem::path> entries;
for (const auto& entry : std::filesystem::directory_iterator{path, ec}) {
if (ec) {
break;
}
if (entries.size() >= options.max_entries) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"FileSystem::list_directory: '{}' exceeded max_entries ({})",
path.string(),
options.max_entries))};
}
entries.push_back(entry.path());
}
if (ec) {
Void::Log::warn("FileSystem",
"list_directory: cannot iterate '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"list_directory: '{}' ({} entries)",
path.string(),
entries.size());
return Void::Result::ok(std::move(entries));
}
/// List all entries in a directory (bounded at 65,536 default).
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
{
return list_directory_bounded(path, ListDirectoryOptions{});
}
/// Copy a single file. Set overwrite=true to allow replacing an existing dst.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
bool overwrite = false)
copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
bool overwrite = false)
{
std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec);
if (ec) {
Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(),
dst.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::copy_file: '{}' -> '{}': {}",
src.string(), dst.string(), ec.message()));
}
Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(),
dst.string());
return {};
std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec);
if (ec) {
Void::Log::warn("FileSystem",
"copy_file: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::copy_file: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_file: '{}' -> '{}'",
src.string(),
dst.string());
return {};
}
/// Recursively copy a directory tree from src to dst.
/// dst must not already exist; its parent must be accessible.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_dir(const std::filesystem::path& src,
const std::filesystem::path& dst)
copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst)
{
std::error_code ec;
std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive,
ec);
if (ec) {
Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(),
dst.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
src.string(), dst.string(), ec.message()));
}
Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(),
dst.string());
return {};
std::error_code ec;
std::filesystem::copy(
src, dst, std::filesystem::copy_options::recursive, ec);
if (ec) {
Void::Log::warn("FileSystem",
"copy_dir: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_dir: '{}' -> '{}'",
src.string(),
dst.string());
return {};
}
} // namespace Void::FileSystem
+224 -99
View File
@@ -1,126 +1,251 @@
#pragma once
#include <Void/System/Path.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
///
/// The directory is created with a unique name on construction and
/// recursively removed on destruction. Useful in tests that need a
/// scratch area without manual cleanup.
///
/// Construction throws `std::system_error` if the directory cannot
/// be created. Use `TempDir::open(prefix)` for a non-throwing
/// `Result`-returning factory.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_")
: m_path(make_unique_dir(prefix))
{
}
/// RAII scoped directory created with private `0700` permissions and removed
/// safely without following symlinks or deleting replaced directories.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_")
{
auto created = create_unique_dir(
std::filesystem::temp_directory_path(), prefix);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempDir() noexcept
{
if (!m_path.empty()) {
Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string());
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
}
~TempDir() noexcept { remove_if_owned(); }
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {}))
{
}
TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_dev(std::exchange(other.m_dev, 0)),
m_ino(std::exchange(other.m_ino, 0))
{
}
TempDir& operator=(TempDir&& other) noexcept
{
if (this != &other) {
if (!m_path.empty()) {
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
m_path = std::exchange(other.m_path, {});
}
return *this;
}
TempDir& operator=(TempDir&& other) noexcept
{
if (this != &other) {
remove_if_owned();
m_path = std::exchange(other.m_path, {});
m_dev = std::exchange(other.m_dev, 0);
m_ino = std::exchange(other.m_ino, 0);
}
return *this;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
/// Build a path inside the temp dir.
/// Example: `auto log_path = tmp / "test.log";`
[[nodiscard]] std::filesystem::path
operator/(std::string_view relative) const
{
return m_path / relative;
}
[[nodiscard]] std::filesystem::path
operator/(std::string_view relative) const
{
return m_path / relative;
}
/// Non-throwing factory.
[[nodiscard]] static Void::Result::Result<TempDir,
Void::Result::Error>
open(std::string_view prefix = "void_test_")
{
try {
return Void::Result::ok(TempDir{prefix});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open(std::string_view prefix = "void_test_")
{
return open_in(std::filesystem::temp_directory_path(), prefix);
}
private:
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_test_")
{
return create_unique_dir(directory, prefix);
}
std::filesystem::path m_path;
private:
struct InternalEmpty {};
explicit TempDir(InternalEmpty) noexcept {}
static std::filesystem::path
make_unique_dir(std::string_view prefix)
{
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path();
for (int attempt = 0; attempt < 16; ++attempt) {
const auto seed =
static_cast<std::uint64_t>(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
(counter.fetch_add(1, std::memory_order_relaxed)
<< 16) ^
static_cast<std::uint64_t>(std::hash<std::thread::id>{}(
std::this_thread::get_id()));
auto candidate =
base / std::format("{}{:016x}", prefix, seed);
std::error_code ec;
if (std::filesystem::create_directory(candidate, ec)) {
Void::Log::debug("FileSystem", "TempDir: created '{}'",
candidate.string());
return candidate;
}
}
throw std::system_error(
std::make_error_code(std::errc::file_exists),
"TempDir: failed to create unique directory after 16 "
"attempts");
}
};
std::filesystem::path m_path;
std::uint64_t m_dev = 0;
std::uint64_t m_ino = 0;
#ifndef _WIN32
static void clear_dir_contents_nofollow(int dir_fd) noexcept
{
const int dup_fd = ::dup(dir_fd);
if (dup_fd < 0) {
return;
}
DIR* dir = ::fdopendir(dup_fd);
if (dir == nullptr) {
(void)::close(dup_fd);
return;
}
std::vector<std::string> subdirs;
std::vector<std::string> files;
while (const struct dirent* ent = ::readdir(dir)) {
const std::string_view name{ent->d_name};
if (name == "." || name == "..") {
continue;
}
struct stat st {};
if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
continue;
}
if (S_ISDIR(st.st_mode)) {
subdirs.emplace_back(name);
} else {
files.emplace_back(name);
}
}
(void)::closedir(dir);
for (const auto& f : files) {
(void)::unlinkat(dir_fd, f.c_str(), 0);
}
for (const auto& d : subdirs) {
const int sub_fd = ::openat(
dir_fd,
d.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (sub_fd >= 0) {
clear_dir_contents_nofollow(sub_fd);
(void)::close(sub_fd);
(void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR);
}
}
}
#endif
void remove_if_owned() noexcept
{
if (m_path.empty()) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) ||
!S_ISDIR(st.st_mode)) {
return;
}
if (static_cast<std::uint64_t>(st.st_dev) != m_dev ||
static_cast<std::uint64_t>(st.st_ino) != m_ino ||
st.st_uid != ::geteuid()) {
return;
}
const int dir_fd = ::open(
m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (dir_fd < 0) {
return;
}
struct stat fd_st {};
if (::fstat(dir_fd, &fd_st) == 0 &&
static_cast<std::uint64_t>(fd_st.st_dev) == m_dev &&
static_cast<std::uint64_t>(fd_st.st_ino) == m_ino) {
clear_dir_contents_nofollow(dir_fd);
}
(void)::close(dir_fd);
(void)::rmdir(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempDir: removed '{}'", m_path.string());
#endif
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
create_unique_dir(const std::filesystem::path& base,
std::string_view prefix)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempDir: prefix must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate = base / std::format("{}{:016x}", prefix, seed);
if (::mkdir(candidate.c_str(), 0700) == 0) {
const int fd = ::open(
candidate.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: open failed after mkdir",
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: fstat failed",
err)};
}
TempDir out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempDir: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"TempDir: failed creating '{}'", candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempDir: failed to create unique directory after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempDir: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem
+163 -105
View File
@@ -2,135 +2,193 @@
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <fstream>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
///
/// A uniquely-named empty file is created on construction and removed on
/// destruction, unless `keep()` was called. Move-only. Useful for staging
/// downloads, copying a shared library to a fresh inode, etc.
///
/// Construction throws `std::system_error` if the file cannot be created;
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
: m_path(make_unique_file(prefix, extension))
{
}
/// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`).
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
{
auto created = create_unique_file(
std::filesystem::temp_directory_path(), prefix, extension);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempFile() noexcept
{
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
m_path.string());
}
}
~TempFile() noexcept { remove_if_owned(); }
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true))
{
}
TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true)),
m_dev(std::exchange(other.m_dev, 0)),
m_ino(std::exchange(other.m_ino, 0))
{
}
TempFile& operator=(TempFile&& other) noexcept
{
if (this != &other) {
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
}
m_path = std::exchange(other.m_path, {});
m_keep = std::exchange(other.m_keep, true);
}
return *this;
}
TempFile& operator=(TempFile&& other) noexcept
{
if (this != &other) {
remove_if_owned();
m_path = std::exchange(other.m_path, {});
m_keep = std::exchange(other.m_keep, true);
m_dev = std::exchange(other.m_dev, 0);
m_ino = std::exchange(other.m_ino, 0);
}
return *this;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
/// Persist the file beyond this object's lifetime (no removal on
/// destruction). Returns the path for convenience.
std::filesystem::path keep() noexcept
{
m_keep = true;
return m_path;
}
std::filesystem::path keep() noexcept
{
m_keep = true;
return m_path;
}
/// Non-throwing factory.
[[nodiscard]] static Void::Result::Result<TempFile,
Void::Result::Error>
open(std::string_view prefix = "void_",
std::string_view extension = "")
{
try {
return Void::Result::ok(TempFile{prefix, extension});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open(std::string_view prefix = "void_",
std::string_view extension = "")
{
return open_in(
std::filesystem::temp_directory_path(), prefix, extension);
}
private:
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_",
std::string_view extension = "")
{
return create_unique_file(directory, prefix, extension);
}
std::filesystem::path m_path;
bool m_keep = false;
private:
struct InternalEmpty {};
explicit TempFile(InternalEmpty) noexcept {}
static std::filesystem::path
make_unique_file(std::string_view prefix,
std::string_view extension)
{
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path();
for (int attempt = 0; attempt < 16; ++attempt) {
const auto seed =
static_cast<std::uint64_t>(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
(counter.fetch_add(1, std::memory_order_relaxed) << 16) ^
static_cast<std::uint64_t>(
std::hash<std::thread::id>{}(
std::this_thread::get_id()));
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
std::error_code ec;
if (!std::filesystem::exists(candidate, ec)) {
std::ofstream f(candidate);
if (f) {
Void::Log::debug("FileSystem",
"TempFile: created '{}'",
candidate.string());
return candidate;
}
}
}
throw std::system_error(
std::make_error_code(std::errc::file_exists),
"TempFile: failed to create unique file after 16 attempts");
}
};
std::filesystem::path m_path;
bool m_keep = true;
std::uint64_t m_dev = 0;
std::uint64_t m_ino = 0;
void remove_if_owned() noexcept
{
if (m_path.empty() || m_keep) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) &&
S_ISREG(st.st_mode) &&
static_cast<std::uint64_t>(st.st_dev) == m_dev &&
static_cast<std::uint64_t>(st.st_ino) == m_ino) {
(void)::unlink(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempFile: removed '{}'", m_path.string());
}
#endif
}
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
create_unique_file(const std::filesystem::path& base,
std::string_view prefix,
std::string_view extension)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos ||
extension.find('/') != std::string_view::npos ||
extension.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempFile: prefix/extension must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
const int fd = ::open(candidate.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
0600);
if (fd >= 0) {
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::unlink(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempFile: fstat failed",
err)};
}
TempFile out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_keep = false;
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempFile: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("TempFile: failed creating '{}'",
candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempFile: failed to create unique file after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
(void)extension;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempFile: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem
+207
View File
@@ -0,0 +1,207 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <format>
#include <string>
#include <string_view>
#include <utility>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::System
{
enum class SystemErrorCode : std::int32_t {
invalid_argument = 1,
not_found = 2,
permission_denied = 3,
already_exists = 4,
spawn_failed = 5,
exec_failed = 6,
timed_out = 7,
cancelled = 8,
output_limit = 9,
line_limit = 10,
io_error = 11,
sync_failed = 12,
durability_unknown = 13,
limit_exceeded = 14,
busy = 15,
self_join = 16,
unsupported = 17,
unavailable = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_system_error(SystemErrorCode code) noexcept
{
switch (code) {
case SystemErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case SystemErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case SystemErrorCode::already_exists:
case SystemErrorCode::busy:
case SystemErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case SystemErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case SystemErrorCode::cancelled:
return Void::Result::ErrorKind::cancelled;
case SystemErrorCode::output_limit:
case SystemErrorCode::line_limit:
case SystemErrorCode::limit_exceeded:
return Void::Result::ErrorKind::exhausted;
case SystemErrorCode::unsupported:
return Void::Result::ErrorKind::unsupported;
case SystemErrorCode::unavailable:
return Void::Result::ErrorKind::overloaded;
case SystemErrorCode::permission_denied:
case SystemErrorCode::spawn_failed:
case SystemErrorCode::exec_failed:
case SystemErrorCode::io_error:
case SystemErrorCode::sync_failed:
case SystemErrorCode::durability_unknown:
return Void::Result::ErrorKind::io;
case SystemErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline SystemErrorCode
map_errno_to_system_code(int sys_errno) noexcept
{
switch (sys_errno) {
case ENOENT:
return SystemErrorCode::not_found;
case EACCES:
case EPERM:
case EROFS:
return SystemErrorCode::permission_denied;
case EEXIST:
return SystemErrorCode::already_exists;
case ETIMEDOUT:
return SystemErrorCode::timed_out;
case ECANCELED:
return SystemErrorCode::cancelled;
case EBUSY:
return SystemErrorCode::busy;
case EINVAL:
case ENAMETOOLONG:
case EISDIR:
case ENOTDIR:
return SystemErrorCode::invalid_argument;
case ENOSYS:
case EOPNOTSUPP:
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
case ENOTSUP:
#endif
return SystemErrorCode::unsupported;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return SystemErrorCode::unavailable;
default:
return SystemErrorCode::io_error;
}
}
[[nodiscard]] inline Void::Result::Error make_system_error(
SystemErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
if (sys_errno != 0) {
detail = std::format("{} (errno={}: {})",
message,
sys_errno,
std::strerror(sys_errno));
} else {
detail.assign(message);
}
std::error_code sys_ec{};
if (sys_errno != 0) {
sys_ec = std::error_code{sys_errno, std::generic_category()};
}
return Void::Result::Error{
classify_system_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kSystemErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
class OwnedFd
{
public:
OwnedFd() noexcept = default;
explicit OwnedFd(int fd) noexcept : fd_(fd) {}
~OwnedFd() noexcept { reset(); }
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
OwnedFd(OwnedFd&& other) noexcept
: fd_(std::exchange(other.fd_, -1))
{
}
OwnedFd& operator=(OwnedFd&& other) noexcept
{
if (this != &other) {
reset();
fd_ = std::exchange(other.fd_, -1);
}
return *this;
}
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] explicit operator bool() const noexcept { return valid(); }
[[nodiscard]] int get() const noexcept { return fd_; }
[[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); }
void reset(int new_fd = -1) noexcept
{
const int old = std::exchange(fd_, new_fd);
#ifndef _WIN32
if (old >= 0) {
(void)::close(old);
}
#else
(void)old;
#endif
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close() noexcept
{
const int old = std::exchange(fd_, -1);
if (old < 0) {
return {};
}
#ifndef _WIN32
if (::close(old) != 0) {
const int err = errno;
return std::unexpected{make_system_error(
map_errno_to_system_code(err), "OwnedFd::close failed", err)};
}
#endif
return {};
}
private:
int fd_{-1};
};
} // namespace Void::System