fix(plugins): add metrics on callbacks and improve plugin method calling (#4304)
* refactor: implement OnSchedulerCallback method in wasmSchedulerCallback Added the OnSchedulerCallback method to the wasmSchedulerCallback struct, enabling it to handle scheduler callback events. This method constructs a SchedulerCallbackRequest and invokes the corresponding plugin method, facilitating better integration with the scheduling system. The changes improve the plugin's ability to respond to scheduled events, enhancing overall functionality. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): update executeCallback method to use callMethod Modified the executeCallback method to accept an additional parameter, methodName, which specifies the callback method to be executed. This change ensures that the correct method is called for each WebSocket event, improving the accuracy of callback execution for plugins. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): capture OnInit metrics Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): improve logging for metrics in callMethod Updated the logging statement in the callMethod function to include the elapsed time as a separate key in the log output. This change enhances the clarity of the logged metrics, making it easier to analyze the performance of plugin requests and troubleshoot any issues that may arise. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): enhance logging for schedule callback execution Signed-off-by: Deluan <deluan@navidrome.org> * refactor(server): streamline scrobbler stopping logic Refactored the logic for stopping scrobbler instances when they are removed. The new implementation introduces a `stoppableScrobbler` interface to simplify the type assertion process, allowing for a more concise and readable code structure. This change ensures that any scrobbler implementing the `Stop` method is properly stopped before removal, improving the overall reliability of the plugin management system. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): improve plugin lifecycle management and error handling Enhanced the plugin lifecycle management by implementing error handling in the OnInit method. The changes include the addition of specific error conditions that can be returned during plugin initialization, allowing for better management of plugin states. Additionally, the unregisterPlugin method was updated to ensure proper cleanup of plugins that fail to initialize, improving overall stability and reliability of the plugin system. Signed-off-by: Deluan <deluan@navidrome.org> * refactor(plugins): remove unused LoadAllPlugins and related methods Eliminated the LoadAllPlugins, LoadAllMediaAgents, and LoadAllScrobblers methods from the manager implementation as they were not utilized in the codebase. This cleanup reduces complexity and improves maintainability by removing redundant code, allowing for a more streamlined plugin management process. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): update logging configuration for plugins Configured logging for multiple plugins to remove timestamps and source file/line information, while adding specific prefixes for better identification. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): clear initialization state when unregistering a plugin Added functionality to clear the initialization state of a plugin in the lifecycle manager when it is unregistered. This change ensures that the lifecycle state is accurately maintained, preventing potential issues with plugins that may be re-registered after being unregistered. The new method `clearInitialized` was implemented to handle this state management. Signed-off-by: Deluan <deluan@navidrome.org> * test: add unit tests for convertError function, rename to checkErr Added comprehensive unit tests for the convertError function to ensure correct behavior across various scenarios, including handling nil responses, typed nils, and responses implementing errorResponse. These tests validate that the function returns the expected results without panicking and correctly wraps original errors when necessary. Signed-off-by: Deluan <deluan@navidrome.org> * fix(plugins): update plugin base implementation and method calls Refactored the plugin base implementation by renaming `wasmBasePlugin` to `baseCapability` across multiple files. Updated method calls in the `wasmMediaAgent`, `wasmSchedulerCallback`, and `wasmScrobblerPlugin` to align with the new base structure. These changes improve code clarity and maintainability by standardizing the plugin architecture, ensuring consistent usage of the base capabilities across different plugin types. Signed-off-by: Deluan <deluan@navidrome.org> * fix(discord): handle failed connections and improve heartbeat checks Added a new method to clean up failed connections, which cancels the heartbeat schedule, closes the WebSocket connection, and removes cache entries. Enhanced the heartbeat check to log failures and trigger the cleanup process on the first failure. These changes ensure better management of user connections and improve the overall reliability of the RPC system. Signed-off-by: Deluan <deluan@navidrome.org> --------- Signed-off-by: Deluan <deluan@navidrome.org>
This commit is contained in:
+37
-62
@@ -10,10 +10,10 @@ package plugins
|
||||
//go:generate protoc --go-plugin_out=. --go-plugin_opt=paths=source_relative host/subsonicapi/subsonicapi.proto
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -53,8 +53,6 @@ var pluginCreators = map[string]pluginConstructor{
|
||||
type WasmPlugin interface {
|
||||
// PluginID returns the unique identifier of the plugin (folder name)
|
||||
PluginID() string
|
||||
// Instantiate creates a new instance of the plugin and returns it along with a cleanup function
|
||||
Instantiate(ctx context.Context) (any, func(), error)
|
||||
}
|
||||
|
||||
type plugin struct {
|
||||
@@ -91,11 +89,8 @@ type Manager interface {
|
||||
EnsureCompiled(name string) error
|
||||
PluginNames(serviceName string) []string
|
||||
LoadPlugin(name string, capability string) WasmPlugin
|
||||
LoadAllPlugins(capability string) []WasmPlugin
|
||||
LoadMediaAgent(name string) (agents.Interface, bool)
|
||||
LoadAllMediaAgents() []agents.Interface
|
||||
LoadScrobbler(name string) (scrobbler.Scrobbler, bool)
|
||||
LoadAllScrobblers() []scrobbler.Scrobbler
|
||||
ScanPlugins()
|
||||
}
|
||||
|
||||
@@ -126,7 +121,7 @@ func GetManager(ds model.DataStore, metrics metrics.Metrics) Manager {
|
||||
func createManager(ds model.DataStore, metrics metrics.Metrics) *managerImpl {
|
||||
m := &managerImpl{
|
||||
plugins: make(map[string]*plugin),
|
||||
lifecycle: newPluginLifecycleManager(),
|
||||
lifecycle: newPluginLifecycleManager(metrics),
|
||||
ds: ds,
|
||||
metrics: metrics,
|
||||
}
|
||||
@@ -170,16 +165,8 @@ func (m *managerImpl) registerPlugin(pluginID, pluginDir, wasmPath string, manif
|
||||
compilationReady: make(chan struct{}),
|
||||
}
|
||||
|
||||
// Start pre-compilation of WASM module in background
|
||||
go func() {
|
||||
precompilePlugin(p)
|
||||
// Check if this plugin implements InitService and hasn't been initialized yet
|
||||
m.initializePluginIfNeeded(p)
|
||||
}()
|
||||
|
||||
// Register the plugin
|
||||
// Register the plugin first
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.plugins[pluginID] = p
|
||||
|
||||
// Register one plugin adapter for each capability
|
||||
@@ -200,6 +187,14 @@ func (m *managerImpl) registerPlugin(pluginID, pluginDir, wasmPath string, manif
|
||||
}
|
||||
m.adapters[pluginID+"_"+capabilityStr] = adapter
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Start pre-compilation of WASM module in background AFTER registration
|
||||
go func() {
|
||||
precompilePlugin(p)
|
||||
// Check if this plugin implements InitService and hasn't been initialized yet
|
||||
m.initializePluginIfNeeded(p)
|
||||
}()
|
||||
|
||||
log.Info("Discovered plugin", "folder", pluginID, "name", manifest.Name, "capabilities", manifest.Capabilities, "wasm", wasmPath, "dev_mode", isSymlink)
|
||||
return m.plugins[pluginID]
|
||||
@@ -213,15 +208,36 @@ func (m *managerImpl) initializePluginIfNeeded(plugin *plugin) {
|
||||
}
|
||||
|
||||
// Check if the plugin implements LifecycleManagement
|
||||
for _, capability := range plugin.Manifest.Capabilities {
|
||||
if capability == CapabilityLifecycleManagement {
|
||||
m.lifecycle.callOnInit(plugin)
|
||||
m.lifecycle.markInitialized(plugin)
|
||||
break
|
||||
if slices.Contains(plugin.Manifest.Capabilities, CapabilityLifecycleManagement) {
|
||||
if err := m.lifecycle.callOnInit(plugin); err != nil {
|
||||
m.unregisterPlugin(plugin.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unregisterPlugin removes a plugin from the manager
|
||||
func (m *managerImpl) unregisterPlugin(pluginID string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
plugin, ok := m.plugins[pluginID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Clear initialization state from lifecycle manager
|
||||
m.lifecycle.clearInitialized(plugin)
|
||||
|
||||
// Unregister plugin adapters
|
||||
for _, capability := range plugin.Manifest.Capabilities {
|
||||
delete(m.adapters, pluginID+"_"+string(capability))
|
||||
}
|
||||
|
||||
// Unregister plugin
|
||||
delete(m.plugins, pluginID)
|
||||
log.Info("Unregistered plugin", "plugin", pluginID)
|
||||
}
|
||||
|
||||
// ScanPlugins scans the plugins directory, discovers all valid plugins, and registers them for use.
|
||||
func (m *managerImpl) ScanPlugins() {
|
||||
// Clear existing plugins
|
||||
@@ -344,23 +360,6 @@ func (m *managerImpl) EnsureCompiled(name string) error {
|
||||
return plugin.waitForCompilation()
|
||||
}
|
||||
|
||||
// LoadAllPlugins instantiates and returns all plugins that implement the specified capability
|
||||
func (m *managerImpl) LoadAllPlugins(capability string) []WasmPlugin {
|
||||
names := m.PluginNames(capability)
|
||||
if len(names) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var plugins []WasmPlugin
|
||||
for _, name := range names {
|
||||
plugin := m.LoadPlugin(name, capability)
|
||||
if plugin != nil {
|
||||
plugins = append(plugins, plugin)
|
||||
}
|
||||
}
|
||||
return plugins
|
||||
}
|
||||
|
||||
// LoadMediaAgent instantiates and returns a media agent plugin by folder name
|
||||
func (m *managerImpl) LoadMediaAgent(name string) (agents.Interface, bool) {
|
||||
plugin := m.LoadPlugin(name, CapabilityMetadataAgent)
|
||||
@@ -371,15 +370,6 @@ func (m *managerImpl) LoadMediaAgent(name string) (agents.Interface, bool) {
|
||||
return agent, ok
|
||||
}
|
||||
|
||||
// LoadAllMediaAgents instantiates and returns all media agent plugins
|
||||
func (m *managerImpl) LoadAllMediaAgents() []agents.Interface {
|
||||
plugins := m.LoadAllPlugins(CapabilityMetadataAgent)
|
||||
|
||||
return slice.Map(plugins, func(p WasmPlugin) agents.Interface {
|
||||
return p.(agents.Interface)
|
||||
})
|
||||
}
|
||||
|
||||
// LoadScrobbler instantiates and returns a scrobbler plugin by folder name
|
||||
func (m *managerImpl) LoadScrobbler(name string) (scrobbler.Scrobbler, bool) {
|
||||
plugin := m.LoadPlugin(name, CapabilityScrobbler)
|
||||
@@ -390,15 +380,6 @@ func (m *managerImpl) LoadScrobbler(name string) (scrobbler.Scrobbler, bool) {
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// LoadAllScrobblers instantiates and returns all scrobbler plugins
|
||||
func (m *managerImpl) LoadAllScrobblers() []scrobbler.Scrobbler {
|
||||
plugins := m.LoadAllPlugins(CapabilityScrobbler)
|
||||
|
||||
return slice.Map(plugins, func(p WasmPlugin) scrobbler.Scrobbler {
|
||||
return p.(scrobbler.Scrobbler)
|
||||
})
|
||||
}
|
||||
|
||||
type noopManager struct{}
|
||||
|
||||
func (n noopManager) SetSubsonicRouter(router SubsonicRouter) {}
|
||||
@@ -409,14 +390,8 @@ func (n noopManager) PluginNames(serviceName string) []string { return nil }
|
||||
|
||||
func (n noopManager) LoadPlugin(name string, capability string) WasmPlugin { return nil }
|
||||
|
||||
func (n noopManager) LoadAllPlugins(capability string) []WasmPlugin { return nil }
|
||||
|
||||
func (n noopManager) LoadMediaAgent(name string) (agents.Interface, bool) { return nil, false }
|
||||
|
||||
func (n noopManager) LoadAllMediaAgents() []agents.Interface { return nil }
|
||||
|
||||
func (n noopManager) LoadScrobbler(name string) (scrobbler.Scrobbler, bool) { return nil, false }
|
||||
|
||||
func (n noopManager) LoadAllScrobblers() []scrobbler.Scrobbler { return nil }
|
||||
|
||||
func (n noopManager) ScanPlugins() {}
|
||||
|
||||
Reference in New Issue
Block a user