| 17 | const WSS_CLIENT_HEALTH_PROBE_INTERVAL = 120000 |
| 18 | |
| 19 | export class WebSocketServerAdapter extends WebServerAdapter implements IWebSocketServerAdapter { |
| 20 | private webSocketsAdapters: WeakMap<WebSocket, IWebSocketAdapter> |
| 21 | |
| 22 | private heartbeatInterval: NodeJS.Timeout |
| 23 | |
| 24 | public constructor( |
| 25 | webServer: Server, |
| 26 | private readonly webSocketServer: WebSocketServer, |
| 27 | private readonly createWebSocketAdapter: Factory< |
| 28 | IWebSocketAdapter, |
| 29 | [WebSocket, IncomingMessage, IWebSocketServerAdapter] |
| 30 | >, |
| 31 | private readonly settings: () => Settings, |
| 32 | ) { |
| 33 | logger('created') |
| 34 | super(webServer) |
| 35 | |
| 36 | this.webSocketsAdapters = new WeakMap() |
| 37 | |
| 38 | this.on(WebSocketServerAdapterEvent.Broadcast, this.onBroadcast.bind(this)) |
| 39 | |
| 40 | this.webSocketServer |
| 41 | .on(WebSocketServerAdapterEvent.Connection, this.onConnection.bind(this)) |
| 42 | .on('error', (error) => { |
| 43 | logger('error: %o', error) |
| 44 | }) |
| 45 | this.heartbeatInterval = setInterval(this.onHeartbeat.bind(this), WSS_CLIENT_HEALTH_PROBE_INTERVAL) |
| 46 | } |
| 47 | |
| 48 | public close(callback?: () => void): void { |
| 49 | super.close(() => { |
| 50 | logger('closing') |
| 51 | clearInterval(this.heartbeatInterval) |
| 52 | this.webSocketServer.clients.forEach((webSocket: WebSocket) => { |
| 53 | const webSocketAdapter = this.webSocketsAdapters.get(webSocket) |
| 54 | if (webSocketAdapter) { |
| 55 | logger('terminating client %s: %s', webSocketAdapter.getClientId(), webSocketAdapter.getClientAddress()) |
| 56 | } |
| 57 | webSocket.terminate() |
| 58 | }) |
| 59 | logger('closing web socket server') |
| 60 | this.webSocketServer.close(() => { |
| 61 | this.webSocketServer.removeAllListeners() |
| 62 | if (typeof callback !== 'undefined') { |
| 63 | callback() |
| 64 | } |
| 65 | logger('closed') |
| 66 | }) |
| 67 | }) |
| 68 | this.removeAllListeners() |
| 69 | } |
| 70 | |
| 71 | private onBroadcast(event: Event) { |
| 72 | this.webSocketServer.clients.forEach((webSocket: WebSocket) => { |
| 73 | if (!propEq('readyState', OPEN)(webSocket)) { |
| 74 | return |
| 75 | } |
| 76 | const webSocketAdapter = this.webSocketsAdapters.get(webSocket) as IWebSocketAdapter |
nothing calls this directly
no outgoing calls
no test coverage detected