upload.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 write_concern_1 = require("./../write_concern");
  8. /**
  9. * A writable stream that enables you to write buffers to GridFS.
  10. *
  11. * Do not instantiate this class directly. Use `openUploadStream()` instead.
  12. * @public
  13. */
  14. class GridFSBucketWriteStream extends stream_1.Writable {
  15. /**
  16. * @param bucket - Handle for this stream's corresponding bucket
  17. * @param filename - The value of the 'filename' key in the files doc
  18. * @param options - Optional settings.
  19. * @internal
  20. */
  21. constructor(bucket, filename, options) {
  22. super();
  23. options = 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).then(() => {
  48. this.bucket.s.checkedIndexes = true;
  49. this.bucket.emit('index');
  50. }, () => null);
  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. /**
  59. * Places this write stream into an aborted state (all future writes fail)
  60. * and deletes all chunks that have already been written.
  61. */
  62. async abort() {
  63. if (this.state.streamEnd) {
  64. // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
  65. throw new error_1.MongoAPIError('Cannot abort a stream that has already completed');
  66. }
  67. if (this.state.aborted) {
  68. // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
  69. throw new error_1.MongoAPIError('Cannot call abort() on a stream twice');
  70. }
  71. this.state.aborted = true;
  72. await this.chunks.deleteMany({ files_id: this.id });
  73. }
  74. end(chunkOrCallback, encodingOrCallback, callback) {
  75. const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback;
  76. const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback;
  77. callback =
  78. typeof chunkOrCallback === 'function'
  79. ? chunkOrCallback
  80. : typeof encodingOrCallback === 'function'
  81. ? encodingOrCallback
  82. : callback;
  83. if (this.state.streamEnd || checkAborted(this, callback))
  84. return this;
  85. this.state.streamEnd = true;
  86. if (callback) {
  87. this.once(GridFSBucketWriteStream.FINISH, (result) => {
  88. if (callback)
  89. callback(undefined, result);
  90. });
  91. }
  92. if (!chunk) {
  93. waitForIndexes(this, () => !!writeRemnant(this));
  94. return this;
  95. }
  96. this.write(chunk, encoding, () => {
  97. writeRemnant(this);
  98. });
  99. return this;
  100. }
  101. }
  102. /** @event */
  103. GridFSBucketWriteStream.CLOSE = 'close';
  104. /** @event */
  105. GridFSBucketWriteStream.ERROR = 'error';
  106. /**
  107. * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB.
  108. * @event
  109. */
  110. GridFSBucketWriteStream.FINISH = 'finish';
  111. exports.GridFSBucketWriteStream = GridFSBucketWriteStream;
  112. function __handleError(stream, error, callback) {
  113. if (stream.state.errored) {
  114. return;
  115. }
  116. stream.state.errored = true;
  117. if (callback) {
  118. return callback(error);
  119. }
  120. stream.emit(GridFSBucketWriteStream.ERROR, error);
  121. }
  122. function createChunkDoc(filesId, n, data) {
  123. return {
  124. _id: new bson_1.ObjectId(),
  125. files_id: filesId,
  126. n,
  127. data
  128. };
  129. }
  130. async function checkChunksIndex(stream) {
  131. const index = { files_id: 1, n: 1 };
  132. let indexes;
  133. try {
  134. indexes = await stream.chunks.listIndexes().toArray();
  135. }
  136. catch (error) {
  137. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  138. indexes = [];
  139. }
  140. else {
  141. throw error;
  142. }
  143. }
  144. const hasChunksIndex = !!indexes.find(index => {
  145. const keys = Object.keys(index.key);
  146. if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
  147. return true;
  148. }
  149. return false;
  150. });
  151. if (!hasChunksIndex) {
  152. await stream.chunks.createIndex(index, {
  153. ...stream.writeConcern,
  154. background: true,
  155. unique: true
  156. });
  157. }
  158. }
  159. function checkDone(stream, callback) {
  160. if (stream.done)
  161. return true;
  162. if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) {
  163. // Set done so we do not trigger duplicate createFilesDoc
  164. stream.done = true;
  165. // Create a new files doc
  166. const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata);
  167. if (checkAborted(stream, callback)) {
  168. return false;
  169. }
  170. stream.files.insertOne(filesDoc, { writeConcern: stream.writeConcern }).then(() => {
  171. stream.emit(GridFSBucketWriteStream.FINISH, filesDoc);
  172. stream.emit(GridFSBucketWriteStream.CLOSE);
  173. }, error => {
  174. return __handleError(stream, error, callback);
  175. });
  176. return true;
  177. }
  178. return false;
  179. }
  180. async function checkIndexes(stream) {
  181. const doc = await stream.files.findOne({}, { projection: { _id: 1 } });
  182. if (doc != null) {
  183. // If at least one document exists assume the collection has the required index
  184. return;
  185. }
  186. const index = { filename: 1, uploadDate: 1 };
  187. let indexes;
  188. try {
  189. indexes = await stream.files.listIndexes().toArray();
  190. }
  191. catch (error) {
  192. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  193. indexes = [];
  194. }
  195. else {
  196. throw error;
  197. }
  198. }
  199. const hasFileIndex = !!indexes.find(index => {
  200. const keys = Object.keys(index.key);
  201. if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
  202. return true;
  203. }
  204. return false;
  205. });
  206. if (!hasFileIndex) {
  207. await stream.files.createIndex(index, { background: false });
  208. }
  209. await checkChunksIndex(stream);
  210. }
  211. function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) {
  212. const ret = {
  213. _id,
  214. length,
  215. chunkSize,
  216. uploadDate: new Date(),
  217. filename
  218. };
  219. if (contentType) {
  220. ret.contentType = contentType;
  221. }
  222. if (aliases) {
  223. ret.aliases = aliases;
  224. }
  225. if (metadata) {
  226. ret.metadata = metadata;
  227. }
  228. return ret;
  229. }
  230. function doWrite(stream, chunk, encoding, callback) {
  231. if (checkAborted(stream, callback)) {
  232. return false;
  233. }
  234. const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
  235. stream.length += inputBuf.length;
  236. // Input is small enough to fit in our buffer
  237. if (stream.pos + inputBuf.length < stream.chunkSizeBytes) {
  238. inputBuf.copy(stream.bufToStore, stream.pos);
  239. stream.pos += inputBuf.length;
  240. callback && callback();
  241. // Note that we reverse the typical semantics of write's return value
  242. // to be compatible with node's `.pipe()` function.
  243. // True means client can keep writing.
  244. return true;
  245. }
  246. // Otherwise, buffer is too big for current chunk, so we need to flush
  247. // to MongoDB.
  248. let inputBufRemaining = inputBuf.length;
  249. let spaceRemaining = stream.chunkSizeBytes - stream.pos;
  250. let numToCopy = Math.min(spaceRemaining, inputBuf.length);
  251. let outstandingRequests = 0;
  252. while (inputBufRemaining > 0) {
  253. const inputBufPos = inputBuf.length - inputBufRemaining;
  254. inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy);
  255. stream.pos += numToCopy;
  256. spaceRemaining -= numToCopy;
  257. let doc;
  258. if (spaceRemaining === 0) {
  259. doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore));
  260. ++stream.state.outstandingRequests;
  261. ++outstandingRequests;
  262. if (checkAborted(stream, callback)) {
  263. return false;
  264. }
  265. stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => {
  266. --stream.state.outstandingRequests;
  267. --outstandingRequests;
  268. if (!outstandingRequests) {
  269. stream.emit('drain', doc);
  270. callback && callback();
  271. checkDone(stream);
  272. }
  273. }, error => {
  274. return __handleError(stream, error);
  275. });
  276. spaceRemaining = stream.chunkSizeBytes;
  277. stream.pos = 0;
  278. ++stream.n;
  279. }
  280. inputBufRemaining -= numToCopy;
  281. numToCopy = Math.min(spaceRemaining, inputBufRemaining);
  282. }
  283. // Note that we reverse the typical semantics of write's return value
  284. // to be compatible with node's `.pipe()` function.
  285. // False means the client should wait for the 'drain' event.
  286. return false;
  287. }
  288. function waitForIndexes(stream, callback) {
  289. if (stream.bucket.s.checkedIndexes) {
  290. return callback(false);
  291. }
  292. stream.bucket.once('index', () => {
  293. callback(true);
  294. });
  295. return true;
  296. }
  297. function writeRemnant(stream, callback) {
  298. // Buffer is empty, so don't bother to insert
  299. if (stream.pos === 0) {
  300. return checkDone(stream, callback);
  301. }
  302. ++stream.state.outstandingRequests;
  303. // Create a new buffer to make sure the buffer isn't bigger than it needs
  304. // to be.
  305. const remnant = Buffer.alloc(stream.pos);
  306. stream.bufToStore.copy(remnant, 0, 0, stream.pos);
  307. const doc = createChunkDoc(stream.id, stream.n, remnant);
  308. // If the stream was aborted, do not write remnant
  309. if (checkAborted(stream, callback)) {
  310. return false;
  311. }
  312. stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => {
  313. --stream.state.outstandingRequests;
  314. checkDone(stream);
  315. }, error => {
  316. return __handleError(stream, error);
  317. });
  318. return true;
  319. }
  320. function checkAborted(stream, callback) {
  321. if (stream.state.aborted) {
  322. if (typeof callback === 'function') {
  323. // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError
  324. callback(new error_1.MongoAPIError('Stream has been aborted'));
  325. }
  326. return true;
  327. }
  328. return false;
  329. }
  330. //# sourceMappingURL=upload.js.map