#pragma once #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Service { /// C entry point a plugin exports to expose a service: /// extern "C" Void::Service::IService* void_plugin_service(void* inst); /// It returns the IService subobject of the plugin's service object /// (which must derive the host interface I, and I must derive /// IService). The host verifies the exported subobject with dynamic_cast; /// host and provider must therefore share RTTI identity for I. using service_factory_fn = IService* (*)(void* instance); inline constexpr const char* kServiceSymbol = "void_plugin_service"; /// Acquire an owning ServiceHandle 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 [[nodiscard]] Void::Result::Result> acquire_plugin_service(Plugin::PluginManager& manager, std::string_view plugin_name, PublicationEpoch epoch = 0) { static_assert(std::is_base_of_v, "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( 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(base); if (iface == nullptr) { return Void::Result::fail(make_service_error( ServiceErrorCode::invalid_argument, "ServicePlugin: incompatible service interface")); } auto owner = std::make_shared(std::move(handle)); std::shared_ptr pinned(std::move(owner), iface); return ServiceHandle{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) /// is re-resolved and re-registered, so FSMs resolving I through their /// context transparently pick up the new implementation on their next /// call. The registry entry pins the plugin instance, so in-flight /// callers never see a freed object. /// /// Requires: I derives Void::Service::IService; the plugin's service /// type derives I; the plugin exports void_plugin_service. RTTI identity /// for I must be shared by host and provider, just like PluginManager's /// host-specific instance_validator interfaces. template class PluginServiceBinding { public: static_assert(std::is_base_of_v, "plugin service interface must derive IService"); using Validator = std::function& service)>; PluginServiceBinding(Plugin::PluginManager& manager, ServiceRegistry& registry, std::string name, Validator validator = {}) : m_state(std::make_shared( manager, registry, std::move(name), std::move(validator))) { } // Lifecycle registration cannot be transferred while callbacks may // be in flight. PluginServiceBinding(const PluginServiceBinding&) = delete; PluginServiceBinding& operator=(const PluginServiceBinding&) = delete; ~PluginServiceBinding() { disable_hot_reload(); } /// Resolve the current instance's service and (re)register it. [[nodiscard]] bool bind() noexcept { return m_state->bind(); } /// Auto-rebind on hot reload (debounced file watching). The /// manager keeps old instances alive while pinned, so the swap /// is seamless. Idempotent. void enable_hot_reload() { std::lock_guard lifecycleLock{m_lifecycleMutex}; if (m_reload_id != 0) { return; } m_state->set_hot_reload_enabled(true); try { std::weak_ptr weakState{m_state}; m_reload_id = m_state->manager().on_reloaded( [weakState](std::string_view name) noexcept { if (auto state = weakState.lock()) { state->rebind(name); } }); m_state->manager().watch(m_state->name()); } catch (...) { m_state->set_hot_reload_enabled(false); if (m_reload_id != 0) { m_state->manager().remove_on_reloaded(m_reload_id); m_reload_id = 0; } throw; } } /// Stop observing reloads (the file watch itself is shared and /// stays). Idempotent; called by the destructor. void disable_hot_reload() noexcept { try { std::lock_guard lifecycleLock{m_lifecycleMutex}; m_state->set_hot_reload_enabled(false); if (m_reload_id != 0) { m_state->manager().remove_on_reloaded(m_reload_id); m_reload_id = 0; } } catch (...) { // Destruction must remain noexcept. The weak callback // cannot keep State alive after m_state is released even if // observer removal itself reports a failure. } } private: class State { public: State(Plugin::PluginManager& manager, ServiceRegistry& registry, std::string name, Validator validator) : m_manager(&manager), m_registry(®istry), m_name(std::move(name)), m_validator(std::move(validator)) { } [[nodiscard]] bool bind() noexcept { try { std::lock_guard lock{m_mutex}; return bind_locked(); } catch (...) { return false; } } void rebind(std::string_view name) noexcept { if (name != m_name) { return; } try { std::lock_guard lock{m_mutex}; if (m_hotReloadEnabled) { (void)bind_locked(); } } catch (...) { } } void set_hot_reload_enabled(bool enabled) { std::lock_guard lock{m_mutex}; m_hotReloadEnabled = enabled; } [[nodiscard]] Plugin::PluginManager& manager() const noexcept { return *m_manager; } [[nodiscard]] const std::string& name() const noexcept { return m_name; } private: [[nodiscard]] bool bind_locked() noexcept { try { auto svc_handle = acquire_plugin_service( *m_manager, m_name); if (!svc_handle) { Void::Log::warn("Service.Plugin", "{}", svc_handle.error().message()); return false; } auto pinned = svc_handle->shared(); if (m_validator && !m_validator(pinned)) { Void::Log::warn( "Service.Plugin", "plugin '{}' service validation failed", m_name); return false; } m_registry->provide(std::move(pinned)); Void::Log::debug("Service.Plugin", "bound service from plugin '{}'", m_name); return true; } catch (const std::exception& error) { Void::Log::warn( "Service.Plugin", "binding service from plugin '{}' threw: {}", m_name, error.what()); } catch (...) { Void::Log::warn( "Service.Plugin", "binding service from plugin '{}' threw", m_name); } return false; } Plugin::PluginManager* m_manager; ServiceRegistry* m_registry; std::string m_name; Validator m_validator; std::mutex m_mutex; bool m_hotReloadEnabled{false}; }; std::shared_ptr m_state; std::mutex m_lifecycleMutex; Plugin::ReloadCallbackId m_reload_id{0}; }; } // namespace Void::Service