managed-upload.js 11 KB

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