From 30dc2f126ef31f17b88173c3d09178ea8c77f8ca Mon Sep 17 00:00:00 2001 From: Kevin Schiffer Date: Tue, 12 Dec 2023 17:34:29 +0900 Subject: [PATCH] dev: Fix race condition in event stream opening logic --- .../console/store/middleware/logics/events.js | 1 + .../src/api/stream/subscribeToWebSocketStream.js | 14 ++++++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/pkg/webui/console/store/middleware/logics/events.js b/pkg/webui/console/store/middleware/logics/events.js index 7d6c0b0b1d..e03e82d85e 100644 --- a/pkg/webui/console/store/middleware/logics/events.js +++ b/pkg/webui/console/store/middleware/logics/events.js @@ -275,6 +275,7 @@ const createEventsConnectLogics = (reducerName, entityName, onEventsStart) => { }), createLogic({ type: SET_EVENT_FILTER, + debounce: 250, process: async ({ action }, dispatch, done) => { if (channel) { try { diff --git a/sdk/js/src/api/stream/subscribeToWebSocketStream.js b/sdk/js/src/api/stream/subscribeToWebSocketStream.js index 7d38acebbb..199d23603c 100644 --- a/sdk/js/src/api/stream/subscribeToWebSocketStream.js +++ b/sdk/js/src/api/stream/subscribeToWebSocketStream.js @@ -93,11 +93,6 @@ export default async ( `ttn.lorawan.v3.header.authorization.bearer.${tokenParsed}`, ]) - // Event listener for 'open' - wsInstances[url].addEventListener('open', () => { - wsInstances[url].send(subscriptionPayload) - }) - // Broadcast connection errors to all listeners. wsInstances[url].addEventListener('error', error => { Object.values(subscriptions) @@ -163,9 +158,16 @@ export default async ( } } }) - } else if (wsInstances[url] && wsInstances[url].readyState === WebSocket.OPEN) { + } + + if (wsInstances[url] && wsInstances[url].readyState === WebSocket.OPEN) { // If the WebSocket connection is already open, only add the subscription. wsInstances[url].send(subscriptionPayload) + } else if (wsInstances[url] && wsInstances[url].readyState === WebSocket.CONNECTING) { + // Otherwise wait for the connection to open and then add the subscription. + wsInstances[url].addEventListener('open', () => { + wsInstances[url].send(subscriptionPayload) + }) } } catch (error) { const err = error instanceof Error ? error : new Error(error)