upload.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.GridFSBucketWriteStream = void 0;
  4. const stream_1 = require("stream");
  5. const bson_1 = require("../bson");
  6. const error_1 = require("../error");
  7. const utils_1 = require("../utils");
  8. const write_concern_1 = require("./../write_concern");
  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. * @public
  14. */
  15. class GridFSBucketWriteStream extends stream_1.Writable {
  16. /** @internal
  17. * @param bucket - Handle for this stream's corresponding bucket
  18. * @param filename - The value of the 'filename' key in the files doc
  19. * @param options - Optional settings.
  20. */
  21. constructor(bucket, filename, options) {
  22. super();
  23. options = options !== null && options !== void 0 ? options : {};
  24. this.bucket = bucket;
  25. this.chunks = bucket.s._chunksCollection;
  26. this.filename = filename;
  27. this.files = bucket.s._filesCollection;
  28. this.options = options;
  29. this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern;
  30. // Signals the write is all done
  31. this.done = false;
  32. this.id = options.id ? options.id : new bson_1.ObjectId();
  33. // properly inherit the default chunksize from parent
  34. this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes;
  35. this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
  36. this.length = 0;
  37. this.n = 0;
  38. this.pos = 0;
  39. this.state = {
  40. streamEnd: false,
  41. outstandingRequests: 0,
  42. errored: false,
  43. aborted: false
  44. };
  45. if (!this.bucket.s.calledOpenUploadStream) {
  46. this.bucket.s.calledOpenUploadStream = true;
  47. checkIndexes(this, () => {
  48. this.bucket.s.checkedIndexes = true;
  49. this.bucket.emit('index');
  50. });
  51. }
  52. }
  53. write(chunk, encodingOrCallback, callback) {
  54. const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback;
  55. callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;
  56. return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback));
  57. }
  58. abort(callback) {
  59. return (0, utils_1.maybePromise)(callback, callback => {
  60. if (this.state.streamEnd) {
  61. // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
  62. return callback(new error_1.MongoAPIError('Cannot abort a stream that has already completed'));
  63. }
  64. if (this.state.aborted) {
  65. // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
  66. return callback(new error_1.MongoAPIError('Cannot call abort() on a stream twice'));
  67. }
  68. this.state.aborted = true;
  69. this.chunks.deleteMany({ files_id: this.id }, error => callback(error));
  70. });
  71. }
  72. end(chunkOrCallback, encodingOrCallback, callback) {
  73. const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback;
  74. const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback;
  75. callback =
  76. typeof chunkOrCallback === 'function'
  77. ? chunkOrCallback
  78. : typeof encodingOrCallback === 'function'
  79. ? encodingOrCallback
  80. : callback;
  81. if (this.state.streamEnd || checkAborted(this, callback))
  82. return this;
  83. this.state.streamEnd = true;
  84. if (callback) {
  85. this.once(GridFSBucketWriteStream.FINISH, (result) => {
  86. if (callback)
  87. callback(undefined, result);
  88. });
  89. }
  90. if (!chunk) {
  91. waitForIndexes(this, () => !!writeRemnant(this));
  92. return this;
  93. }
  94. this.write(chunk, encoding, () => {
  95. writeRemnant(this);
  96. });
  97. return this;
  98. }
  99. }
  100. exports.GridFSBucketWriteStream = GridFSBucketWriteStream;
  101. /** @event */
  102. GridFSBucketWriteStream.CLOSE = 'close';
  103. /** @event */
  104. GridFSBucketWriteStream.ERROR = 'error';
  105. /**
  106. * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB.
  107. * @event
  108. */
  109. GridFSBucketWriteStream.FINISH = 'finish';
  110. function __handleError(stream, error, callback) {
  111. if (stream.state.errored) {
  112. return;
  113. }
  114. stream.state.errored = true;
  115. if (callback) {
  116. return callback(error);
  117. }
  118. stream.emit(GridFSBucketWriteStream.ERROR, error);
  119. }
  120. function createChunkDoc(filesId, n, data) {
  121. return {
  122. _id: new bson_1.ObjectId(),
  123. files_id: filesId,
  124. n,
  125. data
  126. };
  127. }
  128. function checkChunksIndex(stream, callback) {
  129. stream.chunks.listIndexes().toArray((error, indexes) => {
  130. let index;
  131. if (error) {
  132. // Collection doesn't exist so create index
  133. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  134. index = { files_id: 1, n: 1 };
  135. stream.chunks.createIndex(index, { background: false, unique: true }, error => {
  136. if (error) {
  137. return callback(error);
  138. }
  139. callback();
  140. });
  141. return;
  142. }
  143. return callback(error);
  144. }
  145. let hasChunksIndex = false;
  146. if (indexes) {
  147. indexes.forEach((index) => {
  148. if (index.key) {
  149. const keys = Object.keys(index.key);
  150. if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
  151. hasChunksIndex = true;
  152. }
  153. }
  154. });
  155. }
  156. if (hasChunksIndex) {
  157. callback();
  158. }
  159. else {
  160. index = { files_id: 1, n: 1 };
  161. const writeConcernOptions = getWriteOptions(stream);
  162. stream.chunks.createIndex(index, {
  163. ...writeConcernOptions,
  164. background: true,
  165. unique: true
  166. }, callback);
  167. }
  168. });
  169. }
  170. function checkDone(stream, callback) {
  171. if (stream.done)
  172. return true;
  173. if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) {
  174. // Set done so we do not trigger duplicate createFilesDoc
  175. stream.done = true;
  176. // Create a new files doc
  177. const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata);
  178. if (checkAborted(stream, callback)) {
  179. return false;
  180. }
  181. stream.files.insertOne(filesDoc, getWriteOptions(stream), (error) => {
  182. if (error) {
  183. return __handleError(stream, error, callback);
  184. }
  185. stream.emit(GridFSBucketWriteStream.FINISH, filesDoc);
  186. stream.emit(GridFSBucketWriteStream.CLOSE);
  187. });
  188. return true;
  189. }
  190. return false;
  191. }
  192. function checkIndexes(stream, callback) {
  193. stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => {
  194. if (error) {
  195. return callback(error);
  196. }
  197. if (doc) {
  198. return callback();
  199. }
  200. stream.files.listIndexes().toArray((error, indexes) => {
  201. let index;
  202. if (error) {
  203. // Collection doesn't exist so create index
  204. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  205. index = { filename: 1, uploadDate: 1 };
  206. stream.files.createIndex(index, { background: false }, (error) => {
  207. if (error) {
  208. return callback(error);
  209. }
  210. checkChunksIndex(stream, callback);
  211. });
  212. return;
  213. }
  214. return callback(error);
  215. }
  216. let hasFileIndex = false;
  217. if (indexes) {
  218. indexes.forEach((index) => {
  219. const keys = Object.keys(index.key);
  220. if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
  221. hasFileIndex = true;
  222. }
  223. });
  224. }
  225. if (hasFileIndex) {
  226. checkChunksIndex(stream, callback);
  227. }
  228. else {
  229. index = { filename: 1, uploadDate: 1 };
  230. const writeConcernOptions = getWriteOptions(stream);
  231. stream.files.createIndex(index, {
  232. ...writeConcernOptions,
  233. background: false
  234. }, (error) => {
  235. if (error) {
  236. return callback(error);
  237. }
  238. checkChunksIndex(stream, callback);
  239. });
  240. }
  241. });
  242. });
  243. }
  244. function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) {
  245. const ret = {
  246. _id,
  247. length,
  248. chunkSize,
  249. uploadDate: new Date(),
  250. filename
  251. };
  252. if (contentType) {
  253. ret.contentType = contentType;
  254. }
  255. if (aliases) {
  256. ret.aliases = aliases;
  257. }
  258. if (metadata) {
  259. ret.metadata = metadata;
  260. }
  261. return ret;
  262. }
  263. function doWrite(stream, chunk, encoding, callback) {
  264. if (checkAborted(stream, callback)) {
  265. return false;
  266. }
  267. const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
  268. stream.length += inputBuf.length;
  269. // Input is small enough to fit in our buffer
  270. if (stream.pos + inputBuf.length < stream.chunkSizeBytes) {
  271. inputBuf.copy(stream.bufToStore, stream.pos);
  272. stream.pos += inputBuf.length;
  273. callback && callback();
  274. // Note that we reverse the typical semantics of write's return value
  275. // to be compatible with node's `.pipe()` function.
  276. // True means client can keep writing.
  277. return true;
  278. }
  279. // Otherwise, buffer is too big for current chunk, so we need to flush
  280. // to MongoDB.
  281. let inputBufRemaining = inputBuf.length;
  282. let spaceRemaining = stream.chunkSizeBytes - stream.pos;
  283. let numToCopy = Math.min(spaceRemaining, inputBuf.length);
  284. let outstandingRequests = 0;
  285. while (inputBufRemaining > 0) {
  286. const inputBufPos = inputBuf.length - inputBufRemaining;
  287. inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy);
  288. stream.pos += numToCopy;
  289. spaceRemaining -= numToCopy;
  290. let doc;
  291. if (spaceRemaining === 0) {
  292. doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore));
  293. ++stream.state.outstandingRequests;
  294. ++outstandingRequests;
  295. if (checkAborted(stream, callback)) {
  296. return false;
  297. }
  298. stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => {
  299. if (error) {
  300. return __handleError(stream, error);
  301. }
  302. --stream.state.outstandingRequests;
  303. --outstandingRequests;
  304. if (!outstandingRequests) {
  305. stream.emit('drain', doc);
  306. callback && callback();
  307. checkDone(stream);
  308. }
  309. });
  310. spaceRemaining = stream.chunkSizeBytes;
  311. stream.pos = 0;
  312. ++stream.n;
  313. }
  314. inputBufRemaining -= numToCopy;
  315. numToCopy = Math.min(spaceRemaining, inputBufRemaining);
  316. }
  317. // Note that we reverse the typical semantics of write's return value
  318. // to be compatible with node's `.pipe()` function.
  319. // False means the client should wait for the 'drain' event.
  320. return false;
  321. }
  322. function getWriteOptions(stream) {
  323. const obj = {};
  324. if (stream.writeConcern) {
  325. obj.writeConcern = {
  326. w: stream.writeConcern.w,
  327. wtimeout: stream.writeConcern.wtimeout,
  328. j: stream.writeConcern.j
  329. };
  330. }
  331. return obj;
  332. }
  333. function waitForIndexes(stream, callback) {
  334. if (stream.bucket.s.checkedIndexes) {
  335. return callback(false);
  336. }
  337. stream.bucket.once('index', () => {
  338. callback(true);
  339. });
  340. return true;
  341. }
  342. function writeRemnant(stream, callback) {
  343. // Buffer is empty, so don't bother to insert
  344. if (stream.pos === 0) {
  345. return checkDone(stream, callback);
  346. }
  347. ++stream.state.outstandingRequests;
  348. // Create a new buffer to make sure the buffer isn't bigger than it needs
  349. // to be.
  350. const remnant = Buffer.alloc(stream.pos);
  351. stream.bufToStore.copy(remnant, 0, 0, stream.pos);
  352. const doc = createChunkDoc(stream.id, stream.n, remnant);
  353. // If the stream was aborted, do not write remnant
  354. if (checkAborted(stream, callback)) {
  355. return false;
  356. }
  357. stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => {
  358. if (error) {
  359. return __handleError(stream, error);
  360. }
  361. --stream.state.outstandingRequests;
  362. checkDone(stream);
  363. });
  364. return true;
  365. }
  366. function checkAborted(stream, callback) {
  367. if (stream.state.aborted) {
  368. if (typeof callback === 'function') {
  369. // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError
  370. callback(new error_1.MongoAPIError('Stream has been aborted'));
  371. }
  372. return true;
  373. }
  374. return false;
  375. }
  376. //# sourceMappingURL=upload.js.map