Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify websocket code #425

Merged
merged 13 commits into from
Sep 3, 2024
Merged
74 changes: 68 additions & 6 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@
},
"dependencies": {
"portfinder": "^1.0.32",
"reconnecting-websocket": "^4.4.0",
"vscode-languageserver": "^8.0.2",
"vscode-languageserver-textdocument": "^1.0.8",
"ws": "^8.17.1"
},
"devDependencies": {
"@types/ws": "^8.5.10"
},
"scripts": {}
}
62 changes: 20 additions & 42 deletions server/src/engine/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@ import * as queue from './queue'
import { clearDiagnostics, sendNotification } from '../server'
import { EventEmitter } from 'events'
import { handleCrash, lspCheckResponseHandler } from '../handlers'
import { getPort } from 'portfinder'
magnus-madsen marked this conversation as resolved.
Show resolved Hide resolved
import { USER_MESSAGE } from '../util/userMessages'
import { StatusCode } from '../util/statusCodes'
import ReconnectingWebSocket from 'reconnecting-websocket'
import WebSocket from 'ws'

const WebSocket = require('ws')

let webSocket: any
let webSocket: ReconnectingWebSocket
let webSocketOpen = false

// event emitter to handle communication between socket handlers and connection handlers
Expand Down Expand Up @@ -85,60 +84,39 @@ export function isClosed() {
let lastManualStopTimestamp: number = 0

export function initialiseSocket({ uri, onOpen, onClose }: InitialiseSocketInput) {
if (!uri) {
throw 'Must be called with an uri'
}
webSocket = new WebSocket(uri)
webSocket = new ReconnectingWebSocket(uri, [], {
WebSocket,
maxRetries: 5,
sockmaster27 marked this conversation as resolved.
Show resolved Hide resolved
})

webSocket.on('open', () => {
webSocket.addEventListener('open', () => {
webSocketOpen = true
onOpen && setTimeout(onOpen!, 0)
if (onOpen !== undefined) {
setTimeout(onOpen, 0)
}
})

webSocket.on('close', () => {
webSocket.addEventListener('close', () => {
webSocketOpen = false
if (lastManualStopTimestamp + 15000 < Date.now()) {
// This happends when the connections breaks unintentionally
// This happens when the connections breaks unintentionally
console.log(USER_MESSAGE.CONNECTION_LOST())
tryToConnect({ uri, onOpen, onClose }, 5).then(connected => {
if (!connected) {
console.log(USER_MESSAGE.CONNECTION_LOST_RESTARTING())
sendNotification(jobs.Request.internalRestart)
}
})
return
}
onClose && setTimeout(onClose!, 0)

if (onClose !== undefined) {
setTimeout(onClose, 0)
}
})

webSocket.on('message', (data: string) => {
const flixResponse: FlixResponse = JSON.parse(data)
const job: jobs.EnqueuedJob = jobs.getJob(flixResponse.id)
webSocket.addEventListener('message', message => {
const flixResponse: FlixResponse = JSON.parse(message.data)
const job = jobs.getJob(flixResponse.id)

handleResponse(flixResponse, job)
})
}

async function tryToConnect({ uri, onOpen, onClose }: InitialiseSocketInput, times: number) {
const uriPort = parseInt(uri.slice(-4))
getPort({ port: uriPort }, (err, freePort) => {
if (uriPort === freePort) {
// This happens if the previously used port is now free
sendNotification(jobs.Request.internalRestart)
sockmaster27 marked this conversation as resolved.
Show resolved Hide resolved
return
}
})
let retries = times
while (retries-- > 0) {
initialiseSocket({ uri, onOpen, onClose })
await sleep(1000)
if (webSocketOpen) {
return true
}
}
return false
}

function clearTimer(id: string) {
clearTimeout(sentMessagesMap[id])
delete sentMessagesMap[id]
Expand Down
4 changes: 0 additions & 4 deletions server/src/util/userMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ export class USER_MESSAGE {
return 'Connection to the flix server was lost, trying to reconnect...'
}

static CONNECTION_LOST_RESTARTING() {
return 'Failed to connect to the flix server, restarting the compiler...'
}

static FAILED_TO_START() {
return 'Failed starting Flix'
}
Expand Down
4 changes: 3 additions & 1 deletion server/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"strict": true,
"outDir": "out",
"rootDir": "src",
"allowJs": true
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", ".vscode-test"]
Expand Down
Loading