All files / lib/internal stream_base_commons.js

96.3% Statements 286/297
93.59% Branches 73/78
100% Functions 8/8
96.3% Lines 286/297

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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 29826x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 269x 26x 26x 26x 26x 26x 69241x 69241x 69241x 69241x 69241x 45704x 45704x 45704x 45704x 45703x 45703x 69241x 69241x 3038x 69241x 69241x 20468x 69241x 5x 69241x 69241x 69241x 69241x 4x 69241x 22x 22x 22x 22x 22x 22x 22x 69241x 69241x 26x 5230x 5230x 5230x 5230x 5230x 5230x 2x 2x 5230x 5230x 47x 47x 47x 47x 5183x 5183x 5183x 5230x 7x 7x 7x     7x 7x 5176x 5176x 5176x 5176x 5176x 5176x 5230x 26x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 82342x 26x 13101x 13101x 13101x 13101x 13101x 319x 319x 319x 13101x 12782x 12782x 70702x 70702x 70702x 70702x 12782x 13101x 13101x 13101x 13101x 13101x 13101x 13101x 13101x 26x 69241x 69241x 69241x 69241x 69241x 69241x 69241x 26x 82341x 82341x 82341x 82341x 82341x 82341x 82328x 82341x 77096x 77096x 82341x 26x 62883x 62883x 62883x 62883x 62883x 62883x 62883x 62883x 255x 255x 62882x 62882x 62882x 62883x 43150x 43150x 43150x 43150x 2084x 2084x 2084x 24x 24x 24x 24x 43150x 41066x 41066x 41066x 41066x 43141x 12669x 12669x 12653x 12653x 12653x 12653x 12669x 43139x 43139x 43139x 19732x 62746x     19732x 62738x 9x 9x 9x 9x 9x 19723x 19723x 62732x     62732x 19723x 19723x 19723x 19723x 19723x 19723x 19723x 19723x 19722x 19722x           19722x 19723x 19723x 19723x 19723x 19723x 19723x 19723x 62883x 26x 28111x 28111x 28111x 27350x 27350x 27350x 27350x 27350x 27350x 27350x 27350x 27350x 27350x 27808x 24641x 865x 865x 865x 28111x 2694x 2694x 2694x 2694x 1397x 1397x 1397x 2694x 27317x 28111x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x  
'use strict';
 
const {
  Array,
  Symbol,
} = primordials;
 
const { Buffer } = require('buffer');
const { FastBuffer } = require('internal/buffer');
const {
  WriteWrap,
  kReadBytesOrError,
  kArrayBufferOffset,
  kBytesWritten,
  kLastWriteWasAsync,
  streamBaseState
} = internalBinding('stream_wrap');
const { UV_EOF } = internalBinding('uv');
const {
  errnoException
} = require('internal/errors');
const { owner_symbol } = require('internal/async_hooks').symbols;
const {
  kTimeout,
  setUnrefTimeout,
  getTimerDuration
} = require('internal/timers');
const { isUint8Array } = require('internal/util/types');
const { clearTimeout } = require('timers');
const { validateCallback } = require('internal/validators');
 
const kMaybeDestroy = Symbol('kMaybeDestroy');
const kUpdateTimer = Symbol('kUpdateTimer');
const kAfterAsyncWrite = Symbol('kAfterAsyncWrite');
const kHandle = Symbol('kHandle');
const kSession = Symbol('kSession');
 
let debug = require('internal/util/debuglog').debuglog('stream', (fn) => {
  debug = fn;
});
const kBuffer = Symbol('kBuffer');
const kBufferGen = Symbol('kBufferGen');
const kBufferCb = Symbol('kBufferCb');
 
function handleWriteReq(req, data, encoding) {
  const { handle } = req;
 
  switch (encoding) {
    case 'buffer':
    {
      const ret = handle.writeBuffer(req, data);
      if (streamBaseState[kLastWriteWasAsync])
        req.buffer = data;
      return ret;
    }
    case 'latin1':
    case 'binary':
      return handle.writeLatin1String(req, data);
    case 'utf8':
    case 'utf-8':
      return handle.writeUtf8String(req, data);
    case 'ascii':
      return handle.writeAsciiString(req, data);
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return handle.writeUcs2String(req, data);
    default:
    {
      const buffer = Buffer.from(data, encoding);
      const ret = handle.writeBuffer(req, buffer);
      if (streamBaseState[kLastWriteWasAsync])
        req.buffer = buffer;
      return ret;
    }
  }
}
 
function onWriteComplete(status) {
  debug('onWriteComplete', status, this.error);
 
  let stream = this.handle[owner_symbol];
 
  if (stream.constructor.name === 'ReusedHandle') {
    stream = stream.handle;
  }
 
  if (stream.destroyed) {
    if (typeof this.callback === 'function')
      this.callback(null);
    return;
  }
 
  // TODO (ronag): This should be moved before if(stream.destroyed)
  // in order to avoid swallowing error.
  if (status < 0) {
    const ex = errnoException(status, 'write', this.error);
    if (typeof this.callback === 'function')
      this.callback(ex);
    else
      stream.destroy(ex);
    return;
  }
 
  stream[kUpdateTimer]();
  stream[kAfterAsyncWrite](this);
 
  if (typeof this.callback === 'function')
    this.callback(null);
}
 
function createWriteWrap(handle, callback) {
  const req = new WriteWrap();
 
  req.handle = handle;
  req.oncomplete = onWriteComplete;
  req.async = false;
  req.bytes = 0;
  req.buffer = null;
  req.callback = callback;
 
  return req;
}
 
function writevGeneric(self, data, cb) {
  const req = createWriteWrap(self[kHandle], cb);
  const allBuffers = data.allBuffers;
  let chunks;
  if (allBuffers) {
    chunks = data;
    for (let i = 0; i < data.length; i++)
      data[i] = data[i].chunk;
  } else {
    chunks = new Array(data.length << 1);
    for (let i = 0; i < data.length; i++) {
      const entry = data[i];
      chunks[i * 2] = entry.chunk;
      chunks[i * 2 + 1] = entry.encoding;
    }
  }
  const err = req.handle.writev(req, chunks, allBuffers);
 
  // Retain chunks
  if (err === 0) req._chunks = chunks;
 
  afterWriteDispatched(req, err, cb);
  return req;
}
 
function writeGeneric(self, data, encoding, cb) {
  const req = createWriteWrap(self[kHandle], cb);
  const err = handleWriteReq(req, data, encoding);
 
  afterWriteDispatched(req, err, cb);
  return req;
}
 
function afterWriteDispatched(req, err, cb) {
  req.bytes = streamBaseState[kBytesWritten];
  req.async = !!streamBaseState[kLastWriteWasAsync];
 
  if (err !== 0)
    return cb(errnoException(err, 'write', req.error));
 
  if (!req.async && typeof req.callback === 'function') {
    req.callback();
  }
}
 
function onStreamRead(arrayBuffer) {
  const nread = streamBaseState[kReadBytesOrError];
 
  const handle = this;
 
  let stream = this[owner_symbol];
 
  if (stream.constructor.name === 'ReusedHandle') {
    stream = stream.handle;
  }
 
  stream[kUpdateTimer]();
 
  if (nread > 0 && !stream.destroyed) {
    let ret;
    let result;
    const userBuf = stream[kBuffer];
    if (userBuf) {
      result = (stream[kBufferCb](nread, userBuf) !== false);
      const bufGen = stream[kBufferGen];
      if (bufGen !== null) {
        const nextBuf = bufGen();
        if (isUint8Array(nextBuf))
          stream[kBuffer] = ret = nextBuf;
      }
    } else {
      const offset = streamBaseState[kArrayBufferOffset];
      const buf = new FastBuffer(arrayBuffer, offset, nread);
      result = stream.push(buf);
    }
    if (!result) {
      handle.reading = false;
      if (!stream.destroyed) {
        const err = handle.readStop();
        if (err)
          stream.destroy(errnoException(err, 'read'));
      }
    }
 
    return ret;
  }
 
  if (nread === 0) {
    return;
  }
 
  if (nread !== UV_EOF) {
    // CallJSOnreadMethod expects the return value to be a buffer.
    // Ref: https://github.com/nodejs/node/pull/34375
    stream.destroy(errnoException(nread, 'read'));
    return;
  }
 
  // Defer this until we actually emit end
  if (stream._readableState.endEmitted) {
    if (stream[kMaybeDestroy])
      stream[kMaybeDestroy]();
  } else {
    if (stream[kMaybeDestroy])
      stream.on('end', stream[kMaybeDestroy]);
 
    // TODO(ronag): Without this `readStop`, `onStreamRead`
    // will be called once more (i.e. after Readable.ended)
    // on Windows causing a ECONNRESET, failing the
    // test-https-truncate test.
    if (handle.readStop) {
      const err = handle.readStop();
      if (err) {
        // CallJSOnreadMethod expects the return value to be a buffer.
        // Ref: https://github.com/nodejs/node/pull/34375
        stream.destroy(errnoException(err, 'read'));
        return;
      }
    }
 
    // Push a null to signal the end of data.
    // Do it before `maybeDestroy` for correct order of events:
    // `end` -> `close`
    stream.push(null);
    stream.read(0);
  }
}
 
function setStreamTimeout(msecs, callback) {
  if (this.destroyed)
    return this;
 
  this.timeout = msecs;
 
  // Type checking identical to timers.enroll()
  msecs = getTimerDuration(msecs, 'msecs');
 
  // Attempt to clear an existing timer in both cases -
  //  even if it will be rescheduled we don't want to leak an existing timer.
  clearTimeout(this[kTimeout]);
 
  if (msecs === 0) {
    if (callback !== undefined) {
      validateCallback(callback);
      this.removeListener('timeout', callback);
    }
  } else {
    this[kTimeout] = setUnrefTimeout(this._onTimeout.bind(this), msecs);
    if (this[kSession]) this[kSession][kUpdateTimer]();
 
    if (callback !== undefined) {
      validateCallback(callback);
      this.once('timeout', callback);
    }
  }
  return this;
}
 
module.exports = {
  writevGeneric,
  writeGeneric,
  onStreamRead,
  kAfterAsyncWrite,
  kMaybeDestroy,
  kUpdateTimer,
  kHandle,
  kSession,
  setStreamTimeout,
  kBuffer,
  kBufferCb,
  kBufferGen
};