_stream_transform.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. module.exports = Transform;
  63. var Duplex = require('./_stream_duplex');
  64. /*<replacement>*/
  65. var util = require('core-util-is');
  66. util.inherits = require('inherits');
  67. /*</replacement>*/
  68. util.inherits(Transform, Duplex);
  69. function TransformState(options, stream) {
  70. this.afterTransform = function(er, data) {
  71. return afterTransform(stream, er, data);
  72. };
  73. this.needTransform = false;
  74. this.transforming = false;
  75. this.writecb = null;
  76. this.writechunk = null;
  77. }
  78. function afterTransform(stream, er, data) {
  79. var ts = stream._transformState;
  80. ts.transforming = false;
  81. var cb = ts.writecb;
  82. if (!cb)
  83. return stream.emit('error', new Error('no writecb in Transform class'));
  84. ts.writechunk = null;
  85. ts.writecb = null;
  86. if (data !== null && data !== undefined)
  87. stream.push(data);
  88. if (cb)
  89. cb(er);
  90. var rs = stream._readableState;
  91. rs.reading = false;
  92. if (rs.needReadable || rs.length < rs.highWaterMark) {
  93. stream._read(rs.highWaterMark);
  94. }
  95. }
  96. function Transform(options) {
  97. if (!(this instanceof Transform))
  98. return new Transform(options);
  99. Duplex.call(this, options);
  100. var ts = this._transformState = new TransformState(options, this);
  101. // when the writable side finishes, then flush out anything remaining.
  102. var stream = this;
  103. // start out asking for a readable event once data is transformed.
  104. this._readableState.needReadable = true;
  105. // we have implemented the _read method, and done the other things
  106. // that Readable wants before the first _read call, so unset the
  107. // sync guard flag.
  108. this._readableState.sync = false;
  109. this.once('finish', function() {
  110. if ('function' === typeof this._flush)
  111. this._flush(function(er) {
  112. done(stream, er);
  113. });
  114. else
  115. done(stream);
  116. });
  117. }
  118. Transform.prototype.push = function(chunk, encoding) {
  119. this._transformState.needTransform = false;
  120. return Duplex.prototype.push.call(this, chunk, encoding);
  121. };
  122. // This is the part where you do stuff!
  123. // override this function in implementation classes.
  124. // 'chunk' is an input chunk.
  125. //
  126. // Call `push(newChunk)` to pass along transformed output
  127. // to the readable side. You may call 'push' zero or more times.
  128. //
  129. // Call `cb(err)` when you are done with this chunk. If you pass
  130. // an error, then that'll put the hurt on the whole operation. If you
  131. // never call cb(), then you'll never get another chunk.
  132. Transform.prototype._transform = function(chunk, encoding, cb) {
  133. throw new Error('not implemented');
  134. };
  135. Transform.prototype._write = function(chunk, encoding, cb) {
  136. var ts = this._transformState;
  137. ts.writecb = cb;
  138. ts.writechunk = chunk;
  139. ts.writeencoding = encoding;
  140. if (!ts.transforming) {
  141. var rs = this._readableState;
  142. if (ts.needTransform ||
  143. rs.needReadable ||
  144. rs.length < rs.highWaterMark)
  145. this._read(rs.highWaterMark);
  146. }
  147. };
  148. // Doesn't matter what the args are here.
  149. // _transform does all the work.
  150. // That we got here means that the readable side wants more data.
  151. Transform.prototype._read = function(n) {
  152. var ts = this._transformState;
  153. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  154. ts.transforming = true;
  155. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  156. } else {
  157. // mark that we need a transform, so that any data that comes in
  158. // will get processed, now that we've asked for it.
  159. ts.needTransform = true;
  160. }
  161. };
  162. function done(stream, er) {
  163. if (er)
  164. return stream.emit('error', er);
  165. // if there's nothing in the write buffer, then that means
  166. // that nothing more will ever be provided
  167. var ws = stream._writableState;
  168. var rs = stream._readableState;
  169. var ts = stream._transformState;
  170. if (ws.length)
  171. throw new Error('calling transform done when ws.length != 0');
  172. if (ts.transforming)
  173. throw new Error('calling transform done when still transforming');
  174. return stream.push(null);
  175. }