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
|
||||
@@ -0,0 +1,944 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <queue>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace Void::Service
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
struct RetentionState {
|
||||
mutable std::mutex mu{};
|
||||
std::condition_variable cv{};
|
||||
std::vector<RetentionEntry> entries{};
|
||||
|
||||
void notify_release() noexcept
|
||||
{
|
||||
std::lock_guard lk{mu};
|
||||
cv.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
struct TokenGuard {
|
||||
std::weak_ptr<RetentionState> state{};
|
||||
~TokenGuard()
|
||||
{
|
||||
if (auto s = state.lock()) {
|
||||
s->notify_release();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
std::shared_ptr<const void>
|
||||
make_retention_token(const std::shared_ptr<RetentionState>& state,
|
||||
PublicationEpoch epoch,
|
||||
std::string label)
|
||||
{
|
||||
auto tok = std::make_shared<TokenGuard>(TokenGuard{state});
|
||||
{
|
||||
std::lock_guard lk{state->mu};
|
||||
std::erase_if(state->entries, [](const RetentionEntry& e) {
|
||||
return e.token.expired();
|
||||
});
|
||||
state->entries.push_back(
|
||||
RetentionEntry{epoch, tok, std::move(label)});
|
||||
}
|
||||
return tok;
|
||||
}
|
||||
|
||||
bool has_in_parent_chain(const SnapshotData& snap,
|
||||
std::type_index key,
|
||||
std::size_t max_levels,
|
||||
std::size_t depth = 0)
|
||||
{
|
||||
if (depth > max_levels) {
|
||||
return false;
|
||||
}
|
||||
if (snap.services.contains(key)) {
|
||||
return true;
|
||||
}
|
||||
if (snap.parent_snap) {
|
||||
return has_in_parent_chain(*snap.parent_snap, key,
|
||||
max_levels, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
} // namespace detail
|
||||
|
||||
ServiceRegistry::ServiceRegistry()
|
||||
: ServiceRegistry(ServiceLimits{},
|
||||
Void::Time::SystemMonotonicClock::instance())
|
||||
{
|
||||
}
|
||||
|
||||
ServiceRegistry::ServiceRegistry(const ServiceRegistry* parent)
|
||||
: ServiceRegistry(ServiceLimits{},
|
||||
Void::Time::SystemMonotonicClock::instance())
|
||||
{
|
||||
if (parent != nullptr) {
|
||||
auto snap = std::make_shared<detail::SnapshotData>();
|
||||
snap->live_parent = parent;
|
||||
m_active_snapshot = std::move(snap);
|
||||
}
|
||||
}
|
||||
|
||||
ServiceRegistry::ServiceRegistry(ServiceLimits limits,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
: m_limits(limits), m_clock(&clock),
|
||||
m_retention_state(std::make_shared<detail::RetentionState>())
|
||||
{
|
||||
m_active_snapshot = std::make_shared<detail::SnapshotData>();
|
||||
}
|
||||
|
||||
ServiceRegistry::~ServiceRegistry()
|
||||
{
|
||||
// Detach the active snapshot under m_snapshot_mu with m_stopping=true
|
||||
// before destroying providers, so a provider destructor reentering the
|
||||
// registry cannot increment the use_count of a half-destroyed SnapshotData.
|
||||
std::shared_ptr<const detail::SnapshotData> last_snap;
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
m_stopping = true;
|
||||
last_snap = std::move(m_active_snapshot);
|
||||
}
|
||||
last_snap.reset();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<ServiceRegistry>>
|
||||
ServiceRegistry::from_parent_snapshot(
|
||||
ServiceSnapshot parent, ServiceLimits limits,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
{
|
||||
if (!parent) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServiceRegistry: parent snapshot must not be empty"));
|
||||
}
|
||||
std::size_t depth = 1;
|
||||
const detail::SnapshotData* cur = parent.m_data.get();
|
||||
while (cur->parent_snap != nullptr) {
|
||||
++depth;
|
||||
if (depth > limits.max_parent_levels) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::overloaded,
|
||||
"ServiceRegistry: parent snapshot nesting exceeds max_parent_levels"));
|
||||
}
|
||||
cur = cur->parent_snap.get();
|
||||
}
|
||||
auto reg = std::make_unique<ServiceRegistry>(limits, clock);
|
||||
auto snap = std::make_shared<detail::SnapshotData>();
|
||||
snap->parent_snap = std::move(parent.m_data);
|
||||
reg->m_active_snapshot = std::move(snap);
|
||||
return reg;
|
||||
}
|
||||
|
||||
void ServiceRegistry::refresh_parent(const ServiceRegistry& parent)
|
||||
{
|
||||
auto parent_snap = parent.snapshot();
|
||||
std::shared_ptr<const detail::SnapshotData> old_snap;
|
||||
{
|
||||
std::lock_guard write_lk{m_write_mu};
|
||||
auto next = std::make_shared<detail::SnapshotData>(*m_active_snapshot);
|
||||
next->parent_snap = parent_snap.m_data;
|
||||
next->live_parent = nullptr;
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
if (m_stopping) {
|
||||
return;
|
||||
}
|
||||
old_snap = std::exchange(m_active_snapshot, std::move(next));
|
||||
}
|
||||
// old_snap released here outside all locks.
|
||||
}
|
||||
|
||||
ServiceSnapshot ServiceRegistry::snapshot() const
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
return ServiceSnapshot{m_active_snapshot, m_limits.max_parent_levels};
|
||||
}
|
||||
|
||||
std::shared_ptr<const detail::SnapshotData>
|
||||
ServiceRegistry::acquire_snapshot() const
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
if (m_stopping) {
|
||||
return nullptr;
|
||||
}
|
||||
return m_active_snapshot;
|
||||
}
|
||||
|
||||
void ServiceRegistry::provide_erased(std::type_index key,
|
||||
std::shared_ptr<void> impl,
|
||||
const void* object_key,
|
||||
IService* service)
|
||||
{
|
||||
std::shared_ptr<const detail::SnapshotData> old_snap;
|
||||
{
|
||||
std::lock_guard write_lk{m_write_mu};
|
||||
if (m_stopping) {
|
||||
return;
|
||||
}
|
||||
auto next =
|
||||
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
|
||||
next->epoch = ++m_epoch;
|
||||
if (!next->services.contains(key)) {
|
||||
next->legacy_order.push_back(key);
|
||||
}
|
||||
next->services.insert_or_assign(
|
||||
key, detail::SnapshotEntry{std::move(impl), service, {}});
|
||||
|
||||
// Rebuild lifecycle list in legacy registration order (deduping
|
||||
// shared object instances if multiple interfaces point to one
|
||||
// IService).
|
||||
next->lifecycle_nodes.clear();
|
||||
std::unordered_set<const void*> seen_objs;
|
||||
for (const auto& k : next->legacy_order) {
|
||||
const auto it = next->services.find(k);
|
||||
if (it == next->services.end() || it->second.service == nullptr) {
|
||||
continue;
|
||||
}
|
||||
const void* obj = static_cast<const void*>(it->second.service);
|
||||
if (!seen_objs.insert(obj).second) {
|
||||
continue;
|
||||
}
|
||||
next->lifecycle_nodes.push_back(detail::LifecycleNode{
|
||||
.id = std::string{it->second.service->service_name()},
|
||||
.object_key = obj,
|
||||
.owner = it->second.impl,
|
||||
.service = it->second.service,
|
||||
.managed = dynamic_cast<IManagedService*>(it->second.service),
|
||||
.seq = next->lifecycle_nodes.size(),
|
||||
.dep_indices = {},
|
||||
});
|
||||
}
|
||||
(void)object_key;
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
old_snap = std::exchange(m_active_snapshot, std::move(next));
|
||||
}
|
||||
}
|
||||
// old_snap (and any replaced provider whose external refs reached 0)
|
||||
// destroys here AFTER releasing all registry locks.
|
||||
}
|
||||
|
||||
bool ServiceRegistry::remove_erased(std::type_index key)
|
||||
{
|
||||
std::shared_ptr<const detail::SnapshotData> old_snap;
|
||||
bool removed = false;
|
||||
{
|
||||
std::lock_guard write_lk{m_write_mu};
|
||||
if (m_stopping || !m_active_snapshot->services.contains(key)) {
|
||||
return false;
|
||||
}
|
||||
auto next =
|
||||
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
|
||||
next->epoch = ++m_epoch;
|
||||
removed = next->services.erase(key) > 0;
|
||||
std::erase(next->legacy_order, key);
|
||||
|
||||
next->lifecycle_nodes.clear();
|
||||
std::unordered_set<const void*> seen_objs;
|
||||
for (const auto& k : next->legacy_order) {
|
||||
const auto it = next->services.find(k);
|
||||
if (it == next->services.end() || it->second.service == nullptr) {
|
||||
continue;
|
||||
}
|
||||
const void* obj = static_cast<const void*>(it->second.service);
|
||||
if (!seen_objs.insert(obj).second) {
|
||||
continue;
|
||||
}
|
||||
next->lifecycle_nodes.push_back(detail::LifecycleNode{
|
||||
.id = std::string{it->second.service->service_name()},
|
||||
.object_key = obj,
|
||||
.owner = it->second.impl,
|
||||
.service = it->second.service,
|
||||
.managed = dynamic_cast<IManagedService*>(it->second.service),
|
||||
.seq = next->lifecycle_nodes.size(),
|
||||
.dep_indices = {},
|
||||
});
|
||||
}
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
old_snap = std::exchange(m_active_snapshot, std::move(next));
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
void ServiceRegistry::start_all()
|
||||
{
|
||||
auto snap = acquire_snapshot();
|
||||
if (!snap) {
|
||||
return;
|
||||
}
|
||||
// Snapshot copied; callbacks invoke strictly outside registry locks.
|
||||
for (const auto& node : snap->lifecycle_nodes) {
|
||||
if (node.service != nullptr) {
|
||||
node.service->on_start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ServiceRegistry::stop_all()
|
||||
{
|
||||
std::shared_ptr<const detail::SnapshotData> snap;
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
snap = m_active_snapshot;
|
||||
}
|
||||
if (!snap) {
|
||||
return;
|
||||
}
|
||||
for (auto it = snap->lifecycle_nodes.rbegin();
|
||||
it != snap->lifecycle_nodes.rend(); ++it) {
|
||||
if (it->service != nullptr) {
|
||||
it->service->on_stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t ServiceRegistry::size() const
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
return m_active_snapshot ? m_active_snapshot->services.size() : 0;
|
||||
}
|
||||
|
||||
std::size_t ServiceRegistry::prune_and_count_retained_locked()
|
||||
{
|
||||
std::lock_guard lk{m_retention_state->mu};
|
||||
std::erase_if(m_retention_state->entries,
|
||||
[](const detail::RetentionEntry& e) {
|
||||
return e.token.expired();
|
||||
});
|
||||
return m_retention_state->entries.size();
|
||||
}
|
||||
|
||||
std::size_t ServiceRegistry::retained_generation_count() const
|
||||
{
|
||||
std::lock_guard lk{m_retention_state->mu};
|
||||
std::size_t live = 0;
|
||||
for (const auto& e : m_retention_state->entries) {
|
||||
if (!e.token.expired()) {
|
||||
++live;
|
||||
}
|
||||
}
|
||||
return live;
|
||||
}
|
||||
|
||||
PublicationEpoch ServiceRegistry::epoch() const noexcept
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
return m_epoch;
|
||||
}
|
||||
|
||||
bool ServiceRegistry::is_stopping() const noexcept
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
return m_stopping;
|
||||
}
|
||||
|
||||
std::size_t ServiceRegistry::add_observer(ObserverCallback cb)
|
||||
{
|
||||
std::lock_guard lk{m_observer_mu};
|
||||
const std::size_t id = m_next_observer_id++;
|
||||
m_observers.emplace_back(id, std::move(cb));
|
||||
return id;
|
||||
}
|
||||
|
||||
void ServiceRegistry::remove_observer(std::size_t id)
|
||||
{
|
||||
std::lock_guard lk{m_observer_mu};
|
||||
std::erase_if(m_observers,
|
||||
[id](const auto& pair) { return pair.first == id; });
|
||||
}
|
||||
|
||||
void ServiceRegistry::notify_observers(const ServiceObservation& obs)
|
||||
{
|
||||
std::vector<ObserverCallback> copy;
|
||||
{
|
||||
std::lock_guard lk{m_observer_mu};
|
||||
copy.reserve(m_observers.size());
|
||||
for (const auto& [_, cb] : m_observers) {
|
||||
if (cb) {
|
||||
copy.push_back(cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& cb : copy) {
|
||||
try {
|
||||
cb(obs);
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<PreparedPublication>
|
||||
ServiceRegistry::prepare_batch(ProviderSet set, ExpectedEpoch expected)
|
||||
{
|
||||
std::shared_ptr<const detail::SnapshotData> current_snap;
|
||||
PublicationEpoch current_epoch = 0;
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
if (m_stopping) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry::prepare_batch: registry is stopping"));
|
||||
}
|
||||
current_epoch = m_epoch;
|
||||
current_snap = m_active_snapshot;
|
||||
}
|
||||
if (expected.has_value() && *expected != current_epoch) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::conflict,
|
||||
"ServiceRegistry::prepare_batch: expected epoch mismatch"));
|
||||
}
|
||||
|
||||
const auto& items = set.items();
|
||||
if (items.size() > m_limits.max_staged_changes ||
|
||||
items.size() > m_limits.max_providers) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::overloaded,
|
||||
"ServiceRegistry::prepare_batch: staged provider limit exceeded"));
|
||||
}
|
||||
|
||||
if (m_limits.max_retained_generations > 0 &&
|
||||
retained_generation_count() >= m_limits.max_retained_generations) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::retention_limit,
|
||||
"ServiceRegistry::prepare_batch: retained generation limit reached"));
|
||||
}
|
||||
|
||||
auto staged = std::make_shared<detail::SnapshotData>();
|
||||
staged->parent_snap = current_snap ? current_snap->parent_snap : nullptr;
|
||||
staged->live_parent = current_snap ? current_snap->live_parent : nullptr;
|
||||
|
||||
// Validate interfaces, IDs, nulls, edge caps, and coalesce shared-object
|
||||
// lifecycle aliases into single nodes.
|
||||
std::unordered_map<std::type_index, std::size_t> iface_to_node;
|
||||
std::unordered_map<const void*, std::size_t> obj_to_node;
|
||||
std::unordered_map<std::string, const void*> id_to_obj;
|
||||
std::vector<detail::LifecycleNode> raw_nodes;
|
||||
std::size_t total_edges = 0;
|
||||
|
||||
for (const auto& item : items) {
|
||||
if (!item.owner || item.object_key == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServiceRegistry::prepare_batch: null service provider"));
|
||||
}
|
||||
if (staged->services.contains(item.interface_type)) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::duplicate_interface,
|
||||
"ServiceRegistry::prepare_batch: duplicate interface in batch"));
|
||||
}
|
||||
|
||||
const void* canonical_obj =
|
||||
item.service != nullptr
|
||||
? static_cast<const void*>(item.service)
|
||||
: item.object_key;
|
||||
if (!item.id.empty()) {
|
||||
const auto [it, inserted] =
|
||||
id_to_obj.emplace(item.id, canonical_obj);
|
||||
if (!inserted && it->second != canonical_obj) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::conflict,
|
||||
"ServiceRegistry::prepare_batch: conflicting service id '" +
|
||||
item.id + "'"));
|
||||
}
|
||||
}
|
||||
|
||||
staged->services.emplace(
|
||||
item.interface_type,
|
||||
detail::SnapshotEntry{item.owner, item.service, item.id});
|
||||
staged->legacy_order.push_back(item.interface_type);
|
||||
|
||||
total_edges += item.required_deps.size() + item.optional_deps.size();
|
||||
if (total_edges > m_limits.max_dependency_edges) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::overloaded,
|
||||
"ServiceRegistry::prepare_batch: dependency edge limit exceeded"));
|
||||
}
|
||||
|
||||
auto [oit, o_inserted] =
|
||||
obj_to_node.emplace(canonical_obj, raw_nodes.size());
|
||||
if (o_inserted) {
|
||||
std::string node_id = item.id;
|
||||
if (node_id.empty() && item.service != nullptr) {
|
||||
node_id = std::string{item.service->service_name()};
|
||||
}
|
||||
raw_nodes.push_back(detail::LifecycleNode{
|
||||
.id = std::move(node_id),
|
||||
.object_key = canonical_obj,
|
||||
.owner = item.owner,
|
||||
.service = item.service,
|
||||
.managed = item.managed,
|
||||
.seq = raw_nodes.size(),
|
||||
.dep_indices = {},
|
||||
});
|
||||
}
|
||||
iface_to_node.emplace(item.interface_type, oit->second);
|
||||
}
|
||||
|
||||
// Build DAG edges: dep_idx -> dependent_idx.
|
||||
const std::size_t n = raw_nodes.size();
|
||||
std::vector<std::vector<std::size_t>> adj(n);
|
||||
std::vector<std::size_t> indegree(n, 0);
|
||||
std::unordered_set<std::uint64_t> edge_dedup;
|
||||
|
||||
for (const auto& item : items) {
|
||||
const std::size_t u = iface_to_node.at(item.interface_type);
|
||||
auto add_dep = [&](std::type_index dep_iface,
|
||||
bool required) -> Void::Result::Result<void> {
|
||||
const auto dit = iface_to_node.find(dep_iface);
|
||||
if (dit == iface_to_node.end()) {
|
||||
bool in_parent = false;
|
||||
if (staged->parent_snap) {
|
||||
in_parent = detail::has_in_parent_chain(
|
||||
*staged->parent_snap, dep_iface,
|
||||
m_limits.max_parent_levels);
|
||||
}
|
||||
if (!in_parent && staged->live_parent != nullptr) {
|
||||
if (auto ps = staged->live_parent->acquire_snapshot()) {
|
||||
in_parent = ps->services.contains(dep_iface);
|
||||
}
|
||||
}
|
||||
if (required && !in_parent) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_dependency,
|
||||
"ServiceRegistry::prepare_batch: missing required dependency"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
const std::size_t dep = dit->second;
|
||||
if (dep == u) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::cycle_detected,
|
||||
"ServiceRegistry::prepare_batch: self-dependency cycle"));
|
||||
}
|
||||
const std::uint64_t edge_key =
|
||||
(static_cast<std::uint64_t>(dep) << 32) |
|
||||
static_cast<std::uint64_t>(u);
|
||||
if (edge_dedup.insert(edge_key).second) {
|
||||
adj[dep].push_back(u);
|
||||
++indegree[u];
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
for (const auto& dep : item.required_deps) {
|
||||
if (auto r = add_dep(dep, true); !r) {
|
||||
return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
}
|
||||
for (const auto& dep : item.optional_deps) {
|
||||
if (auto r = add_dep(dep, false); !r) {
|
||||
return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deterministic Kahn topological sort breaking ties by registration seq.
|
||||
std::priority_queue<std::size_t, std::vector<std::size_t>,
|
||||
std::greater<std::size_t>>
|
||||
ready;
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
if (indegree[i] == 0) {
|
||||
ready.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<detail::LifecycleNode> sorted;
|
||||
sorted.reserve(n);
|
||||
while (!ready.empty()) {
|
||||
const std::size_t u = ready.top();
|
||||
ready.pop();
|
||||
sorted.push_back(std::move(raw_nodes[u]));
|
||||
for (const std::size_t v : adj[u]) {
|
||||
if (--indegree[v] == 0) {
|
||||
ready.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sorted.size() != n) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::cycle_detected,
|
||||
"ServiceRegistry::prepare_batch: dependency cycle detected"));
|
||||
}
|
||||
|
||||
staged->lifecycle_nodes = std::move(sorted);
|
||||
PreparedPublication prep;
|
||||
prep.expected_epoch = expected;
|
||||
prep.snapshot = std::move(staged);
|
||||
prep.valid = true;
|
||||
prep.started = false;
|
||||
prep.aborted = false;
|
||||
return prep;
|
||||
}
|
||||
|
||||
Void::Result::Result<void> ServiceRegistry::rollback_started_nodes(
|
||||
const std::vector<detail::LifecycleNode>& nodes, std::size_t count,
|
||||
const Void::Result::Error& primary_error)
|
||||
{
|
||||
std::string stop_errs;
|
||||
for (std::size_t i = count; i > 0; --i) {
|
||||
const auto& node = nodes[i - 1];
|
||||
if (node.managed != nullptr) {
|
||||
auto sr = node.managed->stop_checked();
|
||||
if (!sr) {
|
||||
if (!stop_errs.empty()) stop_errs += "; ";
|
||||
stop_errs += sr.error().message();
|
||||
}
|
||||
} else if (node.service != nullptr) {
|
||||
try {
|
||||
node.service->on_stop();
|
||||
} catch (const std::exception& ex) {
|
||||
if (!stop_errs.empty()) stop_errs += "; ";
|
||||
stop_errs += ex.what();
|
||||
} catch (...) {
|
||||
if (!stop_errs.empty()) stop_errs += "; ";
|
||||
stop_errs += "unknown stop exception";
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stop_errs.empty()) {
|
||||
return Void::Result::fail(primary_error);
|
||||
}
|
||||
return Void::Result::fail(make_service_error(
|
||||
static_cast<ServiceErrorCode>(primary_error.code().value),
|
||||
primary_error.message() + " (rollback stop errors: " + stop_errs +
|
||||
")"));
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ServiceRegistry::start_staged(PreparedPublication& prepared,
|
||||
Async::OperationOptions options)
|
||||
{
|
||||
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServiceRegistry::start_staged: invalid or aborted publication"));
|
||||
}
|
||||
if (prepared.started) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const auto& nodes = prepared.snapshot->lifecycle_nodes;
|
||||
for (std::size_t i = 0; i < nodes.size(); ++i) {
|
||||
if (options.stop.stop_requested()) {
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(
|
||||
ServiceErrorCode::cancelled,
|
||||
"ServiceRegistry::start_staged: cancelled during startup"));
|
||||
}
|
||||
if (Async::is_deadline_expired(options, *m_clock)) {
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(
|
||||
ServiceErrorCode::timeout,
|
||||
"ServiceRegistry::start_staged: deadline expired during startup"));
|
||||
}
|
||||
|
||||
const auto& node = nodes[i];
|
||||
if (node.managed != nullptr) {
|
||||
auto sr = node.managed->start_checked();
|
||||
if (!sr) {
|
||||
node.managed->abort_start();
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(nodes, i, sr.error());
|
||||
}
|
||||
auto rr = node.managed->check_readiness();
|
||||
if (!rr) {
|
||||
node.managed->abort_start();
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::not_ready,
|
||||
rr.error().message()));
|
||||
}
|
||||
} else if (node.service != nullptr) {
|
||||
try {
|
||||
node.service->on_start();
|
||||
} catch (const std::exception& ex) {
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::start_failed,
|
||||
ex.what()));
|
||||
} catch (...) {
|
||||
prepared.aborted = true;
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(
|
||||
ServiceErrorCode::start_failed,
|
||||
"ServiceRegistry: service on_start threw"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
prepared.started = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<PublicationEpoch>
|
||||
ServiceRegistry::publish(PreparedPublication&& prepared)
|
||||
{
|
||||
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServiceRegistry::publish: invalid or aborted publication"));
|
||||
}
|
||||
|
||||
PublicationEpoch new_epoch = 0;
|
||||
std::size_t provider_count = 0;
|
||||
std::size_t retained = 0;
|
||||
std::shared_ptr<const detail::SnapshotData> old_snap;
|
||||
|
||||
{
|
||||
std::lock_guard write_lk{m_write_mu};
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
if (m_stopping) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry::publish: registry is stopping"));
|
||||
}
|
||||
if (prepared.expected_epoch.has_value() &&
|
||||
*prepared.expected_epoch != m_epoch) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::conflict,
|
||||
"ServiceRegistry::publish: expected epoch conflict"));
|
||||
}
|
||||
}
|
||||
|
||||
if (m_limits.max_retained_generations > 0 &&
|
||||
prune_and_count_retained_locked() >=
|
||||
m_limits.max_retained_generations) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::retention_limit,
|
||||
"ServiceRegistry::publish: retained generation limit reached"));
|
||||
}
|
||||
|
||||
new_epoch = ++m_epoch;
|
||||
prepared.snapshot->epoch = new_epoch;
|
||||
prepared.snapshot->gen_token = detail::make_retention_token(
|
||||
m_retention_state, new_epoch,
|
||||
"generation#" + std::to_string(new_epoch));
|
||||
provider_count = prepared.snapshot->services.size();
|
||||
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
if (m_stopping) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry::publish: registry is stopping"));
|
||||
}
|
||||
old_snap = std::exchange(m_active_snapshot,
|
||||
std::move(prepared.snapshot));
|
||||
}
|
||||
retained = prune_and_count_retained_locked();
|
||||
m_started = prepared.started;
|
||||
}
|
||||
prepared.valid = false;
|
||||
|
||||
// Retire old snapshot strictly outside locks, then notify observers.
|
||||
old_snap.reset();
|
||||
notify_observers(ServiceObservation{
|
||||
.epoch = new_epoch,
|
||||
.provider_count = provider_count,
|
||||
.retained_generations = retained,
|
||||
.duration_ns = 0,
|
||||
.rollback = false,
|
||||
.detail = "published",
|
||||
});
|
||||
return new_epoch;
|
||||
}
|
||||
|
||||
Void::Result::Result<PublicationEpoch>
|
||||
ServiceRegistry::start_and_publish(ProviderSet set,
|
||||
ExpectedEpoch expected,
|
||||
Async::OperationOptions options)
|
||||
{
|
||||
const auto t0 = m_clock->now();
|
||||
auto prep = prepare_batch(std::move(set), expected);
|
||||
if (!prep) {
|
||||
return Void::Result::fail(std::move(prep).error());
|
||||
}
|
||||
auto staged = std::move(*prep);
|
||||
if (auto sr = start_staged(staged, options); !sr) {
|
||||
const auto dt = static_cast<std::uint64_t>(
|
||||
std::max<std::int64_t>(0, (m_clock->now() - t0).count()));
|
||||
notify_observers(ServiceObservation{
|
||||
.epoch = epoch(),
|
||||
.provider_count = 0,
|
||||
.retained_generations = retained_generation_count(),
|
||||
.duration_ns = dt,
|
||||
.rollback = true,
|
||||
.detail = sr.error().message(),
|
||||
});
|
||||
return Void::Result::fail(std::move(sr).error());
|
||||
}
|
||||
auto snapshot_copy = staged.snapshot;
|
||||
auto pub = publish(std::move(staged));
|
||||
if (!pub) {
|
||||
return Void::Result::fail(
|
||||
rollback_started_nodes(snapshot_copy->lifecycle_nodes,
|
||||
snapshot_copy->lifecycle_nodes.size(),
|
||||
pub.error())
|
||||
.error());
|
||||
}
|
||||
return pub;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ServiceRegistry::start(Async::OperationOptions options)
|
||||
{
|
||||
auto snap = acquire_snapshot();
|
||||
if (!snap) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry::start: registry is stopping"));
|
||||
}
|
||||
|
||||
const auto& nodes = snap->lifecycle_nodes;
|
||||
for (std::size_t i = 0; i < nodes.size(); ++i) {
|
||||
if (options.stop.stop_requested()) {
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::cancelled,
|
||||
"ServiceRegistry::start: cancelled"));
|
||||
}
|
||||
if (Async::is_deadline_expired(options, *m_clock)) {
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::timeout,
|
||||
"ServiceRegistry::start: timed out"));
|
||||
}
|
||||
const auto& node = nodes[i];
|
||||
if (node.managed != nullptr) {
|
||||
auto sr = node.managed->start_checked();
|
||||
if (!sr) {
|
||||
node.managed->abort_start();
|
||||
return rollback_started_nodes(nodes, i, sr.error());
|
||||
}
|
||||
auto rr = node.managed->check_readiness();
|
||||
if (!rr) {
|
||||
node.managed->abort_start();
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::not_ready,
|
||||
rr.error().message()));
|
||||
}
|
||||
} else if (node.service != nullptr) {
|
||||
try {
|
||||
node.service->on_start();
|
||||
} catch (const std::exception& ex) {
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(ServiceErrorCode::start_failed,
|
||||
ex.what()));
|
||||
} catch (...) {
|
||||
return rollback_started_nodes(
|
||||
nodes, i,
|
||||
make_service_error(
|
||||
ServiceErrorCode::start_failed,
|
||||
"ServiceRegistry::start: on_start threw"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::lock_guard write_lk{m_write_mu};
|
||||
m_started = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<ShutdownReport>
|
||||
ServiceRegistry::close_and_join(Async::OperationOptions options)
|
||||
{
|
||||
std::shared_ptr<const detail::SnapshotData> active_to_stop;
|
||||
{
|
||||
std::lock_guard snap_lk{m_snapshot_mu};
|
||||
m_stopping = true;
|
||||
active_to_stop = std::exchange(
|
||||
m_active_snapshot, std::make_shared<detail::SnapshotData>());
|
||||
}
|
||||
|
||||
ShutdownReport report;
|
||||
if (active_to_stop) {
|
||||
for (auto it = active_to_stop->lifecycle_nodes.rbegin();
|
||||
it != active_to_stop->lifecycle_nodes.rend(); ++it) {
|
||||
const auto& node = *it;
|
||||
const std::string label =
|
||||
!node.id.empty() ? node.id : std::string{"<service>"};
|
||||
if (node.managed != nullptr) {
|
||||
auto sr = node.managed->stop_checked();
|
||||
if (!sr) {
|
||||
report.stop_errors.push_back(std::move(sr).error());
|
||||
} else {
|
||||
report.stopped_services.push_back(label);
|
||||
}
|
||||
} else if (node.service != nullptr) {
|
||||
try {
|
||||
node.service->on_stop();
|
||||
report.stopped_services.push_back(label);
|
||||
} catch (const std::exception& ex) {
|
||||
report.stop_errors.push_back(make_service_error(
|
||||
ServiceErrorCode::stop_failed, ex.what()));
|
||||
} catch (...) {
|
||||
report.stop_errors.push_back(make_service_error(
|
||||
ServiceErrorCode::stop_failed,
|
||||
"ServiceRegistry::close_and_join: on_stop threw"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
active_to_stop.reset();
|
||||
|
||||
// Check retained generation pins; wait up to deadline only when using the
|
||||
// real monotonic clock and an explicit deadline.
|
||||
const bool can_wait_deadline =
|
||||
options.deadline.has_value() &&
|
||||
m_clock == &Void::Time::SystemMonotonicClock::instance();
|
||||
|
||||
std::unique_lock lk{m_retention_state->mu};
|
||||
auto collect_live = [&]() {
|
||||
std::erase_if(m_retention_state->entries,
|
||||
[](const detail::RetentionEntry& e) {
|
||||
return e.token.expired();
|
||||
});
|
||||
return m_retention_state->entries.empty();
|
||||
};
|
||||
|
||||
if (!collect_live() && can_wait_deadline && !options.stop.stop_requested()) {
|
||||
while (!collect_live() && !options.stop.stop_requested()) {
|
||||
const auto now = m_clock->now();
|
||||
if (now >= *options.deadline) {
|
||||
break;
|
||||
}
|
||||
const auto rem = *options.deadline - now;
|
||||
m_retention_state->cv.wait_for(
|
||||
lk, std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
rem));
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& entry : m_retention_state->entries) {
|
||||
if (!entry.token.expired()) {
|
||||
report.incomplete_owners.push_back(entry.label);
|
||||
}
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
} // namespace Void::Service
|
||||
@@ -1,3 +1,4 @@
|
||||
void_add_module(Service
|
||||
INTERNAL_DEPS Core Functional LogState
|
||||
INTERNAL_DEPS Core Functional Time Async LogState
|
||||
EXCLUDE_HEADERS Void/Service/PluginService.hpp
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(ServicePlugin
|
||||
INTERNAL_DEPS Service Plugin LogState
|
||||
EXTRA_HEADERS Void/Service/PluginService.hpp
|
||||
)
|
||||
@@ -237,6 +237,21 @@ if(_has_storage)
|
||||
run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_service Service Core Functional Time Async LogState)
|
||||
if(_has_service)
|
||||
run_consumer(ServiceOnly "${install_prefix}" "ServiceOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_service_plugin ServicePlugin Service Plugin Functional System Data LogState Text Time Async Core)
|
||||
if(_has_service_plugin)
|
||||
run_consumer(ServicePluginOnly "${install_prefix}" "ServicePluginOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidServiceOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Service)
|
||||
|
||||
add_executable(void_service_only_consumer main.cpp)
|
||||
target_link_libraries(void_service_only_consumer PRIVATE Void::Service)
|
||||
target_compile_features(void_service_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME ServiceOnlyConsumer COMMAND void_service_only_consumer)
|
||||
@@ -0,0 +1,36 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Service/Types.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct ICounter {
|
||||
virtual ~ICounter() = default;
|
||||
virtual int value() const = 0;
|
||||
};
|
||||
|
||||
struct Counter final : Void::Service::IManagedService, ICounter {
|
||||
std::string_view service_name() const override { return "counter"; }
|
||||
int value() const override { return 42; }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Service::ServiceRegistry reg;
|
||||
Void::Service::ProviderSet set;
|
||||
set.add<ICounter>("counter", std::make_shared<Counter>());
|
||||
auto ep = reg.start_and_publish(std::move(set));
|
||||
if (!ep) {
|
||||
return 1;
|
||||
}
|
||||
auto handle = reg.acquire<ICounter>();
|
||||
if (!handle || (*handle)->value() != 42 || handle->generation() != *ep) {
|
||||
return 2;
|
||||
}
|
||||
auto report = reg.close_and_join();
|
||||
return report && !report->clean() ? 0 : 3; // handle still held until return
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidServicePluginOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS ServicePlugin)
|
||||
|
||||
add_executable(void_service_plugin_only_consumer main.cpp)
|
||||
target_link_libraries(void_service_plugin_only_consumer PRIVATE Void::ServicePlugin)
|
||||
target_compile_features(void_service_plugin_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME ServicePluginOnlyConsumer COMMAND void_service_plugin_only_consumer)
|
||||
@@ -0,0 +1,12 @@
|
||||
#include <Void/Service/PluginService.hpp>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Plugin::PluginManager plugins;
|
||||
Void::Service::ServiceRegistry registry;
|
||||
Void::Service::PluginServiceBinding<Void::Service::IService> binding{
|
||||
plugins, registry, "missing"};
|
||||
auto direct = Void::Service::acquire_plugin_service<Void::Service::IService>(
|
||||
plugins, "missing");
|
||||
return !binding.bind() && !direct.has_value() ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Service/Types.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <typeindex>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Service::ExpectedEpoch;
|
||||
using Void::Service::IManagedService;
|
||||
using Void::Service::IService;
|
||||
using Void::Service::ProviderSet;
|
||||
using Void::Service::ServiceErrorCode;
|
||||
using Void::Service::ServiceLimits;
|
||||
using Void::Service::ServiceRegistry;
|
||||
using Void::Time::ManualClock;
|
||||
|
||||
struct IA {
|
||||
virtual ~IA() = default;
|
||||
[[nodiscard]] virtual int id() const = 0;
|
||||
};
|
||||
|
||||
struct IB {
|
||||
virtual ~IB() = default;
|
||||
[[nodiscard]] virtual int tag() const = 0;
|
||||
};
|
||||
|
||||
struct IC {
|
||||
virtual ~IC() = default;
|
||||
[[nodiscard]] virtual int rank() const = 0;
|
||||
};
|
||||
|
||||
class TrackedService final : public IManagedService, public IA
|
||||
{
|
||||
public:
|
||||
|
||||
TrackedService(std::string name, int val,
|
||||
std::vector<std::string>* log,
|
||||
bool fail_start = false,
|
||||
bool fail_ready = false,
|
||||
bool throw_stop = false)
|
||||
: m_name(std::move(name)), m_val(val), m_log(log),
|
||||
m_fail_start(fail_start), m_fail_ready(fail_ready),
|
||||
m_throw_stop(throw_stop)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view service_name() const override
|
||||
{
|
||||
return m_name;
|
||||
}
|
||||
|
||||
[[nodiscard]] int id() const override { return m_val; }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start_checked() override
|
||||
{
|
||||
if (m_log != nullptr) {
|
||||
m_log->push_back("start:" + m_name);
|
||||
}
|
||||
if (m_fail_start) {
|
||||
return Void::Result::fail(Void::Service::make_service_error(
|
||||
ServiceErrorCode::start_failed,
|
||||
"start failed for " + m_name));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
check_readiness() const override
|
||||
{
|
||||
if (m_fail_ready) {
|
||||
return Void::Result::fail(Void::Service::make_service_error(
|
||||
ServiceErrorCode::not_ready,
|
||||
"not ready: " + m_name));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void abort_start() noexcept override
|
||||
{
|
||||
if (m_log != nullptr) {
|
||||
m_log->push_back("abort:" + m_name);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> stop_checked() override
|
||||
{
|
||||
if (m_log != nullptr) {
|
||||
m_log->push_back("stop:" + m_name);
|
||||
}
|
||||
if (m_throw_stop) {
|
||||
return Void::Result::fail(Void::Service::make_service_error(
|
||||
ServiceErrorCode::stop_failed,
|
||||
"stop boom: " + m_name));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string m_name;
|
||||
int m_val;
|
||||
std::vector<std::string>* m_log;
|
||||
bool m_fail_start;
|
||||
bool m_fail_ready;
|
||||
bool m_throw_stop;
|
||||
};
|
||||
|
||||
class DualInterfaceService final : public IManagedService, public IA, public IB
|
||||
{
|
||||
public:
|
||||
|
||||
explicit DualInterfaceService(std::vector<std::string>* log)
|
||||
: m_log(log)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view service_name() const override
|
||||
{
|
||||
return "Dual";
|
||||
}
|
||||
[[nodiscard]] int id() const override { return 10; }
|
||||
[[nodiscard]] int tag() const override { return 20; }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start_checked() override
|
||||
{
|
||||
++starts;
|
||||
if (m_log != nullptr) m_log->push_back("dual:start");
|
||||
return {};
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<void> stop_checked() override
|
||||
{
|
||||
++stops;
|
||||
if (m_log != nullptr) m_log->push_back("dual:stop");
|
||||
return {};
|
||||
}
|
||||
|
||||
int starts{0};
|
||||
int stops{0};
|
||||
std::vector<std::string>* m_log;
|
||||
};
|
||||
|
||||
class ReentrantDtorProvider final : public IA
|
||||
{
|
||||
public:
|
||||
|
||||
ReentrantDtorProvider(ServiceRegistry& reg, int val,
|
||||
std::atomic<int>* observations)
|
||||
: m_reg(reg), m_val(val), m_obs(observations)
|
||||
{
|
||||
}
|
||||
|
||||
~ReentrantDtorProvider() override
|
||||
{
|
||||
if (auto h = m_reg.acquire<IA>(); h) {
|
||||
if (m_obs != nullptr) {
|
||||
m_obs->fetch_add((*h)->id(), std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] int id() const override { return m_val; }
|
||||
|
||||
private:
|
||||
|
||||
ServiceRegistry& m_reg;
|
||||
int m_val;
|
||||
std::atomic<int>* m_obs;
|
||||
};
|
||||
|
||||
class ReentrantStartService final : public IService, public IB
|
||||
{
|
||||
public:
|
||||
|
||||
ReentrantStartService(ServiceRegistry& reg, std::atomic<int>* seen)
|
||||
: m_reg(reg), m_seen(seen)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view service_name() const override
|
||||
{
|
||||
return "ReentrantStart";
|
||||
}
|
||||
|
||||
void on_start() override
|
||||
{
|
||||
if (auto a = m_reg.acquire<IA>(); a) {
|
||||
m_seen->store((*a)->id(), std::memory_order_relaxed);
|
||||
}
|
||||
m_reg.provide<IC>(std::make_shared<SimpleC>(99));
|
||||
}
|
||||
|
||||
[[nodiscard]] int tag() const override { return 7; }
|
||||
|
||||
private:
|
||||
|
||||
struct SimpleC final : IC {
|
||||
explicit SimpleC(int r) : rank_val(r) {}
|
||||
[[nodiscard]] int rank() const override { return rank_val; }
|
||||
int rank_val;
|
||||
};
|
||||
|
||||
ServiceRegistry& m_reg;
|
||||
std::atomic<int>* m_seen;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test service_concurrent_remove_acquire_and_reentrant_dtor()
|
||||
{
|
||||
ServiceRegistry reg;
|
||||
std::atomic<int> dtor_observations{0};
|
||||
reg.provide<IA>(
|
||||
std::make_shared<ReentrantDtorProvider>(reg, 1, &dtor_observations));
|
||||
|
||||
auto held_first = reg.acquire<IA>();
|
||||
Void::Testing::expect(held_first.has_value());
|
||||
Void::Testing::expect_eq((*held_first)->id(), 1);
|
||||
|
||||
// Replace with another ReentrantDtorProvider; releasing held_first
|
||||
// later must invoke ~ReentrantDtorProvider cleanly without deadlocking.
|
||||
std::atomic<bool> stop{false};
|
||||
std::thread writer([&] {
|
||||
for (int i = 2; i < 60 && !stop.load(std::memory_order_relaxed); ++i) {
|
||||
reg.provide<IA>(std::make_shared<ReentrantDtorProvider>(
|
||||
reg, i, &dtor_observations));
|
||||
if (i % 7 == 0) {
|
||||
(void)reg.remove<IA>();
|
||||
}
|
||||
}
|
||||
});
|
||||
std::thread reader([&] {
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
if (auto h = reg.acquire<IA>(); h) {
|
||||
Void::Testing::expect((*h)->id() >= 1);
|
||||
}
|
||||
}
|
||||
stop.store(true, std::memory_order_relaxed);
|
||||
});
|
||||
writer.join();
|
||||
reader.join();
|
||||
|
||||
Void::Testing::expect_eq((*held_first)->id(), 1);
|
||||
held_first = Void::Result::fail(Void::Service::make_service_error(
|
||||
ServiceErrorCode::missing_service, "drop"));
|
||||
Void::Testing::expect(dtor_observations.load(std::memory_order_relaxed) >=
|
||||
0);
|
||||
}
|
||||
|
||||
Void::Testing::Test service_start_all_allows_reentrant_acquire_and_provide()
|
||||
{
|
||||
ServiceRegistry reg;
|
||||
std::vector<std::string> log;
|
||||
std::atomic<int> seen{0};
|
||||
reg.provide<IA>(std::make_shared<TrackedService>("A", 42, &log));
|
||||
reg.provide<IB>(std::make_shared<ReentrantStartService>(reg, &seen));
|
||||
|
||||
reg.start_all();
|
||||
Void::Testing::expect_eq(seen.load(std::memory_order_relaxed), 42);
|
||||
auto c = reg.acquire<IC>();
|
||||
Void::Testing::expect(c.has_value());
|
||||
Void::Testing::expect_eq((*c)->rank(), 99);
|
||||
}
|
||||
|
||||
Void::Testing::Test service_dag_ordering_aliases_cycles_and_rollback()
|
||||
{
|
||||
std::vector<std::string> log;
|
||||
ServiceRegistry reg;
|
||||
|
||||
// Baseline snapshot that must remain untouched if staged batch fails.
|
||||
{
|
||||
ProviderSet base;
|
||||
base.add<IA>("baseline", std::make_shared<TrackedService>("base", 100, &log));
|
||||
auto ep = reg.start_and_publish(std::move(base));
|
||||
Void::Testing::expect(ep.has_value());
|
||||
Void::Testing::expect_eq(*ep, std::uint64_t{1});
|
||||
}
|
||||
log.clear();
|
||||
|
||||
// Missing dependency rejected.
|
||||
{
|
||||
ProviderSet bad;
|
||||
bad.add<IB>("B", std::make_shared<DualInterfaceService>(&log),
|
||||
{std::type_index{typeid(IC)}});
|
||||
auto prep = reg.prepare_batch(std::move(bad));
|
||||
Void::Testing::expect(!prep.has_value());
|
||||
Void::Testing::expect_eq(prep.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
ServiceErrorCode::missing_dependency));
|
||||
}
|
||||
|
||||
// Cycle rejected.
|
||||
{
|
||||
ProviderSet cyc;
|
||||
auto dual = std::make_shared<DualInterfaceService>(&log);
|
||||
cyc.add<IA>("A", std::make_shared<TrackedService>("A", 1, &log),
|
||||
{std::type_index{typeid(IB)}});
|
||||
cyc.add<IB>("B", dual, {std::type_index{typeid(IA)}});
|
||||
auto prep = reg.prepare_batch(std::move(cyc));
|
||||
Void::Testing::expect(!prep.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
prep.error().code().value,
|
||||
static_cast<std::int32_t>(ServiceErrorCode::cycle_detected));
|
||||
}
|
||||
|
||||
// Middle node failure aborts failed node and rolls back started nodes in
|
||||
// reverse dependency order, leaving baseline untouched.
|
||||
{
|
||||
struct RankImpl final : IManagedService, IC {
|
||||
RankImpl(std::string n, std::vector<std::string>* l, bool fail)
|
||||
: impl(std::move(n), 3, l, fail) {}
|
||||
std::string_view service_name() const override
|
||||
{ return impl.service_name(); }
|
||||
Void::Result::Result<void> start_checked() override
|
||||
{ return impl.start_checked(); }
|
||||
Void::Result::Result<void> check_readiness() const override
|
||||
{ return impl.check_readiness(); }
|
||||
void abort_start() noexcept override { impl.abort_start(); }
|
||||
Void::Result::Result<void> stop_checked() override
|
||||
{ return impl.stop_checked(); }
|
||||
int rank() const override { return 3; }
|
||||
TrackedService impl;
|
||||
};
|
||||
auto dual = std::make_shared<DualInterfaceService>(&log);
|
||||
ProviderSet fail_batch;
|
||||
// IB depends on IA; IA registered second so DAG must still start IA before IB.
|
||||
fail_batch.add<IB>("B", dual, {std::type_index{typeid(IA)}});
|
||||
fail_batch.add<IA>("A", std::make_shared<TrackedService>("A", 1, &log));
|
||||
fail_batch.add<IC>(
|
||||
"C", std::make_shared<RankImpl>("C", &log, true),
|
||||
{std::type_index{typeid(IB)}});
|
||||
|
||||
auto res = reg.start_and_publish(std::move(fail_batch));
|
||||
Void::Testing::expect(!res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res.error().code().value,
|
||||
static_cast<std::int32_t>(ServiceErrorCode::start_failed));
|
||||
// Baseline handle still resolves to id 100.
|
||||
auto active = reg.acquire<IA>();
|
||||
Void::Testing::expect(active.has_value());
|
||||
Void::Testing::expect_eq((*active)->id(), 100);
|
||||
// Sequence: start:A, dual:start, start:C, abort:C, dual:stop, stop:A.
|
||||
Void::Testing::expect_eq(log.size(), std::size_t{6});
|
||||
Void::Testing::expect_eq(log[0], std::string{"start:A"});
|
||||
Void::Testing::expect_eq(log[1], std::string{"dual:start"});
|
||||
Void::Testing::expect_eq(log[2], std::string{"start:C"});
|
||||
Void::Testing::expect_eq(log[3], std::string{"abort:C"});
|
||||
Void::Testing::expect_eq(log[4], std::string{"dual:stop"});
|
||||
Void::Testing::expect_eq(log[5], std::string{"stop:A"});
|
||||
}
|
||||
|
||||
// Alias of one lifecycle object starts/stops ONCE.
|
||||
log.clear();
|
||||
auto dual = std::make_shared<DualInterfaceService>(&log);
|
||||
ProviderSet alias_batch;
|
||||
alias_batch.add<IA>("dual.svc", dual);
|
||||
alias_batch.add_alias<IB>("dual.svc.alias", dual);
|
||||
auto ep = reg.start_and_publish(std::move(alias_batch));
|
||||
Void::Testing::expect(ep.has_value());
|
||||
Void::Testing::expect_eq(dual->starts, 1);
|
||||
Void::Testing::expect_eq(reg.acquire<IA>().value()->id(), 10);
|
||||
Void::Testing::expect_eq(reg.acquire<IB>().value()->tag(), 20);
|
||||
}
|
||||
|
||||
Void::Testing::Test service_snapshot_parent_survives_parent_destruction()
|
||||
{
|
||||
std::unique_ptr<ServiceRegistry> child;
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
ProviderSet ps;
|
||||
ps.add<IA>("A", std::make_shared<TrackedService>("A", 77, nullptr));
|
||||
Void::Testing::expect(
|
||||
parent.start_and_publish(std::move(ps)).has_value());
|
||||
|
||||
auto built = ServiceRegistry::from_parent_snapshot(parent.snapshot());
|
||||
Void::Testing::expect(built.has_value());
|
||||
child = std::move(*built);
|
||||
} // parent destroyed here!
|
||||
|
||||
auto h = child->acquire<IA>();
|
||||
Void::Testing::expect(h.has_value());
|
||||
Void::Testing::expect_eq((*h)->id(), 77);
|
||||
}
|
||||
|
||||
Void::Testing::Test service_retention_cap_and_close_incomplete_owners()
|
||||
{
|
||||
ManualClock clock;
|
||||
ServiceLimits limits{};
|
||||
limits.max_retained_generations = 4;
|
||||
|
||||
ServiceRegistry reg{limits, clock};
|
||||
std::vector<std::string> log;
|
||||
std::vector<Void::Service::ServiceHandle<IA>> pinned;
|
||||
|
||||
for (int gen = 1; gen <= 4; ++gen) {
|
||||
ProviderSet ps;
|
||||
ps.add<IA>(
|
||||
"A",
|
||||
std::make_shared<TrackedService>(
|
||||
"A" + std::to_string(gen), gen, &log, false, false, gen == 4));
|
||||
auto ep = reg.start_and_publish(std::move(ps));
|
||||
Void::Testing::expect(ep.has_value());
|
||||
auto h = reg.acquire<IA>();
|
||||
Void::Testing::expect(h.has_value());
|
||||
Void::Testing::expect_eq(h->generation(), *ep);
|
||||
pinned.push_back(std::move(*h));
|
||||
}
|
||||
|
||||
// 4 distinct generations pinned -> 5th publication rejected with retention_limit.
|
||||
{
|
||||
ProviderSet ps5;
|
||||
ps5.add<IA>("A", std::make_shared<TrackedService>("A5", 5, &log));
|
||||
auto prep5 = reg.prepare_batch(std::move(ps5));
|
||||
Void::Testing::expect(!prep5.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
prep5.error().code().value,
|
||||
static_cast<std::int32_t>(ServiceErrorCode::retention_limit));
|
||||
}
|
||||
|
||||
// Dropping oldest handle frees generation 1, allowing generation 5.
|
||||
pinned.erase(pinned.begin());
|
||||
{
|
||||
ProviderSet ps5;
|
||||
ps5.add<IA>("A", std::make_shared<TrackedService>("A5", 5, &log));
|
||||
auto ep5 = reg.start_and_publish(std::move(ps5));
|
||||
Void::Testing::expect(ep5.has_value());
|
||||
}
|
||||
|
||||
// close_and_join closes admission, reports any stop error, and reports
|
||||
// surviving pinned generations in incomplete_owners without freeing them.
|
||||
auto rep = reg.close_and_join();
|
||||
Void::Testing::expect(rep.has_value());
|
||||
Void::Testing::expect(!rep->clean());
|
||||
Void::Testing::expect(!rep->incomplete_owners.empty());
|
||||
|
||||
auto post_close = reg.acquire<IA>();
|
||||
Void::Testing::expect(!post_close.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
post_close.error().code().value,
|
||||
static_cast<std::int32_t>(ServiceErrorCode::service_stopping));
|
||||
|
||||
// Pinned handles remain dereferenceable until dropped.
|
||||
Void::Testing::expect_eq(pinned.front()->id(), 2);
|
||||
}
|
||||
Reference in new issue
Block a user