@cloudbase/manager-node 4.2.2 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/package.json +4 -3
  3. package/lib/access/index.js +0 -141
  4. package/lib/access/types.js +0 -2
  5. package/lib/billing/index.js +0 -36
  6. package/lib/cam/index.js +0 -77
  7. package/lib/cloudBaseRun/index.js +0 -36
  8. package/lib/cloudBaseRun/types.js +0 -2
  9. package/lib/common/index.js +0 -39
  10. package/lib/constant.js +0 -51
  11. package/lib/context.js +0 -14
  12. package/lib/database/index.js +0 -244
  13. package/lib/debug.js +0 -34
  14. package/lib/env/index.js +0 -488
  15. package/lib/environment.js +0 -124
  16. package/lib/environmentManager.js +0 -44
  17. package/lib/error.js +0 -16
  18. package/lib/function/index.js +0 -1022
  19. package/lib/function/packer.js +0 -129
  20. package/lib/function/types.js +0 -2
  21. package/lib/hosting/index.js +0 -461
  22. package/lib/index.js +0 -83
  23. package/lib/interfaces/base.interface.js +0 -2
  24. package/lib/interfaces/billing.interface.js +0 -2
  25. package/lib/interfaces/cam.interface.js +0 -2
  26. package/lib/interfaces/flexdb.interface.js +0 -2
  27. package/lib/interfaces/function.interface.js +0 -2
  28. package/lib/interfaces/index.js +0 -19
  29. package/lib/interfaces/storage.interface.js +0 -2
  30. package/lib/interfaces/tcb.interface.js +0 -2
  31. package/lib/storage/index.js +0 -1035
  32. package/lib/third/index.js +0 -18
  33. package/lib/user/index.js +0 -136
  34. package/lib/user/types.js +0 -2
  35. package/lib/utils/auth.js +0 -97
  36. package/lib/utils/cloud-api-request.js +0 -205
  37. package/lib/utils/cloudbase-request.js +0 -69
  38. package/lib/utils/envLazy.js +0 -18
  39. package/lib/utils/fs.js +0 -64
  40. package/lib/utils/http-request.js +0 -44
  41. package/lib/utils/index.js +0 -103
  42. package/lib/utils/parallel.js +0 -69
  43. package/lib/utils/uuid.js +0 -18
  44. package/src/access/index.ts +0 -168
  45. package/src/access/types.ts +0 -55
  46. package/src/billing/index.ts +0 -43
  47. package/src/cam/index.ts +0 -106
  48. package/src/cloudBaseRun/index.ts +0 -40
  49. package/src/cloudBaseRun/types.ts +0 -24
  50. package/src/common/index.ts +0 -54
  51. package/src/constant.ts +0 -56
  52. package/src/context.ts +0 -18
  53. package/src/database/index.ts +0 -369
  54. package/src/debug.ts +0 -34
  55. package/src/env/index.ts +0 -614
  56. package/src/environment.ts +0 -156
  57. package/src/environmentManager.ts +0 -50
  58. package/src/error.ts +0 -27
  59. package/src/function/index.ts +0 -1378
  60. package/src/function/packer.ts +0 -164
  61. package/src/function/types.ts +0 -165
  62. package/src/hosting/index.ts +0 -698
  63. package/src/index.ts +0 -127
  64. package/src/interfaces/base.interface.ts +0 -8
  65. package/src/interfaces/billing.interface.ts +0 -21
  66. package/src/interfaces/cam.interface.ts +0 -28
  67. package/src/interfaces/flexdb.interface.ts +0 -104
  68. package/src/interfaces/function.interface.ts +0 -75
  69. package/src/interfaces/index.ts +0 -7
  70. package/src/interfaces/storage.interface.ts +0 -29
  71. package/src/interfaces/tcb.interface.ts +0 -642
  72. package/src/storage/index.ts +0 -1281
  73. package/src/third/index.ts +0 -24
  74. package/src/user/index.ts +0 -174
  75. package/src/user/types.ts +0 -21
  76. package/src/utils/auth.ts +0 -112
  77. package/src/utils/cloud-api-request.ts +0 -252
  78. package/src/utils/cloudbase-request.ts +0 -109
  79. package/src/utils/envLazy.ts +0 -15
  80. package/src/utils/fs.ts +0 -57
  81. package/src/utils/http-request.ts +0 -37
  82. package/src/utils/index.ts +0 -103
  83. package/src/utils/parallel.ts +0 -82
  84. package/src/utils/uuid.ts +0 -14
  85. package/types/access/index.d.ts +0 -38
  86. package/types/access/types.d.ts +0 -42
  87. package/types/billing/index.d.ts +0 -21
  88. package/types/cam/index.d.ts +0 -63
  89. package/types/cloudBaseRun/index.d.ts +0 -12
  90. package/types/cloudBaseRun/types.d.ts +0 -21
  91. package/types/common/index.d.ts +0 -18
  92. package/types/constant.d.ts +0 -37
  93. package/types/context.d.ts +0 -17
  94. package/types/database/index.d.ts +0 -66
  95. package/types/debug.d.ts +0 -1
  96. package/types/env/index.d.ts +0 -144
  97. package/types/environment.d.ts +0 -51
  98. package/types/environmentManager.d.ts +0 -13
  99. package/types/error.d.ts +0 -18
  100. package/types/function/index.d.ts +0 -379
  101. package/types/function/packer.d.ts +0 -37
  102. package/types/function/types.d.ts +0 -156
  103. package/types/hosting/index.d.ts +0 -253
  104. package/types/index.d.ts +0 -52
  105. package/types/interfaces/base.interface.d.ts +0 -7
  106. package/types/interfaces/billing.interface.d.ts +0 -18
  107. package/types/interfaces/cam.interface.d.ts +0 -24
  108. package/types/interfaces/flexdb.interface.d.ts +0 -67
  109. package/types/interfaces/function.interface.d.ts +0 -65
  110. package/types/interfaces/index.d.ts +0 -7
  111. package/types/interfaces/storage.interface.d.ts +0 -26
  112. package/types/interfaces/tcb.interface.d.ts +0 -305
  113. package/types/storage/index.d.ts +0 -324
  114. package/types/third/index.d.ts +0 -11
  115. package/types/user/index.d.ts +0 -52
  116. package/types/user/types.d.ts +0 -20
  117. package/types/utils/auth.d.ts +0 -8
  118. package/types/utils/cloud-api-request.d.ts +0 -21
  119. package/types/utils/cloudbase-request.d.ts +0 -14
  120. package/types/utils/envLazy.d.ts +0 -1
  121. package/types/utils/fs.d.ts +0 -7
  122. package/types/utils/http-request.d.ts +0 -2
  123. package/types/utils/index.d.ts +0 -20
  124. package/types/utils/parallel.d.ts +0 -17
  125. package/types/utils/uuid.d.ts +0 -2
@@ -1,1022 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __importDefault = (this && this.__importDefault) || function (mod) {
9
- return (mod && mod.__esModule) ? mod : { "default": mod };
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.FunctionService = void 0;
13
- const fs_1 = __importDefault(require("fs"));
14
- const path_1 = __importDefault(require("path"));
15
- const packer_1 = require("./packer");
16
- const error_1 = require("../error");
17
- const utils_1 = require("../utils");
18
- const constant_1 = require("../constant");
19
- // 是否为 Node 函数
20
- function isNodeFunction(runtime) {
21
- // 不严格限制
22
- return runtime === 'Nodejs10.15' || runtime === 'Nodejs8.9' || (runtime === null || runtime === void 0 ? void 0 : runtime.includes('Nodejs'));
23
- }
24
- // 解析函数配置,换成请求参数
25
- function configToParams(options) {
26
- var _a, _b, _c, _d, _e;
27
- const { func, codeSecret, baseParams } = options;
28
- let installDependency;
29
- // Node 函数默认安装依赖
30
- installDependency = isNodeFunction(func.runtime) ? 'TRUE' : 'FALSE';
31
- // 是否安装依赖,选项可以覆盖
32
- if (typeof func.installDependency !== 'undefined') {
33
- installDependency = func.installDependency ? 'TRUE' : 'FALSE';
34
- }
35
- // 转换环境变量
36
- const envVariables = Object.keys(func.envVariables || {}).map(key => ({
37
- Key: key,
38
- Value: func.envVariables[key]
39
- }));
40
- // 当不存在 L5 配置时,不修改 L5 状态,否则根据 true/false 进行修改
41
- const l5Enable = typeof (func === null || func === void 0 ? void 0 : func.l5) === 'undefined' ? null : (func === null || func === void 0 ? void 0 : func.l5) ? 'TRUE' : 'FALSE';
42
- const params = Object.assign(Object.assign({}, baseParams), { FunctionName: func.name,
43
- // 不可选择
44
- L5Enable: l5Enable });
45
- // 函数绑定的角色
46
- params.Role = func.role || params.Role;
47
- // 修复参数存在 undefined 字段时,会出现鉴权失败的情况
48
- // Environment 为覆盖式修改,不保留已有字段
49
- envVariables.length && (params.Environment = { Variables: envVariables });
50
- // 处理入口
51
- params.Handler = func.handler || 'index.main';
52
- // 默认超时时间为 10S
53
- params.Timeout = Number(func.timeout) || 10;
54
- // 默认运行环境 Nodejs8.9
55
- params.Runtime = func.runtime || 'Nodejs8.9';
56
- if (((_a = func === null || func === void 0 ? void 0 : func.vpc) === null || _a === void 0 ? void 0 : _a.subnetId) !== undefined && ((_b = func === null || func === void 0 ? void 0 : func.vpc) === null || _b === void 0 ? void 0 : _b.vpcId) !== undefined) {
57
- // VPC 网络
58
- params.VpcConfig = {
59
- SubnetId: (_c = func === null || func === void 0 ? void 0 : func.vpc) === null || _c === void 0 ? void 0 : _c.subnetId,
60
- VpcId: (_d = func === null || func === void 0 ? void 0 : func.vpc) === null || _d === void 0 ? void 0 : _d.vpcId
61
- };
62
- }
63
- // 运行内存
64
- params.MemorySize = func.memorySize || 256;
65
- // 自动安装依赖
66
- params.InstallDependency = installDependency;
67
- // 代码保护
68
- if (codeSecret || func.codeSecret) {
69
- params.CodeSecret = codeSecret || func.codeSecret;
70
- }
71
- // 函数层
72
- if ((_e = func === null || func === void 0 ? void 0 : func.layers) === null || _e === void 0 ? void 0 : _e.length) {
73
- const transformLayers = func.layers.map(item => ({
74
- LayerName: item.name,
75
- LayerVersion: item.version
76
- }));
77
- params.Layers = transformLayers;
78
- }
79
- return params;
80
- }
81
- class FunctionService {
82
- constructor(environment) {
83
- this.environment = environment;
84
- this.scfService = new utils_1.CloudService(environment.cloudBaseContext, 'scf', '2018-04-16');
85
- this.vpcService = new utils_1.CloudService(environment.cloudBaseContext, 'vpc', '2017-03-12');
86
- }
87
- /**
88
- * 增量更新函数代码
89
- * @param {IUpdateFunctionIncrementalCodeParam} funcParam
90
- * @returns {Promise<void>}
91
- * @memberof FunctionService
92
- */
93
- async updateFunctionIncrementalCode(funcParam) {
94
- const { namespace } = this.getFunctionConfig();
95
- const { functionRootPath, func, deleteFiles, addFiles } = funcParam;
96
- const { name, runtime } = func;
97
- const params = {
98
- FunctionName: name,
99
- Namespace: namespace
100
- };
101
- let packer;
102
- let base64;
103
- if (deleteFiles) {
104
- params.DeleteFiles = deleteFiles;
105
- }
106
- if (addFiles) {
107
- // 将选中的增量文件或增量文件夹 转base64
108
- const codeType = runtime === 'Java8' ? packer_1.CodeType.JavaFile : packer_1.CodeType.File;
109
- packer = new packer_1.FunctionPacker({
110
- codeType,
111
- name,
112
- root: functionRootPath,
113
- ignore: [],
114
- incrementalPath: addFiles
115
- });
116
- await packer.build();
117
- base64 = await packer.getBase64Code();
118
- if (!base64) {
119
- throw new error_1.CloudBaseError('函数不存在!');
120
- }
121
- params.AddFiles = base64;
122
- }
123
- return this.scfService.request('UpdateFunctionIncrementalCode', params);
124
- }
125
- /**
126
- * 创建云函数
127
- * @param {ICreateFunctionParam} funcParam
128
- * @returns {(Promise<IResponseInfo | ICreateFunctionRes>)}
129
- */
130
- async createFunction(funcParam) {
131
- const { namespace } = this.getFunctionConfig();
132
- const { func, functionRootPath, force = false, base64Code, codeSecret, functionPath } = funcParam;
133
- const funcName = func.name;
134
- const params = configToParams({
135
- func,
136
- codeSecret,
137
- baseParams: {
138
- Namespace: namespace,
139
- Role: 'TCB_QcsRole',
140
- Stamp: 'MINI_QCBASE'
141
- }
142
- });
143
- params.Code = await this.getCodeParams({
144
- func,
145
- base64Code,
146
- functionPath,
147
- functionRootPath
148
- }, params.InstallDependency);
149
- const { TopicId, LogsetId } = this.getClsServiceConfig();
150
- params.ClsTopicId = TopicId;
151
- params.ClsLogsetId = LogsetId;
152
- try {
153
- // 创建云函数
154
- const res = await this.scfService.request('CreateFunction', params);
155
- // 等待函数状态正常
156
- await this.waitFunctionActive(funcName, codeSecret);
157
- // 创建函数触发器、失败自动重试
158
- await this.retryCreateTrigger(funcName, func.triggers);
159
- // 设置路径,创建云接入路径
160
- if (func.path) {
161
- await this.createAccessPath(funcName, func.path);
162
- }
163
- // 检查函数状态
164
- await this.waitFunctionActive(funcName, codeSecret);
165
- return res;
166
- }
167
- catch (e) {
168
- // 函数存在
169
- const functionExist = e.code === 'ResourceInUse.FunctionName' || e.code === 'ResourceInUse.Function';
170
- // 已存在同名函数,强制更新
171
- if (functionExist && force) {
172
- // 1. 更新函数配置和代码,同名函数可能存在 codeSecret,先修改代码,清除 codeSecret
173
- const codeRes = await this.updateFunctionCode({
174
- func,
175
- base64Code,
176
- functionPath,
177
- functionRootPath,
178
- codeSecret: codeSecret
179
- });
180
- // 等待函数状态正常
181
- await this.waitFunctionActive(funcName, codeSecret);
182
- // 2. 更新函数配置
183
- const configRes = await this.updateFunctionConfig(func);
184
- // 等待函数状态正常
185
- await this.waitFunctionActive(funcName, codeSecret);
186
- // 3. 创建函数触发器
187
- const triggerRes = await this.retryCreateTrigger(funcName, func.triggers);
188
- // 设置路径,创建云接入路径
189
- if (func.path) {
190
- await this.createAccessPath(funcName, func.path);
191
- }
192
- // 检查函数状态
193
- await this.waitFunctionActive(funcName, codeSecret);
194
- // 返回全部操作的响应值
195
- return {
196
- triggerRes,
197
- configRes,
198
- codeRes
199
- };
200
- }
201
- // 不强制覆盖,抛出错误
202
- if (e.message && !force) {
203
- throw new error_1.CloudBaseError(`[${funcName}] 部署失败:\n${e.message}`, {
204
- code: e.code,
205
- requestId: e.requestId
206
- });
207
- }
208
- throw e;
209
- }
210
- }
211
- /**
212
- * @param {number} [limit=20]
213
- * @param {number} [offset=0]
214
- * @returns {Promise<{
215
- * Functions: Record<string, string>[]
216
- * RequestId: string
217
- * TotalCount: number
218
- * }>}
219
- * @memberof FunctionService
220
- */
221
- async getFunctionList(limit = 20, offset = 0) {
222
- // 获取Function 环境配置
223
- const { namespace } = this.getFunctionConfig();
224
- const res = await this.scfService.request('ListFunctions', {
225
- Namespace: namespace,
226
- Limit: limit,
227
- Offset: offset
228
- });
229
- return res;
230
- }
231
- /**
232
- * 列出函数
233
- * @param {number} [limit=20]
234
- * @param {number} [offset=0]
235
- * @returns {Promise<Record<string, string>[]>}
236
- */
237
- async listFunctions(limit = 20, offset = 0) {
238
- // 获取Function 环境配置
239
- const { namespace } = this.getFunctionConfig();
240
- const res = await this.scfService.request('ListFunctions', {
241
- Namespace: namespace,
242
- Limit: limit,
243
- Offset: offset
244
- });
245
- const { Functions = [] } = res;
246
- const data = [];
247
- Functions.forEach(func => {
248
- const { FunctionId, FunctionName, Runtime, AddTime, ModTime, Status } = func;
249
- data.push({
250
- FunctionId,
251
- FunctionName,
252
- Runtime,
253
- AddTime,
254
- ModTime,
255
- Status
256
- });
257
- });
258
- return data;
259
- }
260
- /**
261
- * 删除云函数
262
- * @param {string} name 云函数名称
263
- * @param {string} qualifier 需要删除的版本号,不填默认删除函数下全部版本。
264
- * @returns {Promise<IResponseInfo>}
265
- */
266
- async deleteFunction(name, qualifier) {
267
- const { namespace } = this.getFunctionConfig();
268
- return this.scfService.request('DeleteFunction', {
269
- FunctionName: name,
270
- Namespace: namespace,
271
- Qualifier: qualifier
272
- });
273
- }
274
- /**
275
- * 获取云函数详细信息
276
- * @param {string} name 云函数名称
277
- * @returns {Promise<Record<string, string>>}
278
- */
279
- async getFunctionDetail(name, codeSecret) {
280
- const { namespace } = this.getFunctionConfig();
281
- const params = {
282
- FunctionName: name,
283
- Namespace: namespace,
284
- ShowCode: 'TRUE'
285
- };
286
- if (codeSecret) {
287
- params.CodeSecret = codeSecret;
288
- }
289
- const data = await this.scfService.request('GetFunction', params);
290
- // 解析 VPC 配置
291
- const { VpcId = '', SubnetId = '' } = data.VpcConfig || {};
292
- if (VpcId && SubnetId) {
293
- try {
294
- const vpcs = await this.getVpcs();
295
- const subnets = await this.getSubnets(VpcId);
296
- const vpc = vpcs.find(item => item.VpcId === VpcId);
297
- const subnet = subnets.find(item => item.SubnetId === SubnetId);
298
- data.VpcConfig = {
299
- vpc,
300
- subnet
301
- };
302
- }
303
- catch (e) {
304
- data.VpcConfig = {
305
- vpc: '',
306
- subnet: ''
307
- };
308
- }
309
- }
310
- return data;
311
- }
312
- /**
313
- * 获取函数日志
314
- * @param {{
315
- * name: string
316
- * offset: number
317
- * limit: number
318
- * order: string
319
- * orderBy: string
320
- * startTime: string
321
- * endTime: string
322
- * requestId: string
323
- * }} options
324
- * @returns {Promise<IFunctionLogRes>}
325
- */
326
- async getFunctionLogs(options) {
327
- const { name, offset = 0, limit = 10, order, orderBy, startTime, endTime, requestId } = options;
328
- const { namespace } = this.getFunctionConfig();
329
- const params = {
330
- Namespace: namespace,
331
- FunctionName: name,
332
- Offset: offset,
333
- Limit: limit,
334
- Order: order,
335
- OrderBy: orderBy,
336
- StartTime: startTime,
337
- EndTime: endTime,
338
- FunctionRequestId: requestId
339
- };
340
- const res = await this.scfService.request('GetFunctionLogs', params);
341
- return res;
342
- }
343
- /**
344
- * 更新云函数配置
345
- * @param {ICloudFunction} func 云函数配置
346
- * @returns {Promise<IResponseInfo>}
347
- */
348
- async updateFunctionConfig(func) {
349
- var _a, _b, _c, _d, _e;
350
- const { namespace } = this.getFunctionConfig();
351
- const envVariables = Object.keys(func.envVariables || {}).map(key => ({
352
- Key: key,
353
- Value: func.envVariables[key]
354
- }));
355
- // 当不存在 L5 配置时,不修改 L5 状态,否则根据 true/false 进行修改
356
- const l5Enable = typeof func.l5 === 'undefined' ? null : func.l5 ? 'TRUE' : 'FALSE';
357
- const params = {
358
- FunctionName: func.name,
359
- Namespace: namespace,
360
- L5Enable: l5Enable
361
- };
362
- // 修复参数存在 undefined 字段时,会出现鉴权失败的情况
363
- // Environment 为覆盖式修改,不保留已有字段
364
- envVariables.length && (params.Environment = { Variables: envVariables });
365
- // 不设默认超时时间,防止覆盖已有配置
366
- func.timeout && (params.Timeout = func.timeout);
367
- // 运行时
368
- func.runtime && (params.Runtime = func.runtime);
369
- if (((_a = func === null || func === void 0 ? void 0 : func.vpc) === null || _a === void 0 ? void 0 : _a.subnetId) !== undefined && ((_b = func === null || func === void 0 ? void 0 : func.vpc) === null || _b === void 0 ? void 0 : _b.vpcId) !== undefined) {
370
- // VPC 网络
371
- params.VpcConfig = {
372
- SubnetId: (_c = func === null || func === void 0 ? void 0 : func.vpc) === null || _c === void 0 ? void 0 : _c.subnetId,
373
- VpcId: (_d = func === null || func === void 0 ? void 0 : func.vpc) === null || _d === void 0 ? void 0 : _d.vpcId
374
- };
375
- }
376
- // 内存
377
- func.memorySize && (params.MemorySize = func.memorySize);
378
- // Node 函数默认安装依赖
379
- isNodeFunction(func.runtime) && (params.InstallDependency = 'TRUE');
380
- // 是否安装依赖,选项可以覆盖
381
- if (typeof func.installDependency !== 'undefined') {
382
- params.InstallDependency = func.installDependency ? 'TRUE' : 'FALSE';
383
- }
384
- // 函数层
385
- if ((_e = func === null || func === void 0 ? void 0 : func.layers) === null || _e === void 0 ? void 0 : _e.length) {
386
- const transformLayers = func.layers.map(item => ({
387
- LayerName: item.name,
388
- LayerVersion: item.version
389
- }));
390
- params.Layers = transformLayers;
391
- }
392
- return this.scfService.request('UpdateFunctionConfiguration', params);
393
- }
394
- /**
395
- *
396
- * @param {IUpdateFunctionCodeParam} funcParam
397
- * @returns {Promise<IResponseInfo>}
398
- * @memberof FunctionService
399
- */
400
- async updateFunctionCode(funcParam) {
401
- const { func, functionRootPath, base64Code, codeSecret, functionPath } = funcParam;
402
- const funcName = func.name;
403
- const { namespace } = this.getFunctionConfig();
404
- let installDependency;
405
- // Node 函数默认安装依赖
406
- installDependency = isNodeFunction(func.runtime) ? 'TRUE' : 'FALSE';
407
- // 是否安装依赖,选项可以覆盖
408
- if (typeof func.installDependency !== 'undefined') {
409
- installDependency = func.installDependency ? 'TRUE' : 'FALSE';
410
- }
411
- const codeParams = await this.getCodeParams({
412
- func,
413
- functionPath,
414
- functionRootPath,
415
- base64Code
416
- }, installDependency);
417
- const params = Object.assign({ FunctionName: funcName, Namespace: namespace, Handler: func.handler || 'index.main', InstallDependency: installDependency }, codeParams);
418
- if (codeSecret) {
419
- params.CodeSecret = codeSecret;
420
- }
421
- try {
422
- // 等待函数状态正常
423
- await this.waitFunctionActive(funcName, codeSecret);
424
- // 更新云函数代码
425
- const res = await this.scfService.request('UpdateFunctionCode', params);
426
- if (installDependency && func.isWaitInstall === true) {
427
- await this.waitFunctionActive(funcName, codeSecret);
428
- }
429
- return res;
430
- }
431
- catch (e) {
432
- throw new error_1.CloudBaseError(`[${funcName}] 函数代码更新失败: ${e.message}`, {
433
- code: e.code
434
- });
435
- }
436
- }
437
- /**
438
- * 调用云函数
439
- * @param {string} name 云函数名称
440
- * @param {Record<string, any>} params 调用函数传入参数
441
- * @returns {Promise<IFunctionInvokeRes>}
442
- */
443
- async invokeFunction(name, params) {
444
- const { namespace } = this.getFunctionConfig();
445
- const _params = {
446
- FunctionName: name,
447
- Namespace: namespace,
448
- LogType: 'Tail'
449
- };
450
- if (params) {
451
- _params.ClientContext = JSON.stringify(params);
452
- }
453
- try {
454
- const { RequestId, Result } = await this.scfService.request('Invoke', _params);
455
- return Object.assign({ RequestId }, Result);
456
- }
457
- catch (e) {
458
- throw new error_1.CloudBaseError(`[${name}] 调用失败:\n${e.message}`);
459
- }
460
- }
461
- /**
462
- * 复制云函数
463
- * @param {string} name 云函数名称
464
- * @param {string} newFunctionName 新的云函数名称
465
- * @param {string} targetEnvId 目标环境 Id
466
- * @param {boolean} [force=false] 是否覆盖同名云函数
467
- * @returns {Promise<IResponseInfo>}
468
- */
469
- /* eslint-disable-next-line */
470
- async copyFunction(name, newFunctionName, targetEnvId, force = false) {
471
- const { namespace } = this.getFunctionConfig();
472
- if (!namespace || !name || !newFunctionName) {
473
- throw new error_1.CloudBaseError('参数缺失');
474
- }
475
- return this.scfService.request('CopyFunction', {
476
- FunctionName: name,
477
- NewFunctionName: newFunctionName,
478
- Namespace: namespace,
479
- TargetNamespace: targetEnvId || namespace,
480
- Override: force ? true : false
481
- });
482
- }
483
- /**
484
- * 创建云函数触发器
485
- * @param {string} name 云函数名称
486
- * @param {ICloudFunctionTrigger[]} triggers 云函数触发器配置
487
- * @returns {Promise<IResponseInfo>}
488
- */
489
- async createFunctionTriggers(name, triggers = []) {
490
- if (!triggers || !triggers.length)
491
- return null;
492
- const { namespace } = this.getFunctionConfig();
493
- const parsedTriggers = triggers.map(item => {
494
- if (item.type !== 'timer') {
495
- throw new error_1.CloudBaseError(`不支持的触发器类型 [${item.type}],目前仅支持定时触发器(timer)!`);
496
- }
497
- return {
498
- TriggerName: item.name,
499
- Type: item.type,
500
- TriggerDesc: item.config
501
- };
502
- });
503
- return this.scfService.request('BatchCreateTrigger', {
504
- FunctionName: name,
505
- Namespace: namespace,
506
- Triggers: JSON.stringify(parsedTriggers),
507
- Count: parsedTriggers.length
508
- });
509
- }
510
- /**
511
- * 删除云函数触发器
512
- * @param {string} name 云函数名称
513
- * @param {string} triggerName 云函数触发器名称
514
- * @returns {Promise<IResponseInfo>}
515
- */
516
- async deleteFunctionTrigger(name, triggerName) {
517
- const { namespace } = this.getFunctionConfig();
518
- return this.scfService.request('DeleteTrigger', {
519
- FunctionName: name,
520
- Namespace: namespace,
521
- TriggerName: triggerName,
522
- Type: 'timer'
523
- });
524
- }
525
- /**
526
- * 获取云函数代码下载 链接
527
- * @param {string} functionName
528
- * @param {string} [codeSecret]
529
- * @returns {Promise<IFunctionDownloadUrlRes>}
530
- * @memberof FunctionService
531
- */
532
- async getFunctionDownloadUrl(functionName, codeSecret) {
533
- const { namespace } = this.getFunctionConfig();
534
- const params = {
535
- FunctionName: functionName,
536
- Namespace: namespace
537
- };
538
- if (codeSecret) {
539
- params.CodeSecret = codeSecret;
540
- }
541
- try {
542
- const { Url, CodeSha256, RequestId } = await this.scfService.request('GetFunctionAddress', params);
543
- return { Url, RequestId, CodeSha256 };
544
- }
545
- catch (e) {
546
- throw new error_1.CloudBaseError(`[${functionName}] 获取函数代码下载链接失败:\n${e.message}`);
547
- }
548
- }
549
- // 创建文件层版本
550
- async createLayer(options) {
551
- const { env } = this.getFunctionConfig();
552
- const { contentPath = '', name, base64Content = '', runtimes = [], description = '', licenseInfo = '' } = options;
553
- let base64;
554
- if (base64Content) {
555
- base64 = base64Content;
556
- }
557
- else if (utils_1.isDirectory(contentPath)) {
558
- // 压缩文件夹
559
- const dirName = path_1.default.parse(contentPath).name;
560
- const dest = path_1.default.join(process.cwd(), `temp-${dirName}.zip`);
561
- // ZIP 文件存在,删除 ZIP 文件
562
- if (utils_1.checkFullAccess(dest)) {
563
- utils_1.delSync(dest);
564
- }
565
- await utils_1.compressToZip({
566
- dirPath: contentPath,
567
- outputPath: dest
568
- });
569
- // 转换成 base64
570
- const fileBuffer = await fs_1.default.promises.readFile(dest);
571
- base64 = fileBuffer.toString('base64');
572
- utils_1.delSync(dest);
573
- }
574
- else {
575
- const fileType = path_1.default.extname(contentPath);
576
- if (fileType !== '.zip') {
577
- throw new error_1.CloudBaseError('文件类型不正确,目前只支持 ZIP 文件!');
578
- }
579
- const fileBuffer = await fs_1.default.promises.readFile(contentPath);
580
- base64 = fileBuffer.toString('base64');
581
- }
582
- return this.scfService.request('PublishLayerVersion', {
583
- LayerName: name,
584
- CompatibleRuntimes: runtimes,
585
- Content: {
586
- // 最大支持 20M
587
- ZipFile: base64
588
- },
589
- Description: description,
590
- LicenseInfo: licenseInfo,
591
- Src: `TCB_${env}`
592
- });
593
- }
594
- // 删除文件层版本
595
- async deleteLayerVersion(options) {
596
- const { name, version } = options;
597
- return this.scfService.request('DeleteLayerVersion', {
598
- LayerName: name,
599
- LayerVersion: version
600
- });
601
- }
602
- // 获取层版本列表
603
- async listLayerVersions(options) {
604
- const { name, runtimes } = options;
605
- let param = {
606
- LayerName: name
607
- };
608
- if (runtimes === null || runtimes === void 0 ? void 0 : runtimes.length) {
609
- param.CompatibleRuntime = runtimes;
610
- }
611
- return this.scfService.request('ListLayerVersions', param);
612
- }
613
- // 获取文件层列表
614
- async listLayers(options) {
615
- const { env } = this.getFunctionConfig();
616
- const { limit = 20, offset = 0, runtime, searchKey } = options;
617
- let param = {
618
- Limit: limit,
619
- Offset: offset,
620
- SearchKey: searchKey,
621
- SearchSrc: `TCB_${env}`
622
- };
623
- if (runtime) {
624
- param.CompatibleRuntime = runtime;
625
- }
626
- return this.scfService.request('ListLayers', param);
627
- }
628
- // 获取层版本详细信息
629
- async getLayerVersion(options) {
630
- const { name, version } = options;
631
- return this.scfService.request('GetLayerVersion', {
632
- LayerName: name,
633
- LayerVersion: version
634
- });
635
- }
636
- /**
637
- * 设置预置并发
638
- * @private
639
- * @param {IProvisionedConcurrencyConfig} concurrencyConfig
640
- * @returns
641
- * @memberof FunctionService
642
- */
643
- async setProvisionedConcurrencyConfig(concurrencyConfig) {
644
- const { namespace } = this.getFunctionConfig();
645
- const { functionName: FunctionName, qualifier: Qualifier, versionProvisionedConcurrencyNum: VersionProvisionedConcurrencyNum } = concurrencyConfig;
646
- return this.scfService.request('PutProvisionedConcurrencyConfig', {
647
- FunctionName,
648
- Qualifier,
649
- VersionProvisionedConcurrencyNum,
650
- Namespace: namespace
651
- });
652
- }
653
- /**
654
- * 获取函数预置并发详情
655
- * @private
656
- * @param {IGetProvisionedConcurrencyConfig} concurrencyConfig
657
- * @returns {Promise<IGetProvisionedConcurrencyRes>}
658
- * @memberof FunctionService
659
- */
660
- async getProvisionedConcurrencyConfig(concurrencyConfig) {
661
- const { namespace } = this.getFunctionConfig();
662
- const { functionName: FunctionName, qualifier: Qualifier } = concurrencyConfig;
663
- return this.scfService.request('GetProvisionedConcurrencyConfig', {
664
- FunctionName,
665
- Qualifier,
666
- Namespace: namespace
667
- });
668
- }
669
- /**
670
- * 删除预置并发
671
- * @private
672
- * @param {IGetProvisionedConcurrencyConfig} concurrencyConfig
673
- * @returns {Promise<IResponseInfo>}
674
- * @memberof FunctionService
675
- */
676
- async deleteProvisionedConcurrencyConfig(concurrencyConfig) {
677
- const { namespace } = this.getFunctionConfig();
678
- const { functionName: FunctionName, qualifier: Qualifier } = concurrencyConfig;
679
- return this.scfService.request('DeleteProvisionedConcurrencyConfig', {
680
- FunctionName,
681
- Qualifier,
682
- Namespace: namespace
683
- });
684
- }
685
- /**
686
- * 发布新版本
687
- * @param {IPublishVersionParams} publishParams
688
- * @returns {Promise<IPublishVersionRes>}
689
- * @memberof FunctionService
690
- */
691
- async publishVersion(publishParams) {
692
- const { namespace } = this.getFunctionConfig();
693
- const { functionName: FunctionName, description: Description } = publishParams;
694
- return this.scfService.request('PublishVersion', {
695
- FunctionName,
696
- Description,
697
- Namespace: namespace
698
- });
699
- }
700
- /**
701
- * 查询函数版本详情
702
- * @param {IListFunctionVersionParams} listVersionParams
703
- * @returns {Promise<IFunctionVersionsRes>}
704
- * @memberof FunctionService
705
- */
706
- async listVersionByFunction(listVersionParams) {
707
- const { namespace } = this.getFunctionConfig();
708
- const { functionName: FunctionName, offset: Offset, limit: Limit, order: Order, orderBy: OrderBy } = listVersionParams;
709
- return this.scfService.request('ListVersionByFunction', {
710
- FunctionName,
711
- Namespace: namespace,
712
- Offset,
713
- Limit,
714
- Order,
715
- OrderBy
716
- });
717
- }
718
- /**
719
- *
720
- * @param {IUpdateFunctionAliasConfig} updateVersionConfigParams
721
- * @returns {Promise<IResponseInfo>}
722
- * @memberof FunctionService
723
- */
724
- async updateFunctionAliasConfig(updateVersionConfigParams) {
725
- const { namespace } = this.getFunctionConfig();
726
- const { functionName: FunctionName, name: Name, functionVersion: FunctionVersion, routingConfig: RoutingConfig, description: Description } = updateVersionConfigParams;
727
- return this.scfService.request('UpdateAlias', {
728
- FunctionName,
729
- Name,
730
- Namespace: namespace,
731
- FunctionVersion,
732
- RoutingConfig,
733
- Description
734
- });
735
- }
736
- /**
737
- * 查询函数别名详情
738
- * @param {IGetFunctionAlias} params
739
- * @returns {Promise<IGetFunctionAliasRes>}
740
- * @memberof FunctionService
741
- */
742
- async getFunctionAlias(params) {
743
- const { namespace } = this.getFunctionConfig();
744
- const { functionName: FunctionName, name: Name } = params;
745
- return this.scfService.request('GetAlias', {
746
- FunctionName,
747
- Name,
748
- Namespace: namespace
749
- });
750
- }
751
- async createAccessPath(name, path) {
752
- const access = this.environment.getAccessService();
753
- try {
754
- await access.createAccess({
755
- name,
756
- path
757
- });
758
- }
759
- catch (e) {
760
- // 当 Path 存在时,校验 Path 绑定的函数是不是当前函数
761
- if (e.code === 'InvalidParameter.APICreated') {
762
- const { APISet } = await access.getAccessList({
763
- name
764
- });
765
- if ((APISet === null || APISet === void 0 ? void 0 : APISet[0].Name) !== name || (APISet === null || APISet === void 0 ? void 0 : APISet[0].Type) !== 1) {
766
- throw e;
767
- }
768
- }
769
- else {
770
- throw e;
771
- }
772
- }
773
- }
774
- async getCodeParams(options, installDependency) {
775
- const { func, functionPath, functionRootPath, base64Code } = options;
776
- // 20MB
777
- const BIG_LENGTH = 167772160;
778
- if ((base64Code === null || base64Code === void 0 ? void 0 : base64Code.length) > BIG_LENGTH) {
779
- throw new error_1.CloudBaseError('base64 不能大于 20 MB');
780
- }
781
- if (base64Code === null || base64Code === void 0 ? void 0 : base64Code.length) {
782
- return {
783
- ZipFile: base64Code
784
- };
785
- }
786
- const codeType = func.runtime === 'Java8' ? packer_1.CodeType.JavaFile : packer_1.CodeType.File;
787
- // 云端安装依赖,自动忽略 node_modules 目录
788
- const ignore = installDependency === 'TRUE'
789
- ? ['node_modules/**/*', 'node_modules', ...(func.ignore || [])]
790
- : [...(func.ignore || [])];
791
- const packer = new packer_1.FunctionPacker({
792
- ignore,
793
- codeType,
794
- functionPath,
795
- name: func.name,
796
- root: functionRootPath
797
- });
798
- await packer.build();
799
- // 通过云 API 传输的代码大小不能超过 50MB
800
- const reachMax = await packer.isReachMaxSize();
801
- if (reachMax) {
802
- throw new error_1.CloudBaseError('函数代码不能大于 50MB');
803
- }
804
- const base64 = await packer.getBase64Code();
805
- if (!(base64 === null || base64 === void 0 ? void 0 : base64.length)) {
806
- throw new error_1.CloudBaseError('文件不能为空');
807
- }
808
- return {
809
- ZipFile: base64
810
- };
811
- }
812
- // 获取 COS 临时信息
813
- async getTempCosInfo(name) {
814
- const { env, appId } = await this.getFunctionConfig();
815
- /**
816
- * Response:
817
- * Date: "2020-03-18"
818
- * RequestId: "91876f56-7cd3-42bb-bc32-b74df5d0516e"
819
- * Sign: "Gc8QvXD50dx7yBfsl2yEYFwIL45hPTEyNTM2NjU4MTkm
820
- */
821
- return this.scfService.request('GetTempCosInfo', {
822
- ObjectPath: `${appId}/${env}/${name}.zip"`
823
- });
824
- }
825
- async retryCreateTrigger(name, triggers, count = 0) {
826
- try {
827
- const res = await this.createFunctionTriggers(name, triggers);
828
- return res;
829
- }
830
- catch (e) {
831
- if (count < 3) {
832
- await utils_1.sleep(500);
833
- const res = await this.retryCreateTrigger(name, triggers, count + 1);
834
- return res;
835
- }
836
- else {
837
- throw e;
838
- }
839
- }
840
- }
841
- /**
842
- * 获取函数配置信息
843
- * @private
844
- * @returns
845
- * @memberof FunctionService
846
- */
847
- getFunctionConfig() {
848
- var _a;
849
- const envConfig = this.environment.lazyEnvironmentConfig;
850
- const namespace = envConfig.Functions[0].Namespace;
851
- const appId = (_a = envConfig.Storages[0]) === null || _a === void 0 ? void 0 : _a.AppId;
852
- const { proxy } = this.environment.cloudBaseContext;
853
- return {
854
- proxy,
855
- appId,
856
- namespace,
857
- env: envConfig.EnvId
858
- };
859
- }
860
- /**
861
- * 获取日志cls配置信息
862
- */
863
- getClsServiceConfig() {
864
- var _a, _b;
865
- const currentEnv = this.environment.lazyEnvironmentConfig;
866
- const customLogServices = (_a = currentEnv === null || currentEnv === void 0 ? void 0 : currentEnv.CustomLogServices) === null || _a === void 0 ? void 0 : _a[0];
867
- const logServices = (_b = currentEnv === null || currentEnv === void 0 ? void 0 : currentEnv.LogServices) === null || _b === void 0 ? void 0 : _b[0];
868
- return {
869
- TopicId: (customLogServices === null || customLogServices === void 0 ? void 0 : customLogServices.ClsTopicId) || (logServices === null || logServices === void 0 ? void 0 : logServices.TopicId),
870
- LogsetId: (customLogServices === null || customLogServices === void 0 ? void 0 : customLogServices.ClsLogsetId) || (logServices === null || logServices === void 0 ? void 0 : logServices.LogsetId)
871
- };
872
- }
873
- /**
874
- * 获取 vpc 信息
875
- * @returns
876
- */
877
- async getVpcs() {
878
- const { VpcSet } = await this.vpcService.request('DescribeVpcs');
879
- return VpcSet;
880
- }
881
- /**
882
- * 获取子网
883
- * @param {string} vpcId
884
- * @returns
885
- */
886
- async getSubnets(vpcId) {
887
- const { SubnetSet } = await this.vpcService.request('DescribeSubnets', {
888
- Filters: [
889
- {
890
- Name: 'vpc-id',
891
- Values: [vpcId]
892
- }
893
- ]
894
- });
895
- return SubnetSet;
896
- }
897
- // 检查函数状态,部分操作在函数更新中时不可进行
898
- async waitFunctionActive(funcName, codeSecret) {
899
- let ticker;
900
- let timer;
901
- let resolved;
902
- return new Promise((resolve, reject) => {
903
- // 超时时间 5 分钟
904
- timer = setTimeout(() => {
905
- clearInterval(ticker);
906
- if (!resolved) {
907
- reject(new error_1.CloudBaseError('函数状态异常,检查超时'));
908
- }
909
- }, 300000);
910
- ticker = setInterval(async () => {
911
- try {
912
- const { Status } = await this.getFunctionDetail(funcName, codeSecret);
913
- // 更新中
914
- if (Status === constant_1.SCF_STATUS.CREATING || Status === constant_1.SCF_STATUS.UPDATING)
915
- return;
916
- // 创建失败
917
- if (Status === constant_1.SCF_STATUS.CREATE_FAILED) {
918
- throw new error_1.CloudBaseError('云函数创建失败');
919
- }
920
- // 函数状态正常
921
- clearInterval(ticker);
922
- clearTimeout(timer);
923
- resolve();
924
- }
925
- catch (e) {
926
- clearInterval(ticker);
927
- clearTimeout(timer);
928
- reject(e);
929
- }
930
- resolved = true;
931
- }, 1000);
932
- });
933
- }
934
- }
935
- __decorate([
936
- utils_1.preLazy()
937
- ], FunctionService.prototype, "updateFunctionIncrementalCode", null);
938
- __decorate([
939
- utils_1.preLazy()
940
- ], FunctionService.prototype, "createFunction", null);
941
- __decorate([
942
- utils_1.preLazy()
943
- ], FunctionService.prototype, "getFunctionList", null);
944
- __decorate([
945
- utils_1.preLazy()
946
- ], FunctionService.prototype, "listFunctions", null);
947
- __decorate([
948
- utils_1.preLazy()
949
- ], FunctionService.prototype, "deleteFunction", null);
950
- __decorate([
951
- utils_1.preLazy()
952
- ], FunctionService.prototype, "getFunctionDetail", null);
953
- __decorate([
954
- utils_1.preLazy()
955
- ], FunctionService.prototype, "getFunctionLogs", null);
956
- __decorate([
957
- utils_1.preLazy()
958
- ], FunctionService.prototype, "updateFunctionConfig", null);
959
- __decorate([
960
- utils_1.preLazy()
961
- ], FunctionService.prototype, "updateFunctionCode", null);
962
- __decorate([
963
- utils_1.preLazy()
964
- ], FunctionService.prototype, "invokeFunction", null);
965
- __decorate([
966
- utils_1.preLazy()
967
- ], FunctionService.prototype, "copyFunction", null);
968
- __decorate([
969
- utils_1.preLazy()
970
- ], FunctionService.prototype, "createFunctionTriggers", null);
971
- __decorate([
972
- utils_1.preLazy()
973
- ], FunctionService.prototype, "deleteFunctionTrigger", null);
974
- __decorate([
975
- utils_1.preLazy()
976
- ], FunctionService.prototype, "getFunctionDownloadUrl", null);
977
- __decorate([
978
- utils_1.preLazy()
979
- ], FunctionService.prototype, "createLayer", null);
980
- __decorate([
981
- utils_1.preLazy()
982
- ], FunctionService.prototype, "deleteLayerVersion", null);
983
- __decorate([
984
- utils_1.preLazy()
985
- ], FunctionService.prototype, "listLayerVersions", null);
986
- __decorate([
987
- utils_1.preLazy()
988
- ], FunctionService.prototype, "listLayers", null);
989
- __decorate([
990
- utils_1.preLazy()
991
- ], FunctionService.prototype, "getLayerVersion", null);
992
- __decorate([
993
- utils_1.preLazy()
994
- ], FunctionService.prototype, "setProvisionedConcurrencyConfig", null);
995
- __decorate([
996
- utils_1.preLazy()
997
- ], FunctionService.prototype, "getProvisionedConcurrencyConfig", null);
998
- __decorate([
999
- utils_1.preLazy()
1000
- ], FunctionService.prototype, "deleteProvisionedConcurrencyConfig", null);
1001
- __decorate([
1002
- utils_1.preLazy()
1003
- ], FunctionService.prototype, "publishVersion", null);
1004
- __decorate([
1005
- utils_1.preLazy()
1006
- ], FunctionService.prototype, "listVersionByFunction", null);
1007
- __decorate([
1008
- utils_1.preLazy()
1009
- ], FunctionService.prototype, "updateFunctionAliasConfig", null);
1010
- __decorate([
1011
- utils_1.preLazy()
1012
- ], FunctionService.prototype, "getFunctionAlias", null);
1013
- __decorate([
1014
- utils_1.preLazy()
1015
- ], FunctionService.prototype, "createAccessPath", null);
1016
- __decorate([
1017
- utils_1.preLazy()
1018
- ], FunctionService.prototype, "getCodeParams", null);
1019
- __decorate([
1020
- utils_1.preLazy()
1021
- ], FunctionService.prototype, "getTempCosInfo", null);
1022
- exports.FunctionService = FunctionService;