| 148 | }; |
| 149 | |
| 150 | class Socket { |
| 151 | ws: WebSocket; |
| 152 | httpRequest: $Request; |
| 153 | viewer: ?Viewer; |
| 154 | redis: ?RedisSubscriber; |
| 155 | redisPromiseResolver: SequentialPromiseResolver<ServerServerSocketMessage>; |
| 156 | |
| 157 | stateCheckConditions: StateCheckConditions = { |
| 158 | activityRecentlyOccurred: true, |
| 159 | stateCheckOngoing: false, |
| 160 | }; |
| 161 | stateCheckTimeoutID: ?TimeoutID; |
| 162 | |
| 163 | constructor(ws: WebSocket, httpRequest: $Request) { |
| 164 | this.ws = ws; |
| 165 | this.httpRequest = httpRequest; |
| 166 | ws.on('message', this.onMessage); |
| 167 | ws.on('close', this.onClose); |
| 168 | this.resetTimeout(); |
| 169 | this.redisPromiseResolver = new SequentialPromiseResolver(this.sendMessage); |
| 170 | } |
| 171 | |
| 172 | onMessage = async ( |
| 173 | messageString: string | Buffer | ArrayBuffer | Array<Buffer>, |
| 174 | ): Promise<void> => { |
| 175 | invariant(typeof messageString === 'string', 'message should be string'); |
| 176 | let responseTo = null; |
| 177 | try { |
| 178 | this.resetTimeout(); |
| 179 | const messageObject = JSON.parse(messageString); |
| 180 | const clientSocketMessageWithClientIDs = checkInputValidator( |
| 181 | clientSocketMessageInputValidator, |
| 182 | messageObject, |
| 183 | 'socket message', |
| 184 | ); |
| 185 | responseTo = clientSocketMessageWithClientIDs.id; |
| 186 | if ( |
| 187 | clientSocketMessageWithClientIDs.type === |
| 188 | clientSocketMessageTypes.INITIAL |
| 189 | ) { |
| 190 | if (this.viewer) { |
| 191 | // This indicates that the user sent multiple INITIAL messages. |
| 192 | throw new ServerError('socket_already_initialized'); |
| 193 | } |
| 194 | this.viewer = await fetchViewerForSocket( |
| 195 | this.httpRequest, |
| 196 | clientSocketMessageWithClientIDs, |
| 197 | ); |
| 198 | } |
| 199 | const { viewer } = this; |
| 200 | if (!viewer) { |
| 201 | // This indicates a non-INITIAL message was sent by the client before |
| 202 | // the INITIAL message. |
| 203 | throw new ServerError('socket_uninitialized'); |
| 204 | } |
| 205 | if (viewer.sessionChanged) { |
| 206 | // This indicates that the cookie was invalid, and we've assigned a new |
| 207 | // anonymous one. |
nothing calls this directly
no test coverage detected