Skip to content

Commit

Permalink
Reconnect to WebSocket on close and wait less time for block time to …
Browse files Browse the repository at this point in the history
…appear.
  • Loading branch information
NoahSaso committed Oct 4, 2023
1 parent fd6ae6c commit e555647
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 22 deletions.
45 changes: 23 additions & 22 deletions src/scripts/export/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ const trace = async () => {
const { blockHeight } = trace.metadata

// If not in cache but WebSocket is connected and every block is less than
// the current one, wait for up to 5 seconds for it to be added to the
// the current one, wait for up to 3 seconds for it to be added to the
// cache. We might be just a moment ahead of the new block event.
if (!blockHeightToTimeCache.has(blockHeight) && webSocketConnected) {
const blockHeights = blockHeightToTimeCache.dump().map(([key]) => key)
Expand Down Expand Up @@ -143,7 +143,7 @@ const trace = async () => {
const timeout = setTimeout(() => {
clearInterval(interval)
resolve(undefined)
}, 5000)
}, 3000)
})

if (time !== undefined) {
Expand Down Expand Up @@ -504,26 +504,27 @@ const trace = async () => {
processTraceQueue()
},
onError: async (error) => {
// If fails to connect, retry after three seconds.
if (error.message.includes('ECONNREFUSED')) {
console.error(
'Failed to connect to WebSocket. Retrying in 3 seconds...',
error
)
webSocket.terminate()

setTimeout(setUpWebSocket, 3000)
} else {
console.error('WebSocket error', error)

Sentry.captureException(error, {
tags: {
type: 'websocket-error',
script: 'export',
chainId: (await State.getSingleton())?.chainId ?? 'unknown',
},
})
}
// On error, reconnect.
console.error(
'WebSocket errored, reconnecting in 3 seconds...',
error
)
Sentry.captureException(error, {
tags: {
type: 'websocket-error',
script: 'export',
chainId: (await State.getSingleton())?.chainId ?? 'unknown',
},
})

webSocketConnected = false
webSocket.terminate()
setTimeout(setUpWebSocket, 3000)
},
onClose: () => {
// On close, reconnect.
webSocketConnected = false
setTimeout(setUpWebSocket, 3000)
},
})
}
Expand Down
6 changes: 6 additions & 0 deletions src/scripts/export/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,15 @@ type WebSocketNewBlockListenerOptions = {
rpc: string
onNewBlock: (block: unknown) => void | Promise<void>
onConnect?: () => void
onClose?: () => void
onError?: (error: Error) => void
}

export const setUpWebSocketNewBlockListener = ({
rpc,
onNewBlock,
onConnect,
onClose,
onError,
}: WebSocketNewBlockListenerOptions): WebSocket => {
// Get new-block WebSocket.
Expand Down Expand Up @@ -247,6 +249,10 @@ export const setUpWebSocketNewBlockListener = ({
onError?.(error)
})

webSocket.on('close', () => {
onClose?.()
})

return webSocket
}

Expand Down

0 comments on commit e555647

Please sign in to comment.