Skip to content

Commit

Permalink
feat(server): gracefully close websocket connections on server shutdo…
Browse files Browse the repository at this point in the history
…wn (#143)

* feat(server): gracefully close websocket connections on server shutdown

* websocket connections are automatically closed upon server closure

* pr comments
  • Loading branch information
laurentlp committed Aug 23, 2021
1 parent cff7316 commit 02b1619
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
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

0 comments on commit 02b1619

Please sign in to comment.