Skip to content

Commit

Permalink
dev: Fix race condition in event stream opening logic
Browse files Browse the repository at this point in the history
  • Loading branch information
kschiffer committed Dec 12, 2023
1 parent c0687cf commit 30dc2f1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
1 change: 1 addition & 0 deletions pkg/webui/console/store/middleware/logics/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ const createEventsConnectLogics = (reducerName, entityName, onEventsStart) => {
}),
createLogic({
type: SET_EVENT_FILTER,
debounce: 250,
process: async ({ action }, dispatch, done) => {
if (channel) {
try {
Expand Down
14 changes: 8 additions & 6 deletions sdk/js/src/api/stream/subscribeToWebSocketStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 30dc2f1

Please sign in to comment.