UNPKG

@confluentinc/schemaregistry

Version:
60 lines (59 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OAuthClient = void 0; const simple_oauth2_1 = require("simple-oauth2"); const retry_helper_1 = require("../retry-helper"); const boom_1 = require("@hapi/boom"); const TOKEN_EXPIRATION_THRESHOLD_SECONDS = 30 * 60; // 30 minutes class OAuthClient { constructor(clientId, clientSecret, tokenHost, tokenPath, scope, maxRetries, retriesWaitMs, retriesMaxWaitMs) { const clientConfig = { client: { id: clientId, secret: clientSecret, }, auth: { tokenHost: tokenHost, tokenPath: tokenPath } }; this.tokenParams = { scope }; this.client = new simple_oauth2_1.ClientCredentials(clientConfig); this.maxRetries = maxRetries; this.retriesWaitMs = retriesWaitMs; this.retriesMaxWaitMs = retriesMaxWaitMs; } async getAccessToken() { if (!this.token || this.token.expired(TOKEN_EXPIRATION_THRESHOLD_SECONDS)) { await this.generateAccessToken(); } return this.getAccessTokenString(); } async generateAccessToken() { for (let i = 0; i < this.maxRetries + 1; i++) { try { const token = await this.client.getToken(this.tokenParams); this.token = token; } catch (error) { if ((0, boom_1.isBoom)(error) && i < this.maxRetries) { const statusCode = error.output.statusCode; if ((0, retry_helper_1.isRetriable)(statusCode)) { const waitTime = (0, retry_helper_1.fullJitter)(this.retriesWaitMs, this.retriesMaxWaitMs, i); await (0, retry_helper_1.sleep)(waitTime); continue; } } throw new Error(`Failed to get token from server: ${error}`); } } } async getAccessTokenString() { const accessToken = this.token?.token?.['access_token']; if (typeof accessToken === 'string') { return accessToken; } throw new Error('Access token is not available'); } } exports.OAuthClient = OAuthClient;