base.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. var __assign = (this && this.__assign) || function () {
  2. __assign = Object.assign || function(t) {
  3. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4. s = arguments[i];
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6. t[p] = s[p];
  7. }
  8. return t;
  9. };
  10. return __assign.apply(this, arguments);
  11. };
  12. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  13. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  14. return new (P || (P = Promise))(function (resolve, reject) {
  15. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  16. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  17. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  18. step((generator = generator.apply(thisArg, _arguments || [])).next());
  19. });
  20. };
  21. var __generator = (this && this.__generator) || function (thisArg, body) {
  22. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  23. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  24. function verb(n) { return function (v) { return step([n, v]); }; }
  25. function step(op) {
  26. if (f) throw new TypeError("Generator is already executing.");
  27. while (_) try {
  28. 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;
  29. if (y = 0, t) op = [op[0] & 2, t.value];
  30. switch (op[0]) {
  31. case 0: case 1: t = op; break;
  32. case 4: _.label++; return { value: op[1], done: false };
  33. case 5: _.label++; y = op[1]; op = [0]; continue;
  34. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  35. default:
  36. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  37. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  38. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  39. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  40. if (t[2]) _.ops.pop();
  41. _.trys.pop(); continue;
  42. }
  43. op = body.call(thisArg, _);
  44. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  45. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  46. }
  47. };
  48. import { getUploadUrl } from '../api';
  49. import * as utils from '../utils';
  50. export var DEFAULT_CHUNK_SIZE = 4; // 单位 MB
  51. var GB = Math.pow(1024, 3);
  52. var Base = /** @class */ (function () {
  53. function Base(options, handlers, logger) {
  54. this.logger = logger;
  55. this.xhrList = [];
  56. this.aborted = false;
  57. this.retryCount = 0;
  58. this.config = __assign({ useCdnDomain: true, disableStatisticsReport: false, retryCount: 3, checkByMD5: false, uphost: '', upprotocol: 'https:', forceDirect: false, chunkSize: DEFAULT_CHUNK_SIZE, concurrentRequestLimit: 3 }, options.config);
  59. logger.info('config inited.', this.config);
  60. this.putExtra = __assign({ fname: '' }, options.putExtra);
  61. logger.info('putExtra inited.', this.putExtra);
  62. this.file = options.file;
  63. this.key = options.key;
  64. this.token = options.token;
  65. this.onData = handlers.onData;
  66. this.onError = handlers.onError;
  67. this.onComplete = handlers.onComplete;
  68. try {
  69. this.bucket = utils.getPutPolicy(this.token).bucket;
  70. }
  71. catch (e) {
  72. logger.error('get bucket from token failed.', e);
  73. this.onError(e);
  74. }
  75. }
  76. Base.prototype.handleError = function (message) {
  77. var err = new Error(message);
  78. this.logger.error(message);
  79. this.onError(err);
  80. };
  81. /**
  82. * @returns Promise 返回结果与上传最终状态无关,状态信息请通过 [Subscriber] 获取。
  83. * @description 上传文件,状态信息请通过 [Subscriber] 获取。
  84. */
  85. Base.prototype.putFile = function () {
  86. return __awaiter(this, void 0, void 0, function () {
  87. var _a, result, err_1, reqId, code, needRetry, notReachRetryCount;
  88. return __generator(this, function (_b) {
  89. switch (_b.label) {
  90. case 0:
  91. this.aborted = false;
  92. if (!this.putExtra.fname) {
  93. this.logger.info('use file.name as fname.');
  94. this.putExtra.fname = this.file.name;
  95. }
  96. if (this.file.size > 10000 * GB) {
  97. this.handleError('file size exceed maximum value 10000G.');
  98. return [2 /*return*/];
  99. }
  100. if (this.putExtra.customVars) {
  101. if (!utils.isCustomVarsValid(this.putExtra.customVars)) {
  102. this.handleError('customVars key should start width x:.');
  103. return [2 /*return*/];
  104. }
  105. }
  106. if (this.putExtra.metadata) {
  107. if (!utils.isMetaDataValid(this.putExtra.metadata)) {
  108. this.handleError('metadata key should start with x-qn-meta-.');
  109. return [2 /*return*/];
  110. }
  111. }
  112. _b.label = 1;
  113. case 1:
  114. _b.trys.push([1, 4, , 5]);
  115. _a = this;
  116. return [4 /*yield*/, getUploadUrl(this.config, this.token)];
  117. case 2:
  118. _a.uploadUrl = _b.sent();
  119. this.logger.info('get uploadUrl from api.', this.uploadUrl);
  120. this.uploadAt = new Date().getTime();
  121. return [4 /*yield*/, this.run()];
  122. case 3:
  123. result = _b.sent();
  124. this.onComplete(result.data);
  125. this.sendLog(result.reqId, 200);
  126. return [2 /*return*/];
  127. case 4:
  128. err_1 = _b.sent();
  129. this.logger.error(err_1);
  130. this.clear();
  131. if (err_1.isRequestError) {
  132. reqId = this.aborted ? '' : err_1.reqId;
  133. code = this.aborted ? -2 : err_1.code;
  134. this.sendLog(reqId, code);
  135. }
  136. needRetry = err_1.isRequestError && err_1.code === 0 && !this.aborted;
  137. notReachRetryCount = ++this.retryCount <= this.config.retryCount;
  138. // 以下条件满足其中之一则会进行重新上传:
  139. // 1. 满足 needRetry 的条件且 retryCount 不为 0
  140. // 2. uploadId 无效时在 resume 里会清除本地数据,并且这里触发重新上传
  141. if (needRetry && notReachRetryCount || err_1.code === 612) {
  142. this.logger.warn("error auto retry: " + this.retryCount + "/" + this.config.retryCount + ".");
  143. this.putFile();
  144. return [2 /*return*/];
  145. }
  146. this.onError(err_1);
  147. return [3 /*break*/, 5];
  148. case 5: return [2 /*return*/];
  149. }
  150. });
  151. });
  152. };
  153. Base.prototype.clear = function () {
  154. this.logger.info('start cleaning all xhr.');
  155. this.xhrList.forEach(function (xhr) {
  156. xhr.onreadystatechange = null;
  157. xhr.abort();
  158. });
  159. this.logger.info('cleanup completed.');
  160. this.xhrList = [];
  161. };
  162. Base.prototype.stop = function () {
  163. this.logger.info('stop.');
  164. this.clear();
  165. this.aborted = true;
  166. };
  167. Base.prototype.addXhr = function (xhr) {
  168. this.xhrList.push(xhr);
  169. };
  170. Base.prototype.sendLog = function (reqId, code) {
  171. this.logger.report({
  172. code: code,
  173. reqId: reqId,
  174. host: utils.getDomainFromUrl(this.uploadUrl),
  175. remoteIp: '',
  176. port: utils.getPortFromUrl(this.uploadUrl),
  177. duration: (new Date().getTime() - this.uploadAt) / 1000,
  178. time: Math.floor(this.uploadAt / 1000),
  179. bytesSent: this.progress ? this.progress.total.loaded : 0,
  180. upType: 'jssdk-h5',
  181. size: this.file.size
  182. });
  183. };
  184. Base.prototype.getProgressInfoItem = function (loaded, size) {
  185. return {
  186. loaded: loaded,
  187. size: size,
  188. percent: loaded / size * 100
  189. };
  190. };
  191. return Base;
  192. }());
  193. export default Base;
  194. //# sourceMappingURL=base.js.map