Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

download.js 10KB

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