navidrome/plugins/host_websocket_test.go
Deluan Quintão 66eaac2762
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>
2025-07-05 09:03:49 -03:00

232 lines
6.0 KiB
Go

package plugins
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
gorillaws "github.com/gorilla/websocket"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/plugins/host/websocket"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("WebSocket Host Service", func() {
var (
wsService *websocketService
manager *managerImpl
ctx context.Context
server *httptest.Server
upgrader gorillaws.Upgrader
serverMessages []string
serverMu sync.Mutex
)
// WebSocket echo server handler
echoHandler := func(w http.ResponseWriter, r *http.Request) {
// Check headers
if r.Header.Get("X-Test-Header") != "test-value" {
http.Error(w, "Missing or invalid X-Test-Header", http.StatusBadRequest)
return
}
// Upgrade connection to WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
// Echo messages back
for {
mt, message, err := conn.ReadMessage()
if err != nil {
break
}
// Store the received message for verification
if mt == gorillaws.TextMessage {
msg := string(message)
serverMu.Lock()
serverMessages = append(serverMessages, msg)
serverMu.Unlock()
}
// Echo it back
err = conn.WriteMessage(mt, message)
if err != nil {
break
}
// If message is "close", close the connection
if mt == gorillaws.TextMessage && string(message) == "close" {
_ = conn.WriteControl(
gorillaws.CloseMessage,
gorillaws.FormatCloseMessage(gorillaws.CloseNormalClosure, "bye"),
time.Now().Add(time.Second),
)
break
}
}
}
BeforeEach(func() {
ctx = context.Background()
serverMessages = make([]string, 0)
serverMu = sync.Mutex{}
// Create a test WebSocket server
//upgrader = gorillaws.Upgrader{}
server = httptest.NewServer(http.HandlerFunc(echoHandler))
DeferCleanup(server.Close)
// Create a new manager and websocket service
manager = createManager(nil, metrics.NewNoopInstance())
wsService = newWebsocketService(manager)
})
Describe("WebSocket operations", func() {
var (
pluginName string
connectionID string
wsURL string
)
BeforeEach(func() {
pluginName = "test-plugin"
connectionID = "test-connection-id"
wsURL = "ws" + strings.TrimPrefix(server.URL, "http")
})
It("connects to a WebSocket server", func() {
// Connect to the WebSocket server
req := &websocket.ConnectRequest{
Url: wsURL,
Headers: map[string]string{
"X-Test-Header": "test-value",
},
ConnectionId: connectionID,
}
resp, err := wsService.connect(ctx, pluginName, req, nil)
Expect(err).ToNot(HaveOccurred())
Expect(resp.ConnectionId).ToNot(BeEmpty())
connectionID = resp.ConnectionId
// Verify that the connection was added to the service
internalID := pluginName + ":" + connectionID
Expect(wsService.hasConnection(internalID)).To(BeTrue())
})
It("sends and receives text messages", func() {
// Connect to the WebSocket server
req := &websocket.ConnectRequest{
Url: wsURL,
Headers: map[string]string{
"X-Test-Header": "test-value",
},
ConnectionId: connectionID,
}
resp, err := wsService.connect(ctx, pluginName, req, nil)
Expect(err).ToNot(HaveOccurred())
connectionID = resp.ConnectionId
// Send a text message
textReq := &websocket.SendTextRequest{
ConnectionId: connectionID,
Message: "hello websocket",
}
_, err = wsService.sendText(ctx, pluginName, textReq)
Expect(err).ToNot(HaveOccurred())
// Wait a bit for the message to be processed
Eventually(func() []string {
serverMu.Lock()
defer serverMu.Unlock()
return serverMessages
}, "1s").Should(ContainElement("hello websocket"))
})
It("closes a WebSocket connection", func() {
// Connect to the WebSocket server
req := &websocket.ConnectRequest{
Url: wsURL,
Headers: map[string]string{
"X-Test-Header": "test-value",
},
ConnectionId: connectionID,
}
resp, err := wsService.connect(ctx, pluginName, req, nil)
Expect(err).ToNot(HaveOccurred())
connectionID = resp.ConnectionId
initialCount := wsService.connectionCount()
// Close the connection
closeReq := &websocket.CloseRequest{
ConnectionId: connectionID,
Code: 1000, // Normal closure
Reason: "test complete",
}
_, err = wsService.close(ctx, pluginName, closeReq)
Expect(err).ToNot(HaveOccurred())
// Verify that the connection was removed
Eventually(func() int {
return wsService.connectionCount()
}, "1s").Should(Equal(initialCount - 1))
internalID := pluginName + ":" + connectionID
Expect(wsService.hasConnection(internalID)).To(BeFalse())
})
It("handles connection errors gracefully", func() {
if testing.Short() {
GinkgoT().Skip("skipping test in short mode.")
}
// Try to connect to an invalid URL
req := &websocket.ConnectRequest{
Url: "ws://invalid-url-that-does-not-exist",
Headers: map[string]string{},
ConnectionId: connectionID,
}
_, err := wsService.connect(ctx, pluginName, req, nil)
Expect(err).To(HaveOccurred())
})
It("returns error when attempting to use non-existent connection", func() {
// Try to send a message to a non-existent connection
textReq := &websocket.SendTextRequest{
ConnectionId: "non-existent-connection",
Message: "this should fail",
}
sendResp, err := wsService.sendText(ctx, pluginName, textReq)
Expect(err).ToNot(HaveOccurred())
Expect(sendResp.Error).To(ContainSubstring("connection not found"))
// Try to close a non-existent connection
closeReq := &websocket.CloseRequest{
ConnectionId: "non-existent-connection",
Code: 1000,
Reason: "test complete",
}
closeResp, err := wsService.close(ctx, pluginName, closeReq)
Expect(err).ToNot(HaveOccurred())
Expect(closeResp.Error).To(ContainSubstring("connection not found"))
})
})
})