upload.js 14 KB

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