UNPKG

@tencent-sdk/faas

Version:
946 lines (925 loc) 54.5 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('dayjs'), require('@tencent-sdk/capi'), require('@tencent-sdk/common'), require('got'), require('@tencent-sdk/cls')) : typeof define === 'function' && define.amd ? define(['exports', 'dayjs', '@tencent-sdk/capi', '@tencent-sdk/common', 'got', '@tencent-sdk/cls'], factory) : (factory((global.faas = {}),global.dayjs,global['@tencent-sdk/capi'],global['@tencent-sdk/common'],global.got,global['@tencent-sdk/cls'])); }(this, (function (exports,dayjs,capi,common,got,cls) { 'use strict'; var dayjs__default = 'default' in dayjs ? dayjs['default'] : dayjs; got = got && got.hasOwnProperty('default') ? got['default'] : got; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var timezone = createCommonjsModule(function (module, exports) { !function(t,e){module.exports=e();}(commonjsGlobal,function(){var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,r){var o,u=r().utcOffset(),a=function(t,n,i){void 0===i&&(i={});var r=new Date(t);return function(t,n){void 0===n&&(n={});var i=n.timeZoneName||"short",r=t+"|"+i,o=e[r];return o||(o=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:i}),e[r]=o),o}(n,i).formatToParts(r)},f=function(e,n){for(var i=a(e,n),o=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(o[c]=parseInt(m,10));}var d=o[3],v=24===d?0:d,h=o[0]+"-"+o[1]+"-"+o[2]+" "+v+":"+o[4]+":"+o[5]+":000",l=+e;return (r.utc(h).valueOf()-(l-=l%1e3))/6e4},s=i.prototype;s.tz=function(t,e){void 0===t&&(t=o);var n=this.utcOffset(),i=this.toDate().toLocaleString("en-US",{timeZone:t}),a=Math.round((this.toDate()-new Date(i))/1e3/60),f=r(i).$set("millisecond",this.$ms).utcOffset(u-a,!0);if(e){var s=f.utcOffset();f=f.add(n-s,"minute");}return f.$x.$timezone=t,f},s.offsetName=function(t){var e=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find(function(t){return "timezonename"===t.type.toLowerCase()});return n&&n.value};var m=s.startOf;s.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return m.call(this,t,e);var n=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return m.call(n,t,e).tz(this.$x.$timezone,!0)},r.tz=function(t,e,n){var i=n&&e,u=n||e||o,a=f(+r(),u);if("string"!=typeof t)return r(t).tz(u);var s=function(t,e,n){var i=t-60*e*1e3,r=f(i,n);if(e===r)return [i,e];var o=f(i-=60*(r-e)*1e3,n);return r===o?[i,r]:[t-60*Math.min(r,o)*1e3,Math.max(r,o)]}(r.utc(t,i).valueOf(),a,u),m=s[0],c=s[1],d=r(m).utcOffset(c);return d.$x.$timezone=u,d},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(t){o=t;};}}); }); var utc = createCommonjsModule(function (module, exports) { !function(t,i){module.exports=i();}(commonjsGlobal,function(){return function(t,i,e){var s=i.prototype;e.utc=function(t){return new i({date:t,utc:!0,args:arguments})},s.utc=function(t){var i=e(this.toDate(),{locale:this.$L,utc:!0});return t?i.add(this.utcOffset(),"minute"):i},s.local=function(){return e(this.toDate(),{locale:this.$L,utc:!1})};var f=s.parse;s.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),f.call(this,t);};var n=s.init;s.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds();}else n.call(this);};var u=s.utcOffset;s.utcOffset=function(t,i){var e=this.$utils().u;if(e(t))return this.$u?0:e(this.$offset)?u.call(this):this.$offset;var s=Math.abs(t)<=16?60*t:t,f=this;if(i)return f.$offset=s,f.$u=0===t,f;if(0!==t){var n=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(f=this.local().add(s+n,"minute")).$offset=s,f.$x.$localOffset=n;}else f=this.utc();return f};var o=s.format;s.format=function(t){var i=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return o.call(this,i)},s.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||(new Date).getTimezoneOffset());return this.$d.valueOf()-6e4*t},s.isUTC=function(){return !!this.$u},s.toISOString=function(){return this.toDate().toISOString()},s.toString=function(){return this.toDate().toUTCString()};var r=s.toDate;s.toDate=function(t){return "s"===t&&this.$offset?e(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():r.call(this)};var a=s.diff;s.diff=function(t,i,s){if(t&&this.$u===t.$u)return a.call(this,t,i,s);var f=this.local(),n=e(t).local();return a.call(f,n,i,s)};}}); }); dayjs__default.extend(timezone); dayjs__default.extend(utc); dayjs__default.tz.setDefault('Asia/Shanghai'); var dtz = function (date) { if (date === void 0) { date = Date.now(); } return dayjs__default.tz(date); }; var TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; var TIME_FORMAT_TIMEZONE = 'YYYY-MM-DDTHH:mm:ssZ'; function formatDate(date, withTimeout) { if (withTimeout === void 0) { withTimeout = false; } if (typeof date === 'number') { date = ("" + date).length === 10 ? date * 1000 : date; } return dtz(date).format(withTimeout ? TIME_FORMAT_TIMEZONE : TIME_FORMAT); } var ACTIONS = [ 'CreateFunction', 'DeleteFunction', 'GetFunction', 'UpdateFunctionCode', 'UpdateFunctionConfiguration', 'CreateTrigger', 'DeleteTrigger', 'PublishVersion', 'ListAliases', 'CreateAlias', 'UpdateAlias', 'DeleteAlias', 'GetAlias', 'Invoke', 'ListTriggers', 'ListNamespaces', 'ListVersionByFunction', 'ListAliases', ]; function initializeApis(_a) { var _b = _a.isV3, isV3 = _b === void 0 ? true : _b, _c = _a.debug, debug = _c === void 0 ? false : _c; return capi.ApiFactory({ isV3: isV3, debug: debug, serviceType: capi.ServiceType.faas, version: '2018-04-16', actions: ACTIONS, errorHandler: function (e) { console.log(e); }, }); } var StatusMap = { success: 'SCF_StatusCode=200', fail: 'SCF_StatusCode != 200 AND SCF_StatusCode != 202 AND SCF_StatusCode != 499', retry: 'SCF_RetryNum > 0', interrupt: 'SCF_StatusCode = 499', timeout: 'SCF_StatusCode = 433', exceed: 'SCF_StatusCode = 434', codeError: 'SCF_StatusCode = 500', }; function formatWhere(_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, status = _a.status, startTime = _a.startTime, endTime = _a.endTime; var where = "SCF_Namespace='" + namespace + "' AND SCF_Qualifier='" + qualifier + "'"; if (startTime && endTime) { where += " AND (SCF_StartTime between " + startTime + " AND " + endTime + ")"; } if (name) { where += " AND SCF_FunctionName='" + name + "'"; } if (status) { where += " AND " + StatusMap[status] + "'"; } return where; } function getSearchSql(options) { var where = formatWhere(options); var sql = "* | SELECT SCF_RequestId as requestId, SCF_RetryNum as retryNum, MAX(SCF_StartTime) as startTime WHERE " + where + " GROUP BY SCF_RequestId, SCF_RetryNum ORDER BY startTime desc"; return sql; } /** * 判断是否包含字符串 * @param {string} msg - string * @returns {boolean} */ function isContain(msg, subStr) { return msg.indexOf(subStr) > -1; } function hasStartMark(msg) { return isContain(msg, 'START RequestId'); } function hasEndMark(msg) { return isContain(msg, 'END RequestId'); } function hasReportMark(msg) { return isContain(msg, 'Report RequestId'); } /** * 判断是否是完整的日志 * @param {string} msg - log message * @returns {boolean} */ function isCompleted(msg) { return hasStartMark(msg) && hasEndMark(msg) && hasReportMark(msg); } function formatFaasLog(detailLog) { var memoryUsage = ''; var duration = ''; var message = (detailLog || []) .map(function (_a) { var content = _a.content; try { var info = JSON.parse(content); if (info.SCF_Type === 'Custom') { memoryUsage = info.SCF_MemUsage; duration = info.SCF_Duration; } return info.SCF_Message; } catch (e) { return ''; } }) .join(''); return { memoryUsage: memoryUsage, duration: duration, message: message, isCompleted: isCompleted(message), }; } var ACTIONS$1 = ['GetMonitorData']; var APIS = capi.ApiFactory({ isV3: true, serviceType: capi.ServiceType.monitor, version: '2018-07-24', actions: ACTIONS$1, }); /** * 格式化监控数据 * @param {MonitorData} data raw monitor data * @returns {FormatedMonitorData[]} 格式化后的监控数据 */ function formatMetricData(data) { var _a = data.DataPoints, DataPoints = _a === void 0 ? [] : _a; var list = []; DataPoints.forEach(function (point) { var _a = point.Timestamps, Timestamps = _a === void 0 ? [] : _a, _b = point.Values, Values = _b === void 0 ? [] : _b; Timestamps.forEach(function (time, i) { list.push({ time: formatDate(time), value: Values[i], timestamp: time, }); }); }); return list; } var Monitor = /** @class */ (function () { function Monitor(_a) { var secretId = _a.secretId, secretKey = _a.secretKey, token = _a.token, _b = _a.region, region = _b === void 0 ? 'ap-guangzhou' : _b, _c = _a.debug, debug = _c === void 0 ? false : _c; this.credentials = { secretId: secretId, secretKey: secretKey, token: token, }; this.region = region; this.capi = new capi.Capi({ debug: debug, region: region, serviceType: capi.ServiceType.monitor, secretId: secretId, secretKey: secretKey, token: token, }); } /** * 获取监控数据 * @param {GetMonitorDataOptions} options 参数 * @returns */ Monitor.prototype.get = function (options) { return __awaiter(this, void 0, void 0, function () { var metric, name, _a, namespace, alias, _b, period, _c, interval, startTime, _d, endTime, _e, isRaw, endDate, startDate, formatedStartTime, formatedEndTime, dimensions, res; return __generator(this, function (_f) { switch (_f.label) { case 0: metric = options.metric, name = options.name, _a = options.namespace, namespace = _a === void 0 ? 'default' : _a, alias = options.alias, _b = options.period, period = _b === void 0 ? 60 : _b, _c = options.interval, interval = _c === void 0 ? 900 : _c, startTime = options.startTime, _d = options.endTime, endTime = _d === void 0 ? Date.now() : _d, _e = options.isRaw, isRaw = _e === void 0 ? false : _e; endDate = dtz(endTime); startDate = startTime ? dtz(startTime) : endDate.add(0 - interval, 'second'); formatedStartTime = formatDate(startDate, true); formatedEndTime = formatDate(endDate, true); dimensions = [ { Name: 'namespace', Value: namespace, }, { Name: 'functionName', Value: name, }, ]; if (alias) { dimensions.push({ Name: 'alias', Value: alias, }); } return [4 /*yield*/, this.request({ MetricName: metric, Action: 'GetMonitorData', Namespace: 'QCE/SCF_V2', Instances: [ { Dimensions: dimensions, }, ], Period: period, StartTime: formatedStartTime, EndTime: formatedEndTime, })]; case 1: res = _f.sent(); return [2 /*return*/, isRaw ? res : formatMetricData(res)]; } }); }); }; Monitor.prototype.request = function (_a) { var Action = _a.Action, data = __rest(_a, ["Action"]); return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, APIS[Action](this.capi, common.pascalCaseProps(data))]; case 1: result = _b.sent(); return [2 /*return*/, result]; } }); }); }; return Monitor; }()); (function (LogType) { LogType["none"] = "None"; LogType["tail"] = "Tail"; })(exports.LogType || (exports.LogType = {})); (function (InvokeType) { InvokeType["request"] = "RequestResponse"; InvokeType["event"] = "Event"; })(exports.InvokeType || (exports.InvokeType = {})); var ERRORS = { OTHER_GET_FAAS_ERROR: { type: 'API_FAAS_get', code: "1000", }, GET_FAAS_ERROR: { type: 'API_FAAS_get', code: "1001", message: "[FAAS] \u65E0\u6CD5\u627E\u5230\u6307\u5B9A\u51FD\u6570\uFF0C\u8BF7\u90E8\u7F72\u540E\u8C03\u7528\u6216\u68C0\u67E5\u51FD\u6570\u540D\u79F0", }, GET_CLS_CONFIG_ERROR: { type: 'API_FAAS_getClsConfig', code: "1002", message: "[FAAS] \u65E0\u6CD5\u83B7\u53D6\u51FD\u6570 CLS \u914D\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u51FD\u6570\u662F\u5426\u914D\u7F6E CLS \u529F\u80FD", }, REQUEST_ID_INVALID: { type: 'API_FAAS_getLogByReqId', code: "1003", message: "[FAAS] \u53C2\u6570 reqId(\u8BF7\u6C42 ID) \u65E0\u6548", }, WEB_FAAS_NO_TRIGGERS: { type: 'API_FAAS_getTriggers', code: "1004", message: "[FAAS] WEB \u7C7B\u578B\u51FD\u6570\u5FC5\u987B\u914D\u7F6E API \u7F51\u5173\u89E6\u53D1\u5668\u624D\u80FD\u6267\u884C", }, NAMESPACE_NOT_EXIST_ERROR: { type: 'API_FAAS_namespace', code: "1005", message: '[FAAS] 未找到指定的 namespace,请创建后再试', }, QUALIFIER_NOT_EXIST_ERROR: { type: 'API_FAAS_qualifier', code: "1006", message: '[FAAS] 未找到指定的 qualifier (版本或者别名)', }, }; var FaaS = /** @class */ (function () { function FaaS(_a) { var secretId = _a.secretId, secretKey = _a.secretKey, token = _a.token, _b = _a.region, region = _b === void 0 ? 'ap-guangzhou' : _b, _c = _a.debug, debug = _c === void 0 ? false : _c; this.credentials = { secretId: secretId, secretKey: secretKey, token: token, }; this.debug = debug; this.region = region; this.capi = new capi.Capi({ debug: debug, region: region, serviceType: capi.ServiceType.faas, secretId: secretId, secretKey: secretKey, token: token, }); this.cls = new cls.Cls({ debug: debug, region: this.region, secretId: secretId, secretKey: secretKey, token: token, }); this.monitor = new Monitor({ debug: debug, region: this.region, secretId: secretId, secretKey: secretKey, token: token, }); // 函数 CLS 配置缓存 this.clsConfigCache = {}; this.apis = initializeApis({ debug: debug, }); } /** * 设置当前地域 * @param {string} region 地区 */ FaaS.prototype.setRegion = function (region) { this.region = region; this.cls.options.region = region; }; /** * 获取当前地域 * @returns {string} 地域 */ FaaS.prototype.getRegion = function () { return this.region; }; FaaS.prototype.request = function (_a) { var Action = _a.Action, data = __rest(_a, ["Action"]); return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.apis[Action](this.capi, data)]; case 1: result = _b.sent(); return [2 /*return*/, result]; } }); }); }; FaaS.prototype.getTriggers = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.page, page = _c === void 0 ? 0 : _c; return __awaiter(this, void 0, void 0, function () { var limit, _d, _e, Triggers, TotalCount, res; return __generator(this, function (_f) { switch (_f.label) { case 0: limit = 100; return [4 /*yield*/, this.request({ Action: 'ListTriggers', FunctionName: name, Namespace: namespace, Limit: limit, Offset: page * limit, })]; case 1: _d = _f.sent(), _e = _d.Triggers, Triggers = _e === void 0 ? [] : _e, TotalCount = _d.TotalCount; if (!(TotalCount > 100)) return [3 /*break*/, 3]; return [4 /*yield*/, this.getTriggers({ name: name, namespace: namespace, page: page + 1, })]; case 2: res = _f.sent(); return [2 /*return*/, Triggers.concat(res)]; case 3: return [2 /*return*/, Triggers]; } }); }); }; /** * 获取 faas 命名空间列表 */ FaaS.prototype.getNamespaces = function (options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var _a, page, _b, limit, _c, Namespaces, res; return __generator(this, function (_d) { switch (_d.label) { case 0: _a = options.page, page = _a === void 0 ? 0 : _a, _b = options.limit, limit = _b === void 0 ? 20 : _b; return [4 /*yield*/, this.request({ Action: 'ListNamespaces', Offset: page * limit, Limit: limit, })]; case 1: _c = (_d.sent()).Namespaces, Namespaces = _c === void 0 ? [] : _c; if (!(Namespaces.length >= limit)) return [3 /*break*/, 3]; return [4 /*yield*/, this.getNamespaces({ page: page + 1, limit: limit, })]; case 2: res = _d.sent(); Namespaces = Namespaces.concat(res); _d.label = 3; case 3: return [2 /*return*/, Namespaces]; } }); }); }; /** * 获取 faas 版本列表 * @param {getVersionsOptions} options 参数 * @returns {Promise<Version[]>} 函数版本列表,字符串数组 */ FaaS.prototype.getVersions = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.page, page = _c === void 0 ? 0 : _c, _d = _a.limit, limit = _d === void 0 ? 20 : _d, _e = _a.order, order = _e === void 0 ? 'DESC' : _e, _f = _a.orderBy, orderBy = _f === void 0 ? 'AddTime' : _f; return __awaiter(this, void 0, void 0, function () { var _g, Versions, res; return __generator(this, function (_h) { switch (_h.label) { case 0: return [4 /*yield*/, this.request({ Action: 'ListVersionByFunction', Namespace: namespace, FunctionName: name, Offset: page * limit, Limit: limit, Order: order, OrderBy: orderBy, })]; case 1: _g = (_h.sent()).Versions, Versions = _g === void 0 ? [] : _g; if (!(Versions.length >= limit)) return [3 /*break*/, 3]; return [4 /*yield*/, this.getVersions({ name: name, namespace: namespace, page: page + 1, limit: limit, order: order, orderBy: orderBy, })]; case 2: res = _h.sent(); Versions = Versions.concat(res); _h.label = 3; case 3: return [2 /*return*/, Versions]; } }); }); }; /** * 获取 faas 别名列表 * @param {GetAliasesOptions} options 参数 * @returns {Promise<Alias[]>} 函数版本列表,字符串数组 */ FaaS.prototype.getAliases = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.page, page = _c === void 0 ? 0 : _c, _d = _a.limit, limit = _d === void 0 ? 20 : _d; return __awaiter(this, void 0, void 0, function () { var _e, Aliases, res; return __generator(this, function (_f) { switch (_f.label) { case 0: return [4 /*yield*/, this.request({ Action: 'ListAliases', Namespace: namespace, FunctionName: name, // FIXME: 云 API 定义 Offset 和 Limit 必须是 string 类型 Offset: "" + page * limit, Limit: "" + limit, })]; case 1: _e = (_f.sent()).Aliases, Aliases = _e === void 0 ? [] : _e; if (!(Aliases.length >= limit)) return [3 /*break*/, 3]; return [4 /*yield*/, this.getAliases({ name: name, namespace: namespace, page: page + 1, limit: limit, })]; case 2: res = _f.sent(); Aliases = Aliases.concat(res); _f.label = 3; case 3: return [2 /*return*/, Aliases]; } }); }); }; FaaS.prototype.isVersionExist = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, version = _a.version; return __awaiter(this, void 0, void 0, function () { var versionList, versions; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, this.getVersions({ name: name, namespace: namespace, })]; case 1: versionList = _c.sent(); versions = versionList.map(function (item) { return item.Version; }); return [2 /*return*/, versions.indexOf(version) > -1]; } }); }); }; FaaS.prototype.isAliasExist = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, alias = _a.alias; return __awaiter(this, void 0, void 0, function () { var aliasList, aliases; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, this.getAliases({ name: name, namespace: namespace, })]; case 1: aliasList = _c.sent(); aliases = aliasList.map(function (item) { return item.Name; }); return [2 /*return*/, aliases.indexOf(alias) > -1]; } }); }); }; /** * 获取 faas 详情 * @param {GetFaasOptions} options 参数 * @returns {Promise<FunctionInfo | null>} 函数详情,如果不存在则返回 null */ FaaS.prototype.get = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, _d = _a.showCode, showCode = _d === void 0 ? false : _d, _e = _a.showTriggers, showTriggers = _e === void 0 ? false : _e; return __awaiter(this, void 0, void 0, function () { var namespacesList, namespaces, versionExist, aliasExist, e_1, Response_1, e_2; return __generator(this, function (_f) { switch (_f.label) { case 0: _f.trys.push([0, 5, , 6]); return [4 /*yield*/, this.getNamespaces()]; case 1: namespacesList = _f.sent(); namespaces = namespacesList.map(function (item) { return item.Name; }); if (namespaces.indexOf(namespace) === -1) { throw new capi.CommonError(ERRORS.NAMESPACE_NOT_EXIST_ERROR); } return [4 /*yield*/, this.isVersionExist({ name: name, namespace: namespace, version: qualifier, })]; case 2: versionExist = _f.sent(); if (!!versionExist) return [3 /*break*/, 4]; return [4 /*yield*/, this.isAliasExist({ name: name, namespace: namespace, alias: qualifier, })]; case 3: aliasExist = _f.sent(); if (!aliasExist) { throw new capi.CommonError(ERRORS.QUALIFIER_NOT_EXIST_ERROR); } _f.label = 4; case 4: return [3 /*break*/, 6]; case 5: e_1 = _f.sent(); // 可能是其他参数导致的,比如 region 不存在,直接返回 null,排除函数不存在异常 if (e_1.code !== ERRORS.NAMESPACE_NOT_EXIST_ERROR.code && e_1.code !== ERRORS.QUALIFIER_NOT_EXIST_ERROR.code) { return [2 /*return*/, null]; } throw e_1; case 6: _f.trys.push([6, 8, , 9]); return [4 /*yield*/, this.request({ Action: 'GetFunction', FunctionName: name, Namespace: namespace, Qualifier: qualifier, ShowCode: showCode ? 'TRUE' : 'FALSE', ShowTriggers: showTriggers ? 'TRUE' : 'FALSE', })]; case 7: Response_1 = _f.sent(); return [2 /*return*/, Response_1]; case 8: e_2 = _f.sent(); if (e_2.code === 'ResourceNotFound.Namespace') { throw new capi.CommonError(ERRORS.NAMESPACE_NOT_EXIST_ERROR); } if (e_2.code === 'ResourceNotFound.FunctionName' || e_2.code === 'ResourceNotFound.Function') { return [2 /*return*/, null]; } // 除以上错误码的其他信息 throw new capi.CommonError(__assign(__assign({}, ERRORS.OTHER_GET_FAAS_ERROR), { message: e_2.message, reqId: e_2.reqId })); case 9: return [2 /*return*/]; } }); }); }; FaaS.prototype.invokeHTTPFaas = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.event, event = _c === void 0 ? {} : _c; return __awaiter(this, void 0, void 0, function () { var triggers, TriggerDesc, service, baseUrl, _d, method, _e, path, data, urlObj, realPath, url, body; return __generator(this, function (_f) { switch (_f.label) { case 0: return [4 /*yield*/, this.getTriggers({ name: name, namespace: namespace, })]; case 1: triggers = _f.sent(); if (triggers.length === 0) { throw new capi.CommonError(ERRORS.WEB_FAAS_NO_TRIGGERS); } TriggerDesc = triggers[0].TriggerDesc; service = JSON.parse(TriggerDesc).service; baseUrl = service.subDomain; _d = event.method, method = _d === void 0 ? 'GET' : _d, _e = event.path, path = _e === void 0 ? '/' : _e, data = event.data; urlObj = new URL(baseUrl + "/" + path); realPath = urlObj.pathname.replace(/\/+/g, '/'); url = "" + urlObj.origin + realPath; return [4 /*yield*/, got({ url: url, method: method, form: data, })]; case 2: body = (_f.sent()).body; return [2 /*return*/, body]; } }); }); }; /** * 调用函数 * @param {InvokeOptions} options 参数 * @returns {Promise<InvokeResult>} 函数执行结果 */ FaaS.prototype.invoke = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, _d = _a.event, event = _d === void 0 ? {} : _d, _e = _a.logType, logType = _e === void 0 ? exports.LogType.tail : _e, _f = _a.invokeType, invokeType = _f === void 0 ? exports.InvokeType.request : _f; return __awaiter(this, void 0, void 0, function () { var detail, Result; return __generator(this, function (_g) { switch (_g.label) { case 0: return [4 /*yield*/, this.get({ name: name, namespace: namespace, qualifier: qualifier, })]; case 1: detail = _g.sent(); if (!detail) { throw new capi.CommonError(ERRORS.GET_FAAS_ERROR); } if (detail.Type === 'HTTP') { return [2 /*return*/, this.invokeHTTPFaas({ name: name, namespace: namespace, event: event, qualifier: qualifier, })]; } return [4 /*yield*/, this.request({ Action: 'Invoke', FunctionName: name, Namespace: namespace, Qualifier: qualifier, ClientContext: JSON.stringify(event), LogType: logType, InvocationType: invokeType, })]; case 2: Result = (_g.sent()).Result; return [2 /*return*/, common.camelCaseProps(Result)]; } }); }); }; /** * 获取 faas 的 CLS 配置 * @param {FaasBaseConfig} options 参数 * @returns {Promise<ClsConfig>} 函数 CLS 配置 */ FaaS.prototype.getClsConfig = function (_a) { var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c; return __awaiter(this, void 0, void 0, function () { var cacheKey, detail, clsConfig; return __generator(this, function (_d) { switch (_d.label) { case 0: cacheKey = name + "-" + namespace + "-" + qualifier; if (this.clsConfigCache[cacheKey]) { return [2 /*return*/, this.clsConfigCache[cacheKey]]; } return [4 /*yield*/, this.get({ name: name, namespace: namespace, qualifier: qualifier, })]; case 1: detail = _d.sent(); if (!detail) { throw new capi.CommonError(ERRORS.GET_FAAS_ERROR); } clsConfig = { logsetId: detail.ClsLogsetId, topicId: detail.ClsTopicId, }; this.clsConfigCache[cacheKey] = clsConfig; return [2 /*return*/, clsConfig]; } }); }); }; /** * 获取函数日志列表,默认 近1个小时 * 注意如果同时定义了 startTime 和 endTime,interval 参数将不起作用 * @param {GetLogOptions} options 参数 * @returns {Promise<SearchLogItem[]>} 日志列表 */ FaaS.prototype.getLogList = function (_a) { var name = _a.name, namespace = _a.namespace, qualifier = _a.qualifier, status = _a.status, _b = _a.endTime, endTime = _b === void 0 ? Date.now() : _b, _c = _a.interval, interval = _c === void 0 ? 600 : _c, _d = _a.limit, limit = _d === void 0 ? 10 : _d, startTime = _a.startTime, _e = _a.isFilterCompleted, isFilterCompleted = _e === void 0 ? false : _e; return __awaiter(this, void 0, void 0, function () { var _f, logsetId, topicId, startDate, endDate, sql, searchParameters, _g, results, logs, i, len, curReq, detailLog, formatedInfo; return __generator(this, function (_h) { switch (_h.label) { case 0: return [4 /*yield*/, this.getClsConfig({ name: name, namespace: namespace, qualifier: qualifier, })]; case 1: _f = _h.sent(), logsetId = _f.logsetId, topicId = _f.topicId; if (!logsetId || !topicId) { throw new capi.CommonError(ERRORS.GET_CLS_CONFIG_ERROR); } // 默认获取从当前到一个小时前时间段的日志 if (!endTime) { endDate = dtz(); } else { endDate = dtz(endTime); } if (!startTime) { startDate = dtz(endDate.valueOf() - Number(interval) * 1000); } else { startDate = dtz(startTime); } sql = getSearchSql({ name: name, namespace: namespace, qualifier: qualifier, status: status, startTime: startDate.valueOf(), endTime: endDate.valueOf(), }); searchParameters = { logset_id: logsetId, topic_ids: topicId, start_time: startDate.format(TIME_FORMAT), end_time: endDate.format(TIME_FORMAT), query_string: sql, limit: limit || 10, sort: 'desc', }; return [4 /*yield*/, this.cls.searchLog(searchParameters)]; case 2: _g = (_h.sent()).results, results = _g === void 0 ? [] : _g; logs = []; i = 0, len = results.length; _h.label = 3; case 3: if (!(i < len)) return [3 /*break*/, 6]; curReq = results[i]; curReq.isCompleted = false; curReq.startTime = formatDate(curReq.startTime); return [4 /*yield*/, this.getLogDetail({ logsetId: logsetId, topicId: topicId, reqId: curReq.requestId, startTime: startDate.format(TIME_FORMAT), endTime: endDate.format(TIME_FORMAT), })]; case 4: detailLog = _h.sent(); formatedInfo = formatFaasLog(detailLog || []); curReq.message = formatedInfo.message; curReq.memoryUsage = formatedInfo.memoryUsage; curReq.isCompleted = formatedInfo.isCompleted; curReq.duration = formatedInfo.duration; logs.push(curReq); _h.label = 5; case 5: i++; return [3 /*break*/, 3]; case 6: return [2 /*return*/, isFilterCompleted ? logs.filter(function (item) { return item.isCompleted; }) : logs]; } }); }); }; /** * 获取请求 ID日志详情,包含多条日志(流式日志),需要自定义拼接 * @param {GetLogDetailOptions} options 参数 * @returns {Promise<SearchLogDetailItem[]>} 日志详情列表 */ FaaS.prototype.getLogDetail = function (_a) { var startTime = _a.startTime, logsetId = _a.logsetId, topicId = _a.topicId, reqId = _a.reqId, _b = _a.endTime, endTime = _b === void 0 ? formatDate(Date.now()) : _b; return __awaiter(this, void 0, void 0, function () { var sql, searchParameters, _c, results; return __generator(this, function (_d) { switch (_d.label) { case 0: startTime = startTime || dtz(endTime) .add(-1, 'hour') .format(TIME_FORMAT); sql = "SCF_RequestId:" + reqId + " AND SCF_RetryNum:0"; searchParameters = { logset_id: logsetId, topic_ids: topicId, start_time: startTime, end_time: endTime, query_string: sql, limit: 100, sort: 'asc', }; return [4 /*yield*/, this.cls.searchLog(searchParameters)]; case 1: _c = (_d.sent()).results, results = _c === void 0 ? [] : _c; return [2 /*return*/, results];