#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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". template [[nodiscard]] std::string interface_name() { return Void::Meta::type_name(); } #endif class ServiceRegistry; namespace detail { struct RetentionEntry { PublicationEpoch epoch{0}; std::weak_ptr token{}; std::string label{}; }; struct RetentionState; struct LifecycleNode { std::string id{}; const void* object_key{nullptr}; std::shared_ptr owner{}; IService* service{nullptr}; IManagedService* managed{nullptr}; std::size_t seq{0}; std::vector dep_indices{}; }; struct SnapshotEntry { std::shared_ptr impl{}; // holds provider (+ optional pin) IService* service{nullptr}; std::string id{}; }; struct SnapshotData { PublicationEpoch epoch{0}; std::shared_ptr gen_token{}; std::unordered_map services{}; std::vector legacy_order{}; std::vector lifecycle_nodes{}; std::shared_ptr 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 [[nodiscard]] std::shared_ptr 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(it->second.impl); } cur = cur->parent_snap.get(); ++depth; } return nullptr; } template [[nodiscard]] bool has() const { return get() != 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 data, std::size_t max_parent_levels = 16) noexcept : m_data(std::move(data)), m_max_parent_levels(max_parent_levels) { } std::shared_ptr 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 owner{}; const void* object_key{nullptr}; IService* service{nullptr}; IManagedService* managed{nullptr}; std::vector required_deps{}; std::vector optional_deps{}; }; template ProviderSet& add( std::string id, std::shared_ptr impl, std::vector required_deps = {}, std::vector 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 ProviderSet& add_alias( std::string id, std::shared_ptr impl, std::vector required_deps = {}, std::vector optional_deps = {}, ServicePin pin = {}) { return add(std::move(id), std::move(impl), std::move(required_deps), std::move(optional_deps), std::move(pin)); } [[nodiscard]] const std::vector& items() const noexcept { return m_items; } private: template static std::shared_ptr pack_owner(const std::shared_ptr& impl, ServicePin pin) { if (!impl) { return nullptr; } if (!pin) { return std::shared_ptr(impl, impl.get()); } struct PinnedBox { std::shared_ptr impl; ServicePin pin; }; auto box = std::make_shared( PinnedBox{std::shared_ptr(impl, impl.get()), std::move(pin)}); return std::shared_ptr(std::move(box), impl.get()); } template static IService* extract_service(I* raw) { if (raw == nullptr) { return nullptr; } if constexpr (std::is_base_of_v) { return static_cast(raw); } else if constexpr (std::is_polymorphic_v) { return dynamic_cast(raw); } else { return nullptr; } } template static IManagedService* extract_managed(I* raw) { if (raw == nullptr) { return nullptr; } if constexpr (std::is_base_of_v) { return static_cast(raw); } else if constexpr (std::is_polymorphic_v) { return dynamic_cast(raw); } else { return nullptr; } } std::vector m_items{}; }; /// Validated, topologically ordered candidate batch returned by /// ServiceRegistry::prepare_batch(). struct PreparedPublication { ExpectedEpoch expected_epoch{}; std::shared_ptr 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()` returns an unpinned reference after unlocking and is /// kept for legacy compatibility; new code and coroutines should use /// `acquire()` and retain the returned `ServiceHandle` 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> 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 void provide(std::shared_ptr impl) { IService* svc = nullptr; if (impl) { if constexpr (std::is_base_of_v) { svc = static_cast(impl.get()); } else if constexpr (std::is_polymorphic_v) { svc = dynamic_cast(impl.get()); } } provide_erased( std::type_index{typeid(I)}, impl ? std::shared_ptr(impl, impl.get()) : std::shared_ptr{}, impl.get(), svc); } template bool remove() { return remove_erased(std::type_index{typeid(I)}); } template [[nodiscard]] std::shared_ptr get() const { auto h = acquire(); if (!h) { return nullptr; } return h->shared(); } template [[nodiscard]] I& require() const { auto p = get(); if (!p) { throw std::runtime_error( std::string{"ServiceRegistry: no service for '"} + typeid(I).name() + "'"); } return *p; } template [[nodiscard]] bool has() const { return acquire().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 [[nodiscard]] Void::Result::Result> 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(*snap, 0); } [[nodiscard]] Void::Result::Result prepare_batch(ProviderSet set, ExpectedEpoch expected = std::nullopt); [[nodiscard]] Void::Result::Result start_staged(PreparedPublication& prepared, Async::OperationOptions options = {}); [[nodiscard]] Void::Result::Result publish(PreparedPublication&& prepared); [[nodiscard]] Void::Result::Result start_and_publish(ProviderSet set, ExpectedEpoch expected = std::nullopt, Async::OperationOptions options = {}); [[nodiscard]] Void::Result::Result start(Async::OperationOptions options = {}); [[nodiscard]] Void::Result::Result 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; 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 impl, const void* object_key, IService* service); bool remove_erased(std::type_index key); std::shared_ptr acquire_snapshot() const; template [[nodiscard]] Void::Result::Result> 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(it->second.impl.get()); return ServiceHandle{raw, it->second.impl, snap.gen_token, snap.epoch}; } if (snap.parent_snap) { return acquire_from_snapshot(*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(*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 rollback_started_nodes( const std::vector& 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 m_retention_state; mutable std::mutex m_write_mu{}; mutable std::mutex m_snapshot_mu{}; std::shared_ptr m_active_snapshot{}; PublicationEpoch m_epoch{0}; bool m_stopping{false}; bool m_started{false}; mutable std::mutex m_observer_mu{}; std::vector> m_observers{}; std::size_t m_next_observer_id{1}; }; } // namespace Void::Service