hosts.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
  3. var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
  4. _Object$defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.HostPool = exports.Host = void 0;
  8. var _map = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/map"));
  9. var _iterator = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/symbol/iterator"));
  10. var _symbol = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/symbol"));
  11. var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
  12. var _api = require("../api");
  13. var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  14. function adopt(value) {
  15. return value instanceof P ? value : new P(function (resolve) {
  16. resolve(value);
  17. });
  18. }
  19. return new (P || (P = _promise["default"]))(function (resolve, reject) {
  20. function fulfilled(value) {
  21. try {
  22. step(generator.next(value));
  23. } catch (e) {
  24. reject(e);
  25. }
  26. }
  27. function rejected(value) {
  28. try {
  29. step(generator["throw"](value));
  30. } catch (e) {
  31. reject(e);
  32. }
  33. }
  34. function step(result) {
  35. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  36. }
  37. step((generator = generator.apply(thisArg, _arguments || [])).next());
  38. });
  39. };
  40. var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
  41. var _ = {
  42. label: 0,
  43. sent: function sent() {
  44. if (t[0] & 1) throw t[1];
  45. return t[1];
  46. },
  47. trys: [],
  48. ops: []
  49. },
  50. f,
  51. y,
  52. t,
  53. g;
  54. return g = {
  55. next: verb(0),
  56. "throw": verb(1),
  57. "return": verb(2)
  58. }, typeof _symbol["default"] === "function" && (g[_iterator["default"]] = function () {
  59. return this;
  60. }), g;
  61. function verb(n) {
  62. return function (v) {
  63. return step([n, v]);
  64. };
  65. }
  66. function step(op) {
  67. if (f) throw new TypeError("Generator is already executing.");
  68. while (_) {
  69. try {
  70. 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;
  71. if (y = 0, t) op = [op[0] & 2, t.value];
  72. switch (op[0]) {
  73. case 0:
  74. case 1:
  75. t = op;
  76. break;
  77. case 4:
  78. _.label++;
  79. return {
  80. value: op[1],
  81. done: false
  82. };
  83. case 5:
  84. _.label++;
  85. y = op[1];
  86. op = [0];
  87. continue;
  88. case 7:
  89. op = _.ops.pop();
  90. _.trys.pop();
  91. continue;
  92. default:
  93. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  94. _ = 0;
  95. continue;
  96. }
  97. if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
  98. _.label = op[1];
  99. break;
  100. }
  101. if (op[0] === 6 && _.label < t[1]) {
  102. _.label = t[1];
  103. t = op;
  104. break;
  105. }
  106. if (t && _.label < t[2]) {
  107. _.label = t[2];
  108. _.ops.push(op);
  109. break;
  110. }
  111. if (t[2]) _.ops.pop();
  112. _.trys.pop();
  113. continue;
  114. }
  115. op = body.call(thisArg, _);
  116. } catch (e) {
  117. op = [6, e];
  118. y = 0;
  119. } finally {
  120. f = t = 0;
  121. }
  122. }
  123. if (op[0] & 5) throw op[1];
  124. return {
  125. value: op[0] ? op[1] : void 0,
  126. done: true
  127. };
  128. }
  129. };
  130. var __read = void 0 && (void 0).__read || function (o, n) {
  131. var m = typeof _symbol["default"] === "function" && o[_iterator["default"]];
  132. if (!m) return o;
  133. var i = m.call(o),
  134. r,
  135. ar = [],
  136. e;
  137. try {
  138. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
  139. ar.push(r.value);
  140. }
  141. } catch (error) {
  142. e = {
  143. error: error
  144. };
  145. } finally {
  146. try {
  147. if (r && !r.done && (m = i["return"])) m.call(i);
  148. } finally {
  149. if (e) throw e.error;
  150. }
  151. }
  152. return ar;
  153. };
  154. var __spread = void 0 && (void 0).__spread || function () {
  155. for (var ar = [], i = 0; i < arguments.length; i++) {
  156. ar = ar.concat(__read(arguments[i]));
  157. }
  158. return ar;
  159. };
  160. /**
  161. * @description 解冻时间,key 是 host,value 为解冻时间
  162. */
  163. var unfreezeTimeMap = new _map["default"]();
  164. var Host =
  165. /** @class */
  166. function () {
  167. function Host(host, protocol) {
  168. this.host = host;
  169. this.protocol = protocol;
  170. }
  171. /**
  172. * @description 当前 host 是否为冻结状态
  173. */
  174. Host.prototype.isFrozen = function () {
  175. var currentTime = new Date().getTime();
  176. var unfreezeTime = unfreezeTimeMap.get(this.host);
  177. return unfreezeTime != null && unfreezeTime >= currentTime;
  178. };
  179. /**
  180. * @param {number} time 单位秒,默认 20s
  181. * @description 冻结该 host 对象,该 host 将在指定时间内不可用
  182. */
  183. Host.prototype.freeze = function (time) {
  184. if (time === void 0) {
  185. time = 20;
  186. }
  187. var unfreezeTime = new Date().getTime() + time * 1000;
  188. unfreezeTimeMap.set(this.host, unfreezeTime);
  189. };
  190. /**
  191. * @description 解冻该 host
  192. */
  193. Host.prototype.unfreeze = function () {
  194. unfreezeTimeMap["delete"](this.host);
  195. };
  196. /**
  197. * @description 获取当前 host 的完整 url
  198. */
  199. Host.prototype.getUrl = function () {
  200. return this.protocol + "://" + this.host;
  201. };
  202. /**
  203. * @description 获取解冻时间
  204. */
  205. Host.prototype.getUnfreezeTime = function () {
  206. return unfreezeTimeMap.get(this.host);
  207. };
  208. return Host;
  209. }();
  210. exports.Host = Host;
  211. var HostPool =
  212. /** @class */
  213. function () {
  214. /**
  215. * @param {string[]} initHosts
  216. * @description 如果在构造时传入 initHosts,则该 host 池始终使用传入的 initHosts 做为可用的数据
  217. */
  218. function HostPool(initHosts) {
  219. if (initHosts === void 0) {
  220. initHosts = [];
  221. }
  222. this.initHosts = initHosts;
  223. /**
  224. * @description 缓存的 host 表,以 bucket 和 accessKey 作为 key
  225. */
  226. this.cachedHostsMap = new _map["default"]();
  227. }
  228. /**
  229. * @param {string} accessKey
  230. * @param {string} bucketName
  231. * @param {string[]} hosts
  232. * @param {InternalConfig['upprotocol']} protocol
  233. * @returns {void}
  234. * @description 注册可用 host
  235. */
  236. HostPool.prototype.register = function (accessKey, bucketName, hosts, protocol) {
  237. this.cachedHostsMap.set(accessKey + "@" + bucketName, hosts.map(function (host) {
  238. return new Host(host, protocol);
  239. }));
  240. };
  241. /**
  242. * @param {string} accessKey
  243. * @param {string} bucketName
  244. * @param {InternalConfig['upprotocol']} protocol
  245. * @returns {Promise<void>}
  246. * @description 刷新最新的 host 数据,如果用户在构造时该类时传入了 host 或者已经存在缓存则不会发起请求
  247. */
  248. HostPool.prototype.refresh = function (accessKey, bucketName, protocol) {
  249. var _a, _b, _c, _d;
  250. return __awaiter(this, void 0, void 0, function () {
  251. var cachedHostList, response, stashHosts;
  252. return __generator(this, function (_e) {
  253. switch (_e.label) {
  254. case 0:
  255. cachedHostList = this.cachedHostsMap.get(accessKey + "@" + bucketName) || [];
  256. if (cachedHostList.length > 0) return [2
  257. /*return*/
  258. ];
  259. if (this.initHosts.length > 0) {
  260. this.register(accessKey, bucketName, this.initHosts, protocol);
  261. return [2
  262. /*return*/
  263. ];
  264. }
  265. return [4
  266. /*yield*/
  267. , (0, _api.getUpHosts)(accessKey, bucketName, protocol)];
  268. case 1:
  269. response = _e.sent();
  270. if ((response === null || response === void 0 ? void 0 : response.data) != null) {
  271. stashHosts = __spread(((_b = (_a = response.data.up) === null || _a === void 0 ? void 0 : _a.acc) === null || _b === void 0 ? void 0 : _b.main) || [], ((_d = (_c = response.data.up) === null || _c === void 0 ? void 0 : _c.acc) === null || _d === void 0 ? void 0 : _d.backup) || []);
  272. this.register(accessKey, bucketName, stashHosts, protocol);
  273. }
  274. return [2
  275. /*return*/
  276. ];
  277. }
  278. });
  279. });
  280. };
  281. /**
  282. * @param {string} accessKey
  283. * @param {string} bucketName
  284. * @param {InternalConfig['upprotocol']} protocol
  285. * @returns {Promise<Host | null>}
  286. * @description 获取一个可用的上传 Host,排除已冻结的
  287. */
  288. HostPool.prototype.getUp = function (accessKey, bucketName, protocol) {
  289. return __awaiter(this, void 0, void 0, function () {
  290. var cachedHostList, availableHostList, priorityQueue;
  291. return __generator(this, function (_a) {
  292. switch (_a.label) {
  293. case 0:
  294. return [4
  295. /*yield*/
  296. , this.refresh(accessKey, bucketName, protocol)];
  297. case 1:
  298. _a.sent();
  299. cachedHostList = this.cachedHostsMap.get(accessKey + "@" + bucketName) || [];
  300. if (cachedHostList.length === 0) return [2
  301. /*return*/
  302. , null];
  303. availableHostList = cachedHostList.filter(function (host) {
  304. return !host.isFrozen();
  305. });
  306. if (availableHostList.length > 0) return [2
  307. /*return*/
  308. , availableHostList[0] // 无可用的,去取离解冻最近的 host
  309. ];
  310. priorityQueue = cachedHostList.slice().sort(function (hostA, hostB) {
  311. return (hostA.getUnfreezeTime() || 0) - (hostB.getUnfreezeTime() || 0);
  312. });
  313. return [2
  314. /*return*/
  315. , priorityQueue[0]];
  316. }
  317. });
  318. });
  319. };
  320. return HostPool;
  321. }();
  322. exports.HostPool = HostPool;