Source: lib/gridfs-stream/download.js

  1. var stream = require('stream'),
  2. util = require('util');
  3. module.exports = GridFSBucketReadStream;
  4. /**
  5. * A readable stream that enables you to read buffers from GridFS.
  6. *
  7. * Do not instantiate this class directly. Use `openDownloadStream()` instead.
  8. *
  9. * @class
  10. * @param {Collection} chunks Handle for chunks collection
  11. * @param {Collection} files Handle for files collection
  12. * @param {Object} readPreference The read preference to use
  13. * @param {Object} filter The query to use to find the file document
  14. * @param {Object} [options=null] Optional settings.
  15. * @param {Number} [options.sort=null] Optional sort for the file find query
  16. * @param {Number} [options.skip=null] Optional skip for the file find query
  17. * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from
  18. * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before
  19. * @fires GridFSBucketReadStream#error
  20. * @fires GridFSBucketReadStream#file
  21. * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance.
  22. */
  23. function GridFSBucketReadStream(chunks, files, readPreference, filter, options) {
  24. this.s = {
  25. bytesRead: 0,
  26. chunks: chunks,
  27. cursor: null,
  28. expected: 0,
  29. files: files,
  30. filter: filter,
  31. init: false,
  32. expectedEnd: 0,
  33. file: null,
  34. options: options,
  35. readPreference: readPreference
  36. };
  37. stream.Readable.call(this);
  38. }
  39. util.inherits(GridFSBucketReadStream, stream.Readable);
  40. /**
  41. * An error occurred
  42. *
  43. * @event GridFSBucketReadStream#error
  44. * @type {Error}
  45. */
  46. /**
  47. * Fires when the stream loaded the file document corresponding to the
  48. * provided id.
  49. *
  50. * @event GridFSBucketReadStream#file
  51. * @type {object}
  52. */
  53. /**
  54. * Emitted when a chunk of data is available to be consumed.
  55. *
  56. * @event GridFSBucketReadStream#data
  57. * @type {object}
  58. */
  59. /**
  60. * Fired when the stream is exhausted (no more data events).
  61. *
  62. * @event GridFSBucketReadStream#end
  63. * @type {object}
  64. */
  65. /**
  66. * Fired when the stream is exhausted and the underlying cursor is killed
  67. *
  68. * @event GridFSBucketReadStream#close
  69. * @type {object}
  70. */
  71. /**
  72. * Reads from the cursor and pushes to the stream.
  73. * @method
  74. */
  75. GridFSBucketReadStream.prototype._read = function() {
  76. var _this = this;
  77. if (this.destroyed) {
  78. return;
  79. }
  80. waitForFile(_this, function() {
  81. doRead(_this);
  82. });
  83. };
  84. /**
  85. * Sets the 0-based offset in bytes to start streaming from. Throws
  86. * an error if this stream has entered flowing mode
  87. * (e.g. if you've already called `on('data')`)
  88. * @method
  89. * @param {Number} start Offset in bytes to start reading at
  90. * @return {GridFSBucketReadStream}
  91. */
  92. GridFSBucketReadStream.prototype.start = function(start) {
  93. throwIfInitialized(this);
  94. this.s.options.start = start;
  95. return this;
  96. };
  97. /**
  98. * Sets the 0-based offset in bytes to start streaming from. Throws
  99. * an error if this stream has entered flowing mode
  100. * (e.g. if you've already called `on('data')`)
  101. * @method
  102. * @param {Number} end Offset in bytes to stop reading at
  103. * @return {GridFSBucketReadStream}
  104. */
  105. GridFSBucketReadStream.prototype.end = function(end) {
  106. throwIfInitialized(this);
  107. this.s.options.end = end;
  108. return this;
  109. };
  110. /**
  111. * Marks this stream as aborted (will never push another `data` event)
  112. * and kills the underlying cursor. Will emit the 'end' event, and then
  113. * the 'close' event once the cursor is successfully killed.
  114. *
  115. * @method
  116. * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred.
  117. * @fires GridFSBucketWriteStream#close
  118. * @fires GridFSBucketWriteStream#end
  119. */
  120. GridFSBucketReadStream.prototype.abort = function(callback) {
  121. var _this = this;
  122. this.push(null);
  123. this.destroyed = true;
  124. if (this.s.cursor) {
  125. this.s.cursor.close(function(error) {
  126. _this.emit('close');
  127. callback && callback(error);
  128. });
  129. } else {
  130. if (!this.s.init) {
  131. // If not initialized, fire close event because we will never
  132. // get a cursor
  133. _this.emit('close');
  134. }
  135. callback && callback();
  136. }
  137. };
  138. /**
  139. * @ignore
  140. */
  141. function throwIfInitialized(self) {
  142. if (self.s.init) {
  143. throw new Error('You cannot change options after the stream has entered' +
  144. 'flowing mode!');
  145. }
  146. }
  147. /**
  148. * @ignore
  149. */
  150. function doRead(_this) {
  151. if (_this.destroyed) {
  152. return;
  153. }
  154. _this.s.cursor.next(function(error, doc) {
  155. if (_this.destroyed) {
  156. return;
  157. }
  158. if (error) {
  159. return __handleError(_this, error);
  160. }
  161. if (!doc) {
  162. _this.push(null);
  163. return _this.s.cursor.close(function(error) {
  164. if (error) {
  165. return __handleError(_this, error);
  166. }
  167. _this.emit('close');
  168. });
  169. }
  170. var bytesRemaining = _this.s.file.length - _this.s.bytesRead;
  171. var expectedN = _this.s.expected++;
  172. var expectedLength = Math.min(_this.s.file.chunkSize,
  173. bytesRemaining);
  174. if (doc.n > expectedN) {
  175. var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n +
  176. ', expected: ' + expectedN;
  177. return __handleError(_this, new Error(errmsg));
  178. }
  179. if (doc.n < expectedN) {
  180. errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n +
  181. ', expected: ' + expectedN;
  182. return __handleError(_this, new Error(errmsg));
  183. }
  184. var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;
  185. if (buf.length !== expectedLength) {
  186. if (bytesRemaining <= 0) {
  187. errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;
  188. return __handleError(_this, new Error(errmsg));
  189. }
  190. errmsg = 'ChunkIsWrongSize: Got unexpected length: ' +
  191. buf.length + ', expected: ' + expectedLength;
  192. return __handleError(_this, new Error(errmsg));
  193. }
  194. _this.s.bytesRead += buf.length;
  195. if (buf.length === 0) {
  196. return _this.push(null);
  197. }
  198. var sliceStart = null;
  199. var sliceEnd = null;
  200. if (_this.s.bytesToSkip != null) {
  201. sliceStart = _this.s.bytesToSkip;
  202. _this.s.bytesToSkip = 0;
  203. }
  204. if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) {
  205. sliceEnd = _this.s.bytesToTrim;
  206. }
  207. // If the remaining amount of data left is < chunkSize read the right amount of data
  208. if (_this.s.options.end && (
  209. (_this.s.options.end - _this.s.bytesToSkip) < buf.length
  210. )) {
  211. sliceEnd = (_this.s.options.end - _this.s.bytesToSkip);
  212. }
  213. if (sliceStart != null || sliceEnd != null) {
  214. buf = buf.slice(sliceStart || 0, sliceEnd || buf.length);
  215. }
  216. _this.push(buf);
  217. })
  218. }
  219. /**
  220. * @ignore
  221. */
  222. function init(self) {
  223. var findOneOptions = {};
  224. if (self.s.readPreference) {
  225. findOneOptions.readPreference = self.s.readPreference;
  226. }
  227. if (self.s.options && self.s.options.sort) {
  228. findOneOptions.sort = self.s.options.sort;
  229. }
  230. if (self.s.options && self.s.options.skip) {
  231. findOneOptions.skip = self.s.options.skip;
  232. }
  233. self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) {
  234. if (error) {
  235. return __handleError(self, error);
  236. }
  237. if (!doc) {
  238. var identifier = self.s.filter._id ?
  239. self.s.filter._id.toString() : self.s.filter.filename;
  240. var errmsg = 'FileNotFound: file ' + identifier + ' was not found';
  241. var err = new Error(errmsg);
  242. err.code = 'ENOENT';
  243. return __handleError(self, err);
  244. }
  245. // If document is empty, kill the stream immediately and don't
  246. // execute any reads
  247. if (doc.length <= 0) {
  248. self.push(null);
  249. return;
  250. }
  251. if (self.destroyed) {
  252. // If user destroys the stream before we have a cursor, wait
  253. // until the query is done to say we're 'closed' because we can't
  254. // cancel a query.
  255. self.emit('close');
  256. return;
  257. }
  258. self.s.bytesToSkip = handleStartOption(self, doc, self.s.options);
  259. var filter = { files_id: doc._id };
  260. // Currently (MongoDB 3.4.4) skip function does not support the index,
  261. // it needs to retrieve all the documents first and then skip them. (CS-25811)
  262. // As work around we use $gte on the "n" field.
  263. if (self.s.options && self.s.options.start != null){
  264. var skip = Math.floor(self.s.options.start / doc.chunkSize);
  265. if (skip > 0){
  266. filter["n"] = {"$gte": skip};
  267. }
  268. }
  269. self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 });
  270. if (self.s.readPreference) {
  271. self.s.cursor.setReadPreference(self.s.readPreference);
  272. }
  273. self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
  274. self.s.file = doc;
  275. self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor,
  276. self.s.options);
  277. self.emit('file', doc);
  278. });
  279. }
  280. /**
  281. * @ignore
  282. */
  283. function waitForFile(_this, callback) {
  284. if (_this.s.file) {
  285. return callback();
  286. }
  287. if (!_this.s.init) {
  288. init(_this);
  289. _this.s.init = true;
  290. }
  291. _this.once('file', function() {
  292. callback();
  293. })
  294. }
  295. /**
  296. * @ignore
  297. */
  298. function handleStartOption(stream, doc, options) {
  299. if (options && options.start != null) {
  300. if (options.start > doc.length) {
  301. throw new Error('Stream start (' + options.start + ') must not be ' +
  302. 'more than the length of the file (' + doc.length +')');
  303. }
  304. if (options.start < 0) {
  305. throw new Error('Stream start (' + options.start + ') must not be ' +
  306. 'negative');
  307. }
  308. if (options.end != null && options.end < options.start) {
  309. throw new Error('Stream start (' + options.start + ') must not be ' +
  310. 'greater than stream end (' + options.end + ')');
  311. }
  312. stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) *
  313. doc.chunkSize;
  314. stream.s.expected = Math.floor(options.start / doc.chunkSize);
  315. return options.start - stream.s.bytesRead;
  316. }
  317. }
  318. /**
  319. * @ignore
  320. */
  321. function handleEndOption(stream, doc, cursor, options) {
  322. if (options && options.end != null) {
  323. if (options.end > doc.length) {
  324. throw new Error('Stream end (' + options.end + ') must not be ' +
  325. 'more than the length of the file (' + doc.length +')')
  326. }
  327. if (options.start < 0) {
  328. throw new Error('Stream end (' + options.end + ') must not be ' +
  329. 'negative');
  330. }
  331. var start = options.start != null ?
  332. Math.floor(options.start / doc.chunkSize) :
  333. 0;
  334. cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
  335. stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
  336. return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) -
  337. options.end;
  338. }
  339. }
  340. /**
  341. * @ignore
  342. */
  343. function __handleError(_this, error) {
  344. _this.emit('error', error);
  345. }