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

feat(server): gracefully close websocket connections on server shutdown #143

Merged
merged 3 commits into from
Aug 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/server/src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,17 @@ export class Launcher {
if (!this.shuttingDown) {
this.shuttingDown = true

if (!yn(process.env.SPINNED)) {
this.logger.info('Server gracefully closing down...')
}

await this.api.sockets.destroy()
await this.httpTerminator?.terminate()
await this.app.destroy()

if (!yn(process.env.SPINNED)) {
this.logger.info('Server shutdown complete')
}
}
process.exit(code)
}
Expand Down
25 changes: 23 additions & 2 deletions packages/server/src/socket/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,38 @@ import { SocketService } from './service'

export class SocketManager {
private logger = new Logger('Socket')
private ws: Socket.Server | undefined
private handlers: { [type: string]: SocketHandler } = {}

constructor(private sockets: SocketService) {}

async setup(server: Server) {
if (yn(process.env.ENABLE_EXPERIMENTAL_SOCKETS)) {
const ws = new Socket.Server(server, { cors: { origin: '*' } })
ws.on('connection', this.handleSocketConnection.bind(this))
this.ws = new Socket.Server(server, { cors: { origin: '*' } })
this.ws.on('connection', this.handleSocketConnection.bind(this))
}
}

async destroy() {
if (!this.ws) {
return
}

await new Promise((resolve, reject) => {
// This is kind of hack to make sure that socket.io does not
// try to close the HTTP server before http-terminator
this.ws!['httpServer'] = undefined

this.ws!.close((err) => {
if (err) {
this.logger.error(err, 'An error occurred when closing the websocket server.')
}

resolve(undefined)
})
})
}

public handle(type: string, callback: SocketHandler) {
this.handlers[type] = callback
}
Expand Down