539 lines
14 KiB
C++
539 lines
14 KiB
C++
#pragma once
|
|
|
|
#include <Void/Fsm/StateKey.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
#include <Void/Service/Registry.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Fsm
|
|
{
|
|
enum class SupervisionMode : std::uint8_t {
|
|
StopOnFault = 0,
|
|
BoundedRestart
|
|
};
|
|
|
|
struct SupervisionPolicy {
|
|
SupervisionMode mode{SupervisionMode::StopOnFault};
|
|
std::size_t max_restarts{3};
|
|
std::chrono::nanoseconds restart_window{std::chrono::seconds{60}};
|
|
std::chrono::nanoseconds initial_backoff{
|
|
std::chrono::milliseconds{10}};
|
|
};
|
|
|
|
struct OrchestratorLimits {
|
|
std::size_t max_supervised{1024};
|
|
};
|
|
|
|
struct SupervisionEvent {
|
|
enum class Kind : std::uint8_t {
|
|
Launched = 0,
|
|
RestartScheduled,
|
|
Restarted,
|
|
Released,
|
|
Exhausted
|
|
};
|
|
Kind kind{Kind::Launched};
|
|
Status status{Status::Idle};
|
|
TerminationReason reason{TerminationReason::none};
|
|
std::size_t restarts{0};
|
|
std::string detail{};
|
|
};
|
|
|
|
namespace Detail
|
|
{
|
|
// Type-erased supervised FSM. Models wrap a concrete Machine<R>
|
|
// subclass; the orchestrator drives lifecycle, status, and bounded
|
|
// restart.
|
|
class FsmConcept
|
|
{
|
|
public:
|
|
|
|
virtual ~FsmConcept() = default;
|
|
virtual void stop() = 0;
|
|
virtual void restart() = 0;
|
|
[[nodiscard]] virtual Status status() const = 0;
|
|
[[nodiscard]] virtual TerminationReason
|
|
termination_reason() const = 0;
|
|
[[nodiscard]] virtual std::optional<FsmError>
|
|
system_error() const = 0;
|
|
};
|
|
|
|
template <typename F> class FsmModel final : public FsmConcept
|
|
{
|
|
public:
|
|
|
|
explicit FsmModel(std::unique_ptr<F> fsm)
|
|
: m_fsm(std::move(fsm))
|
|
{
|
|
}
|
|
|
|
~FsmModel() override
|
|
{
|
|
if (m_fsm) {
|
|
m_fsm->stop();
|
|
}
|
|
}
|
|
|
|
void stop() override { m_fsm->stop(); }
|
|
void restart() override { m_fsm->restart(); }
|
|
[[nodiscard]] Status status() const override
|
|
{
|
|
return m_fsm->status();
|
|
}
|
|
[[nodiscard]] TerminationReason
|
|
termination_reason() const override
|
|
{
|
|
return m_fsm->termination_reason();
|
|
}
|
|
[[nodiscard]] std::optional<FsmError>
|
|
system_error() const override
|
|
{
|
|
return m_fsm->system_error();
|
|
}
|
|
|
|
[[nodiscard]] F& get() noexcept { return *m_fsm; }
|
|
|
|
private:
|
|
|
|
std::unique_ptr<F> m_fsm;
|
|
};
|
|
|
|
struct SupervisedEntry {
|
|
std::shared_ptr<FsmConcept> model;
|
|
SupervisionPolicy policy{};
|
|
std::vector<Time::MonotonicClock::time_point>
|
|
restart_timestamps;
|
|
std::optional<Time::MonotonicClock::time_point>
|
|
next_restart_at;
|
|
std::atomic<std::size_t> restarts{0};
|
|
mutable std::mutex evidence_mu;
|
|
bool released{false};
|
|
Status final_status{Status::Idle};
|
|
TerminationReason final_reason{TerminationReason::none};
|
|
std::optional<FsmError> final_error{};
|
|
};
|
|
} // namespace Detail
|
|
|
|
/// Owning handle to a supervised FSM instance: holds a shared_ptr so
|
|
/// immutable termination evidence and any still-required cleanup ownership
|
|
/// survive even after the Orchestrator releases a finished entry from
|
|
/// active supervision.
|
|
class FsmHandle
|
|
{
|
|
public:
|
|
|
|
FsmHandle() = default;
|
|
|
|
void stop() const
|
|
{
|
|
if (m_entry && m_entry->model) {
|
|
m_entry->model->stop();
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] Status status() const
|
|
{
|
|
if (!m_entry) {
|
|
return Status::Idle;
|
|
}
|
|
std::lock_guard lk{m_entry->evidence_mu};
|
|
if (m_entry->released) {
|
|
return m_entry->final_status;
|
|
}
|
|
return m_entry->model ? m_entry->model->status() : Status::Idle;
|
|
}
|
|
|
|
[[nodiscard]] bool finished() const { return terminal(status()); }
|
|
|
|
[[nodiscard]] TerminationReason termination_reason() const
|
|
{
|
|
if (!m_entry) {
|
|
return TerminationReason::none;
|
|
}
|
|
std::lock_guard lk{m_entry->evidence_mu};
|
|
if (m_entry->released) {
|
|
return m_entry->final_reason;
|
|
}
|
|
return m_entry->model ? m_entry->model->termination_reason()
|
|
: TerminationReason::none;
|
|
}
|
|
|
|
[[nodiscard]] std::optional<FsmError> system_error() const
|
|
{
|
|
if (!m_entry) {
|
|
return std::nullopt;
|
|
}
|
|
std::lock_guard lk{m_entry->evidence_mu};
|
|
if (m_entry->released) {
|
|
return m_entry->final_error;
|
|
}
|
|
return m_entry->model ? m_entry->model->system_error()
|
|
: std::nullopt;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t restart_count() const noexcept
|
|
{
|
|
return m_entry
|
|
? m_entry->restarts.load(std::memory_order_acquire)
|
|
: 0;
|
|
}
|
|
|
|
[[nodiscard]] explicit operator bool() const noexcept
|
|
{
|
|
return m_entry != nullptr && m_entry->model != nullptr;
|
|
}
|
|
|
|
private:
|
|
|
|
friend class Orchestrator;
|
|
explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
|
|
: m_entry(std::move(entry))
|
|
{
|
|
}
|
|
|
|
std::shared_ptr<Detail::SupervisedEntry> m_entry;
|
|
};
|
|
|
|
// ── Orchestrator ──────────────────────────────────────────────────────
|
|
class Orchestrator
|
|
{
|
|
public:
|
|
|
|
using ObserverCallback =
|
|
std::function<void(const SupervisionEvent&)>;
|
|
|
|
explicit Orchestrator(
|
|
const Time::MonotonicClock* clock = nullptr,
|
|
OrchestratorLimits limits = {}) noexcept
|
|
: m_clock(clock != nullptr
|
|
? clock
|
|
: &Time::SystemMonotonicClock::instance()),
|
|
m_limits(limits)
|
|
{
|
|
}
|
|
|
|
~Orchestrator() { stop_all(); }
|
|
|
|
Orchestrator(const Orchestrator&) = delete;
|
|
Orchestrator& operator=(const Orchestrator&) = delete;
|
|
|
|
[[nodiscard]] Service::ServiceRegistry& services() noexcept
|
|
{
|
|
return m_registry;
|
|
}
|
|
|
|
void start_services()
|
|
{
|
|
m_registry.start_all();
|
|
m_services_started = true;
|
|
m_services_stopped = false;
|
|
}
|
|
|
|
template <typename F, typename... Args>
|
|
[[nodiscard]] Void::Result::Result<FsmHandle>
|
|
try_launch(SupervisionPolicy policy, Args&&... args)
|
|
{
|
|
std::vector<ObserverCallback> observers_copy;
|
|
std::shared_ptr<Detail::SupervisedEntry> entry;
|
|
{
|
|
reap_finished_and_notify();
|
|
std::lock_guard lock{m_mutex};
|
|
if (m_limits.max_supervised > 0 &&
|
|
m_entries.size() >= m_limits.max_supervised) {
|
|
return Void::Result::fail(make_fsm_error(
|
|
FsmErrorCode::limit_exceeded,
|
|
"Orchestrator: max_supervised limit reached"));
|
|
}
|
|
auto fsm =
|
|
std::make_unique<F>(std::forward<Args>(args)...);
|
|
fsm->set_services(m_registry);
|
|
fsm->start();
|
|
auto model =
|
|
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
|
|
entry = std::make_shared<Detail::SupervisedEntry>();
|
|
entry->model = std::move(model);
|
|
entry->policy = policy;
|
|
m_entries.push_back(entry);
|
|
}
|
|
|
|
notify_observers(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::Launched,
|
|
.status = entry->model->status(),
|
|
.reason = entry->model->termination_reason(),
|
|
.restarts = 0,
|
|
.detail = {}});
|
|
return FsmHandle{std::move(entry)};
|
|
}
|
|
|
|
template <typename F, typename... Args>
|
|
FsmHandle launch(Args&&... args)
|
|
{
|
|
auto r = try_launch<F>(SupervisionPolicy{},
|
|
std::forward<Args>(args)...);
|
|
return r ? *r : FsmHandle{};
|
|
}
|
|
|
|
/// Drive supervision rules (bounded restarts with injected Time
|
|
/// backoff, and releasing terminal entries while handles keep
|
|
/// immutable evidence). Returns actions taken (restarts + releases).
|
|
std::size_t supervise_step()
|
|
{
|
|
std::vector<SupervisionEvent> events;
|
|
std::vector<std::shared_ptr<Detail::SupervisedEntry>>
|
|
to_restart;
|
|
const auto now = m_clock->now();
|
|
|
|
{
|
|
std::lock_guard lock{m_mutex};
|
|
for (auto it = m_entries.begin(); it != m_entries.end();) {
|
|
auto& e = *it;
|
|
const auto st = e->model->status();
|
|
if (!terminal(st)) {
|
|
++it;
|
|
continue;
|
|
}
|
|
|
|
if (e->policy.mode == SupervisionMode::BoundedRestart &&
|
|
st == Status::Faulted) {
|
|
std::erase_if(
|
|
e->restart_timestamps, [&](const auto ts) {
|
|
return (now - ts) >=
|
|
e->policy.restart_window;
|
|
});
|
|
if (e->restart_timestamps.size() <
|
|
e->policy.max_restarts) {
|
|
if (!e->next_restart_at.has_value()) {
|
|
const std::size_t attempt =
|
|
e->restart_timestamps.size();
|
|
const auto shift =
|
|
attempt < 16 ? attempt : 16;
|
|
const auto backoff =
|
|
e->policy.initial_backoff *
|
|
(std::size_t{1} << shift);
|
|
e->next_restart_at = now + backoff;
|
|
events.push_back(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::
|
|
RestartScheduled,
|
|
.status = st,
|
|
.reason =
|
|
e->model->termination_reason(),
|
|
.restarts = e->restarts.load(
|
|
std::memory_order_acquire),
|
|
.detail = e->model->system_error()
|
|
? e->model->system_error()
|
|
->message
|
|
: std::string{}});
|
|
++it;
|
|
continue;
|
|
}
|
|
if (now < *e->next_restart_at) {
|
|
++it;
|
|
continue;
|
|
}
|
|
e->restart_timestamps.push_back(now);
|
|
e->next_restart_at.reset();
|
|
e->restarts.fetch_add(
|
|
1, std::memory_order_acq_rel);
|
|
to_restart.push_back(e);
|
|
++it;
|
|
continue;
|
|
}
|
|
|
|
snapshot_released_evidence(*e);
|
|
events.push_back(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::Exhausted,
|
|
.status = e->final_status,
|
|
.reason = e->final_reason,
|
|
.restarts =
|
|
e->restarts.load(std::memory_order_acquire),
|
|
.detail =
|
|
e->final_error
|
|
? e->final_error->message
|
|
: std::string{"restart budget exhausted"}});
|
|
it = m_entries.erase(it);
|
|
continue;
|
|
}
|
|
|
|
snapshot_released_evidence(*e);
|
|
events.push_back(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::Released,
|
|
.status = e->final_status,
|
|
.reason = e->final_reason,
|
|
.restarts =
|
|
e->restarts.load(std::memory_order_acquire),
|
|
.detail = e->final_error ? e->final_error->message
|
|
: std::string{}});
|
|
it = m_entries.erase(it);
|
|
}
|
|
}
|
|
|
|
for (auto& e : to_restart) {
|
|
e->model->restart();
|
|
events.push_back(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::Restarted,
|
|
.status = e->model->status(),
|
|
.reason = e->model->termination_reason(),
|
|
.restarts = e->restarts.load(std::memory_order_acquire),
|
|
.detail = {}});
|
|
}
|
|
|
|
const std::size_t count = events.size();
|
|
for (const auto& ev : events) {
|
|
notify_observers(ev);
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/// Release finished stop-on-fault (or non-faulted) entries from
|
|
/// active supervision while existing handles retain evidence.
|
|
std::size_t reap_finished() { return reap_finished_and_notify(); }
|
|
|
|
void stop_all()
|
|
{
|
|
std::vector<std::shared_ptr<Detail::SupervisedEntry>> running;
|
|
{
|
|
std::lock_guard lock{m_mutex};
|
|
running.swap(m_entries);
|
|
}
|
|
for (auto& e : running) {
|
|
e->model->stop();
|
|
snapshot_released_evidence(*e);
|
|
}
|
|
running.clear();
|
|
if (m_services_started && !m_services_stopped) {
|
|
m_registry.stop_all();
|
|
m_services_stopped = true;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::size_t running_count() const
|
|
{
|
|
std::lock_guard lock{m_mutex};
|
|
return m_entries.size();
|
|
}
|
|
|
|
std::size_t observe_supervision(ObserverCallback cb)
|
|
{
|
|
std::lock_guard lock{m_obs_mu};
|
|
const std::size_t id = m_next_obs_id++;
|
|
m_observers.emplace_back(id, std::move(cb));
|
|
return id;
|
|
}
|
|
|
|
void remove_supervision_observer(std::size_t id)
|
|
{
|
|
std::lock_guard lock{m_obs_mu};
|
|
std::erase_if(m_observers, [id](const auto& pair) {
|
|
return pair.first == id;
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] std::vector<std::string> observer_errors() const
|
|
{
|
|
std::lock_guard lock{m_obs_mu};
|
|
return m_observer_errors;
|
|
}
|
|
|
|
private:
|
|
|
|
static void
|
|
snapshot_released_evidence(Detail::SupervisedEntry& entry)
|
|
{
|
|
std::lock_guard elk{entry.evidence_mu};
|
|
if (entry.released) {
|
|
return;
|
|
}
|
|
entry.final_status = entry.model->status();
|
|
entry.final_reason = entry.model->termination_reason();
|
|
entry.final_error = entry.model->system_error();
|
|
entry.released = true;
|
|
}
|
|
|
|
std::size_t reap_finished_and_notify()
|
|
{
|
|
std::vector<SupervisionEvent> events;
|
|
{
|
|
std::lock_guard lock{m_mutex};
|
|
for (auto it = m_entries.begin(); it != m_entries.end();) {
|
|
auto& e = *it;
|
|
const auto st = e->model->status();
|
|
if (!terminal(st)) {
|
|
++it;
|
|
continue;
|
|
}
|
|
if (e->policy.mode == SupervisionMode::BoundedRestart &&
|
|
st == Status::Faulted) {
|
|
++it;
|
|
continue;
|
|
}
|
|
snapshot_released_evidence(*e);
|
|
events.push_back(SupervisionEvent{
|
|
.kind = SupervisionEvent::Kind::Released,
|
|
.status = e->final_status,
|
|
.reason = e->final_reason,
|
|
.restarts =
|
|
e->restarts.load(std::memory_order_acquire),
|
|
.detail = e->final_error ? e->final_error->message
|
|
: std::string{}});
|
|
it = m_entries.erase(it);
|
|
}
|
|
}
|
|
for (const auto& ev : events) {
|
|
notify_observers(ev);
|
|
}
|
|
return events.size();
|
|
}
|
|
|
|
void notify_observers(const SupervisionEvent& ev)
|
|
{
|
|
std::vector<ObserverCallback> copy;
|
|
{
|
|
std::lock_guard lock{m_obs_mu};
|
|
copy.reserve(m_observers.size());
|
|
for (const auto& [id, fn] : m_observers) {
|
|
if (fn) {
|
|
copy.push_back(fn);
|
|
}
|
|
}
|
|
}
|
|
for (const auto& fn : copy) {
|
|
try {
|
|
fn(ev);
|
|
} catch (const std::exception& ex) {
|
|
std::lock_guard lock{m_obs_mu};
|
|
m_observer_errors.push_back(ex.what());
|
|
} catch (...) {
|
|
std::lock_guard lock{m_obs_mu};
|
|
m_observer_errors.push_back("observer threw unknown");
|
|
}
|
|
}
|
|
}
|
|
|
|
const Time::MonotonicClock* m_clock;
|
|
OrchestratorLimits m_limits{};
|
|
Service::ServiceRegistry m_registry;
|
|
mutable std::mutex m_mutex;
|
|
std::vector<std::shared_ptr<Detail::SupervisedEntry>> m_entries;
|
|
bool m_services_started{false};
|
|
bool m_services_stopped{false};
|
|
|
|
mutable std::mutex m_obs_mu;
|
|
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers;
|
|
std::vector<std::string> m_observer_errors;
|
|
std::size_t m_next_obs_id{1};
|
|
};
|
|
|
|
} // namespace Void::Fsm
|