Skip to content

Commit

Permalink
fix: Websockets are now properly removed on dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
evrys committed Aug 19, 2024
1 parent a223e37 commit af37c7a
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/NovaClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,13 @@ export class NovaClient {
this.makeWebsocketURL(path),
{
mock: this.mock,
onDispose: () => {
delete this.websocketsByPath[path]
},
},
)
this.websocketsByPath[path] = newWebsocket

return newWebsocket
}
}
Expand Down
10 changes: 8 additions & 2 deletions src/lib/AutoReconnectingWebsocket.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ReconnectingWebSocket, { type ErrorEvent } from "reconnecting-websocket"
import type { MockNovaInstance } from "../mock/MockNovaInstance"
import type { WebSocketEventListenerMap } from "reconnecting-websocket/dist/events"

export class AutoReconnectingWebsocket extends ReconnectingWebSocket {
receivedFirstMessage?: MessageEvent
Expand All @@ -8,7 +9,10 @@ export class AutoReconnectingWebsocket extends ReconnectingWebSocket {

constructor(
targetUrl: string,
readonly opts: { mock?: MockNovaInstance } = {},
readonly opts: {
mock?: MockNovaInstance
onDispose?: () => void
} = {},
) {
console.log("Opening websocket to", targetUrl)

Expand Down Expand Up @@ -72,7 +76,9 @@ export class AutoReconnectingWebsocket extends ReconnectingWebSocket {
dispose() {
this.close()
this.disposed = true
this.dispatchEvent(new Event("dispose"))
if (this.opts.onDispose) {
this.opts.onDispose()
}
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/lib/JoggerConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ export class JoggerConnection {

async dispose() {
if (this.cartesianWebsocket) {
this.cartesianWebsocket.close()
this.cartesianWebsocket.dispose()
}

if (this.jointWebsocket) {
this.jointWebsocket.close()
this.jointWebsocket.dispose()
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/websockets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ test("websocket handling", async () => {
// Unless the websocket was disposed
ws.dispose()
const ws3 = nova.openReconnectingWebsocket(
"/motion-groups/0@mock-ur5e/state-stream?tcp=foo",
"/motion-groups/0@mock-ur5e/state-stream",
)
expect(ws3).not.toBe(ws)
})

0 comments on commit af37c7a

Please sign in to comment.