upload.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. 'use strict';
  2. const MONGODB_ERROR_CODES = require('../error_codes').MONGODB_ERROR_CODES;
  3. const core = require('../core');
  4. const crypto = require('crypto');
  5. const stream = require('stream');
  6. const util = require('util');
  7. const Buffer = require('safe-buffer').Buffer;
  8. const deprecateOptions = require('../utils').deprecateOptions;
  9. /**
  10. * A writable stream that enables you to write buffers to GridFS.
  11. *
  12. * Do not instantiate this class directly. Use `openUploadStream()` instead.
  13. *
  14. * @class
  15. * @extends external:Writable
  16. * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket
  17. * @param {string} filename The value of the 'filename' key in the files doc
  18. * @param {object} [options] Optional settings.
  19. * @param {string|number|object} [options.id] Custom file id for the GridFS file.
  20. * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes
  21. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  22. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  23. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  24. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  25. * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
  26. * @fires GridFSBucketWriteStream#error
  27. * @fires GridFSBucketWriteStream#finish
  28. */
  29. const GridFSBucketWriteStream = deprecateOptions(
  30. {
  31. name: 'GridFSBucketWriteStream',
  32. deprecatedOptions: ['disableMD5'],
  33. optionsIndex: 2
  34. },
  35. function(bucket, filename, options) {
  36. options = options || {};
  37. stream.Writable.call(this, options);
  38. this.bucket = bucket;
  39. this.chunks = bucket.s._chunksCollection;
  40. this.filename = filename;
  41. this.files = bucket.s._filesCollection;
  42. this.options = options;
  43. // Signals the write is all done
  44. this.done = false;
  45. this.id = options.id ? options.id : core.BSON.ObjectId();
  46. this.chunkSizeBytes = this.options.chunkSizeBytes;
  47. this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
  48. this.length = 0;
  49. this.md5 = !options.disableMD5 && crypto.createHash('md5');
  50. this.n = 0;
  51. this.pos = 0;
  52. this.state = {
  53. streamEnd: false,
  54. outstandingRequests: 0,
  55. errored: false,
  56. aborted: false,
  57. promiseLibrary: this.bucket.s.promiseLibrary
  58. };
  59. if (!this.bucket.s.calledOpenUploadStream) {
  60. this.bucket.s.calledOpenUploadStream = true;
  61. var _this = this;
  62. checkIndexes(this, function() {
  63. _this.bucket.s.checkedIndexes = true;
  64. _this.bucket.emit('index');
  65. });
  66. }
  67. }
  68. );
  69. util.inherits(GridFSBucketWriteStream, stream.Writable);
  70. /**
  71. * An error occurred
  72. *
  73. * @event GridFSBucketWriteStream#error
  74. * @type {Error}
  75. */
  76. /**
  77. * `end()` was called and the write stream successfully wrote the file
  78. * metadata and all the chunks to MongoDB.
  79. *
  80. * @event GridFSBucketWriteStream#finish
  81. * @type {object}
  82. */
  83. /**
  84. * Write a buffer to the stream.
  85. *
  86. * @method
  87. * @param {Buffer} chunk Buffer to write
  88. * @param {String} encoding Optional encoding for the buffer
  89. * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
  90. * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise.
  91. */
  92. GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) {
  93. var _this = this;
  94. return waitForIndexes(this, function() {
  95. return doWrite(_this, chunk, encoding, callback);
  96. });
  97. };
  98. /**
  99. * Places this write stream into an aborted state (all future writes fail)
  100. * and deletes all chunks that have already been written.
  101. *
  102. * @method
  103. * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred
  104. * @return {Promise} if no callback specified
  105. */
  106. GridFSBucketWriteStream.prototype.abort = function(callback) {
  107. if (this.state.streamEnd) {
  108. var error = new Error('Cannot abort a stream that has already completed');
  109. if (typeof callback === 'function') {
  110. return callback(error);
  111. }
  112. return this.state.promiseLibrary.reject(error);
  113. }
  114. if (this.state.aborted) {
  115. error = new Error('Cannot call abort() on a stream twice');
  116. if (typeof callback === 'function') {
  117. return callback(error);
  118. }
  119. return this.state.promiseLibrary.reject(error);
  120. }
  121. this.state.aborted = true;
  122. this.chunks.deleteMany({ files_id: this.id }, function(error) {
  123. if (typeof callback === 'function') callback(error);
  124. });
  125. };
  126. /**
  127. * Tells the stream that no more data will be coming in. The stream will
  128. * persist the remaining data to MongoDB, write the files document, and
  129. * then emit a 'finish' event.
  130. *
  131. * @method
  132. * @param {Buffer} chunk Buffer to write
  133. * @param {String} encoding Optional encoding for the buffer
  134. * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB
  135. */
  136. GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) {
  137. var _this = this;
  138. if (typeof chunk === 'function') {
  139. (callback = chunk), (chunk = null), (encoding = null);
  140. } else if (typeof encoding === 'function') {
  141. (callback = encoding), (encoding = null);
  142. }
  143. if (checkAborted(this, callback)) {
  144. return;
  145. }
  146. this.state.streamEnd = true;
  147. if (callback) {
  148. this.once('finish', function(result) {
  149. callback(null, result);
  150. });
  151. }
  152. if (!chunk) {
  153. waitForIndexes(this, function() {
  154. writeRemnant(_this);
  155. });
  156. return;
  157. }
  158. this.write(chunk, encoding, function() {
  159. writeRemnant(_this);
  160. });
  161. };
  162. /**
  163. * @ignore
  164. */
  165. function __handleError(_this, error, callback) {
  166. if (_this.state.errored) {
  167. return;
  168. }
  169. _this.state.errored = true;
  170. if (callback) {
  171. return callback(error);
  172. }
  173. _this.emit('error', error);
  174. }
  175. /**
  176. * @ignore
  177. */
  178. function createChunkDoc(filesId, n, data) {
  179. return {
  180. _id: core.BSON.ObjectId(),
  181. files_id: filesId,
  182. n: n,
  183. data: data
  184. };
  185. }
  186. /**
  187. * @ignore
  188. */
  189. function checkChunksIndex(_this, callback) {
  190. _this.chunks.listIndexes().toArray(function(error, indexes) {
  191. if (error) {
  192. // Collection doesn't exist so create index
  193. if (error.code === MONGODB_ERROR_CODES.NamespaceNotFound) {
  194. var index = { files_id: 1, n: 1 };
  195. _this.chunks.createIndex(index, { background: false, unique: true }, function(error) {
  196. if (error) {
  197. return callback(error);
  198. }
  199. callback();
  200. });
  201. return;
  202. }
  203. return callback(error);
  204. }
  205. var hasChunksIndex = false;
  206. indexes.forEach(function(index) {
  207. if (index.key) {
  208. var keys = Object.keys(index.key);
  209. if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
  210. hasChunksIndex = true;
  211. }
  212. }
  213. });
  214. if (hasChunksIndex) {
  215. callback();
  216. } else {
  217. index = { files_id: 1, n: 1 };
  218. var indexOptions = getWriteOptions(_this);
  219. indexOptions.background = false;
  220. indexOptions.unique = true;
  221. _this.chunks.createIndex(index, indexOptions, function(error) {
  222. if (error) {
  223. return callback(error);
  224. }
  225. callback();
  226. });
  227. }
  228. });
  229. }
  230. /**
  231. * @ignore
  232. */
  233. function checkDone(_this, callback) {
  234. if (_this.done) return true;
  235. if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) {
  236. // Set done so we dont' trigger duplicate createFilesDoc
  237. _this.done = true;
  238. // Create a new files doc
  239. var filesDoc = createFilesDoc(
  240. _this.id,
  241. _this.length,
  242. _this.chunkSizeBytes,
  243. _this.md5 && _this.md5.digest('hex'),
  244. _this.filename,
  245. _this.options.contentType,
  246. _this.options.aliases,
  247. _this.options.metadata
  248. );
  249. if (checkAborted(_this, callback)) {
  250. return false;
  251. }
  252. _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) {
  253. if (error) {
  254. return __handleError(_this, error, callback);
  255. }
  256. _this.emit('finish', filesDoc);
  257. _this.emit('close');
  258. });
  259. return true;
  260. }
  261. return false;
  262. }
  263. /**
  264. * @ignore
  265. */
  266. function checkIndexes(_this, callback) {
  267. _this.files.findOne({}, { _id: 1 }, function(error, doc) {
  268. if (error) {
  269. return callback(error);
  270. }
  271. if (doc) {
  272. return callback();
  273. }
  274. _this.files.listIndexes().toArray(function(error, indexes) {
  275. if (error) {
  276. // Collection doesn't exist so create index
  277. if (error.code === MONGODB_ERROR_CODES.NamespaceNotFound) {
  278. var index = { filename: 1, uploadDate: 1 };
  279. _this.files.createIndex(index, { background: false }, function(error) {
  280. if (error) {
  281. return callback(error);
  282. }
  283. checkChunksIndex(_this, callback);
  284. });
  285. return;
  286. }
  287. return callback(error);
  288. }
  289. var hasFileIndex = false;
  290. indexes.forEach(function(index) {
  291. var keys = Object.keys(index.key);
  292. if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
  293. hasFileIndex = true;
  294. }
  295. });
  296. if (hasFileIndex) {
  297. checkChunksIndex(_this, callback);
  298. } else {
  299. index = { filename: 1, uploadDate: 1 };
  300. var indexOptions = getWriteOptions(_this);
  301. indexOptions.background = false;
  302. _this.files.createIndex(index, indexOptions, function(error) {
  303. if (error) {
  304. return callback(error);
  305. }
  306. checkChunksIndex(_this, callback);
  307. });
  308. }
  309. });
  310. });
  311. }
  312. /**
  313. * @ignore
  314. */
  315. function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) {
  316. var ret = {
  317. _id: _id,
  318. length: length,
  319. chunkSize: chunkSize,
  320. uploadDate: new Date(),
  321. filename: filename
  322. };
  323. if (md5) {
  324. ret.md5 = md5;
  325. }
  326. if (contentType) {
  327. ret.contentType = contentType;
  328. }
  329. if (aliases) {
  330. ret.aliases = aliases;
  331. }
  332. if (metadata) {
  333. ret.metadata = metadata;
  334. }
  335. return ret;
  336. }
  337. /**
  338. * @ignore
  339. */
  340. function doWrite(_this, chunk, encoding, callback) {
  341. if (checkAborted(_this, callback)) {
  342. return false;
  343. }
  344. var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
  345. _this.length += inputBuf.length;
  346. // Input is small enough to fit in our buffer
  347. if (_this.pos + inputBuf.length < _this.chunkSizeBytes) {
  348. inputBuf.copy(_this.bufToStore, _this.pos);
  349. _this.pos += inputBuf.length;
  350. callback && callback();
  351. // Note that we reverse the typical semantics of write's return value
  352. // to be compatible with node's `.pipe()` function.
  353. // True means client can keep writing.
  354. return true;
  355. }
  356. // Otherwise, buffer is too big for current chunk, so we need to flush
  357. // to MongoDB.
  358. var inputBufRemaining = inputBuf.length;
  359. var spaceRemaining = _this.chunkSizeBytes - _this.pos;
  360. var numToCopy = Math.min(spaceRemaining, inputBuf.length);
  361. var outstandingRequests = 0;
  362. while (inputBufRemaining > 0) {
  363. var inputBufPos = inputBuf.length - inputBufRemaining;
  364. inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy);
  365. _this.pos += numToCopy;
  366. spaceRemaining -= numToCopy;
  367. if (spaceRemaining === 0) {
  368. if (_this.md5) {
  369. _this.md5.update(_this.bufToStore);
  370. }
  371. var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore));
  372. ++_this.state.outstandingRequests;
  373. ++outstandingRequests;
  374. if (checkAborted(_this, callback)) {
  375. return false;
  376. }
  377. _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
  378. if (error) {
  379. return __handleError(_this, error);
  380. }
  381. --_this.state.outstandingRequests;
  382. --outstandingRequests;
  383. if (!outstandingRequests) {
  384. _this.emit('drain', doc);
  385. callback && callback();
  386. checkDone(_this);
  387. }
  388. });
  389. spaceRemaining = _this.chunkSizeBytes;
  390. _this.pos = 0;
  391. ++_this.n;
  392. }
  393. inputBufRemaining -= numToCopy;
  394. numToCopy = Math.min(spaceRemaining, inputBufRemaining);
  395. }
  396. // Note that we reverse the typical semantics of write's return value
  397. // to be compatible with node's `.pipe()` function.
  398. // False means the client should wait for the 'drain' event.
  399. return false;
  400. }
  401. /**
  402. * @ignore
  403. */
  404. function getWriteOptions(_this) {
  405. var obj = {};
  406. if (_this.options.writeConcern) {
  407. obj.w = _this.options.writeConcern.w;
  408. obj.wtimeout = _this.options.writeConcern.wtimeout;
  409. obj.j = _this.options.writeConcern.j;
  410. }
  411. return obj;
  412. }
  413. /**
  414. * @ignore
  415. */
  416. function waitForIndexes(_this, callback) {
  417. if (_this.bucket.s.checkedIndexes) {
  418. return callback(false);
  419. }
  420. _this.bucket.once('index', function() {
  421. callback(true);
  422. });
  423. return true;
  424. }
  425. /**
  426. * @ignore
  427. */
  428. function writeRemnant(_this, callback) {
  429. // Buffer is empty, so don't bother to insert
  430. if (_this.pos === 0) {
  431. return checkDone(_this, callback);
  432. }
  433. ++_this.state.outstandingRequests;
  434. // Create a new buffer to make sure the buffer isn't bigger than it needs
  435. // to be.
  436. var remnant = Buffer.alloc(_this.pos);
  437. _this.bufToStore.copy(remnant, 0, 0, _this.pos);
  438. if (_this.md5) {
  439. _this.md5.update(remnant);
  440. }
  441. var doc = createChunkDoc(_this.id, _this.n, remnant);
  442. // If the stream was aborted, do not write remnant
  443. if (checkAborted(_this, callback)) {
  444. return false;
  445. }
  446. _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
  447. if (error) {
  448. return __handleError(_this, error);
  449. }
  450. --_this.state.outstandingRequests;
  451. checkDone(_this);
  452. });
  453. }
  454. /**
  455. * @ignore
  456. */
  457. function checkAborted(_this, callback) {
  458. if (_this.state.aborted) {
  459. if (typeof callback === 'function') {
  460. callback(new Error('this stream has been aborted'));
  461. }
  462. return true;
  463. }
  464. return false;
  465. }
  466. module.exports = GridFSBucketWriteStream;