resume.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 _api = require("../api");
  17. var _errors = require("../errors");
  18. var utils = _interopRequireWildcard(require("../utils"));
  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, mkFileResponse, localKey, uploadChunks, error_1;
  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 _errors.QiniuError(_errors.QiniuErrorName.InvalidChunkSize, 'chunkSize must be a positive integer');
  196. }
  197. if (this.config.chunkSize > 1024) {
  198. throw new _errors.QiniuError(_errors.QiniuErrorName.InvalidChunkSize, 'chunkSize maximum value is 1024');
  199. }
  200. return [4
  201. /*yield*/
  202. , this.initBeforeUploadChunks()];
  203. case 1:
  204. _a.sent();
  205. pool = new utils.Pool(function (chunkInfo) {
  206. return __awaiter(_this, void 0, void 0, function () {
  207. return __generator(this, function (_a) {
  208. switch (_a.label) {
  209. case 0:
  210. if (this.aborted) {
  211. pool.abort();
  212. throw new Error('pool is aborted');
  213. }
  214. return [4
  215. /*yield*/
  216. , this.uploadChunk(chunkInfo)];
  217. case 1:
  218. _a.sent();
  219. return [2
  220. /*return*/
  221. ];
  222. }
  223. });
  224. });
  225. }, this.config.concurrentRequestLimit);
  226. mkFileResponse = null;
  227. localKey = this.getLocalKey();
  228. uploadChunks = this.chunks.map(function (chunk, index) {
  229. return pool.enqueue({
  230. chunk: chunk,
  231. index: index
  232. });
  233. });
  234. _a.label = 2;
  235. case 2:
  236. _a.trys.push([2, 5,, 6]);
  237. return [4
  238. /*yield*/
  239. , _promise["default"].all(uploadChunks)];
  240. case 3:
  241. _a.sent();
  242. return [4
  243. /*yield*/
  244. , this.mkFileReq()];
  245. case 4:
  246. mkFileResponse = _a.sent();
  247. return [3
  248. /*break*/
  249. , 6];
  250. case 5:
  251. error_1 = _a.sent(); // uploadId 无效,上传参数有误(多由于本地存储信息的 uploadId 失效)
  252. if (error_1 instanceof _errors.QiniuRequestError && (error_1.code === 612 || error_1.code === 400)) {
  253. utils.removeLocalFileInfo(localKey, this.logger);
  254. }
  255. throw error_1;
  256. case 6:
  257. // 上传成功,清理本地缓存数据
  258. utils.removeLocalFileInfo(localKey, this.logger);
  259. return [2
  260. /*return*/
  261. , mkFileResponse];
  262. }
  263. });
  264. });
  265. };
  266. Resume.prototype.uploadChunk = function (chunkInfo) {
  267. return __awaiter(this, void 0, void 0, function () {
  268. var index, chunk, cachedInfo, shouldCheckMD5, reuseSaved, md5, onProgress, requestOptions, response;
  269. var _this = this;
  270. return __generator(this, function (_a) {
  271. switch (_a.label) {
  272. case 0:
  273. index = chunkInfo.index, chunk = chunkInfo.chunk;
  274. cachedInfo = this.cachedUploadedList[index];
  275. this.logger.info("upload part " + index + ", cache:", cachedInfo);
  276. shouldCheckMD5 = this.config.checkByMD5;
  277. reuseSaved = function reuseSaved() {
  278. _this.usedCacheList[index] = true;
  279. _this.updateChunkProgress(chunk.size, index);
  280. _this.uploadedList[index] = cachedInfo;
  281. _this.updateLocalCache();
  282. }; // FIXME: 至少判断一下 size
  283. if (cachedInfo && !shouldCheckMD5) {
  284. reuseSaved();
  285. return [2
  286. /*return*/
  287. ];
  288. }
  289. return [4
  290. /*yield*/
  291. , utils.computeMd5(chunk)];
  292. case 1:
  293. md5 = _a.sent();
  294. this.logger.info('computed part md5.', md5);
  295. if (cachedInfo && md5 === cachedInfo.md5) {
  296. reuseSaved();
  297. return [2
  298. /*return*/
  299. ];
  300. } // 没有使用缓存设置标记为 false
  301. this.usedCacheList[index] = false;
  302. onProgress = function onProgress(data) {
  303. _this.updateChunkProgress(data.loaded, index);
  304. };
  305. requestOptions = {
  306. body: chunk,
  307. md5: this.config.checkByServer ? md5 : undefined,
  308. onProgress: onProgress,
  309. onCreate: function onCreate(xhr) {
  310. return _this.addXhr(xhr);
  311. }
  312. };
  313. this.logger.info("part " + index + " start uploading.");
  314. return [4
  315. /*yield*/
  316. , (0, _api.uploadChunk)(this.token, this.key, chunkInfo.index + 1, this.getUploadInfo(), requestOptions)];
  317. case 2:
  318. response = _a.sent();
  319. this.logger.info("part " + index + " upload completed."); // 在某些浏览器环境下,xhr 的 progress 事件无法被触发,progress 为 null,这里在每次分片上传完成后都手动更新下 progress
  320. onProgress({
  321. loaded: chunk.size,
  322. total: chunk.size
  323. });
  324. this.uploadedList[index] = {
  325. etag: response.data.etag,
  326. md5: response.data.md5,
  327. size: chunk.size
  328. };
  329. this.updateLocalCache();
  330. return [2
  331. /*return*/
  332. ];
  333. }
  334. });
  335. });
  336. };
  337. Resume.prototype.mkFileReq = function () {
  338. return __awaiter(this, void 0, void 0, function () {
  339. var data, result;
  340. var _this = this;
  341. return __generator(this, function (_a) {
  342. switch (_a.label) {
  343. case 0:
  344. data = __assign(__assign(__assign({
  345. parts: this.uploadedList.map(function (value, index) {
  346. return {
  347. etag: value.etag,
  348. // 接口要求 index 需要从 1 开始,所以需要整体 + 1
  349. partNumber: index + 1
  350. };
  351. }),
  352. fname: this.putExtra.fname
  353. }, this.putExtra.mimeType && {
  354. mimeType: this.putExtra.mimeType
  355. }), this.putExtra.customVars && {
  356. customVars: this.putExtra.customVars
  357. }), this.putExtra.metadata && {
  358. metadata: this.putExtra.metadata
  359. });
  360. this.logger.info('parts upload completed, make file.', data);
  361. return [4
  362. /*yield*/
  363. , (0, _api.uploadComplete)(this.token, this.key, this.getUploadInfo(), {
  364. onCreate: function onCreate(xhr) {
  365. return _this.addXhr(xhr);
  366. },
  367. body: (0, _stringify["default"])(data)
  368. })];
  369. case 1:
  370. result = _a.sent();
  371. this.logger.info('finish Resume Progress.');
  372. this.updateMkFileProgress(1);
  373. return [2
  374. /*return*/
  375. , result];
  376. }
  377. });
  378. });
  379. };
  380. Resume.prototype.initBeforeUploadChunks = function () {
  381. return __awaiter(this, void 0, void 0, function () {
  382. var cachedInfo, res, infoMessage;
  383. return __generator(this, function (_a) {
  384. switch (_a.label) {
  385. case 0:
  386. this.uploadedList = [];
  387. this.usedCacheList = [];
  388. cachedInfo = utils.getLocalFileInfo(this.getLocalKey(), this.logger);
  389. if (!!cachedInfo) return [3
  390. /*break*/
  391. , 2];
  392. this.logger.info('init upload parts from api.');
  393. return [4
  394. /*yield*/
  395. , (0, _api.initUploadParts)(this.token, this.bucketName, this.key, this.uploadHost.getUrl())];
  396. case 1:
  397. res = _a.sent();
  398. this.logger.info("initd upload parts of id: " + res.data.uploadId + ".");
  399. this.uploadId = res.data.uploadId;
  400. this.cachedUploadedList = [];
  401. return [3
  402. /*break*/
  403. , 3];
  404. case 2:
  405. infoMessage = ['resume upload parts from local cache,', "total " + cachedInfo.data.length + " part,", "id is " + cachedInfo.id + "."];
  406. this.logger.info(infoMessage.join(' '));
  407. this.cachedUploadedList = cachedInfo.data;
  408. this.uploadId = cachedInfo.id;
  409. _a.label = 3;
  410. case 3:
  411. this.chunks = utils.getChunks(this.file, this.config.chunkSize);
  412. this.loaded = {
  413. mkFileProgress: 0,
  414. chunks: this.chunks.map(function (_) {
  415. return 0;
  416. })
  417. };
  418. this.notifyResumeProgress();
  419. return [2
  420. /*return*/
  421. ];
  422. }
  423. });
  424. });
  425. };
  426. Resume.prototype.getUploadInfo = function () {
  427. return {
  428. id: this.uploadId,
  429. url: this.uploadHost.getUrl()
  430. };
  431. };
  432. Resume.prototype.getLocalKey = function () {
  433. return utils.createLocalKey(this.file.name, this.key, this.file.size);
  434. };
  435. Resume.prototype.updateLocalCache = function () {
  436. utils.setLocalFileInfo(this.getLocalKey(), {
  437. id: this.uploadId,
  438. data: this.uploadedList
  439. }, this.logger);
  440. };
  441. Resume.prototype.updateChunkProgress = function (loaded, index) {
  442. this.loaded.chunks[index] = loaded;
  443. this.notifyResumeProgress();
  444. };
  445. Resume.prototype.updateMkFileProgress = function (progress) {
  446. this.loaded.mkFileProgress = progress;
  447. this.notifyResumeProgress();
  448. };
  449. Resume.prototype.notifyResumeProgress = function () {
  450. var _this = this;
  451. this.progress = {
  452. total: this.getProgressInfoItem(utils.sum(this.loaded.chunks) + this.loaded.mkFileProgress, // FIXME: 不准确的 fileSize
  453. this.file.size + 1 // 防止在 complete 未调用的时候进度显示 100%
  454. ),
  455. chunks: this.chunks.map(function (chunk, index) {
  456. var fromCache = _this.usedCacheList[index];
  457. return _this.getProgressInfoItem(_this.loaded.chunks[index], chunk.size, fromCache);
  458. }),
  459. uploadInfo: {
  460. id: this.uploadId,
  461. url: this.uploadHost.getUrl()
  462. }
  463. };
  464. this.onData(this.progress);
  465. };
  466. return Resume;
  467. }(_base["default"]);
  468. var _default = Resume;
  469. exports["default"] = _default;