Add async/resilience/reflection primitives + FSM v2 rewrite

A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 15:45:16 +03:00
1 parent 43b5a81504
commit 80293ee56f
93 files changed
+8500 -3312

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(Configuration
INTERNAL_DEPS Functional System Data
INTERNAL_DEPS Functional System Data Time
)
+3 -1
View File
@@ -1 +1,3 @@
void_add_module(Data)
void_add_module(Data
INTERNAL_DEPS Time
)
+9
View File
@@ -25,6 +25,15 @@ namespace Void::Logging
m_count = fields.size();
}
FieldScope::FieldScope(
std::vector<std::pair<std::string, std::string>> fields)
{
m_count = fields.size();
for (auto& [k, v] : fields) {
t_fields.emplace_back(std::move(k), std::move(v));
}
}
FieldScope::~FieldScope() noexcept
{
if (!m_active) {
+9 -1
View File
@@ -394,9 +394,14 @@ namespace Void::Logging
if (!entry.fields.empty()) {
auto fobj = Json::object();
for (const auto& [k, v] : entry.fields) {
if (!m_fields.allows(k)) {
continue;
}
fobj.as_object().emplace_back(k, Json::Value{v});
}
o.emplace_back("fields", std::move(fobj));
if (!fobj.as_object().empty()) {
o.emplace_back("fields", std::move(fobj));
}
}
o.emplace_back("message", Json::Value{entry.message});
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
@@ -440,6 +445,9 @@ namespace Void::Logging
out += crumb;
}
for (const auto& [k, v] : entry.fields) {
if (!m_fields.allows(k)) {
continue;
}
out += ' ';
out += k;
out += '=';
+24 -12
View File
@@ -101,13 +101,23 @@ namespace Void::Logging
return std::nullopt;
}
// Field allow/deny lists for the structured (json/logfmt) sinks, from
// the per-sink keys `fields.include` / `fields.exclude` (comma lists).
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
return f;
}
std::shared_ptr<const Formatter>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "pattern") {
auto fmt = std::make_shared<PatternFormatter>(
std::string{cfg.get_or(
auto fmt =
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
"pattern", "{time} [{level}] {scopes}{message}")});
if (cfg.get_or_as<bool>("color", false)) {
fmt->set_color_policy(ColorPolicy::defaults());
@@ -115,10 +125,14 @@ namespace Void::Logging
return fmt;
}
if (format == "json") {
return std::make_shared<JsonLinesFormatter>();
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
if (format == "logfmt") {
return std::make_shared<LogfmtFormatter>();
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
return nullptr; // "default": per-sink built-in rendering
}
@@ -214,8 +228,7 @@ namespace Void::Logging
"split.dir");
}
SplitFileLogger::Options opt;
opt.combined =
sub.get_or_as<bool>("split.combined", true);
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes =
sub.get_or_as<std::size_t>("split.max_kb", 1024) * 1024;
opt.max_files =
@@ -223,8 +236,8 @@ namespace Void::Logging
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink = SplitFileLogger::open(
std::filesystem::path{dir}, opt);
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
@@ -241,15 +254,14 @@ namespace Void::Logging
}
HistoryLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("history.max_kb", 8192) *
1024;
sub.get_or_as<std::size_t>("history.max_kb", 8192) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("history.max_files", 10);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink = HistoryLogger::open(
std::filesystem::path{path}, opt);
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
+1
View File
@@ -0,0 +1 @@
void_add_module(Resilience)
+265 -194
View File
@@ -12,16 +12,25 @@ namespace Void::Process
std::vector<std::string>,
std::string_view,
std::chrono::milliseconds)
{
return Void::Result::fail("Process::run: not implemented on Windows");
}
Void::Result::Result<Output, Void::Result::Error>
run_streaming(const std::filesystem::path&,
std::vector<std::string>,
const StreamCallbacks&,
std::string_view,
std::chrono::milliseconds)
{
return Void::Result::fail(
"Process::run: not implemented on Windows");
"Process::run_streaming: not implemented on Windows");
}
Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view, std::chrono::milliseconds)
{
return Void::Result::fail(
"Process::shell: not implemented on Windows");
return Void::Result::fail("Process::shell: not implemented on Windows");
}
} // namespace Void::Process
@@ -40,210 +49,272 @@ namespace Void::Process
namespace Void::Process
{
namespace
{
// Read into buf until EAGAIN (no more data right now) or EOF.
// Returns true on EOF, false on EAGAIN.
bool drain(int fd, std::string& buf)
namespace
{
char tmp[4096];
for (;;) {
ssize_t n = ::read(fd, tmp, sizeof(tmp));
if (n > 0) {
buf.append(tmp, static_cast<std::size_t>(n));
} else if (n == 0) {
return true; // EOF
} else {
if (errno == EINTR) {
continue;
// Read into buf until EAGAIN (no more data right now) or EOF.
// Returns true on EOF, false on EAGAIN.
bool drain(int fd, std::string& buf)
{
char tmp[4096];
for (;;) {
ssize_t n = ::read(fd, tmp, sizeof(tmp));
if (n > 0) {
buf.append(tmp, static_cast<std::size_t>(n));
} else if (n == 0) {
return true; // EOF
} else {
if (errno == EINTR) {
continue;
}
// EAGAIN / EWOULDBLOCK: no data right now
return false;
}
// EAGAIN / EWOULDBLOCK: no data right now
return false;
}
}
}
void set_nonblock(int fd)
{
int flags = ::fcntl(fd, F_GETFL, 0);
if (flags >= 0) {
::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
void set_nonblock(int fd)
{
int flags = ::fcntl(fd, F_GETFL, 0);
if (flags >= 0) {
::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
}
}
// Close an fd if it is >= 0, then set it to -1.
void safe_close(int& fd)
{
if (fd >= 0) {
::close(fd);
fd = -1;
// Close an fd if it is >= 0, then set it to -1.
void safe_close(int& fd)
{
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
}
} // namespace
Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args,
std::string_view stdin_data,
// Emit newly-completed lines from `buf` (from offset `off`), advancing
// `off`. When `flush` is set, any trailing partial line is emitted too.
void emit_lines(const std::string& buf, std::size_t& off,
const std::function<void(std::string_view)>& fn,
bool flush)
{
if (!fn) {
off = buf.size();
return;
}
std::size_t nl;
while ((nl = buf.find('\n', off)) != std::string::npos) {
std::size_t len = nl - off;
if (len > 0 && buf[off + len - 1] == '\r') {
--len; // strip CR of a CRLF
}
fn(std::string_view{buf.data() + off, len});
off = nl + 1;
}
if (flush && off < buf.size()) {
fn(std::string_view{buf.data() + off, buf.size() - off});
off = buf.size();
}
}
} // namespace
namespace
{
Void::Result::Result<Output, Void::Result::Error>
run_impl(const std::filesystem::path& executable,
std::vector<std::string> args, std::string_view stdin_data,
std::chrono::milliseconds timeout,
const StreamCallbacks* cb)
{
// [0] = read end, [1] = write end
int stdin_pipe[2] = {-1, -1};
int stdout_pipe[2] = {-1, -1};
int stderr_pipe[2] = {-1, -1};
if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 ||
::pipe(stderr_pipe) != 0) {
safe_close(stdin_pipe[0]);
safe_close(stdin_pipe[1]);
safe_close(stdout_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[0]);
safe_close(stderr_pipe[1]);
return Void::Result::fail(std::format(
"Process::run: pipe() failed: {}", std::strerror(errno)));
}
Void::Log::debug("Process", "run: '{}'", executable.string());
std::vector<const char*> argv;
argv.push_back(executable.c_str());
for (const auto& a : args) {
argv.push_back(a.c_str());
}
argv.push_back(nullptr);
pid_t pid = ::fork();
if (pid < 0) {
safe_close(stdin_pipe[0]);
safe_close(stdin_pipe[1]);
safe_close(stdout_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[0]);
safe_close(stderr_pipe[1]);
return Void::Result::fail(std::format(
"Process::run: fork() failed: {}", std::strerror(errno)));
}
if (pid == 0) {
// Child process
::dup2(stdin_pipe[0], STDIN_FILENO);
::dup2(stdout_pipe[1], STDOUT_FILENO);
::dup2(stderr_pipe[1], STDERR_FILENO);
::close(stdin_pipe[0]);
::close(stdin_pipe[1]);
::close(stdout_pipe[0]);
::close(stdout_pipe[1]);
::close(stderr_pipe[0]);
::close(stderr_pipe[1]);
::execvp(
executable.c_str(),
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
const_cast<char* const*>(argv.data()));
// execvp only returns on error; 127 is the POSIX convention
::_exit(127);
}
// Parent: close child-side ends
safe_close(stdin_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[1]);
// Write stdin and close immediately so the child sees EOF
if (!stdin_data.empty()) {
const char* p = stdin_data.data();
std::size_t remaining = stdin_data.size();
while (remaining > 0) {
ssize_t n = ::write(stdin_pipe[1], p, remaining);
if (n < 0) {
if (errno == EINTR) {
continue;
}
break; // child likely closed stdin; ignore
}
p += static_cast<std::size_t>(n);
remaining -= static_cast<std::size_t>(n);
}
}
safe_close(stdin_pipe[1]);
set_nonblock(stdout_pipe[0]);
set_nonblock(stderr_pipe[0]);
Output output;
bool out_done = false;
bool err_done = false;
std::size_t out_emitted = 0;
std::size_t err_emitted = 0;
const bool has_timeout = timeout.count() > 0;
const auto deadline =
std::chrono::steady_clock::now() +
(has_timeout ? timeout : std::chrono::milliseconds{30'000});
while (!out_done || !err_done) {
struct pollfd pfds[2];
int nfds = 0;
if (!out_done) {
pfds[nfds++] = {stdout_pipe[0], POLLIN, 0};
}
if (!err_done) {
pfds[nfds++] = {stderr_pipe[0], POLLIN, 0};
}
auto left_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (left_ms <= 0) {
::kill(pid, SIGTERM);
break;
}
int ret = ::poll(pfds, static_cast<nfds_t>(nfds),
static_cast<int>(left_ms));
if (ret < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if (ret == 0) {
// Wall-clock timeout expired
::kill(pid, SIGTERM);
break;
}
for (int i = 0; i < nfds; ++i) {
if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) {
continue;
}
const bool is_out = (pfds[i].fd == stdout_pipe[0]);
bool& done = is_out ? out_done : err_done;
std::string& buf = is_out ? output.out : output.err;
bool eof = drain(pfds[i].fd, buf);
if (cb) {
emit_lines(buf, is_out ? out_emitted : err_emitted,
is_out ? cb->on_stdout : cb->on_stderr,
/*flush=*/false);
}
// POLLHUP means the write end was closed; no more data will
// arrive
if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) {
done = true;
}
}
}
if (cb) {
emit_lines(output.out, out_emitted, cb->on_stdout,
/*flush=*/true);
emit_lines(output.err, err_emitted, cb->on_stderr,
/*flush=*/true);
}
safe_close(stdout_pipe[0]);
safe_close(stderr_pipe[0]);
int status = 0;
::waitpid(pid, &status, 0);
output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
Void::Log::debug("Process", "run: '{}' exited {}",
executable.string(), output.exit_code);
return Void::Result::ok(std::move(output));
}
} // namespace
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)
{
return run_impl(executable, std::move(args), stdin_data, timeout,
nullptr);
}
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)
{
// [0] = read end, [1] = write end
int stdin_pipe[2] = {-1, -1};
int stdout_pipe[2] = {-1, -1};
int stderr_pipe[2] = {-1, -1};
if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 ||
::pipe(stderr_pipe) != 0) {
safe_close(stdin_pipe[0]);
safe_close(stdin_pipe[1]);
safe_close(stdout_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[0]);
safe_close(stderr_pipe[1]);
return Void::Result::fail(std::format("Process::run: pipe() failed: {}",
std::strerror(errno)));
{
return run_impl(executable, std::move(args), stdin_data, timeout,
&callbacks);
}
Void::Log::debug("Process", "run: '{}'", executable.string());
std::vector<const char*> argv;
argv.push_back(executable.c_str());
for (const auto& a : args) {
argv.push_back(a.c_str());
Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command, std::chrono::milliseconds timeout)
{
return run("/bin/sh", {"-c", std::string{command}}, {}, timeout);
}
argv.push_back(nullptr);
pid_t pid = ::fork();
if (pid < 0) {
safe_close(stdin_pipe[0]);
safe_close(stdin_pipe[1]);
safe_close(stdout_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[0]);
safe_close(stderr_pipe[1]);
return Void::Result::fail(std::format("Process::run: fork() failed: {}",
std::strerror(errno)));
}
if (pid == 0) {
// Child process
::dup2(stdin_pipe[0], STDIN_FILENO);
::dup2(stdout_pipe[1], STDOUT_FILENO);
::dup2(stderr_pipe[1], STDERR_FILENO);
::close(stdin_pipe[0]);
::close(stdin_pipe[1]);
::close(stdout_pipe[0]);
::close(stdout_pipe[1]);
::close(stderr_pipe[0]);
::close(stderr_pipe[1]);
::execvp(executable.c_str(),
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
const_cast<char* const*>(argv.data()));
// execvp only returns on error; 127 is the POSIX convention
::_exit(127);
}
// Parent: close child-side ends
safe_close(stdin_pipe[0]);
safe_close(stdout_pipe[1]);
safe_close(stderr_pipe[1]);
// Write stdin and close immediately so the child sees EOF
if (!stdin_data.empty()) {
const char* p = stdin_data.data();
std::size_t remaining = stdin_data.size();
while (remaining > 0) {
ssize_t n = ::write(stdin_pipe[1], p, remaining);
if (n < 0) {
if (errno == EINTR) {
continue;
}
break; // child likely closed stdin; ignore
}
p += static_cast<std::size_t>(n);
remaining -= static_cast<std::size_t>(n);
}
}
safe_close(stdin_pipe[1]);
set_nonblock(stdout_pipe[0]);
set_nonblock(stderr_pipe[0]);
Output output;
bool out_done = false;
bool err_done = false;
const bool has_timeout = timeout.count() > 0;
const auto deadline =
std::chrono::steady_clock::now() +
(has_timeout ? timeout : std::chrono::milliseconds{30'000});
while (!out_done || !err_done) {
struct pollfd pfds[2];
int nfds = 0;
if (!out_done) {
pfds[nfds++] = {stdout_pipe[0], POLLIN, 0};
}
if (!err_done) {
pfds[nfds++] = {stderr_pipe[0], POLLIN, 0};
}
auto left_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (left_ms <= 0) {
::kill(pid, SIGTERM);
break;
}
int ret = ::poll(pfds, static_cast<nfds_t>(nfds),
static_cast<int>(left_ms));
if (ret < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if (ret == 0) {
// Wall-clock timeout expired
::kill(pid, SIGTERM);
break;
}
for (int i = 0; i < nfds; ++i) {
if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) {
continue;
}
bool& done =
(pfds[i].fd == stdout_pipe[0]) ? out_done : err_done;
std::string& buf =
(pfds[i].fd == stdout_pipe[0]) ? output.out : output.err;
bool eof = drain(pfds[i].fd, buf);
// POLLHUP means the write end was closed; no more data will arrive
if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) {
done = true;
}
}
}
safe_close(stdout_pipe[0]);
safe_close(stderr_pipe[0]);
int status = 0;
::waitpid(pid, &status, 0);
output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
Void::Log::debug("Process", "run: '{}' exited {}", executable.string(),
output.exit_code);
return Void::Result::ok(std::move(output));
}
Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command, std::chrono::milliseconds timeout)
{
return run("/bin/sh", {"-c", std::string{command}}, {}, timeout);
}
} // namespace Void::Process