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

+124
View File
@@ -0,0 +1,124 @@
#pragma once
#include <chrono>
#include <cstdint>
#include <optional>
#if defined(__linux__)
#include <fstream>
#include <string>
#include <sys/sysinfo.h>
#include <sys/times.h>
#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()
{
#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;
#else
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
};
/// 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;
#else
return std::nullopt;
#endif
}
// ── CPU ─────────────────────────────────────────────────────────────────
/// 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:
CpuSampler() { reset(); }
void reset()
{
wall_ = std::chrono::steady_clock::now();
#if defined(__linux__)
struct ::tms t{};
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1))
? 0
: (t.tms_utime + t.tms_stime);
#endif
}
[[nodiscard]] double usage()
{
const auto now = std::chrono::steady_clock::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();
#else
return 0.0;
#endif
}
private:
std::chrono::steady_clock::time_point wall_;
#if defined(__linux__)
std::int64_t last_ticks_ = 0;
#endif
};
} // namespace Void::SystemInfo
+49 -27
View File
@@ -5,40 +5,62 @@
#include <chrono>
#include <filesystem>
#include <functional>
#include <string>
#include <string_view>
#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
};
/// 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(). 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;
};
/// 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});
/// 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});
/// 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});
/// 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});
} // namespace Void::Process