managed-upload.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // var debug = require('debug')('ali-oss:multipart');
  2. const util = require('util');
  3. const path = require('path');
  4. const mime = require('mime');
  5. const copy = require('copy-to');
  6. const { isBlob } = require('../common/utils/isBlob');
  7. const { isFile } = require('../common/utils/isFile');
  8. const { isArray } = require('../common/utils/isArray');
  9. const { isBuffer } = require('../common/utils/isBuffer');
  10. const proto = exports;
  11. /**
  12. * Multipart operations
  13. */
  14. /**
  15. * Upload a file to OSS using multipart uploads
  16. * @param {String} name
  17. * @param {String|File|Buffer} file
  18. * @param {Object} options
  19. * {Object} options.callback The callback parameter is composed of a JSON string encoded in Base64
  20. * {String} options.callback.url the OSS sends a callback request to this URL
  21. * {String} options.callback.host The host header value for initiating callback requests
  22. * {String} options.callback.body The value of the request body when a callback is initiated
  23. * {String} options.callback.contentType The Content-Type of the callback requests initiatiated
  24. * {Object} options.callback.customValue Custom parameters are a map of key-values, e.g:
  25. * customValue = {
  26. * key1: 'value1',
  27. * key2: 'value2'
  28. * }
  29. */
  30. proto.multipartUpload = async function multipartUpload(name, file, options = {}) {
  31. this.resetCancelFlag();
  32. if (options.checkpoint && options.checkpoint.uploadId) {
  33. if (file && isFile(file)) options.checkpoint.file = file;
  34. return await this._resumeMultipart(options.checkpoint, options);
  35. }
  36. const minPartSize = 100 * 1024;
  37. if (!options.mime) {
  38. if (isFile(file)) {
  39. options.mime = mime.getType(path.extname(file.name));
  40. } else if (isBlob(file)) {
  41. options.mime = file.type;
  42. } else if (isBuffer(file)) {
  43. options.mime = '';
  44. } else {
  45. options.mime = mime.getType(path.extname(file));
  46. }
  47. }
  48. options.headers = options.headers || {};
  49. this._convertMetaToHeaders(options.meta, options.headers);
  50. const fileSize = await this._getFileSize(file);
  51. if (fileSize < minPartSize) {
  52. options.contentLength = fileSize;
  53. const result = await this.put(name, file, options);
  54. if (options && options.progress) {
  55. await options.progress(1);
  56. }
  57. const ret = {
  58. res: result.res,
  59. bucket: this.options.bucket,
  60. name,
  61. etag: result.res.headers.etag
  62. };
  63. if ((options.headers && options.headers['x-oss-callback']) || options.callback) {
  64. ret.data = result.data;
  65. }
  66. return ret;
  67. }
  68. if (options.partSize && !(parseInt(options.partSize, 10) === options.partSize)) {
  69. throw new Error('partSize must be int number');
  70. }
  71. if (options.partSize && options.partSize < minPartSize) {
  72. throw new Error(`partSize must not be smaller than ${minPartSize}`);
  73. }
  74. const initResult = await this.initMultipartUpload(name, options);
  75. const { uploadId } = initResult;
  76. const partSize = this._getPartSize(fileSize, options.partSize);
  77. const checkpoint = {
  78. file,
  79. name,
  80. fileSize,
  81. partSize,
  82. uploadId,
  83. doneParts: []
  84. };
  85. if (options && options.progress) {
  86. await options.progress(0, checkpoint, initResult.res);
  87. }
  88. return await this._resumeMultipart(checkpoint, options);
  89. };
  90. /*
  91. * Resume multipart upload from checkpoint. The checkpoint will be
  92. * updated after each successful part upload.
  93. * @param {Object} checkpoint the checkpoint
  94. * @param {Object} options
  95. */
  96. proto._resumeMultipart = async function _resumeMultipart(checkpoint, options) {
  97. const that = this;
  98. if (this.isCancel()) {
  99. throw this._makeCancelEvent();
  100. }
  101. const {
  102. file, fileSize, partSize, uploadId, doneParts, name
  103. } = checkpoint;
  104. const internalDoneParts = [];
  105. if (doneParts.length > 0) {
  106. copy(doneParts).to(internalDoneParts);
  107. }
  108. const partOffs = this._divideParts(fileSize, partSize);
  109. const numParts = partOffs.length;
  110. let multipartFinish = false;
  111. let uploadPartJob = function uploadPartJob(self, partNo) {
  112. // eslint-disable-next-line no-async-promise-executor
  113. return new Promise(async (resolve, reject) => {
  114. try {
  115. if (!self.isCancel()) {
  116. const pi = partOffs[partNo - 1];
  117. const stream = self._createStream(file, pi.start, pi.end);
  118. const data = {
  119. stream,
  120. size: pi.end - pi.start
  121. };
  122. if (isArray(self.multipartUploadStreams)) {
  123. self.multipartUploadStreams.push(stream);
  124. } else {
  125. self.multipartUploadStreams = [stream];
  126. }
  127. const removeStreamFromMultipartUploadStreams = function () {
  128. if (!stream.destroyed) {
  129. stream.destroy();
  130. }
  131. const index = self.multipartUploadStreams.indexOf(stream);
  132. if (index !== -1) {
  133. self.multipartUploadStreams.splice(index, 1);
  134. }
  135. };
  136. stream.on('close', removeStreamFromMultipartUploadStreams);
  137. stream.on('end', removeStreamFromMultipartUploadStreams);
  138. stream.on('error', removeStreamFromMultipartUploadStreams);
  139. let result;
  140. try {
  141. result = await self._uploadPart(name, uploadId, partNo, data);
  142. } catch (error) {
  143. removeStreamFromMultipartUploadStreams();
  144. if (error.status === 404) {
  145. throw self._makeAbortEvent();
  146. }
  147. throw error;
  148. }
  149. if (!self.isCancel() && !multipartFinish) {
  150. checkpoint.doneParts.push({
  151. number: partNo,
  152. etag: result.res.headers.etag
  153. });
  154. if (options.progress) {
  155. await options.progress(doneParts.length / numParts, checkpoint, result.res);
  156. }
  157. resolve({
  158. number: partNo,
  159. etag: result.res.headers.etag
  160. });
  161. } else {
  162. resolve();
  163. }
  164. } else {
  165. resolve();
  166. }
  167. } catch (err) {
  168. const tempErr = new Error();
  169. tempErr.name = err.name;
  170. tempErr.message = err.message;
  171. tempErr.stack = err.stack;
  172. tempErr.partNum = partNo;
  173. copy(err).to(tempErr);
  174. reject(tempErr);
  175. }
  176. });
  177. };
  178. const all = Array.from(new Array(numParts), (x, i) => i + 1);
  179. const done = internalDoneParts.map(p => p.number);
  180. const todo = all.filter(p => done.indexOf(p) < 0);
  181. const defaultParallel = 5;
  182. const parallel = options.parallel || defaultParallel;
  183. // upload in parallel
  184. const jobErr = await this._parallel(todo, parallel, value => new Promise((resolve, reject) => {
  185. uploadPartJob(that, value).then((result) => {
  186. if (result) {
  187. internalDoneParts.push(result);
  188. }
  189. resolve();
  190. }).catch((err) => {
  191. reject(err);
  192. });
  193. }));
  194. multipartFinish = true;
  195. const abortEvent = jobErr.find(err => err.name === 'abort');
  196. if (abortEvent) throw abortEvent;
  197. if (this.isCancel()) {
  198. uploadPartJob = null;
  199. throw this._makeCancelEvent();
  200. }
  201. if (jobErr && jobErr.length > 0) {
  202. jobErr[0].message = `Failed to upload some parts with error: ${jobErr[0].toString()} part_num: ${jobErr[0].partNum}`;
  203. throw jobErr[0];
  204. }
  205. return await this.completeMultipartUpload(name, uploadId, internalDoneParts, options);
  206. };
  207. /**
  208. * Get file size
  209. */
  210. proto._getFileSize = async function _getFileSize(file) {
  211. if (isBuffer(file)) {
  212. return file.length;
  213. } else if (isBlob(file) || isFile(file)) {
  214. return file.size;
  215. }
  216. throw new Error('_getFileSize requires Buffer/File/Blob.');
  217. };
  218. /*
  219. * Readable stream for Web File
  220. */
  221. const { Readable } = require('stream');
  222. function WebFileReadStream(file, options) {
  223. if (!(this instanceof WebFileReadStream)) {
  224. return new WebFileReadStream(file, options);
  225. }
  226. Readable.call(this, options);
  227. this.file = file;
  228. this.reader = new FileReader();
  229. this.start = 0;
  230. this.finish = false;
  231. this.fileBuffer = null;
  232. }
  233. util.inherits(WebFileReadStream, Readable);
  234. WebFileReadStream.prototype.readFileAndPush = function readFileAndPush(size) {
  235. if (this.fileBuffer) {
  236. let pushRet = true;
  237. while (pushRet && this.fileBuffer && this.start < this.fileBuffer.length) {
  238. const { start } = this;
  239. let end = start + size;
  240. end = end > this.fileBuffer.length ? this.fileBuffer.length : end;
  241. this.start = end;
  242. pushRet = this.push(this.fileBuffer.slice(start, end));
  243. }
  244. }
  245. };
  246. WebFileReadStream.prototype._read = function _read(size) {
  247. if ((this.file && this.start >= this.file.size) ||
  248. (this.fileBuffer && this.start >= this.fileBuffer.length) ||
  249. (this.finish) || (this.start === 0 && !this.file)) {
  250. if (!this.finish) {
  251. this.fileBuffer = null;
  252. this.finish = true;
  253. }
  254. this.push(null);
  255. return;
  256. }
  257. const defaultReadSize = 16 * 1024;
  258. size = size || defaultReadSize;
  259. const that = this;
  260. this.reader.onload = function onload(e) {
  261. that.fileBuffer = Buffer.from(new Uint8Array(e.target.result));
  262. that.file = null;
  263. that.readFileAndPush(size);
  264. };
  265. if (this.start === 0) {
  266. this.reader.readAsArrayBuffer(this.file);
  267. } else {
  268. this.readFileAndPush(size);
  269. }
  270. };
  271. proto._createStream = function _createStream(file, start, end) {
  272. if (isBlob(file) || isFile(file)) {
  273. return new WebFileReadStream(file.slice(start, end));
  274. } else if (isBuffer(file)) {
  275. // we can't use Readable.from() since it is only support in Node v10
  276. const iterable = file.subarray(start, end);
  277. return new Readable({
  278. read() {
  279. this.push(iterable);
  280. this.push(null);
  281. }
  282. });
  283. }
  284. throw new Error('_createStream requires Buffer/File/Blob.');
  285. };
  286. proto._getPartSize = function _getPartSize(fileSize, partSize) {
  287. const maxNumParts = 10 * 1000;
  288. const defaultPartSize = 1 * 1024 * 1024;
  289. if (!partSize) partSize = defaultPartSize;
  290. const safeSize = Math.ceil(fileSize / maxNumParts);
  291. if (partSize < safeSize) {
  292. partSize = safeSize;
  293. console.warn(`partSize has been set to ${partSize}, because the partSize you provided causes partNumber to be greater than 10,000`);
  294. }
  295. return partSize;
  296. };
  297. proto._divideParts = function _divideParts(fileSize, partSize) {
  298. const numParts = Math.ceil(fileSize / partSize);
  299. const partOffs = [];
  300. for (let i = 0; i < numParts; i++) {
  301. const start = partSize * i;
  302. const end = Math.min(start + partSize, fileSize);
  303. partOffs.push({
  304. start,
  305. end
  306. });
  307. }
  308. return partOffs;
  309. };