UNPKG

liveperson-functions-cli

Version:
295 lines 11.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FaasService = void 0; const got_1 = require("got"); const moment = require("moment"); const hpagent_1 = require("hpagent"); const login_controller_1 = require("../controller/login.controller"); const csds_service_1 = require("./csds.service"); const LogsTransform_1 = require("../transform/LogsTransform"); class FaasService { constructor( /* istanbul ignore next */ { username, loginController = new login_controller_1.LoginController(), csdsClient = new csds_service_1.CsdsClient(), gotDefault = got_1.default, } = {}) { this.username = username || 'cliUser'; this.accountId = undefined; this.token = undefined; this.userId = undefined; this.loginController = loginController; this.csdsClient = csdsClient; this.got = gotDefault; } async undeploy(uuid) { const urlPart = `/deployments/${uuid}`; try { return await this.doFetch({ urlPart, method: 'DELETE' }); } catch (error) { return { message: error.errorMsg, uuid, }; } } async deploy(uuid) { const urlPart = `/deployments/${uuid}`; try { const response = await this.doFetch({ urlPart, method: 'POST' }); return response; } catch (error) { return { message: error.errorMsg, uuid, }; } } async getLambdasByNames(lambdaNames, collectNonExistingLambas) { const url = '/lambdas'; return Promise.all(lambdaNames.map(async (name) => { const lambdas = await this.doFetch({ urlPart: url, method: 'GET', additionalParams: `&name=${name}`, }); const [foundLambda] = lambdas.filter((e) => e.name === name); if (!foundLambda && !collectNonExistingLambas) { throw new Error(`Function ${name} were not found on the platform. Please make sure the function with the name ${name} was pushed to the LivePerson Functions platform`); } return foundLambda || { name }; })); } async getRuntime() { const url = '/runtimes'; const [runtime] = await this.doFetch({ urlPart: url, method: 'GET' }); return runtime; } async getAllLambdas() { const urlPart = '/lambdas'; return this.doFetch({ urlPart, method: 'GET' }); } async createSchedule(schedule) { const urlPart = '/schedules'; return this.doFetch({ urlPart, method: 'POST', body: { ...schedule, uuid: '' }, }); } async addDomain(domain) { return this.doFetch({ urlPart: '/proxy-settings', method: 'POST', body: { domain, id: -1, }, }); } getLambdaInvocationMetrics({ uuid, startTimestamp, endTimestamp, bucketSize, }) { const url = `/reports/invocations/${uuid}`; const additionalParams = `&startTimestamp=${startTimestamp}&endTimestamp=${endTimestamp}&bucketSize=${bucketSize}&invocationStates=UNKOWN&invocationStates=SUCCEEDED&invocationStates=CODING_FAILURE&invocationStates=PLATFORM_FAILURE&invocationStates=TIMEOUT`; return this.doFetch({ urlPart: url, additionalParams, method: 'GET', }); } async getAccountStatistic() { const limitCountsUrl = '/reports/limitCounts'; const lambdaCountsUrl = '/reports/lambdaCounts'; const invocationUrl = '/reports/invocationCounts'; const currentDate = Date.now(); const firstDayOfMonth = moment.utc().startOf('month').format('x'); const limitCounts = this.doFetch({ urlPart: limitCountsUrl, method: 'GET', }); const lambdaCounts = this.doFetch({ urlPart: lambdaCountsUrl, method: 'GET', }); const invocations = this.doFetch({ urlPart: invocationUrl, method: 'GET', additionalParams: `&startTimestamp=${firstDayOfMonth}&endTimestamp=${currentDate}`, }); return (await Promise.all([limitCounts, lambdaCounts, invocations])).reduce((acc, e) => ({ ...acc, ...e }), {}); } async push({ method, body, uuid, }) { var _a; try { const urlPart = `/lambdas${uuid ? `/${uuid}` : ''}`; const response = await this.doFetch({ urlPart, method, body, resolveBody: false, }); return response.statusCode !== 304; } catch (error) { if ((_a = error.errorCode) === null || _a === void 0 ? void 0 : _a.includes('contract-error')) { throw new Error(`Push Error: The code of function '${body.name}' you are trying to push is not a valid lambda.`); } throw new Error(error.errorMsg || error.message); } } async getLambdaByUUID(uuid) { const urlPart = `/lambdas/${uuid}`; const [foundLambda] = await this.doFetch({ urlPart, method: 'GET' }); return foundLambda; } async invoke(uuid, payload) { const urlPart = `/lambdas/${uuid}/invoke`; return this.doFetch({ urlPart, method: 'POST', body: payload, csds: 'faasGW', }); } async getEvents() { return this.doFetch({ urlPart: '/events', method: 'GET' }); } async getLogs({ uuid, start, end, levels, removeHeader, }) { const urlPart = '/logs/export'; let additionalParams = `&lambdaUUID=${uuid}&startTimestamp=${start}&endTimestamp=${end || Date.now()}`; if (levels && levels.length > 0) { levels.forEach((level) => { additionalParams += `&filterLevels=${level}`; }); } return this.getStream({ urlPart, additionalParams, }, new LogsTransform_1.LogsTransform(removeHeader)); } async setup() { try { const { token, userId, username, accountId } = await this.loginController.getLoginInformation(); this.token = token; this.userId = userId; this.username = username; this.accountId = accountId; return this; } catch { this.token = undefined; this.userId = undefined; return this; } } async getCsdsEntry(csdsType) { return this.csdsClient.getUri(this.accountId, csdsType); } async getStream({ urlPart, additionalParams = '', csds = 'faasUI' }, transformer) { var _a, _b; try { const domain = await this.getCsdsEntry(csds); const url = `https://${domain}/api/account/${this.accountId}${urlPart}?userId=${this.userId}&v=1${additionalParams}`; const { HTTPS_PROXY, https_proxy: httpsProxy } = process.env; const proxyURL = HTTPS_PROXY || httpsProxy || ''; await new Promise((resolve, reject) => { this.got .stream(url, { headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json', 'user-agent': 'faas-cli', }, ...(proxyURL && { agent: { https: new hpagent_1.HttpsProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: proxyURL, }), }, }), responseType: 'json', }) .on('error', (e) => { reject(e); }) .pipe(transformer) .on('finish', () => { resolve(); }); }); } catch (error) { /* eslint-disable no-throw-literal */ if ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('401')) { throw { errorCode: '401', errorMsg: 'You are not authorized to perform this action, please check your permissions', }; } if ((_b = error.response) === null || _b === void 0 ? void 0 : _b.body) { throw { errorCode: error.response.body.errorCode, errorMsg: error.response.body.errorMsg, ...(error.response.body.errorLogs && { errorLogs: error.response.body.errorLogs, }), }; } throw error; /* eslint-enable no-throw-literal */ } } async doFetch({ urlPart, method, additionalParams = '', body, csds = 'faasUI', resolveBody = true, }) { var _a; try { const domain = await this.getCsdsEntry(csds); const url = `https://${domain}/api/account/${this.accountId}${urlPart}?userId=${this.userId}&v=1${additionalParams}`; const { HTTPS_PROXY, https_proxy: httpsProxy } = process.env; const proxyURL = HTTPS_PROXY || httpsProxy || ''; const response = await this.got(url, { method, headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json', 'user-agent': 'faas-cli', }, ...(proxyURL && { agent: { https: new hpagent_1.HttpsProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: proxyURL, }), }, }), responseType: 'json', ...(body && { json: { timestamp: 0, ...body } }), }); return resolveBody ? response.body : response; } catch (error) { /* eslint-disable no-throw-literal */ if ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('401')) { throw { errorCode: '401', errorMsg: 'You are not authorized to perform this action, please check your permissions', }; } throw { errorCode: error.response.body.errorCode, errorMsg: error.response.body.errorMsg, ...(error.response.body.errorLogs && { errorLogs: error.response.body.errorLogs, }), }; /* eslint-enable no-throw-literal */ } } } exports.FaasService = FaasService; //# sourceMappingURL=faas.service.js.map