Skip to content

Commit

Permalink
fix: 💅 Handle correctly websocket retries
Browse files Browse the repository at this point in the history
Fix #199
  • Loading branch information
CPatchane committed Feb 5, 2019
1 parent 0891251 commit efd26d8
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions packages/cozy-realtime/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ const WEBSOCKET_STATE = {
const NUM_RETRIES = 3
const RETRY_BASE_DELAY = 1000

// stored subscriptions arguments to rerun while a retry
// stored as a Map { [doctype]: socket }
let subscriptionsState = new Set()

// Send a subscribe message for the given doctype trough the given websocket, but
// only if it is in a ready state. If not, retry a few milliseconds later.
function subscribeWhenReady(doctype, socket) {
Expand Down Expand Up @@ -104,7 +108,8 @@ async function connectWebSocket(
onmessage,
onclose,
numRetries,
retryDelay
retryDelay,
isRetry
) {
validateConfig(config)
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -150,6 +155,12 @@ async function connectWebSocket(
// eslint-disable-next-line no-console
console.error(`WebSocket error: ${error.message}`)

if (isRetry && subscriptionsState.size) {
for (let doctype of subscriptionsState) {
subscribeWhenReady(doctype, socket)
}
}

resolve(socket)
}
})
Expand Down Expand Up @@ -202,7 +213,8 @@ function getCozySocket(config) {
onSocketMessage,
onSocketClose,
--numRetries,
retryDelay + 1000
retryDelay + 1000,
true
)
} catch (error) {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -240,6 +252,10 @@ function getCozySocket(config) {
listeners[doctype][event] = (listeners[doctype][event] || []).concat([
listener
])

if (!subscriptionsState.has(doctype)) {
subscriptionsState.add(doctype)
}
},
unsubscribe: (doctype, event, listener) => {
if (
Expand All @@ -251,6 +267,9 @@ function getCozySocket(config) {
l => l !== listener
)
}
if (subscriptionsState.has(doctype)) {
subscriptionsState.delete(doctype)
}
}
})
})
Expand Down

0 comments on commit efd26d8

Please sign in to comment.