• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22// A bit simpler than readable streams.
23// Implement an async ._write(chunk, encoding, cb), and it'll handle all
24// the drain event emission and buffering.
25
26'use strict';
27
28const {
29  Array,
30  FunctionPrototype,
31  ObjectDefineProperty,
32  ObjectDefineProperties,
33  ObjectSetPrototypeOf,
34  Symbol,
35  SymbolHasInstance,
36} = primordials;
37
38module.exports = Writable;
39Writable.WritableState = WritableState;
40
41const internalUtil = require('internal/util');
42const EE = require('events');
43const Stream = require('stream');
44const { Buffer } = require('buffer');
45const destroyImpl = require('internal/streams/destroy');
46const {
47  getHighWaterMark,
48  getDefaultHighWaterMark
49} = require('internal/streams/state');
50const {
51  ERR_INVALID_ARG_TYPE,
52  ERR_METHOD_NOT_IMPLEMENTED,
53  ERR_MULTIPLE_CALLBACK,
54  ERR_STREAM_CANNOT_PIPE,
55  ERR_STREAM_DESTROYED,
56  ERR_STREAM_NULL_VALUES,
57  ERR_STREAM_WRITE_AFTER_END,
58  ERR_UNKNOWN_ENCODING
59} = require('internal/errors').codes;
60
61const { errorOrDestroy } = destroyImpl;
62
63ObjectSetPrototypeOf(Writable.prototype, Stream.prototype);
64ObjectSetPrototypeOf(Writable, Stream);
65
66function nop() {}
67
68function WritableState(options, stream, isDuplex) {
69  // Duplex streams are both readable and writable, but share
70  // the same options object.
71  // However, some cases require setting options to different
72  // values for the readable and the writable sides of the duplex stream,
73  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
74  if (typeof isDuplex !== 'boolean')
75    isDuplex = stream instanceof Stream.Duplex;
76
77  // Object stream flag to indicate whether or not this stream
78  // contains buffers or objects.
79  this.objectMode = !!(options && options.objectMode);
80
81  if (isDuplex)
82    this.objectMode = this.objectMode ||
83      !!(options && options.writableObjectMode);
84
85  // The point at which write() starts returning false
86  // Note: 0 is a valid value, means that we always return false if
87  // the entire buffer is not flushed immediately on write()
88  this.highWaterMark = options ?
89    getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) :
90    getDefaultHighWaterMark(false);
91
92  // if _final has been called
93  this.finalCalled = false;
94
95  // drain event flag.
96  this.needDrain = false;
97  // At the start of calling end()
98  this.ending = false;
99  // When end() has been called, and returned
100  this.ended = false;
101  // When 'finish' is emitted
102  this.finished = false;
103
104  // Has it been destroyed
105  this.destroyed = false;
106
107  // Should we decode strings into buffers before passing to _write?
108  // this is here so that some node-core streams can optimize string
109  // handling at a lower level.
110  const noDecode = !!(options && options.decodeStrings === false);
111  this.decodeStrings = !noDecode;
112
113  // Crypto is kind of old and crusty.  Historically, its default string
114  // encoding is 'binary' so we have to make this configurable.
115  // Everything else in the universe uses 'utf8', though.
116  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8';
117
118  // Not an actual buffer we keep track of, but a measurement
119  // of how much we're waiting to get pushed to some underlying
120  // socket or file.
121  this.length = 0;
122
123  // A flag to see when we're in the middle of a write.
124  this.writing = false;
125
126  // When true all writes will be buffered until .uncork() call
127  this.corked = 0;
128
129  // A flag to be able to tell if the onwrite cb is called immediately,
130  // or on a later tick.  We set this to true at first, because any
131  // actions that shouldn't happen until "later" should generally also
132  // not happen before the first write call.
133  this.sync = true;
134
135  // A flag to know if we're processing previously buffered items, which
136  // may call the _write() callback in the same tick, so that we don't
137  // end up in an overlapped onwrite situation.
138  this.bufferProcessing = false;
139
140  // The callback that's passed to _write(chunk,cb)
141  this.onwrite = onwrite.bind(undefined, stream);
142
143  // The callback that the user supplies to write(chunk,encoding,cb)
144  this.writecb = null;
145
146  // The amount that is being written when _write is called.
147  this.writelen = 0;
148
149  // Storage for data passed to the afterWrite() callback in case of
150  // synchronous _write() completion.
151  this.afterWriteTickInfo = null;
152
153  this.bufferedRequest = null;
154  this.lastBufferedRequest = null;
155
156  // Number of pending user-supplied write callbacks
157  // this must be 0 before 'finish' can be emitted
158  this.pendingcb = 0;
159
160  // Emit prefinish if the only thing we're waiting for is _write cbs
161  // This is relevant for synchronous Transform streams
162  this.prefinished = false;
163
164  // True if the error was already emitted and should not be thrown again
165  this.errorEmitted = false;
166
167  // Should close be emitted on destroy. Defaults to true.
168  this.emitClose = !options || options.emitClose !== false;
169
170  // Should .destroy() be called after 'finish' (and potentially 'end')
171  this.autoDestroy = !!(options && options.autoDestroy);
172
173  // Count buffered requests
174  this.bufferedRequestCount = 0;
175
176  // Allocate the first CorkedRequest, there is always
177  // one allocated and free to use, and we maintain at most two
178  const corkReq = { next: null, entry: null, finish: undefined };
179  corkReq.finish = onCorkedFinish.bind(undefined, corkReq, this);
180  this.corkedRequestsFree = corkReq;
181}
182
183WritableState.prototype.getBuffer = function getBuffer() {
184  var current = this.bufferedRequest;
185  const out = [];
186  while (current) {
187    out.push(current);
188    current = current.next;
189  }
190  return out;
191};
192
193ObjectDefineProperty(WritableState.prototype, 'buffer', {
194  get: internalUtil.deprecate(function writableStateBufferGetter() {
195    return this.getBuffer();
196  }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
197     'instead.', 'DEP0003')
198});
199
200// Test _writableState for inheritance to account for Duplex streams,
201// whose prototype chain only points to Readable.
202var realHasInstance;
203if (typeof Symbol === 'function' && SymbolHasInstance) {
204  realHasInstance = FunctionPrototype[SymbolHasInstance];
205  ObjectDefineProperty(Writable, SymbolHasInstance, {
206    value: function(object) {
207      if (realHasInstance.call(this, object))
208        return true;
209      if (this !== Writable)
210        return false;
211
212      return object && object._writableState instanceof WritableState;
213    }
214  });
215} else {
216  realHasInstance = function(object) {
217    return object instanceof this;
218  };
219}
220
221function Writable(options) {
222  // Writable ctor is applied to Duplexes, too.
223  // `realHasInstance` is necessary because using plain `instanceof`
224  // would return false, as no `_writableState` property is attached.
225
226  // Trying to use the custom `instanceof` for Writable here will also break the
227  // Node.js LazyTransform implementation, which has a non-trivial getter for
228  // `_writableState` that would lead to infinite recursion.
229
230  // Checking for a Stream.Duplex instance is faster here instead of inside
231  // the WritableState constructor, at least with V8 6.5
232  const isDuplex = (this instanceof Stream.Duplex);
233
234  if (!isDuplex && !realHasInstance.call(Writable, this))
235    return new Writable(options);
236
237  this._writableState = new WritableState(options, this, isDuplex);
238
239  // legacy.
240  this.writable = true;
241
242  if (options) {
243    if (typeof options.write === 'function')
244      this._write = options.write;
245
246    if (typeof options.writev === 'function')
247      this._writev = options.writev;
248
249    if (typeof options.destroy === 'function')
250      this._destroy = options.destroy;
251
252    if (typeof options.final === 'function')
253      this._final = options.final;
254  }
255
256  Stream.call(this, options);
257}
258
259// Otherwise people can pipe Writable streams, which is just wrong.
260Writable.prototype.pipe = function() {
261  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
262};
263
264
265function writeAfterEnd(stream, cb) {
266  const er = new ERR_STREAM_WRITE_AFTER_END();
267  // TODO: defer error events consistently everywhere, not just the cb
268  errorOrDestroy(stream, er);
269  process.nextTick(cb, er);
270}
271
272// Checks that a user-supplied chunk is valid, especially for the particular
273// mode the stream is in. Currently this means that `null` is never accepted
274// and undefined/non-string values are only allowed in object mode.
275function validChunk(stream, state, chunk, cb) {
276  var er;
277
278  if (chunk === null) {
279    er = new ERR_STREAM_NULL_VALUES();
280  } else if (typeof chunk !== 'string' && !state.objectMode) {
281    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
282  }
283  if (er) {
284    errorOrDestroy(stream, er);
285    process.nextTick(cb, er);
286    return false;
287  }
288  return true;
289}
290
291Writable.prototype.write = function(chunk, encoding, cb) {
292  const state = this._writableState;
293  var ret = false;
294  const isBuf = !state.objectMode && Stream._isUint8Array(chunk);
295
296  // Do not use Object.getPrototypeOf as it is slower since V8 7.3.
297  if (isBuf && !(chunk instanceof Buffer)) {
298    chunk = Stream._uint8ArrayToBuffer(chunk);
299  }
300
301  if (typeof encoding === 'function') {
302    cb = encoding;
303    encoding = null;
304  }
305
306  if (isBuf)
307    encoding = 'buffer';
308  else if (!encoding)
309    encoding = state.defaultEncoding;
310
311  if (typeof cb !== 'function')
312    cb = nop;
313
314  if (state.ending)
315    writeAfterEnd(this, cb);
316  else if (isBuf || validChunk(this, state, chunk, cb)) {
317    state.pendingcb++;
318    ret = writeOrBuffer(this, state, chunk, encoding, cb);
319  }
320
321  return ret;
322};
323
324Writable.prototype.cork = function() {
325  this._writableState.corked++;
326};
327
328Writable.prototype.uncork = function() {
329  const state = this._writableState;
330
331  if (state.corked) {
332    state.corked--;
333
334    if (!state.writing &&
335        !state.corked &&
336        !state.bufferProcessing &&
337        state.bufferedRequest)
338      clearBuffer(this, state);
339  }
340};
341
342Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
343  // node::ParseEncoding() requires lower case.
344  if (typeof encoding === 'string')
345    encoding = encoding.toLowerCase();
346  if (!Buffer.isEncoding(encoding))
347    throw new ERR_UNKNOWN_ENCODING(encoding);
348  this._writableState.defaultEncoding = encoding;
349  return this;
350};
351
352// If we're already writing something, then just put this
353// in the queue, and wait our turn.  Otherwise, call _write
354// If we return false, then we need a drain event, so set that flag.
355function writeOrBuffer(stream, state, chunk, encoding, cb) {
356  if (!state.objectMode &&
357      state.decodeStrings !== false &&
358      encoding !== 'buffer' &&
359      typeof chunk === 'string') {
360    chunk = Buffer.from(chunk, encoding);
361    encoding = 'buffer';
362  }
363  const len = state.objectMode ? 1 : chunk.length;
364
365  state.length += len;
366
367  const ret = state.length < state.highWaterMark;
368  // We must ensure that previous needDrain will not be reset to false.
369  if (!ret)
370    state.needDrain = true;
371
372  if (state.writing || state.corked) {
373    var last = state.lastBufferedRequest;
374    state.lastBufferedRequest = {
375      chunk,
376      encoding,
377      callback: cb,
378      next: null
379    };
380    if (last) {
381      last.next = state.lastBufferedRequest;
382    } else {
383      state.bufferedRequest = state.lastBufferedRequest;
384    }
385    state.bufferedRequestCount += 1;
386  } else {
387    doWrite(stream, state, false, len, chunk, encoding, cb);
388  }
389
390  return ret;
391}
392
393function doWrite(stream, state, writev, len, chunk, encoding, cb) {
394  state.writelen = len;
395  state.writecb = cb;
396  state.writing = true;
397  state.sync = true;
398  if (state.destroyed)
399    state.onwrite(new ERR_STREAM_DESTROYED('write'));
400  else if (writev)
401    stream._writev(chunk, state.onwrite);
402  else
403    stream._write(chunk, encoding, state.onwrite);
404  state.sync = false;
405}
406
407function onwriteError(stream, state, sync, er, cb) {
408  --state.pendingcb;
409
410  if (sync) {
411    // Defer the callback if we are being called synchronously
412    // to avoid piling up things on the stack
413    process.nextTick(cb, er);
414    // This can emit finish, and it will always happen
415    // after error
416    process.nextTick(finishMaybe, stream, state);
417    stream._writableState.errorEmitted = true;
418    errorOrDestroy(stream, er);
419  } else {
420    // The caller expect this to happen before if
421    // it is async
422    cb(er);
423    stream._writableState.errorEmitted = true;
424    errorOrDestroy(stream, er);
425    // This can emit finish, but finish must
426    // always follow error
427    finishMaybe(stream, state);
428  }
429}
430
431function onwrite(stream, er) {
432  const state = stream._writableState;
433  const sync = state.sync;
434  const cb = state.writecb;
435
436  if (typeof cb !== 'function')
437    throw new ERR_MULTIPLE_CALLBACK();
438
439  state.writing = false;
440  state.writecb = null;
441  state.length -= state.writelen;
442  state.writelen = 0;
443
444  if (er)
445    onwriteError(stream, state, sync, er, cb);
446  else {
447    // Check if we're actually ready to finish, but don't emit yet
448    var finished = needFinish(state) || stream.destroyed;
449
450    if (!finished &&
451        !state.corked &&
452        !state.bufferProcessing &&
453        state.bufferedRequest) {
454      clearBuffer(stream, state);
455    }
456
457    if (sync) {
458      // It is a common case that the callback passed to .write() is always
459      // the same. In that case, we do not schedule a new nextTick(), but rather
460      // just increase a counter, to improve performance and avoid memory
461      // allocations.
462      if (state.afterWriteTickInfo !== null &&
463          state.afterWriteTickInfo.cb === cb) {
464        state.afterWriteTickInfo.count++;
465      } else {
466        state.afterWriteTickInfo = { count: 1, cb, stream, state };
467        process.nextTick(afterWriteTick, state.afterWriteTickInfo);
468      }
469    } else {
470      afterWrite(stream, state, 1, cb);
471    }
472  }
473}
474
475function afterWriteTick({ stream, state, count, cb }) {
476  state.afterWriteTickInfo = null;
477  return afterWrite(stream, state, count, cb);
478}
479
480function afterWrite(stream, state, count, cb) {
481  const needDrain = !state.ending && !stream.destroyed && state.length === 0 &&
482    state.needDrain;
483  if (needDrain) {
484    state.needDrain = false;
485    stream.emit('drain');
486  }
487
488  while (count-- > 0) {
489    state.pendingcb--;
490    cb();
491  }
492
493  finishMaybe(stream, state);
494}
495
496// If there's something in the buffer waiting, then process it
497function clearBuffer(stream, state) {
498  state.bufferProcessing = true;
499  var entry = state.bufferedRequest;
500
501  if (stream._writev && entry && entry.next) {
502    // Fast case, write everything using _writev()
503    var l = state.bufferedRequestCount;
504    var buffer = new Array(l);
505    var holder = state.corkedRequestsFree;
506    holder.entry = entry;
507
508    var count = 0;
509    var allBuffers = true;
510    while (entry) {
511      buffer[count] = entry;
512      if (entry.encoding !== 'buffer')
513        allBuffers = false;
514      entry = entry.next;
515      count += 1;
516    }
517    buffer.allBuffers = allBuffers;
518
519    doWrite(stream, state, true, state.length, buffer, '', holder.finish);
520
521    // doWrite is almost always async, defer these to save a bit of time
522    // as the hot path ends with doWrite
523    state.pendingcb++;
524    state.lastBufferedRequest = null;
525    if (holder.next) {
526      state.corkedRequestsFree = holder.next;
527      holder.next = null;
528    } else {
529      var corkReq = { next: null, entry: null, finish: undefined };
530      corkReq.finish = onCorkedFinish.bind(undefined, corkReq, state);
531      state.corkedRequestsFree = corkReq;
532    }
533    state.bufferedRequestCount = 0;
534  } else {
535    // Slow case, write chunks one-by-one
536    while (entry) {
537      var chunk = entry.chunk;
538      var encoding = entry.encoding;
539      var cb = entry.callback;
540      var len = state.objectMode ? 1 : chunk.length;
541
542      doWrite(stream, state, false, len, chunk, encoding, cb);
543      entry = entry.next;
544      state.bufferedRequestCount--;
545      // If we didn't call the onwrite immediately, then
546      // it means that we need to wait until it does.
547      // also, that means that the chunk and cb are currently
548      // being processed, so move the buffer counter past them.
549      if (state.writing) {
550        break;
551      }
552    }
553
554    if (entry === null)
555      state.lastBufferedRequest = null;
556  }
557
558  state.bufferedRequest = entry;
559  state.bufferProcessing = false;
560}
561
562Writable.prototype._write = function(chunk, encoding, cb) {
563  if (this._writev) {
564    this._writev([{ chunk, encoding }], cb);
565  } else {
566    cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
567  }
568};
569
570Writable.prototype._writev = null;
571
572Writable.prototype.end = function(chunk, encoding, cb) {
573  const state = this._writableState;
574
575  if (typeof chunk === 'function') {
576    cb = chunk;
577    chunk = null;
578    encoding = null;
579  } else if (typeof encoding === 'function') {
580    cb = encoding;
581    encoding = null;
582  }
583
584  if (chunk !== null && chunk !== undefined)
585    this.write(chunk, encoding);
586
587  // .end() fully uncorks
588  if (state.corked) {
589    state.corked = 1;
590    this.uncork();
591  }
592
593  // Ignore unnecessary end() calls.
594  if (!state.ending)
595    endWritable(this, state, cb);
596
597  return this;
598};
599
600function needFinish(state) {
601  return (state.ending &&
602          state.length === 0 &&
603          state.bufferedRequest === null &&
604          !state.finished &&
605          !state.writing);
606}
607
608function callFinal(stream, state) {
609  stream._final((err) => {
610    state.pendingcb--;
611    if (err) {
612      errorOrDestroy(stream, err);
613    }
614    state.prefinished = true;
615    stream.emit('prefinish');
616    finishMaybe(stream, state);
617  });
618}
619
620function prefinish(stream, state) {
621  if (!state.prefinished && !state.finalCalled) {
622    if (typeof stream._final === 'function' && !state.destroyed) {
623      state.pendingcb++;
624      state.finalCalled = true;
625      process.nextTick(callFinal, stream, state);
626    } else {
627      state.prefinished = true;
628      stream.emit('prefinish');
629    }
630  }
631}
632
633function finishMaybe(stream, state) {
634  const need = needFinish(state);
635  if (need) {
636    prefinish(stream, state);
637    if (state.pendingcb === 0) {
638      state.finished = true;
639      stream.emit('finish');
640
641      if (state.autoDestroy) {
642        // In case of duplex streams we need a way to detect
643        // if the readable side is ready for autoDestroy as well
644        const rState = stream._readableState;
645        if (!rState || (rState.autoDestroy && rState.endEmitted)) {
646          stream.destroy();
647        }
648      }
649    }
650  }
651  return need;
652}
653
654function endWritable(stream, state, cb) {
655  state.ending = true;
656  finishMaybe(stream, state);
657  if (cb) {
658    if (state.finished)
659      process.nextTick(cb);
660    else
661      stream.once('finish', cb);
662  }
663  state.ended = true;
664  stream.writable = false;
665}
666
667function onCorkedFinish(corkReq, state, err) {
668  var entry = corkReq.entry;
669  corkReq.entry = null;
670  while (entry) {
671    var cb = entry.callback;
672    state.pendingcb--;
673    cb(err);
674    entry = entry.next;
675  }
676
677  // Reuse the free corkReq.
678  state.corkedRequestsFree.next = corkReq;
679}
680
681ObjectDefineProperties(Writable.prototype, {
682
683  destroyed: {
684    get() {
685      return this._writableState ? this._writableState.destroyed : false;
686    },
687    set(value) {
688      // Backward compatibility, the user is explicitly managing destroyed
689      if (this._writableState) {
690        this._writableState.destroyed = value;
691      }
692    }
693  },
694
695  writableFinished: {
696    get() {
697      return this._writableState ? this._writableState.finished : false;
698    }
699  },
700
701  writableObjectMode: {
702    get() {
703      return this._writableState ? this._writableState.objectMode : false;
704    }
705  },
706
707  writableBuffer: {
708    get() {
709      return this._writableState && this._writableState.getBuffer();
710    }
711  },
712
713  writableEnded: {
714    get() {
715      return this._writableState ? this._writableState.ending : false;
716    }
717  },
718
719  writableHighWaterMark: {
720    get() {
721      return this._writableState && this._writableState.highWaterMark;
722    }
723  },
724
725  writableCorked: {
726    get() {
727      return this._writableState ? this._writableState.corked : 0;
728    }
729  },
730
731  writableLength: {
732    get() {
733      return this._writableState && this._writableState.length;
734    }
735  }
736});
737
738Writable.prototype.destroy = destroyImpl.destroy;
739Writable.prototype._undestroy = destroyImpl.undestroy;
740Writable.prototype._destroy = function(err, cb) {
741  cb(err);
742};
743
744Writable.prototype[EE.captureRejectionSymbol] = function(err) {
745  this.destroy(err);
746};
747