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

+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