_onReadable()

in foreign/node/src/client/client.socket.ts [169:202]


  _onReadable() {
    while (!this._readPaused) {
      const head = this._socket.read(8);
      if (!head || head.length === 0) return;
      if (head.length < 8) {
        this._socket.unshift(head);
        return;
      }
      /** first chunk[4:8] hold response length */
      const responseSize = head.readUInt32LE(4);
      /** response has no payload (create/update/delete ops...) */
      if (responseSize === 0) {
        this.push(head);
        return;
      }

      const payload = this._socket.read(responseSize);
      debug('payload', payload, responseSize, head.readUInt32LE(0));
      if (!payload) {
        this._socket.unshift(head);
        return;
      }
      /** payload is incomplete, unshift until next read */
      if (payload.length < responseSize) {
        this._socket.unshift(Buffer.concat([head, payload]));
        return;
      }

      const pushOk = this.push(Buffer.concat([head, payload]));
      /** consumer is slower than producer */
      if (!pushOk)
        this._readPaused = true;
    }
  }