@geek-fun/serverlessinsight 0.8.2 → 0.8.3

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 (119) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +14 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +14 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +348 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +14 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +114 -0
  6. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +1 -0
  7. package/README.md +26 -18
  8. package/README.zh-CN.md +19 -6
  9. package/dist/package.json +3 -1
  10. package/dist/src/commands/deploy.js +87 -4
  11. package/dist/src/commands/destroy.js +61 -10
  12. package/dist/src/commands/forceUnlock.js +8 -0
  13. package/dist/src/commands/index.js +34 -2
  14. package/dist/src/commands/login.js +195 -0
  15. package/dist/src/commands/logout.js +17 -0
  16. package/dist/src/commands/show.js +15 -7
  17. package/dist/src/commands/whoami.js +20 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +327 -30
  19. package/dist/src/common/aliyunClient/esOperations.js +43 -29
  20. package/dist/src/common/aliyunClient/fc3Operations.js +481 -207
  21. package/dist/src/common/aliyunClient/ossOperations.js +165 -13
  22. package/dist/src/common/aliyunClient/rdsOperations.js +143 -39
  23. package/dist/src/common/aliyunClient/slsOperations.js +56 -26
  24. package/dist/src/common/aliyunClient/tablestoreOperations.js +25 -22
  25. package/dist/src/common/apiClient.js +102 -0
  26. package/dist/src/common/constants.js +9 -4
  27. package/dist/src/common/credentialStore.js +94 -0
  28. package/dist/src/common/credentials.js +2 -0
  29. package/dist/src/common/eventQueue.js +208 -0
  30. package/dist/src/common/hashUtils.js +87 -11
  31. package/dist/src/common/imsClient.js +1 -0
  32. package/dist/src/common/index.js +3 -0
  33. package/dist/src/common/lockManager.js +61 -54
  34. package/dist/src/common/logger.js +2 -0
  35. package/dist/src/common/polling.js +54 -0
  36. package/dist/src/common/reportResourceEvent.js +8 -0
  37. package/dist/src/common/runtimeMapper.js +11 -12
  38. package/dist/src/common/stateBackend/index.js +10 -1
  39. package/dist/src/common/stateBackend/localStateBackend.js +4 -1
  40. package/dist/src/common/stateBackend/remoteStateBackend.js +6 -3
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +135 -13
  43. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  44. package/dist/src/common/tencentClient/esOperations.js +110 -46
  45. package/dist/src/common/tencentClient/index.js +22 -1
  46. package/dist/src/common/tencentClient/scfOperations.js +255 -133
  47. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  48. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  49. package/dist/src/common/triggerMapper.js +36 -0
  50. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  51. package/dist/src/common/volcengineClient/iamOperations.js +58 -48
  52. package/dist/src/common/volcengineClient/index.js +46 -21
  53. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  54. package/dist/src/common/volcengineClient/tlsOperations.js +229 -178
  55. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  56. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  57. package/dist/src/lang/en.js +84 -0
  58. package/dist/src/lang/zh-CN.js +84 -0
  59. package/dist/src/parser/eventParser.js +2 -0
  60. package/dist/src/parser/functionParser.js +96 -65
  61. package/dist/src/parser/index.js +7 -4
  62. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  63. package/dist/src/stack/aliyunStack/apigwPlanner.js +14 -10
  64. package/dist/src/stack/aliyunStack/apigwResource.js +216 -124
  65. package/dist/src/stack/aliyunStack/apigwTypes.js +16 -3
  66. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  67. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  68. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  69. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  70. package/dist/src/stack/aliyunStack/destroyer.js +2 -2
  71. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  72. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  73. package/dist/src/stack/aliyunStack/fc3Resource.js +327 -64
  74. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  75. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  76. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  77. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  78. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  79. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  80. package/dist/src/stack/alreadyExists.js +26 -0
  81. package/dist/src/stack/ownershipTag.js +40 -0
  82. package/dist/src/stack/rfsStack/index.js +3 -1
  83. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  84. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  85. package/dist/src/stack/scfStack/cosResource.js +167 -64
  86. package/dist/src/stack/scfStack/deployer.js +2 -2
  87. package/dist/src/stack/scfStack/destroyer.js +2 -2
  88. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  89. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  90. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  91. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  92. package/dist/src/stack/scfStack/scfPlanner.js +12 -2
  93. package/dist/src/stack/scfStack/scfResource.js +484 -14
  94. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  95. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  96. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  97. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  98. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  99. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  100. package/dist/src/stack/volcengineStack/apigwResource.js +418 -222
  101. package/dist/src/stack/volcengineStack/apigwTypes.js +76 -66
  102. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  103. package/dist/src/stack/volcengineStack/destroyer.js +1 -1
  104. package/dist/src/stack/volcengineStack/index.js +1 -2
  105. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  106. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  107. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  108. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  109. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  110. package/dist/src/stack/volcengineStack/vefaasPlanner.js +71 -2
  111. package/dist/src/stack/volcengineStack/vefaasResource.js +148 -98
  112. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  113. package/dist/src/types/domains/backend.js +1 -0
  114. package/dist/src/types/domains/state.js +29 -1
  115. package/dist/src/validator/eventSchema.js +10 -0
  116. package/dist/src/validator/functionSchema.js +37 -12
  117. package/dist/src/validator/iacSchema.js +1 -0
  118. package/dist/tsconfig.tsbuildinfo +1 -1
  119. package/package.json +3 -1
@@ -37,11 +37,15 @@ exports.createVefaasOperations = void 0;
37
37
  const openapi_1 = require("@volcengine/openapi");
38
38
  const logger_1 = require("../../common/logger");
39
39
  const lang_1 = require("../../lang");
40
+ const polling_1 = require("../polling");
41
+ const constants_1 = require("../constants");
40
42
  const fs = __importStar(require("node:fs"));
41
43
  const MAX_ZIP_SIZE_MB = 50;
42
44
  const MAX_ZIP_SIZE_BYTES = MAX_ZIP_SIZE_MB * 1024 * 1024;
43
45
  const MAX_TOS_SIZE_MB = 500;
44
46
  const MAX_TOS_SIZE_BYTES = MAX_TOS_SIZE_MB * 1024 * 1024;
47
+ const RELEASE_POLL_INTERVAL_MS = 2000;
48
+ const RELEASE_POLL_MAX_ATTEMPTS = 60;
45
49
  const buildEnvVariables = (envs) => {
46
50
  if (!envs)
47
51
  return undefined;
@@ -126,13 +130,109 @@ const createVefaasOperations = (client) => {
126
130
  const tosClient = new openapi_1.Service({
127
131
  serviceName: 'tos',
128
132
  defaultVersion: '2018-08-01',
129
- protocol: 'https',
130
- host: 'tos-cn-beijing.volces.com',
133
+ host: `tos-${client.region}.volces.com`,
131
134
  accessKeyId: client.accessKeyId,
132
135
  secretKey: client.secretKey,
133
136
  region: client.region,
134
137
  });
135
- return {
138
+ // veFaaS identifies functions by their generated Id (not Name) for
139
+ // GetFunction/Update/Delete; callers probe by name, so list + match on Name.
140
+ const listAllFunctions = async () => {
141
+ const items = [];
142
+ let pageNumber = 1;
143
+ const pageSize = 100;
144
+ for (;;) {
145
+ const response = await client.fetchOpenAPI({
146
+ Action: 'ListFunctions',
147
+ Version: '2024-06-06',
148
+ method: 'POST',
149
+ headers: { 'content-type': 'application/json' },
150
+ data: { PageSize: pageSize, PageNumber: pageNumber },
151
+ });
152
+ const result = (response.Result || {});
153
+ const page = (result.Items || []);
154
+ items.push(...page);
155
+ if (page.length < pageSize)
156
+ break;
157
+ pageNumber += 1;
158
+ }
159
+ return items;
160
+ };
161
+ const resolveFunctionIdByName = async (functionName) => {
162
+ const functions = await listAllFunctions();
163
+ const match = functions.find((fn) => fn.Name === functionName);
164
+ return match?.Id ?? null;
165
+ };
166
+ const operations = {
167
+ // veFaaS 函数代码/配置更新后需发布(Release)才生效;API 网关上游
168
+ // 引用函数时要求函数已发布(OperationDenied.FunctionNotPublished)。
169
+ // RevisionNumber=0 表示发布 Latest 代码并创建新版本(官方 SDK 语义)。
170
+ // Release 是异步的:返回的 Status 可能仍是 inprogress,调用方(如
171
+ // CreateUpstream)必须等发布真正 done 才能引用函数,否则会拿到
172
+ // FunctionNotPublished。这里轮询 GetReleaseStatus 直到 done/failed。
173
+ releaseFunction: async (functionId) => {
174
+ const response = await client.fetchOpenAPI({
175
+ Action: 'Release',
176
+ Version: '2024-06-06',
177
+ method: 'POST',
178
+ headers: { 'content-type': 'application/json' },
179
+ data: {
180
+ FunctionId: functionId,
181
+ RevisionNumber: 0,
182
+ },
183
+ });
184
+ const result = (response.Result || {});
185
+ logger_1.logger.info(lang_1.lang.__('FUNCTION_RELEASED', { functionId }));
186
+ const releaseRecordId = result.ReleaseRecordId ?? undefined;
187
+ const releaseStatus = await (0, polling_1.pollUntil)({
188
+ description: `veFaaS function ${functionId} release to finish`,
189
+ fetch: async () => {
190
+ const statusResponse = await client.fetchOpenAPI({
191
+ Action: 'GetReleaseStatus',
192
+ Version: '2024-06-06',
193
+ method: 'POST',
194
+ headers: { 'content-type': 'application/json' },
195
+ data: { FunctionId: functionId },
196
+ });
197
+ const statusResult = (statusResponse.Result || {});
198
+ return statusResult.Status;
199
+ },
200
+ isDone: (status) => status === 'done' || status === 'failed',
201
+ intervalMs: RELEASE_POLL_INTERVAL_MS,
202
+ maxAttempts: RELEASE_POLL_MAX_ATTEMPTS,
203
+ onProgress: (status, attempt, maxAttempts) => {
204
+ logger_1.logger.info(lang_1.lang.__('WAITING_FOR_FUNCTION_RELEASE', {
205
+ functionId,
206
+ status: status ?? 'unknown',
207
+ attempt: String(attempt),
208
+ maxAttempts: String(maxAttempts),
209
+ }));
210
+ },
211
+ });
212
+ if (releaseStatus === 'failed') {
213
+ throw new Error(`veFaaS function ${functionId} release failed`);
214
+ }
215
+ return releaseRecordId;
216
+ },
217
+ waitForFunctionDeleted: async (functionId) => {
218
+ try {
219
+ await (0, polling_1.pollUntil)({
220
+ description: `veFaaS function ${functionId} to be deleted`,
221
+ fetch: () => operations.getFunctionById(functionId),
222
+ isDone: (info) => info === null,
223
+ intervalMs: constants_1.SCF_STATUS_POLL_INTERVAL_MS,
224
+ maxAttempts: constants_1.SCF_STATUS_POLL_MAX_ATTEMPTS,
225
+ });
226
+ }
227
+ catch (e) {
228
+ if (e instanceof polling_1.PollingTimeoutError) {
229
+ throw new Error(`Timed out waiting for veFaaS function ${functionId} to be deleted`, {
230
+ cause: e,
231
+ });
232
+ }
233
+ throw e;
234
+ }
235
+ },
136
236
  createFunction: async (config, codePath) => {
137
237
  const { size, sizeMB } = await validateCodePackage(codePath);
138
238
  let codeSource;
@@ -164,16 +264,17 @@ const createVefaasOperations = (client) => {
164
264
  };
165
265
  }
166
266
  const params = {
167
- FunctionName: config.functionName,
267
+ Name: config.functionName,
168
268
  Runtime: config.runtime,
169
269
  Handler: config.handler,
170
- MemoryMb: config.memoryMb,
270
+ MemoryMB: config.memoryMb,
171
271
  RequestTimeout: config.requestTimeout,
172
272
  ...(config.description && { Description: config.description }),
173
273
  ...(config.environmentVariables && {
174
274
  Envs: buildEnvVariables(config.environmentVariables),
175
275
  }),
176
276
  ...(config.role && { Role: config.role }),
277
+ ...(config.Tags && { Tags: config.Tags }),
177
278
  ...codeSource,
178
279
  ...(config.vpcConfig && {
179
280
  VpcConfig: {
@@ -195,38 +296,63 @@ const createVefaasOperations = (client) => {
195
296
  },
196
297
  }),
197
298
  ...(config.logConfig && {
198
- LogConfig: {
299
+ TlsConfig: {
199
300
  EnableLog: true,
200
- ProjectName: config.logConfig.project,
201
- TopicName: config.logConfig.topic,
301
+ TlsProjectId: config.logConfig.project,
302
+ TlsTopicId: config.logConfig.topic,
202
303
  },
203
304
  }),
204
305
  };
205
- await client.fetchOpenAPI({
306
+ const response = await client.fetchOpenAPI({
206
307
  Action: 'CreateFunction',
207
308
  Version: '2024-06-06',
208
309
  method: 'POST',
209
310
  headers: { 'content-type': 'application/json' },
210
311
  data: params,
211
312
  });
313
+ const result = (response.Result || {});
314
+ const functionId = result.Id ?? result.FunctionId;
315
+ if (!functionId) {
316
+ throw new Error(`CreateFunction did not return a function Id for ${config.functionName}`);
317
+ }
318
+ const releaseRecordId = await operations.releaseFunction(functionId);
212
319
  logger_1.logger.info(lang_1.lang.__('FUNCTION_CREATED', { functionName: config.functionName }));
320
+ return { functionId, releaseRecordId };
213
321
  },
214
322
  getFunction: async (functionName) => {
215
323
  try {
216
- const response = await client.fetchOpenAPI({
324
+ const functionId = await resolveFunctionIdByName(functionName);
325
+ if (!functionId) {
326
+ return null;
327
+ }
328
+ return operations.getFunctionById(functionId);
329
+ }
330
+ catch (error) {
331
+ if (error && typeof error === 'object' && 'code' in error) {
332
+ if (error.code === 'ResourceNotFound' || error.code === 'FunctionNotFound') {
333
+ return null;
334
+ }
335
+ }
336
+ throw error;
337
+ }
338
+ },
339
+ getFunctionById: async (functionId) => {
340
+ let response;
341
+ try {
342
+ response = await client.fetchOpenAPI({
217
343
  Action: 'GetFunction',
218
344
  Version: '2024-06-06',
219
345
  method: 'POST',
220
346
  headers: { 'content-type': 'application/json' },
221
- data: { FunctionName: functionName },
347
+ data: { Id: functionId },
222
348
  });
223
349
  const data = (response.Result || {});
224
350
  return {
225
- functionId: data.FunctionId,
226
- functionName: data.FunctionName,
351
+ functionId: data.Id ?? data.FunctionId,
352
+ functionName: data.Name ?? data.FunctionName,
227
353
  runtime: data.Runtime,
228
354
  handler: data.Handler,
229
- memoryMb: data.MemoryMb,
355
+ memoryMb: data.MemoryMB ?? data.MemoryMb,
230
356
  requestTimeout: data.RequestTimeout,
231
357
  description: data.Description,
232
358
  environmentVariables: parseEnvVariables(data.Envs),
@@ -234,19 +360,106 @@ const createVefaasOperations = (client) => {
234
360
  createdTime: data.CreationTime,
235
361
  lastModifiedTime: data.LastUpdateTime,
236
362
  role: data.Role,
237
- vpcConfig: data.VpcConfig
238
- ? {
239
- vpcId: data.VpcConfig.VpcId,
240
- subnetIds: data.VpcConfig.SubnetIds,
241
- securityGroupIds: data.VpcConfig.SecurityGroupIds,
242
- }
243
- : undefined,
244
- logConfig: data.LogConfig
245
- ? {
246
- project: data.LogConfig.ProjectName,
247
- topic: data.LogConfig.TopicName,
248
- }
249
- : undefined,
363
+ vpcConfig: (() => {
364
+ const raw = data.VpcConfig;
365
+ if (!raw || Object.keys(raw).length === 0)
366
+ return undefined;
367
+ return {
368
+ vpcId: raw.VpcId,
369
+ subnetIds: raw.SubnetIds,
370
+ securityGroupIds: raw.SecurityGroupIds,
371
+ enableVpc: raw.EnableVpc,
372
+ enableSharedInternetAccess: raw.EnableSharedInternetAccess,
373
+ };
374
+ })(),
375
+ logConfig: (() => {
376
+ const raw = data.TlsConfig ??
377
+ data.LogConfig;
378
+ if (!raw || Object.keys(raw).length === 0)
379
+ return undefined;
380
+ return {
381
+ project: raw.TlsProjectId,
382
+ topic: raw.TlsTopicId,
383
+ enableLog: raw.EnableLog,
384
+ };
385
+ })(),
386
+ Tags: data.Tags?.map((t) => ({
387
+ Key: t.Key,
388
+ Value: t.Value,
389
+ })),
390
+ // Maximum-detail fields — retain everything GetFunction returns so
391
+ // state keeps full resource detail (CPU strategy, concurrency,
392
+ // network/storage/log toggles, async tasks, triggers count, tags).
393
+ exclusiveMode: data.ExclusiveMode,
394
+ maxConcurrency: data.MaxConcurrency,
395
+ codeSize: data.CodeSize,
396
+ codeSizeLimit: data.CodeSizeLimit,
397
+ sourceLocation: data.SourceLocation,
398
+ sourceType: data.SourceType,
399
+ owner: data.Owner,
400
+ triggersCount: data.TriggersCount,
401
+ instanceType: data.InstanceType,
402
+ initializerSec: data.InitializerSec,
403
+ command: data.Command,
404
+ port: data.Port,
405
+ cpuStrategy: data.CpuStrategy,
406
+ projectName: data.ProjectName,
407
+ functionType: data.FunctionType,
408
+ cell: data.Cell,
409
+ enableApmplus: data.EnableApmplus,
410
+ nasStorage: (() => {
411
+ const raw = data.NasStorage;
412
+ if (!raw || Object.keys(raw).length === 0)
413
+ return undefined;
414
+ return {
415
+ enableNas: raw.EnableNas,
416
+ nasConfigs: raw.NasConfigs?.map((c) => ({
417
+ gid: c.Gid,
418
+ uid: c.Uid,
419
+ remotePath: c.RemotePath,
420
+ fileSystemId: c.FileSystemId,
421
+ mountPointId: c.MountPointId,
422
+ localMountPath: c.LocalMountPath,
423
+ })),
424
+ };
425
+ })(),
426
+ tosMountConfig: (() => {
427
+ const raw = data.TosMountConfig;
428
+ if (!raw || Object.keys(raw).length === 0)
429
+ return undefined;
430
+ return {
431
+ enableTos: raw.EnableTos,
432
+ mountPoints: raw.MountPoints?.map((m) => ({
433
+ endpoint: m.Endpoint,
434
+ readOnly: m.ReadOnly,
435
+ bucketName: m.BucketName,
436
+ bucketPath: m.BucketPath,
437
+ localMountPath: m.LocalMountPath,
438
+ })),
439
+ };
440
+ })(),
441
+ asyncTaskConfig: (() => {
442
+ const raw = data.AsyncTaskConfig;
443
+ if (!raw || Object.keys(raw).length === 0)
444
+ return undefined;
445
+ const destination = raw.DestinationConfig;
446
+ const mapDestination = (d) => {
447
+ const obj = d;
448
+ if (!obj)
449
+ return undefined;
450
+ return { destination: obj.Destination };
451
+ };
452
+ return {
453
+ enableAsyncTask: raw.EnableAsyncTask,
454
+ maxRetry: raw.MaxRetry,
455
+ destinationConfig: destination
456
+ ? {
457
+ onSuccess: mapDestination(destination.OnSuccess),
458
+ onFailure: mapDestination(destination.OnFailure),
459
+ }
460
+ : undefined,
461
+ };
462
+ })(),
250
463
  };
251
464
  }
252
465
  catch (error) {
@@ -258,12 +471,12 @@ const createVefaasOperations = (client) => {
258
471
  throw error;
259
472
  }
260
473
  },
261
- updateFunctionConfiguration: async (config) => {
474
+ updateFunctionConfiguration: async (functionId, config) => {
262
475
  const params = {
263
- FunctionName: config.functionName,
476
+ Id: functionId,
264
477
  Handler: config.handler,
265
478
  Runtime: config.runtime,
266
- MemoryMb: config.memoryMb,
479
+ MemoryMB: config.memoryMb,
267
480
  RequestTimeout: config.requestTimeout,
268
481
  ...(config.description !== undefined && { Description: config.description }),
269
482
  ...(config.environmentVariables && {
@@ -290,10 +503,10 @@ const createVefaasOperations = (client) => {
290
503
  },
291
504
  }),
292
505
  ...(config.logConfig && {
293
- LogConfig: {
506
+ TlsConfig: {
294
507
  EnableLog: true,
295
- ProjectName: config.logConfig.project,
296
- TopicName: config.logConfig.topic,
508
+ TlsProjectId: config.logConfig.project,
509
+ TlsTopicId: config.logConfig.topic,
297
510
  },
298
511
  }),
299
512
  };
@@ -304,16 +517,23 @@ const createVefaasOperations = (client) => {
304
517
  headers: { 'content-type': 'application/json' },
305
518
  data: params,
306
519
  });
520
+ // UpdateFunction only edits the draft config — veFaaS serves the last
521
+ // published revision until Release is called. Without it the function
522
+ // stays in an unpublished intermediate state and API Gateway invocations
523
+ // fail. Mirror the create/code-update paths and release after config
524
+ // changes too.
525
+ const releaseRecordId = await operations.releaseFunction(functionId);
307
526
  logger_1.logger.info(lang_1.lang.__('FUNCTION_CONFIGURATION_UPDATED', { functionName: config.functionName }));
527
+ return releaseRecordId;
308
528
  },
309
- updateFunctionCode: async (functionName, codePath) => {
529
+ updateFunctionCode: async (functionId, codePath) => {
310
530
  const { size, sizeMB } = await validateCodePackage(codePath);
311
531
  let codeSource;
312
532
  if (size <= MAX_ZIP_SIZE_BYTES) {
313
533
  const codeContent = await fs.promises.readFile(codePath);
314
534
  const codeBase64 = codeContent.toString('base64');
315
535
  logger_1.logger.info(lang_1.lang.__('UPDATING_FUNCTION_CODE_WITH_ZIP', {
316
- functionName,
536
+ functionName: functionId,
317
537
  size: sizeMB,
318
538
  }));
319
539
  codeSource = {
@@ -323,9 +543,9 @@ const createVefaasOperations = (client) => {
323
543
  }
324
544
  else {
325
545
  const tosBucket = `vefaas-codes-${client.region || 'cn-beijing'}`;
326
- const { bucket, key } = await uploadCodeToTos(tosClient, tosBucket, codePath, functionName);
546
+ const { bucket, key } = await uploadCodeToTos(tosClient, tosBucket, codePath, functionId);
327
547
  logger_1.logger.info(lang_1.lang.__('UPDATING_FUNCTION_CODE_WITH_TOS', {
328
- functionName,
548
+ functionName: functionId,
329
549
  size: sizeMB,
330
550
  bucket,
331
551
  key,
@@ -342,38 +562,35 @@ const createVefaasOperations = (client) => {
342
562
  method: 'POST',
343
563
  headers: { 'content-type': 'application/json' },
344
564
  data: {
345
- FunctionName: functionName,
565
+ Id: functionId,
346
566
  ...codeSource,
347
567
  },
348
568
  });
349
- logger_1.logger.info(lang_1.lang.__('FUNCTION_CODE_UPDATED', { functionName }));
569
+ const releaseRecordId = await operations.releaseFunction(functionId);
570
+ logger_1.logger.info(lang_1.lang.__('FUNCTION_CODE_UPDATED', { functionName: functionId }));
571
+ return { releaseRecordId };
350
572
  },
351
- deleteFunction: async (functionName) => {
573
+ deleteFunction: async (functionId) => {
352
574
  await client.fetchOpenAPI({
353
575
  Action: 'DeleteFunction',
354
576
  Version: '2024-06-06',
355
577
  method: 'POST',
356
578
  headers: { 'content-type': 'application/json' },
357
- data: { FunctionName: functionName },
579
+ data: { Id: functionId },
358
580
  });
359
- logger_1.logger.info(lang_1.lang.__('FUNCTION_DELETED', { functionName }));
581
+ // DeleteFunction returns immediately — wait for the function to be gone so
582
+ // a subsequent create (retry) does not collide with a still-deleting function.
583
+ await operations.waitForFunctionDeleted(functionId);
584
+ logger_1.logger.info(lang_1.lang.__('FUNCTION_DELETED', { functionName: functionId }));
360
585
  },
361
586
  listFunctions: async () => {
362
- const response = await client.fetchOpenAPI({
363
- Action: 'ListFunctions',
364
- Version: '2024-06-06',
365
- method: 'POST',
366
- headers: { 'content-type': 'application/json' },
367
- data: {},
368
- });
369
- const result = (response.Result || {});
370
- const functions = (result.Functions || []);
587
+ const functions = await listAllFunctions();
371
588
  return functions.map((fn) => ({
372
- functionId: fn.FunctionId,
373
- functionName: fn.FunctionName,
589
+ functionId: fn.Id ?? fn.FunctionId,
590
+ functionName: fn.Name ?? fn.FunctionName,
374
591
  runtime: fn.Runtime,
375
592
  handler: fn.Handler,
376
- memoryMb: fn.MemoryMb,
593
+ memoryMb: fn.MemoryMB ?? fn.MemoryMb,
377
594
  requestTimeout: fn.RequestTimeout,
378
595
  description: fn.Description,
379
596
  status: fn.Status,
@@ -382,5 +599,6 @@ const createVefaasOperations = (client) => {
382
599
  }));
383
600
  },
384
601
  };
602
+ return operations;
385
603
  };
386
604
  exports.createVefaasOperations = createVefaasOperations;
@@ -206,6 +206,7 @@ exports.en = {
206
206
  FORCE_UNLOCK_WARNING: '\n⚠️ WARNING: Force unlocking can cause state corruption if another\noperation is still running!',
207
207
  FORCE_UNLOCK_CONFIRM: 'Are you absolutely sure? (yes/no): ',
208
208
  FORCE_UNLOCK_CANCELLED: 'Force unlock cancelled',
209
+ SAAS_FORCE_UNLOCK_NOT_SUPPORTED: 'Force unlock is not supported via CLI for SaaS state. Open {{consoleUrl}} in your browser and unlock the deployment from the Deployments page.',
209
210
  PLAN_COMMAND_NOT_SUPPORTED: 'Plan command is not supported for this provider',
210
211
  // Lock info formatting
211
212
  LOCK_INFO_HEADER: 'Lock Info:',
@@ -222,6 +223,9 @@ exports.en = {
222
223
  LOCK_TIME_AGO_HOURS: '{{hours}} hours ago',
223
224
  // API Gateway messages
224
225
  APIGW_GROUP_FOUND_REUSING: 'Found existing API Group: {{groupName}}, will reuse it',
226
+ APIGW_LOG_ENABLED: 'Access log enabled for API Gateway {{gatewayId}}',
227
+ APIGW_LOG_DISABLED: 'Access log disabled for API Gateway {{gatewayId}}',
228
+ APIGW_LOG_DISABLE_FAILED: 'Failed to disable access log for API Gateway {{gatewayId}}: {{error}}',
225
229
  APIGW_DOMAIN_BINDING_FAILED: 'Failed to bind custom domain: {{error}}',
226
230
  APIGW_DOMAIN_UNBIND_FAILED: 'Failed to unbind domain {{domain}}: {{error}}',
227
231
  APIGW_WWW_DOMAIN_UNBIND_FAILED: 'Failed to unbind www domain {{domain}}: {{error}}',
@@ -560,6 +564,7 @@ exports.en = {
560
564
  VOLCENGINE_CREATING_APIGW: 'Creating Volcengine API Gateway {{gatewayName}}',
561
565
  VOLCENGINE_DELETING_APIGW: 'Deleting Volcengine API Gateway {{gatewayName}}',
562
566
  VOLCENGINE_APIGW_NOT_FOUND: 'Volcengine API Gateway {{gatewayName}} not found',
567
+ VOLCENGINE_APIGW_WAITING_RUNNING: 'Waiting for API Gateway {{gatewayName}} to be Running (status: {{status}}, attempt {{attempt}}/{{maxAttempts}})',
563
568
  // Additional Volcengine-specific messages
564
569
  RESOURCE_STATE_NOT_FOUND: 'Resource state not found for logical ID: {{logicalId}}',
565
570
  RESOURCE_INSTANCE_NOT_FOUND: 'Resource instance not found for logical ID: {{logicalId}}',
@@ -580,6 +585,9 @@ exports.en = {
580
585
  UPDATING_FUNCTION_CODE_WITH_TOS: 'Updating function {{functionName}} code with TOS ({{size}} MB) to {{bucket}}/{{key}}',
581
586
  FUNCTION_CODE_UPDATED: 'Function {{functionName}} code updated',
582
587
  FUNCTION_DELETED: 'Function {{functionName}} deleted',
588
+ FUNCTION_RELEASED: 'Function {{functionId}} released',
589
+ WAITING_FOR_FUNCTION_RELEASE: 'Waiting for function {{functionId}} release (status: {{status}}, attempt {{attempt}}/{{maxAttempts}})...',
590
+ FUNCTION_ALREADY_GONE: 'Function {{functionName}} already gone',
583
591
  // TOS Object Storage messages
584
592
  TOS_BUCKET_CREATED: 'TOS bucket {{bucketName}} created successfully',
585
593
  TOS_BUCKET_DELETED: 'TOS bucket {{bucketName}} deleted successfully',
@@ -636,13 +644,16 @@ exports.en = {
636
644
  TLS_PROJECT_CREATED: 'TLS project {{projectName}} created successfully',
637
645
  TLS_PROJECT_DELETED: 'TLS project {{projectName}} deleted successfully',
638
646
  TLS_PROJECT_NOT_FOUND: 'TLS project {{projectName}} not found',
647
+ TLS_PROJECT_ALREADY_EXISTS: 'TLS project {{projectName}} already exists, adopting existing project',
639
648
  TLS_PROJECT_TIMEOUT: 'Timeout waiting for TLS project {{projectName}} to be ready',
640
649
  TLS_TOPIC_CREATED: 'TLS topic {{topicName}} created successfully',
641
650
  TLS_TOPIC_DELETED: 'TLS topic {{topicName}} deleted successfully',
642
651
  TLS_TOPIC_NOT_FOUND: 'TLS topic {{topicName}} not found',
652
+ TLS_TOPIC_ALREADY_EXISTS: 'TLS topic {{topicName}} already exists, adopting existing topic',
643
653
  TLS_TOPIC_TIMEOUT: 'Timeout waiting for TLS topic {{topicName}} to be ready',
644
654
  TLS_INDEX_CREATED: 'TLS index for topic {{topicName}} created successfully',
645
655
  TLS_INDEX_DELETED: 'TLS index for topic {{topicName}} deleted successfully',
656
+ TLS_INDEX_ALREADY_EXISTS: 'TLS index for topic {{topicName}} already exists, skipping creation',
646
657
  TLS_PROJECT_FAILED: 'TLS project {{projectName}} failed to create',
647
658
  TLS_TOPIC_FAILED: 'TLS topic {{topicName}} failed to create',
648
659
  CREATING_TLS_PROJECT: 'Creating TLS project: {{projectName}}',
@@ -681,4 +692,77 @@ exports.en = {
681
692
  COS_BUCKET_POLICY_DELETED: 'COS bucket policy deleted for {{bucketName}}',
682
693
  TOS_BUCKET_POLICY_SET: 'TOS bucket policy set for {{bucketName}}',
683
694
  TOS_BUCKET_POLICY_DELETED: 'TOS bucket policy deleted for {{bucketName}}',
695
+ // Auth / Login / Logout / Whoami messages
696
+ LOGIN_ALREADY_LOGGED_IN: 'Already logged in as {{userEmail}} (Org: {{orgName}}). Re-authenticate? [y/N]',
697
+ LOGIN_REVOKING_OLD_KEY: 'Revoking old API key...',
698
+ LOGIN_CHOOSE_METHOD: 'How would you like to authenticate?',
699
+ LOGIN_OPTION_BROWSER: 'Login via Web Console (opens browser)',
700
+ LOGIN_OPTION_API_KEY: 'Input API Key (paste an existing key)',
701
+ LOGIN_SELECT_CHOICE: 'Enter choice (1): ',
702
+ LOGIN_ENTER_API_KEY: 'Enter your API Key: ',
703
+ LOGIN_VALIDATING_KEY: 'Validating API key...',
704
+ LOGIN_KEY_INVALID: 'Invalid API key. Please check and try again.',
705
+ LOGIN_KEY_FORMAT_INVALID: 'Invalid API key format. Expected: si_<prefix>_<secret>',
706
+ LOGIN_STARTING_SERVER: 'Starting local server for authentication callback...',
707
+ LOGIN_OPENING_BROWSER: 'Opening browser for Console authorization...',
708
+ LOGIN_BROWSER_UNAVAILABLE: 'Unable to open browser automatically.\nPlease visit the following URL in your browser:\n{{url}}',
709
+ LOGIN_SERVER_DONE: 'Authorization received. Completing login...',
710
+ LOGIN_SUCCESS: '✅ Logged in as {{userEmail}} · Org: {{orgName}}',
711
+ LOGIN_SUCCESS_KEY: '✅ Authenticated with API key · Org: {{orgName}}',
712
+ LOGIN_TIMEOUT: 'Login timed out. Please try again.',
713
+ LOGIN_SERVER_ERROR: 'Login server error: {{error}}',
714
+ LOGIN_CANCELLED: 'Login cancelled.',
715
+ LOGOUT_REVOKING: 'Revoking API key...',
716
+ LOGOUT_DELETING_CREDENTIALS: 'Deleting stored credentials...',
717
+ LOGOUT_SUCCESS: '✅ Logged out',
718
+ LOGOUT_NOT_LOGGED_IN: 'Not logged in.',
719
+ LOGOUT_REVOKE_FAILED: 'Failed to revoke API key: {{error}}',
720
+ WHOAMI_LOGGED_IN: 'Logged in as {{userEmail}}',
721
+ WHOAMI_ORG: 'Org: {{orgName}}',
722
+ WHOAMI_CONSOLE: 'Console: {{url}}',
723
+ WHOAMI_API_KEY: 'API Key: {{keyPrefix}}...',
724
+ WHOAMI_NOT_LOGGED_IN: 'Not logged in. Run `si login` to authenticate.',
725
+ WHOAMI_KEY_ACTIVE: 'active',
726
+ // Credential messages
727
+ CREDENTIAL_NOT_FOUND: 'No credentials found.',
728
+ CREDENTIAL_CORRUPTED: 'Credentials file is corrupted. Run `si login` again.',
729
+ CREDENTIAL_FILE_PERMISSION: 'Warning: credentials.json has permissions {{perms}}, recommend 0600',
730
+ CREDENTIAL_KEY_EXPIRED: 'Stored API key is expired. Run `si login` again.',
731
+ CREDENTIAL_KEY_REVOKED: 'API key revoked. Run `si login` or update SI_API_KEY.',
732
+ CREDENTIAL_KEY_DISABLED: 'API key disabled by administrator. Contact your admin.',
733
+ CREDENTIAL_NETWORK_ERROR: 'Unable to reach Console. Check your connection.',
734
+ CREDENTIAL_KEY_SCOPE: 'API key does not have {{permission}} permission for service {{service}}',
735
+ // SaaS backend messages
736
+ SAAS_BACKEND_LOADING_STATE: 'Loading state from Console...',
737
+ SAAS_BACKEND_SAVING_STATE: 'Saving state to Console...',
738
+ SAAS_BACKEND_DEPLOYMENT_STARTED: 'Starting deployment on Console...',
739
+ SAAS_BACKEND_DEPLOYMENT_EVENT: 'Deployment event: {{logicalId}} {{action}} {{status}}',
740
+ SAAS_BACKEND_DEPLOYMENT_COMPLETE: 'Deployment completed on Console.',
741
+ SAAS_BACKEND_DEPLOYMENT_FAILED: 'Deployment failed on Console: {{error}}',
742
+ SAAS_BACKEND_LOCK_CHECK: 'Checking deployment lock status...',
743
+ SAAS_BACKEND_NO_CREDENTIALS: 'SaaS state requires Console login.\nRun `si login`, or:\n- Set SI_API_KEY environment variable\n- Use --si-api-key flag\n- Configure a local or bucket backend in serverlessinsight.yml',
744
+ SAAS_BACKEND_CONSOLE_UNREACHABLE: 'Unable to reach Console. Deploy requires Console connectivity.',
745
+ // API error messages
746
+ API_ERROR_401: 'API key is invalid or expired. Run `si login` to update.',
747
+ API_ERROR_403: 'Access forbidden. Contact your administrator.',
748
+ API_ERROR_409: 'State conflict: {{message}}',
749
+ API_ERROR_NETWORK: 'Network error: {{message}}. Check your connection.',
750
+ API_ERROR_UNKNOWN: 'API error ({{status}}): {{message}}',
751
+ // HTTP trigger messages
752
+ HTTP_TRIGGER_AUTH_TYPE_REQUIRED: "HTTP trigger '{{functionName}}' requires 'auth_type' (public or iam)",
753
+ CREATING_HTTP_TRIGGER: "Creating HTTP trigger '{{triggerName}}' for function '{{functionName}}'...",
754
+ HTTP_TRIGGER_CREATED: "HTTP trigger '{{triggerName}}' created for function '{{functionName}}'",
755
+ UPDATING_HTTP_TRIGGER: "Recreating HTTP trigger for function '{{functionName}}'...",
756
+ DELETING_HTTP_TRIGGER: "Deleting HTTP trigger '{{triggerName}}' for function '{{functionName}}'...",
757
+ HTTP_TRIGGER_DELETED: "HTTP trigger '{{triggerName}}' deleted",
758
+ HTTP_TRIGGER_NOT_FOUND: "HTTP trigger '{{triggerName}}' not found in provider, skipping delete",
759
+ CREATING_CUSTOM_DOMAIN: "Creating custom domain '{{domainName}}'...",
760
+ CUSTOM_DOMAIN_CREATED: "Custom domain '{{domainName}}' created",
761
+ UPDATING_CUSTOM_DOMAIN: "Updating custom domain '{{domainName}}'...",
762
+ DELETING_CUSTOM_DOMAIN: "Deleting custom domain '{{domainName}}'...",
763
+ CUSTOM_DOMAIN_DELETED: "Custom domain '{{domainName}}' deleted",
764
+ DOMAIN_NOT_SUPPORTED_PROVIDER: "Custom domain is not supported for provider '{{provider}}'",
765
+ EVENT_FLUSH_FAILED: 'Failed to flush deployment events for {{deploymentId}} ({{count}} events): {{error}}',
766
+ EVENT_REPLAY_FAILED: 'Failed to replay event queue file {{file}}: {{error}}',
767
+ INVALID_HTTP_TRIGGER_AUTH_TYPE: "Invalid HTTP trigger auth_type '{{authType}}'; must be 'public' or 'iam'",
684
768
  };