Void::Log facade (header-only, macro-free):
- Leveled function templates trace/debug/info/warn/error/fatal(module,
fmt, args...) with lazy formatting - a disabled call is one relaxed
atomic load, no allocation, no formatting.
- Global min level + per-module overrides (can raise or lower); empty
sink/Disabled level = logging fully off; set_sink remains the splice
point for external logging libraries.
Void::Logging::Logger - async by default, one class for both modes:
- Mode::Async (default): lock-free MPSC queue + logger-owned worker
delivering batches via on_flush outside any lock; Immediate/Buffered
give synchronous behavior via constructor arg or set_mode at runtime.
- Bounded queue with OverflowPolicy{Block, DropNewest, DropOldest};
flush() (now virtual) blocks until everything submitted is delivered;
base destructor only stops/joins the worker, never touches virtuals.
- Fixed a wakeup race: stale park token + fresh release overflowed the
binary semaphore; wakeup is a counting semaphore (spurious wakes are
absorbed by the worker loop).
New sinks and formatters:
- RotatingFileLogger (size-based rotation, max-files cap), NullLogger,
CallbackLogger, MultiLogger (tee via new Logger::relay), SyslogLogger.
- Formatter interface: PatternFormatter ({time}/{level}/{scopes}/...),
JsonLinesFormatter, LogfmtFormatter; installable on Console/File/
Rotating sinks. Console/File sinks now default to Async.
- Logging::from_config builds the whole sink tree from Config keys;
apply_facade_config drives facade levels.
Configuration:
- Typed get_as<T>/get_or_as<T> (numbers, bool spellings, enums by name,
chrono durations), dotted keys, subtree(), sorted keys().
- New sources: from_env_prefix (APP_LOG__LEVEL -> log.level), from_ini
(sections as prefixes), from_json (objects/arrays flattened),
from_args (--key=value / --key value / --flag).
- Bind.hpp: reflection bind<T>(cfg, prefix) fills aggregates; defaults
in the struct are the schema; nested aggregates, optional, vector.
- Watch.hpp: ConfigWatch reloads on change with per-key diff; parse
failures keep the previous config.
System: new FileSystem::FileWatcher - debounced polling watcher (stable
mtime+size across N polls), callbacks off-thread, deletion events;
shared groundwork for plugin hot-reload.
Sweep: all internal Void::Log::log call sites migrated to the leveled
API ("Umbrella.Feature" labels); Plugin loader now logs load/reload.
918 tests green (28 new), stable across 30 consecutive runs, ASan+UBSan
clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
145 lines
4.9 KiB
C++
145 lines
4.9 KiB
C++
#pragma once
|
|
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <fstream>
|
|
#include <ios>
|
|
#include <iterator>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
#include <utility>
|
|
|
|
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 {};
|
|
}
|
|
|
|
/// 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 {};
|
|
}
|
|
|
|
/// 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 {};
|
|
}
|
|
|
|
/// 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 {};
|
|
}
|
|
|
|
} // namespace Void::FileSystem
|