Skip to content

Commit

Permalink
patch(sync): shared connection liveness check
Browse files Browse the repository at this point in the history
  • Loading branch information
Pkmmte committed May 22, 2024
1 parent b44bdc4 commit 89853bd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 27 deletions.
5 changes: 5 additions & 0 deletions .changeset/ten-rivers-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@robojs/sync': patch
---

patch: shared connection liveness check
54 changes: 27 additions & 27 deletions packages/plugin-sync/src/core/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,40 +36,40 @@ function start() {
})
syncLogger.debug('WebSocket server created successfully.')

// Keep track of the connection liveness
setInterval(() => {
if (_connections.length === 0) {
return
}

syncLogger.debug(`Pinging ${_connections.length} connections...`)
const deadIndices: number[] = []
_connections.forEach((conn, index) => {
if (!conn.isAlive) {
syncLogger.warn(`Connection ${conn.id} is dead. Terminating...`)
conn.ws.terminate()
deadIndices.push(index)
return
}

conn.isAlive = false
const ping: MessagePayload = { data: undefined, type: 'ping' }
conn.ws.send(JSON.stringify(ping))
})

// Remove dead connections
deadIndices.forEach((index) => {
_connections.splice(index, 1)
})
}, 30_000)

// Handle incoming connections
_wss.on('connection', (ws) => {
// Register the connection
const connection: Connection = { id: nanoid(), isAlive: true, watch: [], ws }
_connections.push(connection)
syncLogger.debug('New connection established! Registered as', connection.id)

// Keep track of the connection liveness
setInterval(() => {
if (_connections.length === 0) {
return
}

syncLogger.debug(`Pinging ${_connections.length} connections...`)
const deadIndices: number[] = []
_connections.forEach((conn, index) => {
if (!conn.isAlive) {
syncLogger.warn(`Connection ${conn.id} is dead. Terminating...`)
conn.ws.terminate()
deadIndices.push(index)
return
}

conn.isAlive = false
const ping: MessagePayload = { data: undefined, type: 'ping' }
conn.ws.send(JSON.stringify(ping))
})

// Remove dead connections
deadIndices.forEach((index) => {
_connections.splice(index, 1)
})
}, 30_000)

// Detect disconnections
ws.on('close', () => {
const index = _connections.findIndex((c) => c.id === connection.id)
Expand Down

0 comments on commit 89853bd

Please sign in to comment.