#include "echoion/core/PluginHost.hpp" #include "echoion/core/CommandManager.hpp" #include "echoion/core/MusicManager.hpp" #include "echoion/core/sources/TrackSource.hpp" #include #include #include #include #include #include #include #include #include #include namespace Echoion::Core { namespace { class ExtensionCommandAdapter final : public Command { public: ExtensionCommandAdapter(Void::Plugin::PluginManager& plugins, std::string plugin, Api::ExtensionCommand command) : plugins_(plugins), plugin_(std::move(plugin)), command_(std::move(command)) { } void execute(const CommandContext& context) override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast( pin.get()) : nullptr; if (!extension) { context.reply("Plugin is temporarily unavailable."); return; } auto result = extension->executeCommand( {.command = command_.name, .arguments = context.args, .clientId = context.clientId, .invokerName = std::string(context.invokerName)}); context.reply(result ? *result : result.error().message); } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw: {}", plugin_, command_.name, error.what()); context.reply("Plugin command failed."); } catch (...) { Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw", plugin_, command_.name); context.reply("Plugin command failed."); } } std::string_view getDescription() const override { return command_.description; } std::string_view getUsage() const override { return command_.usage; } CommandCategory getCategory() const override { return static_cast(std::min( command_.category, static_cast(CommandCategory::Admin))); } std::vector getAliases() const override { std::vector aliases; aliases.reserve(command_.aliases.size()); for (const auto& alias : command_.aliases) { aliases.push_back(alias); } return aliases; } bool requiresAdmin() const override { return command_.adminOnly; } private: Void::Plugin::PluginManager& plugins_; std::string plugin_; Api::ExtensionCommand command_; }; } // namespace class PluginTrackSource final : public ITrackSource { public: PluginTrackSource(std::weak_ptr host, Void::Plugin::PluginManager& plugins, std::string plugin, Api::ExtensionMediaSource source) : host_(std::move(host)), plugins_(plugins), plugin_(std::move(plugin)), source_(std::move(source)) { } std::string_view name() const override { return source_.name; } bool canHandle(const std::string& query) const override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; return extension && declaredBy(*extension) && extension->canHandleMedia(source_.name, query); } catch (...) { return false; } } bool isAvailable() const override { try { if (host_.expired()) { return false; } auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; return extension && declaredBy(*extension); } catch (...) { return false; } } bool supportsSearch() const override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return false; } auto descriptors = extension->mediaSources(); auto descriptor = std::ranges::find(descriptors, source_.name, &Api::ExtensionMediaSource::name); return descriptor != descriptors.end() && descriptor->supportsSearch; } catch (...) { return false; } } [[nodiscard]] bool represents(std::string_view plugin, std::string_view source) const { return plugin_ == plugin && source_.name == source; } Api::Result search(std::string_view query) override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "plugin media source unavailable"); } auto result = extension->searchMedia(source_.name, query); if (result) { for (auto& track : result->tracks) { track.source = Api::TrackSource::Plugin; } } return result; } catch (const std::exception& error) { return Api::fail(Api::ErrorCode::UnknownError, error.what()); } catch (...) { return Api::fail(Api::ErrorCode::UnknownError, "plugin media search threw an exception"); } } Api::Result resolve(const std::string& query) override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "plugin media source unavailable"); } auto result = extension->resolveMedia(source_.name, query); if (result) { result->source = Api::TrackSource::Plugin; } return result; } catch (const std::exception& error) { return Api::fail(Api::ErrorCode::UnknownError, error.what()); } catch (...) { return Api::fail(Api::ErrorCode::UnknownError, "plugin media resolve threw an exception"); } } Api::Result getStream(const Api::TrackInfo& track) override { try { auto pin = plugins_.acquire(plugin_); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "plugin media source unavailable"); } auto result = extension->streamMedia(source_.name, track); if (!result) { return std::unexpected(result.error()); } return StreamHandle{.url = std::move(result->url), .isLocalFile = result->localFile, .sourceName = source_.name}; } catch (const std::exception& error) { return Api::fail(Api::ErrorCode::UnknownError, error.what()); } catch (...) { return Api::fail(Api::ErrorCode::UnknownError, "plugin media stream threw an exception"); } } private: [[nodiscard]] bool declaredBy(Api::IExtensionPlugin& extension) const { auto descriptors = extension.mediaSources(); return std::ranges::find(descriptors, source_.name, &Api::ExtensionMediaSource::name) != descriptors.end(); } std::weak_ptr host_; Void::Plugin::PluginManager& plugins_; std::string plugin_; Api::ExtensionMediaSource source_; }; PluginHost::PluginHost( CommandManager& commands, std::shared_ptr music, std::function isAdmin, std::function)> mediaSink, Configuration configuration) : commands_(commands), music_(std::move(music)), isAdmin_(std::move(isAdmin)), mediaSink_(std::move(mediaSink)), plugins_(Void::Plugin::PluginManager::Options{ .dlclose_on_swap = false, .copy_on_load = true, .config_provider = [this](std::string_view name) { return pluginConfiguration(name); }, .instance_validator = [](Void::Plugin::IPlugin& plugin, const Void::Plugin::PluginInfo&) { return dynamic_cast(&plugin) != nullptr; }}), configuration_(std::move(configuration)) { reloadCallback_ = plugins_.on_reloaded( [this](std::string_view name) { publish(name); }); } PluginHost::~PluginHost() { plugins_.remove_on_reloaded(reloadCallback_); for (const auto& name : plugins_.names()) { unpublish(name); } } void PluginHost::loadDirectory(const std::filesystem::path& directory) { std::scoped_lock operationLock{reconfigureMutex_}; for (auto& [path, result] : plugins_.load_directory(directory)) { if (!result) { Void::Log::warn("PluginHost", "Failed to load '{}': {}", path.string(), Void::Plugin::to_string(result.error())); continue; } { std::error_code error; auto loadedPath = std::filesystem::weakly_canonical(path, error); std::lock_guard lock(mutex_); loadedPaths_[*result] = error ? path : std::move(loadedPath); } publish(*result); plugins_.watch(*result); } } void PluginHost::loadManagedDirectory(const std::filesystem::path& directory) { std::scoped_lock operationLock{reconfigureMutex_}; std::error_code error; std::filesystem::create_directories(directory, error); managedDirectory_ = std::filesystem::weakly_canonical(directory, error); if (error) { Void::Log::warn("PluginHost", "Cannot prepare managed plugin root '{}': {}", directory.string(), error.message()); return; } for (const auto& entry : std::filesystem::directory_iterator(managedDirectory_, error)) { if (error || !entry.is_directory()) { continue; } const auto id = entry.path().filename().string(); if (id.empty() || id == "." || id == ".." || !std::ranges::all_of(id, [](unsigned char character) { return std::isalnum(character) || character == '.' || character == '_' || character == '-'; })) { continue; } const auto current = std::filesystem::canonical(entry.path() / "current", error); const auto library = current / (id + ".so"); if (error || !std::filesystem::is_regular_file(library)) { continue; } auto loaded = plugins_.load(library); if (!loaded || *loaded != id) { Void::Log::warn( "PluginHost", "Managed plugin '{}' failed to load: {}", id, loaded ? "reported a different name" : std::string(Void::Plugin::to_string(loaded.error()))); continue; } auto handle = plugins_.acquire(id); const auto info = handle ? handle.info() : Void::Plugin::PluginInfo{}; { std::lock_guard lock(mutex_); managed_[id] = { .version = info.plugin_version ? info.plugin_version : "", .path = library}; loadedPaths_[id] = library; } publish(id); plugins_.watch(id); } } bool PluginHost::finalizeLoading() { std::scoped_lock operationLock{reconfigureMutex_}; if (bindShortenerServices()) { return true; } Void::Log::warn("PluginHost", "Loaded plugins do not provide the configured short " "URL service"); return false; } std::string PluginHost::pluginConfiguration(std::string_view name) const { Configuration configuration; { std::lock_guard lock(mutex_); configuration = configuration_; } using Void::Json::Value; Value settings = Void::Json::object(); const auto configPath = configuration.configDirectory / (std::string(name) + ".json"); std::error_code error; if (std::filesystem::is_regular_file(configPath, error)) { std::ifstream file(configPath, std::ios::binary); std::ostringstream content; content << file.rdbuf(); if (content.tellp() <= std::streampos{1024 * 1024}) { if (auto parsed = Void::Json::parse(content.str()); parsed && parsed->is_object()) { settings = std::move(*parsed); } else { Void::Log::warn("PluginHost", "Ignoring invalid plugin config '{}'", configPath.string()); } } else { Void::Log::warn("PluginHost", "Ignoring plugin config larger than 1 MiB '{}'", configPath.string()); } } Value envelope = Void::Json::object(); auto& object = envelope.as_object(); object.emplace_back("schemaVersion", Value{1}); object.emplace_back("pluginId", Value{std::string(name)}); Value host = Void::Json::object(); auto& hostFields = host.as_object(); hostFields.emplace_back("stateDirectory", Value{configuration.stateDirectory.string()}); hostFields.emplace_back("publicUrl", Value{configuration.publicUrl}); std::string publicBaseUrl = configuration.publicUrl; while (publicBaseUrl.ends_with('/')) { publicBaseUrl.pop_back(); } if (!publicBaseUrl.empty()) { publicBaseUrl += "/s"; } hostFields.emplace_back("publicBaseUrl", Value{publicBaseUrl}); object.emplace_back("stateDirectory", Value{configuration.stateDirectory.string()}); object.emplace_back("configPath", Value{configPath.string()}); object.emplace_back("publicUrl", Value{configuration.publicUrl}); object.emplace_back("settings", std::move(settings)); if (configuration.proxy) { Value proxy = Void::Json::object(); auto& fields = proxy.as_object(); std::string kind = "none"; if (configuration.proxy->kind == Void::Net::ProxyConfig::Kind::Http) { kind = "http"; } else if (configuration.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) { kind = "socks5"; } fields.emplace_back("kind", Value{kind}); fields.emplace_back("host", Value{configuration.proxy->host}); fields.emplace_back("port", Value{static_cast( configuration.proxy->port)}); fields.emplace_back("username", configuration.proxy->username ? Value{*configuration.proxy->username} : Value{nullptr}); fields.emplace_back("password", configuration.proxy->password ? Value{*configuration.proxy->password} : Value{nullptr}); hostFields.emplace_back("proxy", proxy); object.emplace_back("proxy", std::move(proxy)); } else { hostFields.emplace_back("proxy", Value{nullptr}); object.emplace_back("proxy", Value{nullptr}); } object.emplace_back("_host", std::move(host)); return Void::Json::serialize(envelope); } bool PluginHost::bindShortenerServices() { using Binding = Void::Service::PluginServiceBinding; constexpr std::string_view kInternal = "url-shortener-internal"; std::string selected; { std::lock_guard lock(mutex_); selected = configuration_.shortenerProvider; } const auto loaded = plugins_.names(); const auto isLoaded = [&loaded](std::string_view name) { return std::ranges::find(loaded, name) != loaded.end(); }; const auto validator = [](std::string expectedProvider, bool requireResolver) -> Binding::Validator { return [expectedProvider = std::move(expectedProvider), requireResolver]( const std::shared_ptr& service) { if (!service || service->service_version() != Void::ShortUrl::kServiceVersion || service->provider_id() != expectedProvider || (requireResolver && !service->supports_resolve())) { return false; } const auto status = service->health().status; return status == Void::ShortUrl::HealthStatus::healthy || status == Void::ShortUrl::HealthStatus::degraded; }; }; auto previousSelected = shortenerRegistry_.get(); auto previousInternal = internalShortenerRegistry_.get(); auto previousSelectedBinding = std::move(shortenerBinding_); auto previousInternalBinding = std::move(internalShortenerBinding_); const auto restorePrevious = [&]() noexcept { // A later binding step may have published and enabled one // replacement before another step failed. Quiesce those callbacks // before restoring the prior registry values, otherwise a delayed // replacement callback could overwrite the rollback. if (shortenerBinding_) { shortenerBinding_->disable_hot_reload(); shortenerBinding_.reset(); } if (internalShortenerBinding_) { internalShortenerBinding_->disable_hot_reload(); internalShortenerBinding_.reset(); } try { if (previousSelected) { shortenerRegistry_.provide( previousSelected); } else { (void) shortenerRegistry_.remove(); } if (previousInternal) { internalShortenerRegistry_ .provide(previousInternal); } else { (void)internalShortenerRegistry_ .remove(); } } catch (const std::exception& error) { Void::Log::error( "PluginHost", "Restoring previous short URL services threw: {}", error.what()); } catch (...) { Void::Log::error("PluginHost", "Restoring previous short URL services threw"); } if (previousSelectedBinding) { try { previousSelectedBinding->enable_hot_reload(); } catch (...) { Void::Log::error("PluginHost", "Failed to re-enable the previous short " "URL provider binding"); } shortenerBinding_ = std::move(previousSelectedBinding); } if (previousInternalBinding) { try { previousInternalBinding->enable_hot_reload(); } catch (...) { Void::Log::error("PluginHost", "Failed to re-enable the previous " "internal resolver binding"); } internalShortenerBinding_ = std::move(previousInternalBinding); } }; try { // Removing an observer is not enough after PluginManager has copied // its callback list. disable_hot_reload() also waits for any // callback already using the binding state, so no old provider can // overwrite a newly-published service after this point. if (previousSelectedBinding) { previousSelectedBinding->disable_hot_reload(); } if (previousInternalBinding) { previousInternalBinding->disable_hot_reload(); } std::unique_ptr selectedBinding; if (!selected.empty()) { selectedBinding = std::make_unique( plugins_, shortenerRegistry_, selected, validator(selected, false)); if (!selectedBinding->bind()) { Void::Log::warn( "PluginHost", "Short URL provider '{}' failed service validation", selected); restorePrevious(); return false; } } std::unique_ptr internalBinding; const bool hasInternal = isLoaded(kInternal); if (hasInternal) { internalBinding = std::make_unique( plugins_, internalShortenerRegistry_, std::string{kInternal}, validator(std::string{kInternal}, true)); if (!internalBinding->bind()) { Void::Log::warn("PluginHost", "Internal short URL resolver failed " "service validation"); restorePrevious(); return false; } } if (selectedBinding) { selectedBinding->enable_hot_reload(); shortenerBinding_ = std::move(selectedBinding); } else { shortenerBinding_.reset(); (void)shortenerRegistry_.remove(); } if (internalBinding) { internalBinding->enable_hot_reload(); internalShortenerBinding_ = std::move(internalBinding); } else { internalShortenerBinding_.reset(); (void)internalShortenerRegistry_ .remove(); } return true; } catch (const std::exception& error) { Void::Log::warn("PluginHost", "Binding short URL services threw: {}", error.what()); } catch (...) { Void::Log::warn("PluginHost", "Binding short URL services threw"); } restorePrevious(); return false; } bool PluginHost::reconfigure(Configuration configuration) { std::scoped_lock operationLock{reconfigureMutex_}; // Keep the previously validated service instances published while // plugins are reconfigured. Reload callbacks must not expose a // partially-applied provider before every plugin accepts the new // configuration. if (shortenerBinding_) { shortenerBinding_->disable_hot_reload(); } if (internalShortenerBinding_) { internalShortenerBinding_->disable_hot_reload(); } Configuration previous; { std::lock_guard lock(mutex_); previous = configuration_; configuration_ = std::move(configuration); } const auto names = plugins_.names(); std::vector reloaded; reloaded.reserve(names.size()); const auto rollback = [&] { { std::lock_guard lock(mutex_); configuration_ = previous; } bool restored = true; for (auto it = reloaded.rbegin(); it != reloaded.rend(); ++it) { if (auto result = plugins_.reload(*it); !result) { restored = false; Void::Log::error( "PluginHost", "Plugin '{}' failed configuration rollback: {}", *it, Void::Plugin::to_string(result.error())); } } if (!bindShortenerServices()) { restored = false; Void::Log::error("PluginHost", "Failed to restore short URL services after " "configuration rollback"); } return restored; }; for (const auto& name : names) { if (auto result = plugins_.reload(name); !result) { Void::Log::warn( "PluginHost", "Plugin '{}' rejected updated configuration: {}", name, Void::Plugin::to_string(result.error())); (void)rollback(); return false; } reloaded.push_back(name); } if (!bindShortenerServices()) { Void::Log::warn( "PluginHost", "Updated configuration failed short URL service validation"); (void)rollback(); return false; } return true; } std::shared_ptr PluginHost::shortener() const { return shortenerRegistry_.get(); } Void::ShortUrl::ResolveResult PluginHost::resolveShortLink(std::string_view key) const { const auto unavailable = [] { return Void::ShortUrl::ResolveResult{ .target_url = {}, .expires_at_unix_seconds = 0, .error = {.code = Void::ShortUrl::ErrorCode::unavailable, .message = "internal short URL resolver is unavailable"}}; }; auto service = internalShortenerRegistry_.get(); if (!service) { return unavailable(); } try { if (service->service_version() != Void::ShortUrl::kServiceVersion || service->provider_id() != "url-shortener-internal" || !service->supports_resolve()) { return unavailable(); } const auto status = service->health().status; if (status != Void::ShortUrl::HealthStatus::healthy && status != Void::ShortUrl::HealthStatus::degraded) { return unavailable(); } return service->resolve({.key = std::string(key)}); } catch (const std::exception& error) { Void::Log::warn("PluginHost", "Internal short URL resolver threw: {}", error.what()); } catch (...) { Void::Log::warn("PluginHost", "Internal short URL resolver threw"); } return unavailable(); } Api::Result PluginHost::manage(const std::string& requestJson) { auto parsed = Void::Json::parse(requestJson); if (!parsed || !parsed->is_object()) { return Api::fail(Api::ErrorCode::ParseError, "managed plugin request must be a JSON object"); } auto field = [&](std::string_view name) { const auto* value = parsed->find(name); return value && value->is_string() ? value->as_string() : std::string{}; }; const auto action = field("action"); if (action == "status") { Void::Json::Value response = Void::Json::object(); Void::Json::Value entries = Void::Json::array(); for (const auto& name : plugins_.names()) { auto handle = plugins_.acquire(name); const auto info = handle ? handle.info() : Void::Plugin::PluginInfo{}; Void::Json::Value entry = Void::Json::object(); auto& object = entry.as_object(); object.emplace_back("id", Void::Json::Value{name}); object.emplace_back( "name", Void::Json::Value{ info.name && *info.name ? info.name : name}); object.emplace_back("version", Void::Json::Value{info.plugin_version ? info.plugin_version : ""}); { std::lock_guard lock(mutex_); object.emplace_back( "managed", Void::Json::Value{managed_.contains(name)}); if (const auto path = loadedPaths_.find(name); path != loadedPaths_.end()) { object.emplace_back( "path", Void::Json::Value{path->second.string()}); } } entries.as_array().push_back(std::move(entry)); } response.as_object().emplace_back("schemaVersion", Void::Json::Value{1LL}); response.as_object().emplace_back("plugins", std::move(entries)); return Void::Json::serialize(response); } if (action != "replace") { return Api::fail(Api::ErrorCode::InvalidArgument, "managed plugin action must be status or replace"); } std::scoped_lock operationLock{reconfigureMutex_}; const auto pluginId = field("pluginId"); const auto version = field("version"); const std::filesystem::path requestedPath{field("path")}; if (pluginId.empty() || version.empty() || requestedPath.empty() || managedDirectory_.empty()) { return Api::fail( Api::ErrorCode::InvalidArgument, "replace requires pluginId, version, path, and a managed root"); } std::error_code error; const auto path = std::filesystem::canonical(requestedPath, error); if (error) { return Api::fail(Api::ErrorCode::PermissionDenied, "managed plugin path must be a regular file below " "the managed root"); } const auto root = std::filesystem::canonical(managedDirectory_, error); const auto rootEnd = std::mismatch(root.begin(), root.end(), path.begin(), path.end()) .first; if (error || rootEnd != root.end() || !std::filesystem::is_regular_file(path)) { return Api::fail(Api::ErrorCode::PermissionDenied, "managed plugin path must be a regular file below " "the managed root"); } const auto loadedNames = plugins_.names(); const bool exists = std::ranges::find(loadedNames, pluginId) != loadedNames.end(); std::optional previousPath; if (exists) { std::lock_guard lock(mutex_); if (const auto current = loadedPaths_.find(pluginId); current != loadedPaths_.end()) { previousPath = current->second; } } if (exists && !previousPath) { return Api::fail(Api::ErrorCode::PluginError, "current plugin path is unavailable; refusing a " "non-rollbackable replacement"); } // Do not let a reload callback publish a service from the candidate // until its complete service contract has been validated below. if (shortenerBinding_) { shortenerBinding_->disable_hot_reload(); } if (internalShortenerBinding_) { internalShortenerBinding_->disable_hot_reload(); } const auto resumeCurrentServices = [&] { if (!bindShortenerServices()) { Void::Log::error( "PluginHost", "Failed to resume short URL services after a rejected " "plugin replacement"); } }; if (exists) { if (auto replaced = plugins_.replace(pluginId, path); !replaced) { resumeCurrentServices(); return Api::fail( Api::ErrorCode::PluginError, std::format("plugin replacement rejected: {}", Void::Plugin::to_string(replaced.error()))); } } else { auto loaded = plugins_.load(path); if (!loaded || *loaded != pluginId) { if (loaded) { std::ignore = plugins_.unload(*loaded); } resumeCurrentServices(); return Api::fail( Api::ErrorCode::PluginError, loaded ? "plugin reported a different name" : std::format("plugin load rejected: {}", Void::Plugin::to_string(loaded.error()))); } } if (!bindShortenerServices()) { std::string rollbackError; if (exists) { if (auto restored = plugins_.replace(pluginId, *previousPath); !restored) { rollbackError = std::format( "; restoring the previous plugin failed: {}", Void::Plugin::to_string(restored.error())); } } else { unpublish(pluginId); if (auto unloaded = plugins_.unload(pluginId); !unloaded) { rollbackError = std::format( "; unloading the rejected plugin failed: {}", Void::Plugin::to_string(unloaded.error())); } } resumeCurrentServices(); return Api::fail( Api::ErrorCode::PluginError, "plugin replacement failed short URL service validation" + rollbackError); } if (!exists) { plugins_.watch(pluginId); } { std::lock_guard lock(mutex_); managed_[pluginId] = {.version = version, .path = path}; loadedPaths_[pluginId] = path; } publish(pluginId); notifyChanged(); Void::Json::Value response = Void::Json::object(); response.as_object().emplace_back("pluginId", Void::Json::Value{pluginId}); response.as_object().emplace_back("version", Void::Json::Value{version}); response.as_object().emplace_back("state", Void::Json::Value{"healthy"}); return Void::Json::serialize(response); } void PluginHost::setChangeCallback(std::function callback) { std::lock_guard lock(mutex_); changeCallback_ = std::move(callback); } void PluginHost::notifyChanged() const { std::function callback; { std::lock_guard lock(mutex_); callback = changeCallback_; } if (callback) { callback(); } } void PluginHost::publish(std::string_view name) { unpublish(name); auto pin = plugins_.acquire(name); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return; } std::vector commands; std::vector mediaSources; try { commands = extension->commands(); mediaSources = extension->mediaSources(); } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' descriptors threw: {}", name, error.what()); return; } catch (...) { Void::Log::error("PluginHost", "Plugin '{}' descriptors threw", name); return; } for (const auto& descriptor : commands) { auto command = std::make_shared( plugins_, std::string(name), descriptor); if (!commands_.registerExternalCommand( std::string(name), descriptor.name, std::move(command))) { Void::Log::warn("PluginHost", "Command '{}' from '{}' conflicts", descriptor.name, name); } } for (auto source : mediaSources) { { std::lock_guard lock(mutex_); if (std::ranges::any_of(sources_, [&](const auto& existing) { return existing->represents(name, source.name); })) { continue; } } auto proxy = std::make_shared( weak_from_this(), plugins_, std::string(name), std::move(source)); music_->addTrackSource(proxy); if (mediaSink_) { mediaSink_(proxy); } std::lock_guard lock(mutex_); sources_.push_back(std::move(proxy)); } Void::Log::info("PluginHost", "Published Echoion plugin '{}'", name); notifyChanged(); } void PluginHost::unpublish(std::string_view name) { commands_.unregisterExternalCommands(name); } void PluginHost::dispatch(const Api::PluginEvent& event) const { for (const auto& name : plugins_.names()) { try { auto pin = plugins_.acquire(name); if (auto* extension = pin ? dynamic_cast(pin.get()) : nullptr) { extension->onEvent(event); } } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' event handler threw: {}", name, error.what()); } catch (...) { Void::Log::error("PluginHost", "Plugin '{}' event handler threw", name); } } } Api::Result PluginHost::call(std::string_view plugin, std::string_view method, std::string params, uint64_t clientId) const { try { auto pin = plugins_.acquire(plugin); auto* extension = pin ? dynamic_cast(pin.get()) : nullptr; if (!extension) { return Api::fail(Api::ErrorCode::NotFound, "plugin not found"); } auto rpc = extension->rpcMethods(); auto descriptor = std::ranges::find(rpc, method, &Api::ExtensionRpc::name); if (descriptor == rpc.end()) { return Api::fail(Api::ErrorCode::NotFound, "plugin RPC method not found"); } if (descriptor->adminOnly && (!isAdmin_ || !isAdmin_(clientId))) { return Api::fail(Api::ErrorCode::PermissionDenied, "admin privileges required"); } return extension->callRpc({.method = std::string(method), .params = std::move(params), .clientId = clientId}); } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw: {}", plugin, method, error.what()); return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); } catch (...) { Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw", plugin, method); return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); } } std::vector PluginHost::webAssets() const { std::vector assets; for (const auto& name : plugins_.names()) { try { auto pin = plugins_.acquire(name); if (auto* extension = pin ? dynamic_cast(pin.get()) : nullptr) { auto current = extension->webAssets(); assets.insert(assets.end(), std::make_move_iterator(current.begin()), std::make_move_iterator(current.end())); } } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' web assets threw: {}", name, error.what()); } catch (...) { Void::Log::error("PluginHost", "Plugin '{}' web assets threw", name); } } return assets; } std::vector PluginHost::names() const { return plugins_.names(); } std::vector PluginHost::snapshotStates() const { std::vector states; for (const auto& name : plugins_.names()) { if (auto state = plugins_.serialize_state(name)) { states.push_back({.name = name, .json = std::move(state->json), .version = state->version}); } } return states; } void PluginHost::restoreStates(const std::vector& states) { for (const auto& state : states) { if (!plugins_.deserialize_state(state.name, state.json, state.version)) { Void::Log::warn("PluginHost", "Plugin '{}' rejected restored state", state.name); } } } } // namespace Echoion::Core