feat(service): immutable snapshots, owning ServiceHandle, DAG lifecycle, and ServicePlugin split
This commit is contained in:
1 parent
6b3dededac
commit
1474a69ab1
12 files changed
+2167
-137
No files matched your search
@@ -26,6 +26,60 @@ namespace Void::Service
|
||||
|
||||
inline constexpr const char* kServiceSymbol = "void_plugin_service";
|
||||
|
||||
/// Acquire an owning ServiceHandle<I> directly from a PluginManager entry,
|
||||
/// pinning the exact PluginHandle so the shared object stays mapped until
|
||||
/// every copy of the returned handle is destroyed.
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
|
||||
acquire_plugin_service(Plugin::PluginManager& manager,
|
||||
std::string_view plugin_name,
|
||||
PublicationEpoch epoch = 0)
|
||||
{
|
||||
static_assert(std::is_base_of_v<IService, I>,
|
||||
"plugin service interface must derive IService");
|
||||
auto handle = manager.acquire(plugin_name);
|
||||
if (!handle) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServicePlugin: plugin '"} +
|
||||
std::string{plugin_name} + "' is not loaded"));
|
||||
}
|
||||
auto* factory = reinterpret_cast<service_factory_fn>(
|
||||
handle.raw_symbol(kServiceSymbol));
|
||||
if (factory == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServicePlugin: plugin '"} +
|
||||
std::string{plugin_name} + "' does not export " +
|
||||
kServiceSymbol));
|
||||
}
|
||||
IService* base = nullptr;
|
||||
try {
|
||||
base = factory(handle.get());
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::internal, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::internal,
|
||||
"ServicePlugin: service factory threw"));
|
||||
}
|
||||
if (base == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
"ServicePlugin: service factory returned null"));
|
||||
}
|
||||
I* iface = dynamic_cast<I*>(base);
|
||||
if (iface == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServicePlugin: incompatible service interface"));
|
||||
}
|
||||
auto owner = std::make_shared<Plugin::PluginHandle>(std::move(handle));
|
||||
std::shared_ptr<void> pinned(std::move(owner), iface);
|
||||
return ServiceHandle<I>{iface, std::move(pinned), nullptr, epoch};
|
||||
}
|
||||
|
||||
/// Binds a plugin-provided service (interface I) into a ServiceRegistry
|
||||
/// and keeps it bound across hot reloads: after each reload the new
|
||||
/// instance's service (carrying state migrated by the plugin's v2 ABI)
|
||||
@@ -174,35 +228,14 @@ namespace Void::Service
|
||||
[[nodiscard]] bool bind_locked() noexcept
|
||||
{
|
||||
try {
|
||||
auto handle = m_manager->acquire(m_name);
|
||||
if (!handle) {
|
||||
auto svc_handle = acquire_plugin_service<I>(
|
||||
*m_manager, m_name);
|
||||
if (!svc_handle) {
|
||||
Void::Log::warn("Service.Plugin", "{}",
|
||||
svc_handle.error().message());
|
||||
return false;
|
||||
}
|
||||
auto* factory =
|
||||
reinterpret_cast<service_factory_fn>(
|
||||
handle.raw_symbol(kServiceSymbol));
|
||||
if (factory == nullptr) {
|
||||
return false;
|
||||
}
|
||||
IService* base = factory(handle.get());
|
||||
if (base == nullptr) {
|
||||
return false;
|
||||
}
|
||||
I* iface = dynamic_cast<I*>(base);
|
||||
if (iface == nullptr) {
|
||||
Void::Log::warn(
|
||||
"Service.Plugin",
|
||||
"plugin '{}' exported an incompatible "
|
||||
"service interface",
|
||||
m_name);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pin the exact instance and shared object that
|
||||
// supplied the factory and service subobject.
|
||||
auto owner = std::make_shared<Plugin::PluginHandle>(
|
||||
std::move(handle));
|
||||
std::shared_ptr<I> pinned(std::move(owner), iface);
|
||||
auto pinned = svc_handle->shared();
|
||||
if (m_validator && !m_validator(pinned)) {
|
||||
Void::Log::warn(
|
||||
"Service.Plugin",
|
||||
|
||||
+394
-109
@@ -1,16 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Service/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Service
|
||||
@@ -25,92 +32,297 @@ namespace Void::Service
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Type-keyed service container: providers register an implementation
|
||||
/// against an interface type, consumers resolve by that interface and
|
||||
/// never name the concrete type — the core of the dependency-inversion
|
||||
/// the orchestrator and FSMs rely on.
|
||||
class ServiceRegistry;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
struct RetentionEntry {
|
||||
PublicationEpoch epoch{0};
|
||||
std::weak_ptr<const void> token{};
|
||||
std::string label{};
|
||||
};
|
||||
|
||||
struct RetentionState;
|
||||
|
||||
struct LifecycleNode {
|
||||
std::string id{};
|
||||
const void* object_key{nullptr};
|
||||
std::shared_ptr<void> owner{};
|
||||
IService* service{nullptr};
|
||||
IManagedService* managed{nullptr};
|
||||
std::size_t seq{0};
|
||||
std::vector<std::size_t> dep_indices{};
|
||||
};
|
||||
|
||||
struct SnapshotEntry {
|
||||
std::shared_ptr<void> impl{}; // holds provider (+ optional pin)
|
||||
IService* service{nullptr};
|
||||
std::string id{};
|
||||
};
|
||||
|
||||
struct SnapshotData {
|
||||
PublicationEpoch epoch{0};
|
||||
std::shared_ptr<const void> gen_token{};
|
||||
std::unordered_map<std::type_index, SnapshotEntry> services{};
|
||||
std::vector<std::type_index> legacy_order{};
|
||||
std::vector<LifecycleNode> lifecycle_nodes{};
|
||||
std::shared_ptr<const SnapshotData> parent_snap{};
|
||||
const ServiceRegistry* live_parent{nullptr};
|
||||
};
|
||||
} // namespace detail
|
||||
|
||||
/// Immutable, self-retaining point-in-time view of a ServiceRegistry
|
||||
/// (and any snapshot-captured parent chain). Safe to hold after the source
|
||||
/// registry is modified or destroyed.
|
||||
class ServiceSnapshot
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceSnapshot() = default;
|
||||
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
const detail::SnapshotData* cur = m_data.get();
|
||||
std::size_t depth = 0;
|
||||
while (cur != nullptr && depth <= m_max_parent_levels) {
|
||||
const auto it =
|
||||
cur->services.find(std::type_index{typeid(I)});
|
||||
if (it != cur->services.end()) {
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
}
|
||||
cur = cur->parent_snap.get();
|
||||
++depth;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <typename I> [[nodiscard]] bool has() const
|
||||
{
|
||||
return get<I>() != nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] PublicationEpoch epoch() const noexcept
|
||||
{
|
||||
return m_data ? m_data->epoch : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return m_data ? m_data->services.size() : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_data != nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class ServiceRegistry;
|
||||
explicit ServiceSnapshot(std::shared_ptr<const detail::SnapshotData> data,
|
||||
std::size_t max_parent_levels = 16) noexcept
|
||||
: m_data(std::move(data)),
|
||||
m_max_parent_levels(max_parent_levels)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<const detail::SnapshotData> m_data{};
|
||||
std::size_t m_max_parent_levels{16};
|
||||
};
|
||||
|
||||
/// Staged description of a coherent batch of services and their dependency
|
||||
/// graph, ready to be validated by ServiceRegistry::prepare_batch().
|
||||
class ProviderSet
|
||||
{
|
||||
public:
|
||||
|
||||
struct StagedItem {
|
||||
std::type_index interface_type;
|
||||
std::string id{};
|
||||
std::shared_ptr<void> owner{};
|
||||
const void* object_key{nullptr};
|
||||
IService* service{nullptr};
|
||||
IManagedService* managed{nullptr};
|
||||
std::vector<std::type_index> required_deps{};
|
||||
std::vector<std::type_index> optional_deps{};
|
||||
};
|
||||
|
||||
template <typename I>
|
||||
ProviderSet& add(
|
||||
std::string id,
|
||||
std::shared_ptr<I> impl,
|
||||
std::vector<std::type_index> required_deps = {},
|
||||
std::vector<std::type_index> optional_deps = {},
|
||||
ServicePin pin = {})
|
||||
{
|
||||
StagedItem item{.interface_type = std::type_index{typeid(I)},
|
||||
.id = std::move(id),
|
||||
.owner = pack_owner(impl, std::move(pin)),
|
||||
.object_key = impl.get(),
|
||||
.service = extract_service(impl.get()),
|
||||
.managed = extract_managed(impl.get()),
|
||||
.required_deps = std::move(required_deps),
|
||||
.optional_deps = std::move(optional_deps)};
|
||||
m_items.push_back(std::move(item));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename AliasI>
|
||||
ProviderSet& add_alias(
|
||||
std::string id,
|
||||
std::shared_ptr<AliasI> impl,
|
||||
std::vector<std::type_index> required_deps = {},
|
||||
std::vector<std::type_index> optional_deps = {},
|
||||
ServicePin pin = {})
|
||||
{
|
||||
return add<AliasI>(std::move(id), std::move(impl),
|
||||
std::move(required_deps),
|
||||
std::move(optional_deps), std::move(pin));
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::vector<StagedItem>& items() const noexcept
|
||||
{
|
||||
return m_items;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template <typename I>
|
||||
static std::shared_ptr<void> pack_owner(const std::shared_ptr<I>& impl,
|
||||
ServicePin pin)
|
||||
{
|
||||
if (!impl) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!pin) {
|
||||
return std::shared_ptr<void>(impl, impl.get());
|
||||
}
|
||||
struct PinnedBox {
|
||||
std::shared_ptr<void> impl;
|
||||
ServicePin pin;
|
||||
};
|
||||
auto box = std::make_shared<PinnedBox>(
|
||||
PinnedBox{std::shared_ptr<void>(impl, impl.get()),
|
||||
std::move(pin)});
|
||||
return std::shared_ptr<void>(std::move(box), impl.get());
|
||||
}
|
||||
|
||||
template <typename I> static IService* extract_service(I* raw)
|
||||
{
|
||||
if (raw == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
return static_cast<IService*>(raw);
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
return dynamic_cast<IService*>(raw);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename I>
|
||||
static IManagedService* extract_managed(I* raw)
|
||||
{
|
||||
if (raw == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (std::is_base_of_v<IManagedService, I>) {
|
||||
return static_cast<IManagedService*>(raw);
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
return dynamic_cast<IManagedService*>(raw);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<StagedItem> m_items{};
|
||||
};
|
||||
|
||||
/// Validated, topologically ordered candidate batch returned by
|
||||
/// ServiceRegistry::prepare_batch().
|
||||
struct PreparedPublication {
|
||||
ExpectedEpoch expected_epoch{};
|
||||
std::shared_ptr<detail::SnapshotData> snapshot{};
|
||||
bool valid{false};
|
||||
bool started{false};
|
||||
bool aborted{false};
|
||||
};
|
||||
|
||||
/// Thread-safe, snapshot-published service container supporting both
|
||||
/// legacy single-service mutations (`provide`/`get`/`require`) and
|
||||
/// transactional DAG lifecycle publication (`acquire`/`prepare_batch`/
|
||||
/// `start_staged`/`publish`/`close_and_join`).
|
||||
///
|
||||
/// registry.provide<IClock>(std::make_shared<SystemClock>());
|
||||
/// auto& clock = registry.require<IClock>(); // no SystemClock dep
|
||||
///
|
||||
/// Thread-safe. Reads (get/require/has) take a shared lock; they are
|
||||
/// the hot path for running FSMs resolving services per step.
|
||||
/// Note: `require<I>()` returns an unpinned reference after unlocking and is
|
||||
/// kept for legacy compatibility; new code and coroutines should use
|
||||
/// `acquire<I>()` and retain the returned `ServiceHandle<I>` across calls
|
||||
/// and `co_await` suspension points.
|
||||
class ServiceRegistry
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceRegistry() = default;
|
||||
ServiceRegistry();
|
||||
explicit ServiceRegistry(const ServiceRegistry* parent);
|
||||
explicit ServiceRegistry(
|
||||
ServiceLimits limits,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
~ServiceRegistry();
|
||||
|
||||
ServiceRegistry(const ServiceRegistry&) = delete;
|
||||
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
|
||||
|
||||
/// Create a scoped child registry that overlays `parent`: lookups
|
||||
/// fall through to the parent when a key is not provided locally,
|
||||
/// and a local provide<I>() shadows the parent's entry. Lifecycle
|
||||
/// (start_all/stop_all) covers only locally-provided services. The
|
||||
/// parent must outlive this registry.
|
||||
explicit ServiceRegistry(const ServiceRegistry* parent)
|
||||
: m_parent{parent}
|
||||
{
|
||||
}
|
||||
/// Construct a child registry retaining an immutable parent
|
||||
/// snapshot so lookups survive destruction of the parent registry.
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::unique_ptr<ServiceRegistry>>
|
||||
from_parent_snapshot(
|
||||
ServiceSnapshot parent,
|
||||
ServiceLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
|
||||
/// Explicitly refresh snapshot-based parent linkage from `parent`.
|
||||
void refresh_parent(const ServiceRegistry& parent);
|
||||
|
||||
/// Capture an immutable point-in-time snapshot.
|
||||
[[nodiscard]] ServiceSnapshot snapshot() const;
|
||||
|
||||
// ── Legacy compatible API ─────────────────────────────────────
|
||||
|
||||
/// Register (or replace) the implementation for interface I.
|
||||
/// If I derives IService, the instance joins the lifecycle.
|
||||
template <typename I> void provide(std::shared_ptr<I> impl)
|
||||
{
|
||||
Entry entry;
|
||||
entry.impl = std::shared_ptr<void>(impl, impl.get());
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
entry.service = static_cast<IService*>(impl.get());
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
// The interface I doesn't derive IService, but the
|
||||
// concrete implementation might — recover the lifecycle
|
||||
// aspect by cross-cast. (dynamic_cast requires a
|
||||
// polymorphic I.)
|
||||
entry.service = dynamic_cast<IService*>(impl.get());
|
||||
} else {
|
||||
// A plain, non-polymorphic service type: storable and
|
||||
// resolvable, but has no IService lifecycle aspect.
|
||||
entry.service = nullptr;
|
||||
}
|
||||
const std::type_index key{typeid(I)};
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (!m_services.contains(key)) {
|
||||
m_order.push_back(key);
|
||||
}
|
||||
m_services.insert_or_assign(key, std::move(entry));
|
||||
}
|
||||
|
||||
/// Withdraw the implementation for interface I from this registry
|
||||
/// (a parent's entry is unaffected: later lookups fall through to
|
||||
/// it again). Consumers still holding the shared_ptr keep the
|
||||
/// instance alive; only new lookups miss. Returns true when an
|
||||
/// entry was removed.
|
||||
template <typename I> bool remove()
|
||||
{
|
||||
const std::type_index key{typeid(I)};
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (m_services.erase(key) == 0) {
|
||||
return false;
|
||||
}
|
||||
std::erase(m_order, key);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Resolve I, or nullptr if not provided. Falls through to the
|
||||
/// parent registry (if any) on a local miss.
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
const auto it = m_services.find(std::type_index{typeid(I)});
|
||||
if (it != m_services.end()) {
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
IService* svc = nullptr;
|
||||
if (impl) {
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
svc = static_cast<IService*>(impl.get());
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
svc = dynamic_cast<IService*>(impl.get());
|
||||
}
|
||||
}
|
||||
return m_parent ? m_parent->get<I>() : nullptr;
|
||||
provide_erased(
|
||||
std::type_index{typeid(I)},
|
||||
impl ? std::shared_ptr<void>(impl, impl.get())
|
||||
: std::shared_ptr<void>{},
|
||||
impl.get(), svc);
|
||||
}
|
||||
|
||||
template <typename I> bool remove()
|
||||
{
|
||||
return remove_erased(std::type_index{typeid(I)});
|
||||
}
|
||||
|
||||
template <typename I>
|
||||
[[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
auto h = acquire<I>();
|
||||
if (!h) {
|
||||
return nullptr;
|
||||
}
|
||||
return h->shared();
|
||||
}
|
||||
|
||||
/// Resolve I; throws std::runtime_error if not provided.
|
||||
template <typename I> [[nodiscard]] I& require() const
|
||||
{
|
||||
auto p = get<I>();
|
||||
@@ -124,55 +336,128 @@ namespace Void::Service
|
||||
|
||||
template <typename I> [[nodiscard]] bool has() const
|
||||
{
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
if (m_services.contains(std::type_index{typeid(I)})) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return m_parent ? m_parent->has<I>() : false;
|
||||
return acquire<I>().has_value();
|
||||
}
|
||||
|
||||
/// Call on_start() on every lifecycle service, registration
|
||||
/// Run on_start() outside registry locks in registration/dependency
|
||||
/// order.
|
||||
void start_all()
|
||||
void start_all();
|
||||
|
||||
/// Run on_stop() outside registry locks in reverse order.
|
||||
void stop_all();
|
||||
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
|
||||
// ── Hardened owning & transactional lifecycle API ───────────────
|
||||
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>> acquire() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
for (const auto& key : m_order) {
|
||||
if (auto* s = m_services.at(key).service) {
|
||||
s->on_start();
|
||||
}
|
||||
auto snap = acquire_snapshot();
|
||||
if (!snap) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry: registry is stopping"));
|
||||
}
|
||||
return acquire_from_snapshot<I>(*snap, 0);
|
||||
}
|
||||
|
||||
/// Call on_stop() on every lifecycle service, reverse order.
|
||||
void stop_all()
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) {
|
||||
if (auto* s = m_services.at(*it).service) {
|
||||
s->on_stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<PreparedPublication>
|
||||
prepare_batch(ProviderSet set,
|
||||
ExpectedEpoch expected = std::nullopt);
|
||||
|
||||
[[nodiscard]] std::size_t size() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
return m_services.size();
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
start_staged(PreparedPublication& prepared,
|
||||
Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<PublicationEpoch>
|
||||
publish(PreparedPublication&& prepared);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<PublicationEpoch>
|
||||
start_and_publish(ProviderSet set,
|
||||
ExpectedEpoch expected = std::nullopt,
|
||||
Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
start(Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport>
|
||||
close_and_join(Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] PublicationEpoch epoch() const noexcept;
|
||||
[[nodiscard]] std::size_t retained_generation_count() const;
|
||||
[[nodiscard]] bool is_stopping() const noexcept;
|
||||
|
||||
using ObserverCallback =
|
||||
std::function<void(const ServiceObservation&)>;
|
||||
std::size_t add_observer(ObserverCallback cb);
|
||||
void remove_observer(std::size_t id);
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
std::shared_ptr<void> impl;
|
||||
IService* service = nullptr; // non-null iff I : IService
|
||||
};
|
||||
void provide_erased(std::type_index key, std::shared_ptr<void> impl,
|
||||
const void* object_key, IService* service);
|
||||
bool remove_erased(std::type_index key);
|
||||
std::shared_ptr<const detail::SnapshotData> acquire_snapshot() const;
|
||||
|
||||
const ServiceRegistry* m_parent = nullptr;
|
||||
mutable std::shared_mutex m_mutex;
|
||||
std::unordered_map<std::type_index, Entry> m_services;
|
||||
std::vector<std::type_index> m_order;
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
|
||||
acquire_from_snapshot(const detail::SnapshotData& snap,
|
||||
std::size_t depth) const
|
||||
{
|
||||
if (depth > m_limits.max_parent_levels) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::overloaded,
|
||||
"ServiceRegistry: parent depth limit exceeded"));
|
||||
}
|
||||
const auto it =
|
||||
snap.services.find(std::type_index{typeid(I)});
|
||||
if (it != snap.services.end()) {
|
||||
auto* raw = static_cast<I*>(it->second.impl.get());
|
||||
return ServiceHandle<I>{raw, it->second.impl,
|
||||
snap.gen_token, snap.epoch};
|
||||
}
|
||||
if (snap.parent_snap) {
|
||||
return acquire_from_snapshot<I>(*snap.parent_snap,
|
||||
depth + 1);
|
||||
}
|
||||
if (snap.live_parent != nullptr) {
|
||||
auto parent_snap = snap.live_parent->acquire_snapshot();
|
||||
if (!parent_snap) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry: parent registry is stopping"));
|
||||
}
|
||||
return acquire_from_snapshot<I>(*parent_snap, depth + 1);
|
||||
}
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServiceRegistry: no service for '"} +
|
||||
typeid(I).name() + "'"));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> rollback_started_nodes(
|
||||
const std::vector<detail::LifecycleNode>& nodes,
|
||||
std::size_t count, const Void::Result::Error& primary_error);
|
||||
|
||||
void notify_observers(const ServiceObservation& obs);
|
||||
[[nodiscard]] std::size_t prune_and_count_retained_locked();
|
||||
|
||||
ServiceLimits m_limits{};
|
||||
const Void::Time::MonotonicClock* m_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
std::shared_ptr<detail::RetentionState> m_retention_state;
|
||||
|
||||
mutable std::mutex m_write_mu{};
|
||||
mutable std::mutex m_snapshot_mu{};
|
||||
std::shared_ptr<const detail::SnapshotData> m_active_snapshot{};
|
||||
PublicationEpoch m_epoch{0};
|
||||
bool m_stopping{false};
|
||||
bool m_started{false};
|
||||
|
||||
mutable std::mutex m_observer_mu{};
|
||||
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers{};
|
||||
std::size_t m_next_observer_id{1};
|
||||
};
|
||||
|
||||
} // namespace Void::Service
|
||||
@@ -0,0 +1,227 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Service
|
||||
{
|
||||
enum class ServiceErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
missing_service = 2,
|
||||
conflict = 3,
|
||||
duplicate_interface = 4,
|
||||
cycle_detected = 5,
|
||||
missing_dependency = 6,
|
||||
start_failed = 7,
|
||||
not_ready = 8,
|
||||
stop_failed = 9,
|
||||
service_stopping = 10,
|
||||
cancelled = 11,
|
||||
timeout = 12,
|
||||
overloaded = 13,
|
||||
retention_limit = 14,
|
||||
internal = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_service_error(ServiceErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case ServiceErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case ServiceErrorCode::invalid_argument:
|
||||
case ServiceErrorCode::cycle_detected:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case ServiceErrorCode::missing_service:
|
||||
case ServiceErrorCode::missing_dependency:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case ServiceErrorCode::conflict:
|
||||
case ServiceErrorCode::duplicate_interface:
|
||||
case ServiceErrorCode::service_stopping:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case ServiceErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case ServiceErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case ServiceErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case ServiceErrorCode::retention_limit:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case ServiceErrorCode::start_failed:
|
||||
case ServiceErrorCode::not_ready:
|
||||
case ServiceErrorCode::stop_failed:
|
||||
case ServiceErrorCode::internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
}
|
||||
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kServiceErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct ServiceLimits {
|
||||
std::size_t max_providers{256};
|
||||
std::size_t max_parent_levels{16};
|
||||
std::size_t max_dependency_edges{1024};
|
||||
std::size_t max_staged_changes{64};
|
||||
std::size_t max_lifecycle_requests{128};
|
||||
std::size_t max_retained_generations{4};
|
||||
};
|
||||
|
||||
using PublicationEpoch = std::uint64_t;
|
||||
using ExpectedEpoch = std::optional<PublicationEpoch>;
|
||||
using ServicePin = std::shared_ptr<const void>;
|
||||
|
||||
enum class LifecyclePhase : std::uint8_t {
|
||||
Constructed = 0,
|
||||
Starting,
|
||||
Ready,
|
||||
Stopping,
|
||||
Stopped,
|
||||
Failed,
|
||||
};
|
||||
|
||||
enum class ServiceHealthStatus : std::uint8_t {
|
||||
Unknown = 0,
|
||||
Healthy,
|
||||
Degraded,
|
||||
Unhealthy,
|
||||
};
|
||||
|
||||
struct ServiceHealth {
|
||||
ServiceHealthStatus status{ServiceHealthStatus::Unknown};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
struct ServiceObservation {
|
||||
PublicationEpoch epoch{0};
|
||||
std::size_t provider_count{0};
|
||||
std::size_t retained_generations{0};
|
||||
std::uint64_t duration_ns{0};
|
||||
bool rollback{false};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
std::vector<std::string> stopped_services{};
|
||||
std::vector<std::string> incomplete_owners{};
|
||||
std::vector<Void::Result::Error> stop_errors{};
|
||||
|
||||
[[nodiscard]] bool clean() const noexcept
|
||||
{
|
||||
return incomplete_owners.empty() && stop_errors.empty();
|
||||
}
|
||||
};
|
||||
|
||||
/// Extended lifecycle contract with checked failure/readiness reporting and
|
||||
/// abort cleanup on partial startup failure.
|
||||
class IManagedService : public IService
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start_checked()
|
||||
{
|
||||
try {
|
||||
on_start();
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::start_failed, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::start_failed,
|
||||
"service start threw unknown exception"));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
check_readiness() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
virtual void abort_start() noexcept {}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> stop_checked()
|
||||
{
|
||||
try {
|
||||
on_stop();
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::stop_failed, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::stop_failed,
|
||||
"service stop threw unknown exception"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/// Owning lease to a resolved provider record: keeps the provider object,
|
||||
/// any external code/resource pin, and its publication generation token alive
|
||||
/// across removal, replacement, parent destruction, and coroutine suspension.
|
||||
template <typename I> class ServiceHandle
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceHandle() noexcept = default;
|
||||
|
||||
ServiceHandle(I* ptr, std::shared_ptr<void> owner,
|
||||
std::shared_ptr<const void> gen_token,
|
||||
PublicationEpoch epoch) noexcept
|
||||
: m_ptr(ptr), m_owner(std::move(owner)),
|
||||
m_gen_token(std::move(gen_token)), m_epoch(epoch)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] I* operator->() const noexcept { return m_ptr; }
|
||||
[[nodiscard]] I& operator*() const noexcept { return *m_ptr; }
|
||||
[[nodiscard]] I* get() const noexcept { return m_ptr; }
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_ptr != nullptr;
|
||||
}
|
||||
[[nodiscard]] PublicationEpoch generation() const noexcept
|
||||
{
|
||||
return m_epoch;
|
||||
}
|
||||
[[nodiscard]] std::shared_ptr<I> shared() const noexcept
|
||||
{
|
||||
return std::shared_ptr<I>(m_owner, m_ptr);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
I* m_ptr{nullptr};
|
||||
std::shared_ptr<void> m_owner{};
|
||||
std::shared_ptr<const void> m_gen_token{};
|
||||
PublicationEpoch m_epoch{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Service
|
||||
Reference in new issue
Block a user