feat(Runtime): add inert Host, validated RuntimeLimits, EmbeddedResources, and topological ResourceGraph (S-RUNTIME-01)

This commit is contained in:
faumaray committed 2026-11-24 09:33:03 +03:00
1 parent 673bb7e8b4
commit 1b3331e3a8
9 files changed
+812 -1

No files matched your search

+249
View File
@@ -0,0 +1,249 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Runtime/ResourceGraph.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace Void::Runtime
{
enum class HostState {
constructed,
starting,
running,
stopping_admission,
draining,
joining,
stopped,
failed_start,
shutdown_incomplete
};
struct EmbeddedResources {
Async::Executor* executor{nullptr};
IO::Driver* io{nullptr};
const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()};
Void::Memory::BudgetResource* memory_budget{nullptr};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (executor == nullptr) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"EmbeddedResources::executor must not be null")};
}
if (io == nullptr) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"EmbeddedResources::io must not be null")};
}
if (clock == nullptr) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"EmbeddedResources::clock must not be null")};
}
return {};
}
};
struct ShutdownReport {
bool complete{true};
HostState state{HostState::stopped};
std::size_t pending_owners{0};
std::vector<std::string> pending_owner_ids{};
};
[[nodiscard]] inline ResourceGraph make_default_resource_graph(bool embedded_mode)
{
const ResourceOwnership own =
embedded_mode ? ResourceOwnership::borrowed : ResourceOwnership::owned;
ResourceGraph g;
(void)g.add_node(ResourceNode{"clock", ResourceKind::clock, own, true});
(void)g.add_node(ResourceNode{"memory_budget", ResourceKind::memory_budget, own, true});
(void)g.add_node(ResourceNode{"executor", ResourceKind::executor, own, true});
(void)g.add_node(ResourceNode{"io_driver", ResourceKind::io_driver, own, true});
(void)g.add_dependency("executor", "clock");
(void)g.add_dependency("executor", "memory_budget");
(void)g.add_dependency("io_driver", "clock");
(void)g.add_dependency("io_driver", "memory_budget");
(void)g.add_dependency("io_driver", "executor");
return g;
}
// Inert P1 Runtime composition handle: validates options, memory/time/IO limits,
// borrowed resources, and topological resource lifecycle order without implicitly
// spawning threads or opening descriptors on construction.
class Host
{
public:
Host(const Host&) = delete;
Host& operator=(const Host&) = delete;
Host(Host&&) noexcept = default;
Host& operator=(Host&&) noexcept = default;
~Host() = default;
[[nodiscard]] static Void::Result::Result<Host> create(Options options = {})
{
if (auto ok = validate_options(options); !ok.has_value()) {
return std::unexpected{std::move(ok.error())};
}
ResourceGraph g = make_default_resource_graph(options.embedded_mode);
auto plan = g.validate_and_plan();
if (!plan.has_value()) {
return std::unexpected{std::move(plan.error())};
}
auto budget = std::make_unique<Void::Memory::BudgetResource>(
options.limits.max_owned_memory_bytes);
return Host{
std::move(options),
std::move(*plan),
EmbeddedResources{},
std::move(budget)};
}
[[nodiscard]] static Void::Result::Result<Host> create_embedded(
Options options, EmbeddedResources embedded)
{
options.embedded_mode = true;
if (auto ok = validate_options(options); !ok.has_value()) {
return std::unexpected{std::move(ok.error())};
}
if (auto eok = embedded.validate(); !eok.has_value()) {
return std::unexpected{std::move(eok.error())};
}
ResourceGraph g = make_default_resource_graph(true);
auto plan = g.validate_and_plan();
if (!plan.has_value()) {
return std::unexpected{std::move(plan.error())};
}
std::unique_ptr<Void::Memory::BudgetResource> budget;
if (embedded.memory_budget == nullptr) {
budget = std::make_unique<Void::Memory::BudgetResource>(
options.limits.max_owned_memory_bytes);
}
return Host{
std::move(options),
std::move(*plan),
embedded,
std::move(budget)};
}
[[nodiscard]] HostState state() const noexcept { return state_; }
[[nodiscard]] bool is_running() const noexcept { return state_ == HostState::running; }
[[nodiscard]] std::size_t started_worker_count() const noexcept { return started_workers_; }
[[nodiscard]] const Options& options() const noexcept { return options_; }
[[nodiscard]] const LifecyclePlan& lifecycle_plan() const noexcept { return plan_; }
[[nodiscard]] const EmbeddedResources& embedded_resources() const noexcept { return embedded_; }
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept
{
return embedded_.clock ? *embedded_.clock
: Void::Time::SystemMonotonicClock::instance();
}
[[nodiscard]] Void::Memory::BudgetResource& memory_budget() noexcept
{
return embedded_.memory_budget ? *embedded_.memory_budget : *owned_budget_;
}
private:
friend class HostBuilder;
Host(Options options,
LifecyclePlan plan,
EmbeddedResources embedded,
std::unique_ptr<Void::Memory::BudgetResource> owned_budget) noexcept
: options_(std::move(options))
, plan_(std::move(plan))
, embedded_(embedded)
, owned_budget_(std::move(owned_budget))
{
}
HostState state_{HostState::constructed};
std::size_t started_workers_{0};
Options options_{};
LifecyclePlan plan_{};
EmbeddedResources embedded_{};
std::unique_ptr<Void::Memory::BudgetResource> owned_budget_{};
};
class HostBuilder
{
public:
HostBuilder()
: graph_(make_default_resource_graph(false))
{
}
HostBuilder& with_options(Options options)
{
options_ = std::move(options);
if (!embedded_.has_value()) {
graph_ = make_default_resource_graph(options_.embedded_mode);
}
return *this;
}
HostBuilder& with_embedded(EmbeddedResources embedded)
{
options_.embedded_mode = true;
embedded_ = embedded;
graph_ = make_default_resource_graph(true);
return *this;
}
[[nodiscard]] Void::Result::Result<void> add_resource(ResourceNode node)
{
return graph_.add_node(std::move(node));
}
[[nodiscard]] Void::Result::Result<void> add_dependency(
std::string dependent, std::string dependency, bool required = true)
{
return graph_.add_dependency(
std::move(dependent), std::move(dependency), required);
}
[[nodiscard]] Void::Result::Result<Host> build() const
{
Options opts = options_;
if (embedded_.has_value()) {
opts.embedded_mode = true;
if (auto eok = embedded_->validate(); !eok.has_value()) {
return std::unexpected{std::move(eok.error())};
}
}
if (auto ok = validate_options(opts); !ok.has_value()) {
return std::unexpected{std::move(ok.error())};
}
auto plan = graph_.validate_and_plan();
if (!plan.has_value()) {
return std::unexpected{std::move(plan.error())};
}
const EmbeddedResources emb = embedded_.value_or(EmbeddedResources{});
std::unique_ptr<Void::Memory::BudgetResource> budget;
if (emb.memory_budget == nullptr) {
budget = std::make_unique<Void::Memory::BudgetResource>(
opts.limits.max_owned_memory_bytes);
}
return Host{std::move(opts), std::move(*plan), emb, std::move(budget)};
}
private:
Options options_{};
std::optional<EmbeddedResources> embedded_{};
ResourceGraph graph_;
};
} // namespace Void::Runtime
+168
View File
@@ -0,0 +1,168 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/IO/Types.hpp>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <string>
#include <thread>
#include <utility>
namespace Void::Runtime
{
inline constexpr std::uint32_t kRuntimeErrorDomain = 11;
enum class RuntimeErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
not_found = 2,
conflict = 3,
cycle_detected = 4,
invalid_state = 5,
unsupported = 6,
internal = 7
};
[[nodiscard]] inline Void::Result::Error make_runtime_error(
RuntimeErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case RuntimeErrorCode::none:
kind = ErrorKind::internal;
break;
case RuntimeErrorCode::invalid_argument:
kind = ErrorKind::invalid_argument;
break;
case RuntimeErrorCode::not_found:
kind = ErrorKind::not_found;
break;
case RuntimeErrorCode::conflict:
case RuntimeErrorCode::cycle_detected:
case RuntimeErrorCode::invalid_state:
kind = ErrorKind::conflict;
break;
case RuntimeErrorCode::unsupported:
kind = ErrorKind::unsupported;
break;
case RuntimeErrorCode::internal:
kind = ErrorKind::internal;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{kRuntimeErrorDomain, static_cast<std::int32_t>(code)}};
}
struct RuntimeLimits {
std::size_t max_cpu_tasks{4096};
std::size_t max_io_operations{8192};
std::size_t max_file_queue{256};
std::size_t max_timers{1024};
std::size_t max_services{256};
std::size_t max_owned_memory_bytes{256ULL * 1024ULL * 1024ULL};
};
struct ShutdownPolicy {
std::chrono::milliseconds drain_grace{5000};
std::chrono::milliseconds export_flush_timeout{5000};
std::chrono::milliseconds total_timeout{30000};
};
[[nodiscard]] inline std::uint32_t default_cpu_workers() noexcept
{
const std::uint32_t hw = std::thread::hardware_concurrency();
return std::clamp<std::uint32_t>(hw, 1u, 8u);
}
struct Options {
std::uint32_t cpu_workers{default_cpu_workers()};
std::uint32_t file_workers{4};
bool embedded_mode{false};
RuntimeLimits limits{};
ShutdownPolicy shutdown{};
IO::BackendOptions io{};
};
[[nodiscard]] inline Void::Result::Result<void> validate_options(const Options& opts)
{
if (!opts.embedded_mode) {
if (opts.cpu_workers == 0) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"Runtime Options::cpu_workers must be >= 1 in managed mode")};
}
if (opts.file_workers == 0) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"Runtime Options::file_workers must be >= 1 in managed mode")};
}
}
const auto& l = opts.limits;
if (l.max_cpu_tasks == 0 ||
l.max_io_operations == 0 ||
l.max_file_queue == 0 ||
l.max_timers == 0 ||
l.max_services == 0 ||
l.max_owned_memory_bytes == 0) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"All RuntimeLimits capacity bounds must be non-zero")};
}
const auto& s = opts.shutdown;
if (s.drain_grace.count() <= 0 ||
s.export_flush_timeout.count() <= 0 ||
s.total_timeout.count() <= 0) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"ShutdownPolicy durations must be strictly positive")};
}
if (s.drain_grace > s.total_timeout || s.export_flush_timeout > s.total_timeout) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"ShutdownPolicy drain_grace and export_flush_timeout must not exceed total_timeout")};
}
if (auto io_ok = IO::validate_limits(opts.io.limits); !io_ok.has_value()) {
return std::unexpected{std::move(io_ok.error())};
}
// Submodule IO caps cannot exceed global host caps.
if (opts.io.limits.max_operations > l.max_io_operations) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"IO::IoLimits::max_operations exceeds RuntimeLimits::max_io_operations")};
}
if (opts.io.limits.max_timers > l.max_timers && opts.io.limits.max_timers != 4096) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"IO::IoLimits::max_timers exceeds RuntimeLimits::max_timers")};
}
if (opts.io.limits.max_file_queue > l.max_file_queue) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"IO::IoLimits::max_file_queue exceeds RuntimeLimits::max_file_queue")};
}
if (opts.io.limits.max_owned_buffer_bytes > l.max_owned_memory_bytes) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"IO::IoLimits::max_owned_buffer_bytes exceeds RuntimeLimits::max_owned_memory_bytes")};
}
return {};
}
} // namespace Void::Runtime
+153
View File
@@ -0,0 +1,153 @@
#pragma once
#include <Void/Algorithms/Graph.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Runtime/Options.hpp>
#include <algorithm>
#include <cstddef>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Runtime
{
enum class ResourceOwnership {
owned,
borrowed
};
enum class ResourceKind {
clock,
memory_budget,
executor,
io_driver,
service,
exporter,
custom
};
struct ResourceNode {
std::string id{};
ResourceKind kind{ResourceKind::custom};
ResourceOwnership ownership{ResourceOwnership::owned};
bool critical{true};
};
struct LifecyclePlan {
std::vector<std::string> startup_order{};
std::vector<std::string> shutdown_order{};
};
class ResourceGraph
{
public:
[[nodiscard]] Void::Result::Result<void> add_node(ResourceNode node)
{
if (node.id.empty()) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"ResourceGraph node id must not be empty")};
}
if (index_by_id_.contains(node.id)) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::conflict,
"Duplicate ResourceGraph node id: " + node.id)};
}
const std::size_t idx = nodes_.size();
index_by_id_.emplace(node.id, idx);
nodes_.push_back(std::move(node));
return {};
}
// Registers that `dependent` requires `dependency` to start first and stop last.
[[nodiscard]] Void::Result::Result<void> add_dependency(
std::string dependent, std::string dependency, bool required = true)
{
if (dependent.empty() || dependency.empty()) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"ResourceGraph dependency ids must not be empty")};
}
edges_.push_back(PendingEdge{
std::move(dependent), std::move(dependency), required});
return {};
}
[[nodiscard]] std::size_t node_count() const noexcept { return nodes_.size(); }
[[nodiscard]] Void::Result::Result<LifecyclePlan> validate_and_plan() const
{
const std::size_t n = nodes_.size();
std::vector<std::vector<std::size_t>> adj(n);
for (const auto& e : edges_) {
const auto dep_it = index_by_id_.find(e.dependent);
if (dep_it == index_by_id_.end()) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::not_found,
"Unknown dependent node in ResourceGraph: " + e.dependent)};
}
const auto target_it = index_by_id_.find(e.dependency);
if (target_it == index_by_id_.end()) {
if (e.required) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::not_found,
"Missing required dependency '" + e.dependency +
"' for resource '" + e.dependent + "'")};
}
continue;
}
const std::size_t from = target_it->second; // dependency starts first
const std::size_t to = dep_it->second; // dependent starts after
if (std::find(adj[from].begin(), adj[from].end(), to) == adj[from].end()) {
adj[from].push_back(to);
}
}
const Void::Algorithms::AdjacencyView view{adj};
const auto topo = Void::Algorithms::topological_order(view);
if (!topo.has_value()) {
if (topo.error().code == Void::Algorithms::AlgorithmError::Code::cycle_detected) {
std::string witness;
for (std::size_t i = 0; i < topo.error().cycle.size(); ++i) {
if (i > 0) {
witness += " -> ";
}
const std::size_t idx = topo.error().cycle[i];
witness += (idx < nodes_.size()) ? nodes_[idx].id : "?";
}
return std::unexpected{make_runtime_error(
RuntimeErrorCode::cycle_detected,
"ResourceGraph dependency cycle detected: " + witness)};
}
return std::unexpected{make_runtime_error(
RuntimeErrorCode::internal, topo.error().message)};
}
LifecyclePlan plan;
plan.startup_order.reserve(n);
for (const std::size_t idx : topo->order) {
plan.startup_order.push_back(nodes_[idx].id);
}
plan.shutdown_order = plan.startup_order;
std::reverse(plan.shutdown_order.begin(), plan.shutdown_order.end());
return plan;
}
private:
struct PendingEdge {
std::string dependent;
std::string dependency;
bool required{true};
};
std::vector<ResourceNode> nodes_{};
std::unordered_map<std::string, std::size_t> index_by_id_{};
std::vector<PendingEdge> edges_{};
};
} // namespace Void::Runtime