Files
Library/include/Void/Service/Registry.hpp
T
faumarayandClaude Fable 5 ee4486e1d2 Plugin: discovery, unload, config entry, multi-observer reloads, state API
Host-side additions for applications embedding a plugin system:

- PluginManager::load_directory(dir) loads every shared-library file in
  a directory (filename order) with per-file expected results.
- PluginManager::unload(name) drops the registry entry; the instance
  dies with its last pinned handle (RCU semantics, as on reload).
- Optional C entry void_plugin_configure(inst, config): fed from
  PluginManagerOptions::config_provider after create and after each
  reload swap, before on_load().
- on_reloaded() is now multi-observer: returns a ReloadCallbackId,
  remove_on_reloaded() unregisters. Manual reload() now notifies
  observers too (previously only watched reloads did, contradicting
  the documented contract). PluginServiceBinding deregisters its
  callback on destruction (was a dangling-callback hazard).
- PluginManager::serialize_state/deserialize_state expose the plugin's
  v2 state exports so an embedder can carry plugin state through its
  own hot reload.
- ServiceRegistry::remove<I>() withdraws a provided service (child
  removal re-exposes a parent's entry).
- EventBus::subscribe_scoped<E>() returns a move-only RAII
  Subscription that unsubscribes on destruction.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv
2026-07-11 23:39:10 +03:00

179 lines
5.3 KiB
C++

#pragma once
#include <Void/Core/Meta.hpp>
#include <Void/Service/Service.hpp>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#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
/// 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.
///
/// 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.
class ServiceRegistry
{
public:
ServiceRegistry() = default;
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}
{
}
/// 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);
}
}
return m_parent ? m_parent->get<I>() : nullptr;
}
/// Resolve I; throws std::runtime_error if not provided.
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
{
{
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;
}
/// Call on_start() on every lifecycle service, registration
/// order.
void start_all()
{
std::shared_lock lock{m_mutex};
for (const auto& key : m_order) {
if (auto* s = m_services.at(key).service) {
s->on_start();
}
}
}
/// 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]] std::size_t size() const
{
std::shared_lock lock{m_mutex};
return m_services.size();
}
private:
struct Entry {
std::shared_ptr<void> impl;
IService* service = nullptr; // non-null iff I : IService
};
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;
};
} // namespace Void::Service