managed-upload.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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, options);
  133. } catch (error) {
  134. removeStreamFromMultipartUploadStreams();
  135. if (error.status === 404) {
  136. throw self._makeAbortEvent();
  137. }
  138. throw error;
  139. }
  140. if (!self.isCancel()) {
  141. doneParts.push({
  142. number: partNo,
  143. etag: result.res.headers.etag
  144. });
  145. checkpoint.doneParts = doneParts;
  146. if (options.progress) {
  147. await options.progress(doneParts.length / (numParts + 1), checkpoint, result.res);
  148. }
  149. }
  150. }
  151. resolve();
  152. } catch (err) {
  153. err.partNum = partNo;
  154. reject(err);
  155. }
  156. });
  157. },
  158. this.options.retryMax,
  159. {
  160. errorHandler: err => {
  161. const _errHandle = _err => {
  162. const statusErr = [-1, -2].includes(_err.status);
  163. const requestErrorRetryHandle = this.options.requestErrorRetryHandle || (() => true);
  164. return statusErr && requestErrorRetryHandle(_err);
  165. };
  166. return !!_errHandle(err);
  167. }
  168. }
  169. );
  170. const all = Array.from(new Array(numParts), (x, i) => i + 1);
  171. const done = doneParts.map(p => p.number);
  172. const todo = all.filter(p => done.indexOf(p) < 0);
  173. const defaultParallel = 5;
  174. const parallel = options.parallel || defaultParallel;
  175. if (this.checkBrowserAndVersion('Internet Explorer', '10') || parallel === 1) {
  176. for (let i = 0; i < todo.length; i++) {
  177. if (this.isCancel()) {
  178. throw this._makeCancelEvent();
  179. }
  180. /* eslint no-await-in-loop: [0] */
  181. await uploadPartJob(this, todo[i]);
  182. }
  183. } else {
  184. // upload in parallel
  185. const jobErr = await this._parallel(todo, parallel, value => {
  186. return new Promise((resolve, reject) => {
  187. uploadPartJob(that, value)
  188. .then(() => {
  189. resolve();
  190. })
  191. .catch(reject);
  192. });
  193. });
  194. const abortEvent = jobErr.find(err => err.name === 'abort');
  195. if (abortEvent) throw abortEvent;
  196. if (this.isCancel()) {
  197. uploadPartJob = null;
  198. throw this._makeCancelEvent();
  199. }
  200. if (jobErr && jobErr.length > 0) {
  201. jobErr[0].message = `Failed to upload some parts with error: ${jobErr[0].toString()} part_num: ${
  202. jobErr[0].partNum
  203. }`;
  204. throw jobErr[0];
  205. }
  206. }
  207. return await this.completeMultipartUpload(name, uploadId, doneParts, options);
  208. };
  209. /**
  210. * Get file size
  211. */
  212. proto._getFileSize = async function _getFileSize(file) {
  213. if (isBuffer(file)) {
  214. return file.length;
  215. } else if (isFile(file)) {
  216. return file.size;
  217. } else if (is.string(file)) {
  218. const stat = await this._statFile(file);
  219. return stat.size;
  220. }
  221. throw new Error('_getFileSize requires Buffer/File/String.');
  222. };
  223. /*
  224. * Readable stream for Web File
  225. */
  226. const { Readable } = require('stream');
  227. function WebFileReadStream(file, options) {
  228. if (!(this instanceof WebFileReadStream)) {
  229. return new WebFileReadStream(file, options);
  230. }
  231. Readable.call(this, options);
  232. this.file = file;
  233. this.reader = new FileReader();
  234. this.start = 0;
  235. this.finish = false;
  236. this.fileBuffer = null;
  237. }
  238. util.inherits(WebFileReadStream, Readable);
  239. WebFileReadStream.prototype.readFileAndPush = function readFileAndPush(size) {
  240. if (this.fileBuffer) {
  241. let pushRet = true;
  242. while (pushRet && this.fileBuffer && this.start < this.fileBuffer.length) {
  243. const { start } = this;
  244. let end = start + size;
  245. end = end > this.fileBuffer.length ? this.fileBuffer.length : end;
  246. this.start = end;
  247. pushRet = this.push(this.fileBuffer.slice(start, end));
  248. }
  249. }
  250. };
  251. WebFileReadStream.prototype._read = function _read(size) {
  252. if (
  253. (this.file && this.start >= this.file.size) ||
  254. (this.fileBuffer && this.start >= this.fileBuffer.length) ||
  255. this.finish ||
  256. (this.start === 0 && !this.file)
  257. ) {
  258. if (!this.finish) {
  259. this.fileBuffer = null;
  260. this.finish = true;
  261. }
  262. this.push(null);
  263. return;
  264. }
  265. const defaultReadSize = 16 * 1024;
  266. size = size || defaultReadSize;
  267. const that = this;
  268. this.reader.onload = function (e) {
  269. that.fileBuffer = Buffer.from(new Uint8Array(e.target.result));
  270. that.file = null;
  271. that.readFileAndPush(size);
  272. };
  273. this.reader.onerror = function onload(e) {
  274. const error = e.srcElement && e.srcElement.error;
  275. if (error) {
  276. throw error;
  277. }
  278. throw e;
  279. };
  280. if (this.start === 0) {
  281. this.reader.readAsArrayBuffer(this.file);
  282. } else {
  283. this.readFileAndPush(size);
  284. }
  285. };
  286. proto._createStream = function _createStream(file, start, end) {
  287. if (is.readableStream(file)) {
  288. return file;
  289. } else if (isFile(file)) {
  290. return new WebFileReadStream(file.slice(start, end));
  291. } else if (isBuffer(file)) {
  292. const iterable = file.subarray(start, end);
  293. // we can't use Readable.from() since it is only support in Node v10
  294. return new Readable({
  295. read() {
  296. this.push(iterable);
  297. this.push(null);
  298. }
  299. });
  300. } else if (is.string(file)) {
  301. return fs.createReadStream(file, {
  302. start,
  303. end: end - 1
  304. });
  305. }
  306. throw new Error('_createStream requires Buffer/File/String.');
  307. };
  308. proto._getPartSize = function _getPartSize(fileSize, partSize) {
  309. const maxNumParts = 10 * 1000;
  310. const defaultPartSize = 1 * 1024 * 1024;
  311. if (!partSize) partSize = defaultPartSize;
  312. const safeSize = Math.ceil(fileSize / maxNumParts);
  313. if (partSize < safeSize) {
  314. partSize = safeSize;
  315. console.warn(
  316. `partSize has been set to ${partSize}, because the partSize you provided causes partNumber to be greater than 10,000`
  317. );
  318. }
  319. return partSize;
  320. };
  321. proto._divideParts = function _divideParts(fileSize, partSize) {
  322. const numParts = Math.ceil(fileSize / partSize);
  323. const partOffs = [];
  324. for (let i = 0; i < numParts; i++) {
  325. const start = partSize * i;
  326. const end = Math.min(start + partSize, fileSize);
  327. partOffs.push({
  328. start,
  329. end
  330. });
  331. }
  332. return partOffs;
  333. };