Files
Library/include/Void/Service/Registry.hpp
T

464 lines
14 KiB
C++

#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 <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Service
{
#ifdef VOID_HAS_META_REFLECTION
/// The reflected (unqualified) name of an interface type — a sensible
/// default service name when an IService impl doesn't override
/// service_name(). E.g. interface_name<IClock>() == "IClock".
template <typename I> [[nodiscard]] std::string interface_name()
{
return Void::Meta::type_name<I>();
}
#endif
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`).
///
/// 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();
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;
/// 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 ─────────────────────────────────────
template <typename I> void provide(std::shared_ptr<I> 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());
}
}
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();
}
template <typename I> [[nodiscard]] I& require() const
{
auto p = get<I>();
if (!p) {
throw std::runtime_error(
std::string{"ServiceRegistry: no service for '"} +
typeid(I).name() + "'");
}
return *p;
}
template <typename I> [[nodiscard]] bool has() const
{
return acquire<I>().has_value();
}
/// Run on_start() outside registry locks in registration/dependency
/// order.
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
{
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);
}
[[nodiscard]] Void::Result::Result<PreparedPublication>
prepare_batch(ProviderSet set,
ExpectedEpoch expected = std::nullopt);
[[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:
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;
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