All files / rpc-server/src/ws/server WsServerConnection.ts

66.66% Statements 100/150
64.15% Branches 34/53
40% Functions 8/20
68.84% Lines 95/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 2251x   1x 1x 1x           1x 13x 13x 13x   13x 4x     13x 13x 13x 6x 6x 6x 1x 1x   5x 5x 1x 1x 1x 1x     13x 13x 13x 13x 13x     13x 13x   13x 13x 13x 13x 45x 45x 45x 79x 30x 30x 1x 1x   29x 16x 16x 16x 9x 9x 9x 9x 9x   7x 7x 7x   13x   65x 65x 34x 7x 7x   27x 9x 9x   18x 1x 1x 1x   17x 17x 6x       6x   17x 6x 6x 6x   11x             13x       13x 13x 13x                                 3x 3x       3x 3x 3x 3x                                             13x 13x     4x 4x 4x 2x                                           4x 4x                                                            
import * as crypto from 'crypto';
import type * as stream from 'stream';
import {utf8Size} from '@jsonjoy.com/util/lib/strings/utf8';
import {listToUint8} from '@jsonjoy.com/buffers/lib/concat';
import {WsCloseFrame, WsFrameDecoder, WsFrameHeader, WsFrameOpcode, WsPingFrame, WsPongFrame} from '../codec';
import type {WsConnection} from '../../types';
import type {WsFrameEncoder} from '../codec/WsFrameEncoder';
 
export type WsServerConnectionSocket = stream.Duplex;
 
export class WsServerConnection implements WsConnection {
  public closed = false;
  public maxIncomingMessage: number = 2 * 1024 * 1024;
  public maxBackpressure: number = 2 * 1024 * 1024;
 
  public readonly defaultOnPing = (data: Uint8Array | null): void => {
    this.sendPong(data);
  };
 
  private _fragments: Uint8Array[] = [];
  private _fragmentsSize = 0;
  public readonly defaultOnFragment = (isLast: boolean, data: Uint8Array, isUtf8: boolean): void => {
    const fragments = this._fragments;
    this._fragmentsSize += data.length;
    if (this._fragmentsSize > this.maxIncomingMessage) {
      this.onClose(1009, 'TOO_LARGE');
      return;
    }
    fragments.push(data);
    if (!isLast) return;
    this._fragments = [];
    this._fragmentsSize = 0;
    const message = listToUint8(fragments);
    this.onmessage(message, isUtf8);
  };
 
  public onmessage: (data: Uint8Array, isUtf8: boolean) => void = () => {};
  public onfragment: (isLast: boolean, data: Uint8Array, isUtf8: boolean) => void = this.defaultOnFragment;
  public onping: (data: Uint8Array | null) => void = this.defaultOnPing;
  public onpong: (data: Uint8Array | null) => void = () => {};
  public onclose: (code: number, reason: string, wasClean: boolean) => void = () => {};
 
  constructor(
    protected readonly encoder: WsFrameEncoder,
    public readonly socket: WsServerConnectionSocket,
  ) {
    const decoder = new WsFrameDecoder();
    let currentFrameHeader: WsFrameHeader | null = null;
    let fragmentStartFrameHeader: WsFrameHeader | null = null;
    const handleData = (data: Uint8Array): void => {
      try {
        decoder.push(data);
        while (true) {
          if (currentFrameHeader instanceof WsFrameHeader) {
            const length = currentFrameHeader.length;
            if (length > this.maxIncomingMessage) {
              this.onClose(1009, 'TOO_LARGE');
              return;
            }
            if (length <= decoder.reader.size()) {
              const buf = new Uint8Array(length);
              decoder.copyFrameData(currentFrameHeader, buf, 0);
              if (fragmentStartFrameHeader instanceof WsFrameHeader) {
                const isText = fragmentStartFrameHeader.opcode === WsFrameOpcode.TEXT;
                const isLast = currentFrameHeader.fin === 1;
                currentFrameHeader = null;
                if (isLast) fragmentStartFrameHeader = null;
                this.onfragment(isLast, buf, isText);
              } else {
                const isText = currentFrameHeader.opcode === WsFrameOpcode.TEXT;
                currentFrameHeader = null;
                this.onmessage(buf, isText);
              }
            } else break;
          }
          const frame = decoder.readFrameHeader();
          if (!frame) break;
          if (frame instanceof WsPingFrame) {
            this.onping(frame.data);
            continue;
          }
          if (frame instanceof WsPongFrame) {
            this.onpong(frame.data);
            continue;
          }
          if (frame instanceof WsCloseFrame) {
            decoder.readCloseFrameData(frame);
            this.onClose(frame.code, frame.reason);
            continue;
          }
          Eif (frame instanceof WsFrameHeader) {
            if (fragmentStartFrameHeader) {
              Iif (frame.opcode !== WsFrameOpcode.CONTINUE) {
                this.onClose(1002, 'DATA');
                return;
              }
              currentFrameHeader = frame;
            }
            if (frame.fin === 0) {
              fragmentStartFrameHeader = frame;
              currentFrameHeader = frame;
              continue;
            }
            currentFrameHeader = frame;
          }
        }
      } catch {
        this.onClose(1002, 'DATA');
      }
    };
    const handleClose = (hadError: boolean): void => {
      if (this.closed) return;
      this.onClose(hadError ? 1001 : 1002, 'END');
    };
    socket.on('data', handleData);
    socket.on('close', handleClose);
    socket.on('error', (err: Error) => {
      // TODO: Improve error handling.
      // tslint:disable-next-line:no-console
      console.log('SOCKET ERROR:', err);
      this.onClose(0, '');
    });
  }
 
  public close(code?: number, reason?: string): void {
    const c = code ?? 1000;
    const r = reason ?? 'CLOSE';
    const frame = this.encoder.encodeClose(r, c);
    this.socket.write(frame);
    this.onClose(c, r, true);
  }
 
  private onClose(code: number, reason: string, wasClean = false): void {
    this.closed = true;
    Iif (this.__writeTimer) {
      clearImmediate(this.__writeTimer);
      this.__writeTimer = null;
    }
    const socket = this.socket;
    socket.removeAllListeners();
    Eif (!socket.destroyed) socket.destroy();
    this.onclose(code, reason, wasClean);
  }
 
  // ----------------------------------------------------------- Handle upgrade
 
  // eslint-disable-next-line
  public upgrade(secWebSocketKey: string, secWebSocketProtocol: string, secWebSocketExtensions?: string): void {
    const accept = secWebSocketKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
    const acceptSha1 = crypto.createHash('sha1').update(accept).digest('base64');
    // biome-ignore format: line per header
    this.socket.write(
      'HTTP/1.1 101 Switching Protocols\r\n' +
        'Upgrade: websocket\r\n' +
        'Connection: Upgrade\r\n' +
        'Sec-WebSocket-Accept: ' + acceptSha1 + '\r\n' +
        (secWebSocketProtocol ? 'Sec-WebSocket-Protocol: ' + secWebSocketProtocol + '\r\n' : '') +
        // 'Sec-WebSocket-Extensions: ""\r\n' +
        '\r\n',
    );
  }
 
  // ---------------------------------------------------------- Write to socket
 
  private __buffer: Uint8Array[] = [];
  private __writeTimer: NodeJS.Immediate | null = null;
 
  public write(buf: Uint8Array): void {
    Iif (this.closed) return;
    this.__buffer.push(buf);
    if (this.__writeTimer) return;
    this.__writeTimer = setImmediate(() => {
      this.__writeTimer = null;
      const buffer = this.__buffer;
      this.__buffer = [];
      if (!buffer.length) return;
      const socket = this.socket;
      if (socket.writableLength > this.maxBackpressure) this.onClose(1009, 'BACKPRESSURE');
      // TODO: benchmark if corking helps
      socket.cork();
      for (let i = 0, len = buffer.length; i < len; i++) socket.write(buffer[i]);
      socket.uncork();
    });
  }
 
  // ------------------------------------------------- Write WebSocket messages
 
  public sendPing(data: Uint8Array | null): void {
    const frame = this.encoder.encodePing(data);
    this.write(frame);
  }
 
  public sendPong(data: Uint8Array | null): void {
    const frame = this.encoder.encodePong(data);
    this.write(frame);
  }
 
  public send(data: Uint8Array): number {
    this.sendBinMsg(data);
    return this.socket.writableLength;
  }
 
  public buffer(): number {
    return this.socket.writableLength;
  }
 
  public sendBinMsg(data: Uint8Array): void {
    const encoder = this.encoder;
    const header = encoder.encodeDataMsgHdrFast(data.length);
    this.write(header);
    this.write(data);
  }
 
  public sendTxtMsg(txt: string): void {
    const encoder = this.encoder;
    const writer = encoder.writer;
    const size = utf8Size(txt);
    encoder.writeHdr(1, WsFrameOpcode.TEXT, size, 0);
    writer.ensureCapacity(size);
    writer.utf8(txt);
    const buf = writer.flush();
    this.write(buf);
  }
}