transform.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. // a transform stream is a readable/writable stream where you do
  22. // something with the data. Sometimes it's called a "filter",
  23. // but that's not a great name for it, since that implies a thing where
  24. // some bits pass through, and others are simply ignored. (That would
  25. // be a valid example of a transform, of course.)
  26. //
  27. // While the output is causally related to the input, it's not a
  28. // necessarily symmetric or synchronous transformation. For example,
  29. // a zlib stream might take multiple plain-text writes(), and then
  30. // emit a single compressed chunk some time in the future.
  31. //
  32. // Here's how this works:
  33. //
  34. // The Transform stream has all the aspects of the readable and writable
  35. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  36. // internally, and returns false if there's a lot of pending writes
  37. // buffered up. When you call read(), that calls _read(n) until
  38. // there's enough pending readable data buffered up.
  39. //
  40. // In a transform stream, the written data is placed in a buffer. When
  41. // _read(n) is called, it transforms the queued up data, calling the
  42. // buffered _write cb's as it consumes chunks. If consuming a single
  43. // written chunk would result in multiple output chunks, then the first
  44. // outputted bit calls the readcb, and subsequent chunks just go into
  45. // the read buffer, and will cause it to emit 'readable' if necessary.
  46. //
  47. // This way, back-pressure is actually determined by the reading side,
  48. // since _read has to be called to start processing a new chunk. However,
  49. // a pathological inflate type of transform can cause excessive buffering
  50. // here. For example, imagine a stream where every byte of input is
  51. // interpreted as an integer from 0-255, and then results in that many
  52. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  53. // 1kb of data being output. In this case, you could write a very small
  54. // amount of input, and end up with a very large amount of output. In
  55. // such a pathological inflating mechanism, there'd be no way to tell
  56. // the system to stop doing the transform. A single 4MB write could
  57. // cause the system to run out of memory.
  58. //
  59. // However, even in such a pathological case, only a single written chunk
  60. // would be consumed, and then the rest would wait (un-transformed) until
  61. // the results of the previous transformed chunk were consumed.
  62. 'use strict'
  63. const { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')
  64. module.exports = Transform
  65. const { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes
  66. const Duplex = require('./duplex')
  67. const { getHighWaterMark } = require('./state')
  68. ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)
  69. ObjectSetPrototypeOf(Transform, Duplex)
  70. const kCallback = Symbol('kCallback')
  71. function Transform(options) {
  72. if (!(this instanceof Transform)) return new Transform(options)
  73. // TODO (ronag): This should preferably always be
  74. // applied but would be semver-major. Or even better;
  75. // make Transform a Readable with the Writable interface.
  76. const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null
  77. if (readableHighWaterMark === 0) {
  78. // A Duplex will buffer both on the writable and readable side while
  79. // a Transform just wants to buffer hwm number of elements. To avoid
  80. // buffering twice we disable buffering on the writable side.
  81. options = {
  82. ...options,
  83. highWaterMark: null,
  84. readableHighWaterMark,
  85. // TODO (ronag): 0 is not optimal since we have
  86. // a "bug" where we check needDrain before calling _write and not after.
  87. // Refs: https://github.com/nodejs/node/pull/32887
  88. // Refs: https://github.com/nodejs/node/pull/35941
  89. writableHighWaterMark: options.writableHighWaterMark || 0
  90. }
  91. }
  92. Duplex.call(this, options)
  93. // We have implemented the _read method, and done the other things
  94. // that Readable wants before the first _read call, so unset the
  95. // sync guard flag.
  96. this._readableState.sync = false
  97. this[kCallback] = null
  98. if (options) {
  99. if (typeof options.transform === 'function') this._transform = options.transform
  100. if (typeof options.flush === 'function') this._flush = options.flush
  101. }
  102. // When the writable side finishes, then flush out anything remaining.
  103. // Backwards compat. Some Transform streams incorrectly implement _final
  104. // instead of or in addition to _flush. By using 'prefinish' instead of
  105. // implementing _final we continue supporting this unfortunate use case.
  106. this.on('prefinish', prefinish)
  107. }
  108. function final(cb) {
  109. if (typeof this._flush === 'function' && !this.destroyed) {
  110. this._flush((er, data) => {
  111. if (er) {
  112. if (cb) {
  113. cb(er)
  114. } else {
  115. this.destroy(er)
  116. }
  117. return
  118. }
  119. if (data != null) {
  120. this.push(data)
  121. }
  122. this.push(null)
  123. if (cb) {
  124. cb()
  125. }
  126. })
  127. } else {
  128. this.push(null)
  129. if (cb) {
  130. cb()
  131. }
  132. }
  133. }
  134. function prefinish() {
  135. if (this._final !== final) {
  136. final.call(this)
  137. }
  138. }
  139. Transform.prototype._final = final
  140. Transform.prototype._transform = function (chunk, encoding, callback) {
  141. throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')
  142. }
  143. Transform.prototype._write = function (chunk, encoding, callback) {
  144. const rState = this._readableState
  145. const wState = this._writableState
  146. const length = rState.length
  147. this._transform(chunk, encoding, (err, val) => {
  148. if (err) {
  149. callback(err)
  150. return
  151. }
  152. if (val != null) {
  153. this.push(val)
  154. }
  155. if (
  156. wState.ended ||
  157. // Backwards compat.
  158. length === rState.length ||
  159. // Backwards compat.
  160. rState.length < rState.highWaterMark
  161. ) {
  162. callback()
  163. } else {
  164. this[kCallback] = callback
  165. }
  166. })
  167. }
  168. Transform.prototype._read = function () {
  169. if (this[kCallback]) {
  170. const callback = this[kCallback]
  171. this[kCallback] = null
  172. callback()
  173. }
  174. }