UNPKG

react-native-cos-sdk

Version:
70 lines (69 loc) 3.26 kB
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } export class ScopeLimitCredentialsProvider { constructor() { _defineProperty(this, "credentialPairs", new Map()); } forceInvalidationScopeCredentials() { this.credentialPairs.clear(); } async fetchScopeLimitCredentials(stsScopesArrayJson, callback) { // 先从缓存中获取,当scope一样的时候并且没有过期则使用缓存,否则调研业务回调方法获取最新的临时秘钥 // 用于解决类似分块上传这种频繁但是秘钥大概率一样的情况 const scopeId = this.hashCode(stsScopesArrayJson); let credentials = this.lookupValidCredentials(scopeId); if (credentials == null) { const stsScopesArray = JSON.parse(stsScopesArrayJson); credentials = await callback(stsScopesArray.map(e => { const scop = { action: e == null ? '' : e.action ?? '', region: e == null ? '' : e.region ?? '', bucket: e == null ? '' : e.bucket ?? '', prefix: e == null ? '' : e.prefix ?? '' }; return scop; })); if (credentials) { this.cacheCredentialsAndCleanUp(scopeId, credentials); } } return credentials; } // 以下为实现范围限制临时秘钥缓存的代码 lookupValidCredentials(scopeId) { const credentials = this.credentialPairs.get(scopeId); if (credentials != null && this.isValid(credentials)) { return credentials; } return null; } cacheCredentialsAndCleanUp(scopeId, newCredentials) { this.credentialPairs.forEach((value, key) => { if (!this.isValid(value)) { this.credentialPairs.delete(key); } }); if (this.credentialPairs.size > ScopeLimitCredentialsProvider.MAX_CACHE_CREDENTIAL_SIZE) { const overSize = this.credentialPairs.size - ScopeLimitCredentialsProvider.MAX_CACHE_CREDENTIAL_SIZE; let count = 0; this.credentialPairs.forEach((_value, key) => { if (count < overSize) { this.credentialPairs.delete(key); count++; } }); } this.credentialPairs.set(scopeId, newCredentials); } hashCode(str) { return str.split('').reduce((prevHash, currVal) => (prevHash << 5) - prevHash + currVal.charCodeAt(0), 0); } isValid(credentials) { const now = new Date(); const timestamp = Math.floor(now.getTime() / 1000); return timestamp <= credentials.expiredTime - 60; } } _defineProperty(ScopeLimitCredentialsProvider, "MAX_CACHE_CREDENTIAL_SIZE", 100); //# sourceMappingURL=scope_credentials.js.map