resume.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. "use strict";
  2. var _interopRequireWildcard = require("@babel/runtime-corejs2/helpers/interopRequireWildcard");
  3. var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
  4. var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
  5. _Object$defineProperty(exports, "__esModule", {
  6. value: true
  7. });
  8. exports["default"] = void 0;
  9. var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));
  10. var _iterator = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/symbol/iterator"));
  11. var _symbol = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/symbol"));
  12. var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
  13. var _assign = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/assign"));
  14. var _create = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/create"));
  15. var _setPrototypeOf = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/set-prototype-of"));
  16. var utils = _interopRequireWildcard(require("../utils"));
  17. var _pool = require("../pool");
  18. var _api = require("../api");
  19. var _base = _interopRequireDefault(require("./base"));
  20. var __extends = void 0 && (void 0).__extends || function () {
  21. var _extendStatics = function extendStatics(d, b) {
  22. _extendStatics = _setPrototypeOf["default"] || {
  23. __proto__: []
  24. } instanceof Array && function (d, b) {
  25. d.__proto__ = b;
  26. } || function (d, b) {
  27. for (var p in b) {
  28. if (b.hasOwnProperty(p)) d[p] = b[p];
  29. }
  30. };
  31. return _extendStatics(d, b);
  32. };
  33. return function (d, b) {
  34. _extendStatics(d, b);
  35. function __() {
  36. this.constructor = d;
  37. }
  38. d.prototype = b === null ? (0, _create["default"])(b) : (__.prototype = b.prototype, new __());
  39. };
  40. }();
  41. var __assign = void 0 && (void 0).__assign || function () {
  42. __assign = _assign["default"] || function (t) {
  43. for (var s, i = 1, n = arguments.length; i < n; i++) {
  44. s = arguments[i];
  45. for (var p in s) {
  46. if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  47. }
  48. }
  49. return t;
  50. };
  51. return __assign.apply(this, arguments);
  52. };
  53. var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  54. function adopt(value) {
  55. return value instanceof P ? value : new P(function (resolve) {
  56. resolve(value);
  57. });
  58. }
  59. return new (P || (P = _promise["default"]))(function (resolve, reject) {
  60. function fulfilled(value) {
  61. try {
  62. step(generator.next(value));
  63. } catch (e) {
  64. reject(e);
  65. }
  66. }
  67. function rejected(value) {
  68. try {
  69. step(generator["throw"](value));
  70. } catch (e) {
  71. reject(e);
  72. }
  73. }
  74. function step(result) {
  75. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  76. }
  77. step((generator = generator.apply(thisArg, _arguments || [])).next());
  78. });
  79. };
  80. var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
  81. var _ = {
  82. label: 0,
  83. sent: function sent() {
  84. if (t[0] & 1) throw t[1];
  85. return t[1];
  86. },
  87. trys: [],
  88. ops: []
  89. },
  90. f,
  91. y,
  92. t,
  93. g;
  94. return g = {
  95. next: verb(0),
  96. "throw": verb(1),
  97. "return": verb(2)
  98. }, typeof _symbol["default"] === "function" && (g[_iterator["default"]] = function () {
  99. return this;
  100. }), g;
  101. function verb(n) {
  102. return function (v) {
  103. return step([n, v]);
  104. };
  105. }
  106. function step(op) {
  107. if (f) throw new TypeError("Generator is already executing.");
  108. while (_) {
  109. try {
  110. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  111. if (y = 0, t) op = [op[0] & 2, t.value];
  112. switch (op[0]) {
  113. case 0:
  114. case 1:
  115. t = op;
  116. break;
  117. case 4:
  118. _.label++;
  119. return {
  120. value: op[1],
  121. done: false
  122. };
  123. case 5:
  124. _.label++;
  125. y = op[1];
  126. op = [0];
  127. continue;
  128. case 7:
  129. op = _.ops.pop();
  130. _.trys.pop();
  131. continue;
  132. default:
  133. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  134. _ = 0;
  135. continue;
  136. }
  137. if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
  138. _.label = op[1];
  139. break;
  140. }
  141. if (op[0] === 6 && _.label < t[1]) {
  142. _.label = t[1];
  143. t = op;
  144. break;
  145. }
  146. if (t && _.label < t[2]) {
  147. _.label = t[2];
  148. _.ops.push(op);
  149. break;
  150. }
  151. if (t[2]) _.ops.pop();
  152. _.trys.pop();
  153. continue;
  154. }
  155. op = body.call(thisArg, _);
  156. } catch (e) {
  157. op = [6, e];
  158. y = 0;
  159. } finally {
  160. f = t = 0;
  161. }
  162. }
  163. if (op[0] & 5) throw op[1];
  164. return {
  165. value: op[0] ? op[1] : void 0,
  166. done: true
  167. };
  168. }
  169. };
  170. /** 是否为正整数 */
  171. function isPositiveInteger(n) {
  172. var re = /^[1-9]\d*$/;
  173. return re.test(String(n));
  174. }
  175. var Resume =
  176. /** @class */
  177. function (_super) {
  178. __extends(Resume, _super);
  179. function Resume() {
  180. return _super !== null && _super.apply(this, arguments) || this;
  181. }
  182. /**
  183. * @returns {Promise<ResponseSuccess<any>>}
  184. * @description 实现了 Base 的 run 接口,处理具体的分片上传事务,并抛出过程中的异常。
  185. */
  186. Resume.prototype.run = function () {
  187. return __awaiter(this, void 0, void 0, function () {
  188. var pool, localKey, uploadChunks, result;
  189. var _this = this;
  190. return __generator(this, function (_a) {
  191. switch (_a.label) {
  192. case 0:
  193. this.logger.info('start run Resume.');
  194. if (!this.config.chunkSize || !isPositiveInteger(this.config.chunkSize)) {
  195. throw new Error('chunkSize must be a positive integer.');
  196. }
  197. if (this.config.chunkSize > 1024) {
  198. throw new Error('chunkSize maximum value is 1024.');
  199. }
  200. return [4
  201. /*yield*/
  202. , this.initBeforeUploadChunks()];
  203. case 1:
  204. _a.sent();
  205. pool = new _pool.Pool(function (chunkInfo) {
  206. return _this.uploadChunk(chunkInfo);
  207. }, this.config.concurrentRequestLimit);
  208. localKey = this.getLocalKey();
  209. uploadChunks = this.chunks.map(function (chunk, index) {
  210. return pool.enqueue({
  211. chunk: chunk,
  212. index: index
  213. });
  214. });
  215. result = _promise["default"].all(uploadChunks).then(function () {
  216. return _this.mkFileReq();
  217. });
  218. result.then(function () {
  219. try {
  220. utils.removeLocalFileInfo(localKey);
  221. } catch (error) {
  222. _this.logger.error(error);
  223. }
  224. }, function (err) {
  225. _this.logger.error('uploadChunks failed.', err); // uploadId 无效,上传参数有误(多由于本地存储信息的 uploadId 失效
  226. if (err.code === 612 || err.code === 400) {
  227. try {
  228. utils.removeLocalFileInfo(localKey);
  229. } catch (error) {
  230. _this.logger.error(error);
  231. }
  232. }
  233. });
  234. return [2
  235. /*return*/
  236. , result];
  237. }
  238. });
  239. });
  240. };
  241. Resume.prototype.uploadChunk = function (chunkInfo) {
  242. return __awaiter(this, void 0, void 0, function () {
  243. var index, chunk, info, shouldCheckMD5, reuseSaved, md5, onProgress, requestOptions, response;
  244. var _this = this;
  245. return __generator(this, function (_a) {
  246. switch (_a.label) {
  247. case 0:
  248. index = chunkInfo.index, chunk = chunkInfo.chunk;
  249. info = this.uploadedList[index];
  250. this.logger.info("upload part " + index + ".", info);
  251. shouldCheckMD5 = this.config.checkByMD5;
  252. reuseSaved = function reuseSaved() {
  253. _this.updateChunkProgress(chunk.size, index);
  254. };
  255. if (info && !shouldCheckMD5) {
  256. reuseSaved();
  257. return [2
  258. /*return*/
  259. ];
  260. }
  261. return [4
  262. /*yield*/
  263. , utils.computeMd5(chunk)];
  264. case 1:
  265. md5 = _a.sent();
  266. this.logger.info("computed part md5.", md5);
  267. if (info && md5 === info.md5) {
  268. reuseSaved();
  269. return [2
  270. /*return*/
  271. ];
  272. }
  273. onProgress = function onProgress(data) {
  274. _this.updateChunkProgress(data.loaded, index);
  275. };
  276. requestOptions = {
  277. body: chunk,
  278. onProgress: onProgress,
  279. onCreate: function onCreate(xhr) {
  280. return _this.addXhr(xhr);
  281. }
  282. };
  283. this.logger.info("part " + index + " start uploading.");
  284. return [4
  285. /*yield*/
  286. , (0, _api.uploadChunk)(this.token, this.key, chunkInfo.index + 1, this.getUploadInfo(), requestOptions)];
  287. case 2:
  288. response = _a.sent();
  289. this.logger.info("part " + index + " upload completed."); // 在某些浏览器环境下,xhr 的 progress 事件无法被触发,progress 为 null,这里在每次分片上传完成后都手动更新下 progress
  290. onProgress({
  291. loaded: chunk.size,
  292. total: chunk.size
  293. });
  294. this.uploadedList[index] = {
  295. etag: response.data.etag,
  296. md5: response.data.md5,
  297. size: chunk.size
  298. };
  299. try {
  300. utils.setLocalFileInfo(this.getLocalKey(), {
  301. id: this.uploadId,
  302. data: this.uploadedList
  303. });
  304. } catch (error) {
  305. this.logger.info("set part " + index + " cache failed.", error);
  306. }
  307. return [2
  308. /*return*/
  309. ];
  310. }
  311. });
  312. });
  313. };
  314. Resume.prototype.mkFileReq = function () {
  315. return __awaiter(this, void 0, void 0, function () {
  316. var data, result;
  317. var _this = this;
  318. return __generator(this, function (_a) {
  319. switch (_a.label) {
  320. case 0:
  321. data = __assign(__assign(__assign({
  322. parts: this.uploadedList.map(function (value, index) {
  323. return {
  324. etag: value.etag,
  325. partNumber: index + 1
  326. };
  327. }),
  328. fname: this.putExtra.fname
  329. }, this.putExtra.mimeType && {
  330. mimeType: this.putExtra.mimeType
  331. }), this.putExtra.customVars && {
  332. customVars: this.putExtra.customVars
  333. }), this.putExtra.metadata && {
  334. metadata: this.putExtra.metadata
  335. });
  336. this.logger.info('parts upload completed, make file.', data);
  337. return [4
  338. /*yield*/
  339. , (0, _api.uploadComplete)(this.token, this.key, this.getUploadInfo(), {
  340. onCreate: function onCreate(xhr) {
  341. return _this.addXhr(xhr);
  342. },
  343. body: (0, _stringify["default"])(data)
  344. })];
  345. case 1:
  346. result = _a.sent();
  347. this.logger.info('finishResumeProgress.');
  348. this.updateMkFileProgress(1);
  349. return [2
  350. /*return*/
  351. , result];
  352. }
  353. });
  354. });
  355. };
  356. Resume.prototype.initBeforeUploadChunks = function () {
  357. return __awaiter(this, void 0, void 0, function () {
  358. var localInfo, res, infoMessage;
  359. return __generator(this, function (_a) {
  360. switch (_a.label) {
  361. case 0:
  362. localInfo = null;
  363. try {
  364. localInfo = utils.getLocalFileInfo(this.getLocalKey());
  365. } catch (error) {
  366. this.logger.warn(error);
  367. }
  368. if (!!localInfo) return [3
  369. /*break*/
  370. , 2];
  371. this.logger.info('resume upload parts from api.');
  372. return [4
  373. /*yield*/
  374. , (0, _api.initUploadParts)(this.token, this.bucket, this.key, this.uploadUrl)];
  375. case 1:
  376. res = _a.sent();
  377. this.logger.info("resume upload parts of id: " + res.data.uploadId + ".");
  378. this.uploadId = res.data.uploadId;
  379. this.uploadedList = [];
  380. return [3
  381. /*break*/
  382. , 3];
  383. case 2:
  384. infoMessage = ['resume upload parts from local cache', "total " + localInfo.data.length + " part", "id is " + localInfo.id + "."];
  385. this.logger.info(infoMessage.join(', '));
  386. this.uploadedList = localInfo.data;
  387. this.uploadId = localInfo.id;
  388. _a.label = 3;
  389. case 3:
  390. this.chunks = utils.getChunks(this.file, this.config.chunkSize);
  391. this.loaded = {
  392. mkFileProgress: 0,
  393. chunks: this.chunks.map(function (_) {
  394. return 0;
  395. })
  396. };
  397. this.notifyResumeProgress();
  398. return [2
  399. /*return*/
  400. ];
  401. }
  402. });
  403. });
  404. };
  405. Resume.prototype.getUploadInfo = function () {
  406. return {
  407. id: this.uploadId,
  408. url: this.uploadUrl
  409. };
  410. };
  411. Resume.prototype.getLocalKey = function () {
  412. return utils.createLocalKey(this.file.name, this.key, this.file.size);
  413. };
  414. Resume.prototype.updateChunkProgress = function (loaded, index) {
  415. this.loaded.chunks[index] = loaded;
  416. this.notifyResumeProgress();
  417. };
  418. Resume.prototype.updateMkFileProgress = function (progress) {
  419. this.loaded.mkFileProgress = progress;
  420. this.notifyResumeProgress();
  421. };
  422. Resume.prototype.notifyResumeProgress = function () {
  423. var _this = this;
  424. this.progress = {
  425. total: this.getProgressInfoItem(utils.sum(this.loaded.chunks) + this.loaded.mkFileProgress, this.file.size + 1 // 防止在 complete 未调用的时候进度显示 100%
  426. ),
  427. chunks: this.chunks.map(function (chunk, index) {
  428. return _this.getProgressInfoItem(_this.loaded.chunks[index], chunk.size);
  429. }),
  430. uploadInfo: {
  431. id: this.uploadId,
  432. url: this.uploadUrl
  433. }
  434. };
  435. this.onData(this.progress);
  436. };
  437. return Resume;
  438. }(_base["default"]);
  439. var _default = Resume;
  440. exports["default"] = _default;