@geek-fun/serverlessinsight 0.8.3 → 0.8.5

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 (61) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +3 -2
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +21 -2
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +46 -35
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +3 -2
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +63 -23
  6. package/CHANGELOG.md +55 -0
  7. package/README.md +1 -1
  8. package/dist/package.json +26 -25
  9. package/dist/src/common/aliyunClient/apigwOperations.js +36 -0
  10. package/dist/src/common/aliyunClient/fc3Operations.js +7 -0
  11. package/dist/src/common/aliyunClient/slsOperations.js +35 -3
  12. package/dist/src/common/constants.js +5 -1
  13. package/dist/src/common/index.js +2 -0
  14. package/dist/src/common/nameBuilder.js +80 -0
  15. package/dist/src/common/providerNames.js +54 -0
  16. package/dist/src/common/runtimeMapper.js +25 -4
  17. package/dist/src/common/stateBackend/remoteStateBackend.js +4 -1
  18. package/dist/src/common/stateManager.js +52 -2
  19. package/dist/src/common/tencentClient/clsOperations.js +137 -0
  20. package/dist/src/common/tencentClient/index.js +21 -1
  21. package/dist/src/common/tencentClient/scfOperations.js +11 -0
  22. package/dist/src/common/volcengineClient/iamOperations.js +33 -0
  23. package/dist/src/common/volcengineClient/tlsOperations.js +84 -1
  24. package/dist/src/lang/en.js +29 -1
  25. package/dist/src/lang/zh-CN.js +29 -1
  26. package/dist/src/parser/index.js +2 -1
  27. package/dist/src/stack/aliyunStack/apigwPlanner.js +2 -0
  28. package/dist/src/stack/aliyunStack/apigwResource.js +118 -1
  29. package/dist/src/stack/aliyunStack/apigwTypes.js +32 -20
  30. package/dist/src/stack/aliyunStack/destroyer.js +25 -0
  31. package/dist/src/stack/aliyunStack/fc3Resource.js +91 -32
  32. package/dist/src/stack/aliyunStack/sharedLogProject.js +137 -0
  33. package/dist/src/stack/ownershipTag.js +19 -1
  34. package/dist/src/stack/scfStack/destroyer.js +13 -0
  35. package/dist/src/stack/scfStack/scfPlanner.js +9 -1
  36. package/dist/src/stack/scfStack/scfResource.js +205 -13
  37. package/dist/src/stack/scfStack/scfTypes.js +6 -0
  38. package/dist/src/stack/scfStack/sharedLogset.js +126 -0
  39. package/dist/src/stack/volcengineStack/apigwResource.js +64 -48
  40. package/dist/src/stack/volcengineStack/apigwTypes.js +10 -7
  41. package/dist/src/stack/volcengineStack/destroyer.js +12 -0
  42. package/dist/src/stack/volcengineStack/sharedLogProject.js +190 -0
  43. package/dist/src/stack/volcengineStack/vefaasPlanner.js +20 -13
  44. package/dist/src/stack/volcengineStack/vefaasResource.js +76 -76
  45. package/dist/src/types/domains/state.js +3 -0
  46. package/dist/src/validator/bucketSchema.js +3 -5
  47. package/dist/src/validator/eventSchema.js +7 -4
  48. package/dist/src/validator/functionSchema.js +3 -2
  49. package/dist/src/validator/iacSchema.js +11 -4
  50. package/dist/src/validator/rootSchema.js +27 -0
  51. package/dist/src/validator/semanticValidation.js +122 -0
  52. package/dist/src/validator/tableschema.js +2 -0
  53. package/dist/src/validator/templateRefSchema.js +23 -3
  54. package/dist/tsconfig.tsbuildinfo +1 -1
  55. package/package.json +26 -25
  56. package/samples/aliyun-poc-fc-gpu.yml +2 -2
  57. package/samples/aliyun-poc-table.yml +1 -1
  58. package/samples/volcengine-poc-advanced.yml +4 -8
  59. package/samples/volcengine-poc-api.yml +1 -1
  60. package/samples/volcengine-poc-function.yml +1 -1
  61. package/samples/volcengine-poc-vpc.yml +3 -7
@@ -84,6 +84,22 @@ const isNotFoundError = (error) => {
84
84
  code === 'ResourceNotFound' ||
85
85
  code === 'NotFound');
86
86
  };
87
+ const listTagsForResource = async (tlsClient, resourceType, resourceId) => {
88
+ try {
89
+ const response = await tlsClient.ListTagsForResources({
90
+ ResourceType: resourceType,
91
+ ResourcesIds: [resourceId],
92
+ MaxResults: 50,
93
+ });
94
+ return (response.ResourceTags ?? []).map((rt) => ({ Key: rt.TagKey, Value: rt.TagValue }));
95
+ }
96
+ catch (error) {
97
+ if (isNotFoundError(error)) {
98
+ return [];
99
+ }
100
+ throw error;
101
+ }
102
+ };
87
103
  const createTlsOperations = (tlsClient) => {
88
104
  const operations = {
89
105
  createProject: async (config) => {
@@ -100,6 +116,7 @@ const createTlsOperations = (tlsClient) => {
100
116
  description: config.description,
101
117
  region: config.region,
102
118
  status: 'Active',
119
+ created: true,
103
120
  };
104
121
  }
105
122
  catch (error) {
@@ -107,13 +124,14 @@ const createTlsOperations = (tlsClient) => {
107
124
  logger_1.logger.warn(lang_1.lang.__('TLS_PROJECT_ALREADY_EXISTS', { projectName: config.projectName }));
108
125
  const existing = await operations.getProject(config.projectName);
109
126
  if (existing) {
110
- return existing;
127
+ return { ...existing, created: false };
111
128
  }
112
129
  return {
113
130
  projectName: config.projectName,
114
131
  description: config.description,
115
132
  region: config.region,
116
133
  status: 'Active',
134
+ created: false,
117
135
  };
118
136
  }
119
137
  throw error;
@@ -142,6 +160,13 @@ const createTlsOperations = (tlsClient) => {
142
160
  throw error;
143
161
  }
144
162
  },
163
+ getProjectTags: async (projectName) => {
164
+ const project = await operations.getProject(projectName);
165
+ if (!project?.projectId) {
166
+ return [];
167
+ }
168
+ return listTagsForResource(tlsClient, 'project', project.projectId);
169
+ },
145
170
  deleteProject: async (projectName) => {
146
171
  try {
147
172
  const existing = await operations.getProject(projectName);
@@ -215,6 +240,7 @@ const createTlsOperations = (tlsClient) => {
215
240
  if (!topic) {
216
241
  return null;
217
242
  }
243
+ const tags = await listTagsForResource(tlsClient, 'topic', topic.TopicId);
218
244
  return {
219
245
  topicId: topic.TopicId,
220
246
  topicName: topic.TopicName,
@@ -223,6 +249,7 @@ const createTlsOperations = (tlsClient) => {
223
249
  ttl: topic.Ttl,
224
250
  createTime: topic.CreateTime,
225
251
  status: 'Active',
252
+ tags,
226
253
  };
227
254
  }
228
255
  catch (error) {
@@ -232,6 +259,30 @@ const createTlsOperations = (tlsClient) => {
232
259
  throw error;
233
260
  }
234
261
  },
262
+ listTopics: async (projectName) => {
263
+ try {
264
+ const project = await operations.getProject(projectName);
265
+ if (!project?.projectId) {
266
+ return [];
267
+ }
268
+ const response = await tlsClient.DescribeTopics({ ProjectId: project.projectId });
269
+ return (response.Topics ?? []).map((topic) => ({
270
+ topicId: topic.TopicId,
271
+ topicName: topic.TopicName,
272
+ projectName,
273
+ description: topic.Description,
274
+ ttl: topic.Ttl,
275
+ createTime: topic.CreateTime,
276
+ status: 'Active',
277
+ }));
278
+ }
279
+ catch (error) {
280
+ if (isNotFoundError(error)) {
281
+ return [];
282
+ }
283
+ throw error;
284
+ }
285
+ },
235
286
  deleteTopic: async (projectName, topicName) => {
236
287
  try {
237
288
  const existing = await operations.getTopic(projectName, topicName);
@@ -301,6 +352,38 @@ const createTlsOperations = (tlsClient) => {
301
352
  waitForTopic: async (projectName, topicName) => {
302
353
  await waitForTopicReady(operations.getTopic, projectName, topicName);
303
354
  },
355
+ addTags: async (config) => {
356
+ try {
357
+ await tlsClient.AddTagsToResource({
358
+ ResourceType: config.resourceType,
359
+ ResourcesList: config.resourcesList,
360
+ Tags: config.tags.map((tag) => ({ Key: tag.key, Value: tag.value })),
361
+ });
362
+ }
363
+ catch (error) {
364
+ if (isNotFoundError(error)) {
365
+ logger_1.logger.warn(lang_1.lang.__('TLS_TAG_TARGET_NOT_FOUND', { resourceType: config.resourceType }));
366
+ return;
367
+ }
368
+ throw error;
369
+ }
370
+ },
371
+ removeTags: async (config) => {
372
+ try {
373
+ await tlsClient.RemoveTagsFromResource({
374
+ ResourceType: config.resourceType,
375
+ ResourcesList: config.resourcesList,
376
+ TagKeyList: config.tagKeys,
377
+ });
378
+ }
379
+ catch (error) {
380
+ if (isNotFoundError(error)) {
381
+ logger_1.logger.warn(lang_1.lang.__('TLS_TAG_TARGET_NOT_FOUND', { resourceType: config.resourceType }));
382
+ return;
383
+ }
384
+ throw error;
385
+ }
386
+ },
304
387
  };
305
388
  return operations;
306
389
  };
@@ -226,6 +226,12 @@ exports.en = {
226
226
  APIGW_LOG_ENABLED: 'Access log enabled for API Gateway {{gatewayId}}',
227
227
  APIGW_LOG_DISABLED: 'Access log disabled for API Gateway {{gatewayId}}',
228
228
  APIGW_LOG_DISABLE_FAILED: 'Failed to disable access log for API Gateway {{gatewayId}}: {{error}}',
229
+ SLS_LOG_CONFIG_FOREIGN: 'Existing PROVIDER gateway log configuration points to {{slsProject}}/{{slsLogStore}}; leaving it untouched',
230
+ SLS_LOGSTORE_WAITING: 'Waiting for SLS logstore {{project}}/{{logstore}} to be ready...',
231
+ SHARED_SLS_PROJECT_IN_USE: '{{count}} logstore(s) still reference shared SLS project {{projectName}}; retaining it',
232
+ SHARED_SLS_PROJECT_ADOPTED: 'Adopting existing shared SLS project {{projectName}} owned by this app',
233
+ SLS_PROJECT_FOREIGN_OWNED: 'SLS project {{projectName}} exists but is not owned by this app; refusing to adopt',
234
+ APIGW_LOG_CONFIG_STILL_REFERENCES_STORE: 'Regional PROVIDER gateway log config still references {{slsLogStore}}; retaining logstore',
229
235
  APIGW_DOMAIN_BINDING_FAILED: 'Failed to bind custom domain: {{error}}',
230
236
  APIGW_DOMAIN_UNBIND_FAILED: 'Failed to unbind domain {{domain}}: {{error}}',
231
237
  APIGW_WWW_DOMAIN_UNBIND_FAILED: 'Failed to unbind www domain {{domain}}: {{error}}',
@@ -388,7 +394,6 @@ exports.en = {
388
394
  DELETING_RAM_ROLE: 'Deleting RAM role: {{id}}',
389
395
  DELETING_SLS_INDEX: 'Deleting SLS index: {{id}}',
390
396
  DELETING_SLS_LOGSTORE: 'Deleting SLS logstore: {{id}}',
391
- DELETING_SLS_PROJECT: 'Deleting SLS project: {{id}}',
392
397
  UNKNOWN_RESOURCE_TYPE: 'Unknown resource type: {{type}}',
393
398
  FAILED_TO_DELETE_RESOURCE: 'Failed to delete resource {{type}}:{{id}}: {{error}}',
394
399
  // OSS Resource messages
@@ -402,6 +407,12 @@ exports.en = {
402
407
  CANNOT_RESOLVE_FUNCTION_REF: 'Cannot resolve function reference {{backendRef}}: IAC not available in context',
403
408
  FUNCTION_REF_NOT_RESOLVED: 'Function reference {{backendRef}} could not be resolved from IAC',
404
409
  RESOLVED_FUNCTION_REF: 'Resolved function reference {{backendRef}} to function name: {{functionName}}',
410
+ // Pre-deploy semantic validation (issue #222)
411
+ PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: 'Backend type BUCKET_STORE requires both "bucket" and "key" fields',
412
+ SEMANTIC_DUPLICATE_TRIGGER: 'Duplicate trigger in event "{{eventKey}}": {{method}} {{path}} is defined more than once',
413
+ SEMANTIC_DUPLICATE_GENERATED_API_NAME: 'Generated API Gateway apiName "{{apiName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
414
+ SEMANTIC_DUPLICATE_ROUTE_NAME: 'Generated API Gateway route name "{{routeName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
415
+ SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: 'Trigger backend "{{reference}}" in event "{{eventKey}}" does not match any function definition in the configuration',
405
416
  // Show command messages
406
417
  LOADING_STATE_FOR: 'Loading state for app: {{app}}, service: {{service}}, stage: {{stage}}...',
407
418
  NO_RESOURCES_FOUND: 'No resources found in state.',
@@ -649,6 +660,12 @@ exports.en = {
649
660
  TLS_TOPIC_CREATED: 'TLS topic {{topicName}} created successfully',
650
661
  TLS_TOPIC_DELETED: 'TLS topic {{topicName}} deleted successfully',
651
662
  TLS_TOPIC_NOT_FOUND: 'TLS topic {{topicName}} not found',
663
+ TLS_TAG_TARGET_NOT_FOUND: 'TLS {{resourceType}} not found while applying tags; skipping',
664
+ VOLCENGINE_ROLE_NOT_FOUND_FOR_TAG: 'IAM role {{roleName}} not found while applying tags; skipping',
665
+ SHARED_TLS_PROJECT_IN_USE: '{{count}} topic(s) still reference shared TLS project {{projectName}}; retaining it',
666
+ SHARED_TLS_PROJECT_DELETED: 'Deleted unused shared TLS project {{projectName}}',
667
+ TLS_SHARED_PROJECT_NOT_OWNED: 'Shared TLS project {{projectName}} exists but is not owned by this app (missing or foreign ownership tag); refusing to adopt or delete it',
668
+ TLS_TOPIC_FOREIGN_OWNED: 'TLS topic {{topicName}} exists but is owned by another stack; refusing to adopt',
652
669
  TLS_TOPIC_ALREADY_EXISTS: 'TLS topic {{topicName}} already exists, adopting existing topic',
653
670
  TLS_TOPIC_TIMEOUT: 'Timeout waiting for TLS topic {{topicName}} to be ready',
654
671
  TLS_INDEX_CREATED: 'TLS index for topic {{topicName}} created successfully',
@@ -663,6 +680,17 @@ exports.en = {
663
680
  DELETING_TLS_TOPIC: 'Deleting TLS topic: {{id}}',
664
681
  DELETING_TLS_INDEX: 'Deleting TLS index: {{id}}',
665
682
  WAITING_FOR_TLS_RESOURCES: 'Waiting for TLS resources to be ready: {{projectName}}/{{topicName}}',
683
+ // Tencent CLS (Cloud Log Service) messages
684
+ SHARED_CLS_LOGSET_IN_USE: '{{count}} topic(s) still reference shared CLS logset {{logsetName}}; retaining it',
685
+ SHARED_CLS_LOGSET_DELETED: 'Deleted unused shared CLS logset {{logsetName}}',
686
+ CLS_TOPIC_FOREIGN_OWNED: 'CLS topic {{topicName}} exists but is owned by another stack; refusing to adopt',
687
+ CLS_LOGSET_FOREIGN_OWNED: 'CLS logset {{logsetName}} exists but is not owned by this app; refusing to adopt',
688
+ CREATING_CLS_LOGSET: 'Creating CLS logset: {{logsetName}}',
689
+ CREATING_CLS_TOPIC: 'Creating CLS topic: {{topicName}}',
690
+ CREATING_CLS_INDEX: 'Creating CLS index for topic: {{topicName}}',
691
+ DELETING_CLS_TOPIC: 'Deleting CLS topic: {{id}}',
692
+ DELETING_CLS_INDEX: 'Deleting CLS index for topic: {{topicName}}',
693
+ CLS_LOG_DISABLED: 'Disabled CLS log delivery for function {{functionName}}',
666
694
  // Volcengine veFaaS dependent resources
667
695
  VEFAAS_DEPENDENT_RESOURCES_TRACKED: 'Dependent resources (TLS, IAM) are tracked in state',
668
696
  VEFAAS_CAN_RETRY_DEPLOYMENT: 'You can retry deployment - the system will reuse existing dependent resources',
@@ -226,6 +226,12 @@ exports.zhCN = {
226
226
  APIGW_LOG_ENABLED: '已为 API 网关 {{gatewayId}} 开启访问日志',
227
227
  APIGW_LOG_DISABLED: '已为 API 网关 {{gatewayId}} 关闭访问日志',
228
228
  APIGW_LOG_DISABLE_FAILED: '关闭 API 网关 {{gatewayId}} 访问日志失败:{{error}}',
229
+ SLS_LOG_CONFIG_FOREIGN: '已存在的 PROVIDER 网关日志配置指向 {{slsProject}}/{{slsLogStore}},保持不变',
230
+ SLS_LOGSTORE_WAITING: '等待 SLS 日志库 {{project}}/{{logstore}} 就绪...',
231
+ SHARED_SLS_PROJECT_IN_USE: '仍有 {{count}} 个日志库引用共享 SLS 项目 {{projectName}},予以保留',
232
+ SHARED_SLS_PROJECT_ADOPTED: '采用当前应用已有的共享 SLS 项目 {{projectName}}',
233
+ SLS_PROJECT_FOREIGN_OWNED: 'SLS 项目 {{projectName}} 已存在但不属于当前应用,拒绝采用',
234
+ APIGW_LOG_CONFIG_STILL_REFERENCES_STORE: '区域级 PROVIDER 网关日志配置仍引用 {{slsLogStore}},保留该日志库',
229
235
  APIGW_DOMAIN_BINDING_FAILED: '绑定自定义域名失败:{{error}}',
230
236
  APIGW_DOMAIN_UNBIND_FAILED: '解绑域名 {{domain}} 失败:{{error}}',
231
237
  APIGW_WWW_DOMAIN_UNBIND_FAILED: '解绑 www 域名 {{domain}} 失败:{{error}}',
@@ -385,7 +391,6 @@ exports.zhCN = {
385
391
  DELETING_RAM_ROLE: '正在删除 RAM 角色: {{id}}',
386
392
  DELETING_SLS_INDEX: '正在删除 SLS 索引: {{id}}',
387
393
  DELETING_SLS_LOGSTORE: '正在删除 SLS 日志库: {{id}}',
388
- DELETING_SLS_PROJECT: '正在删除 SLS 项目: {{id}}',
389
394
  UNKNOWN_RESOURCE_TYPE: '未知资源类型: {{type}}',
390
395
  FAILED_TO_DELETE_RESOURCE: '删除资源 {{type}}:{{id}} 失败: {{error}}',
391
396
  // OSS Resource messages
@@ -399,6 +404,12 @@ exports.zhCN = {
399
404
  CANNOT_RESOLVE_FUNCTION_REF: '无法解析函数引用 {{backendRef}}: 上下文中无 IAC',
400
405
  FUNCTION_REF_NOT_RESOLVED: '无法从 IAC 解析函数引用 {{backendRef}}',
401
406
  RESOLVED_FUNCTION_REF: '已将函数引用 {{backendRef}} 解析为函数名: {{functionName}}',
407
+ // Pre-deploy semantic validation (issue #222)
408
+ PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: '后端类型 BUCKET_STORE 需要同时提供 "bucket" 和 "key" 字段',
409
+ SEMANTIC_DUPLICATE_TRIGGER: '事件 "{{eventKey}}" 中存在重复触发器: {{method}} {{path}} 定义了不止一次',
410
+ SEMANTIC_DUPLICATE_GENERATED_API_NAME: '生成的 API Gateway apiName "{{apiName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
411
+ SEMANTIC_DUPLICATE_ROUTE_NAME: '生成的 API Gateway route name "{{routeName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
412
+ SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: '事件 "{{eventKey}}" 的触发器后端 "{{reference}}" 未匹配到配置中的任何函数定义',
402
413
  // Show command messages
403
414
  LOADING_STATE_FOR: '正在加载应用 {{app}}、服务 {{service}}、阶段 {{stage}} 的状态...',
404
415
  NO_RESOURCES_FOUND: '状态中未找到资源。',
@@ -643,6 +654,12 @@ exports.zhCN = {
643
654
  TLS_TOPIC_CREATED: 'TLS 主题 {{topicName}} 创建成功',
644
655
  TLS_TOPIC_DELETED: 'TLS 主题 {{topicName}} 删除成功',
645
656
  TLS_TOPIC_NOT_FOUND: 'TLS 主题 {{topicName}} 未找到',
657
+ TLS_TAG_TARGET_NOT_FOUND: '应用标签时未找到 TLS {{resourceType}},已跳过',
658
+ VOLCENGINE_ROLE_NOT_FOUND_FOR_TAG: '应用标签时未找到 IAM 角色 {{roleName}},已跳过',
659
+ SHARED_TLS_PROJECT_IN_USE: '仍有 {{count}} 个主题引用共享 TLS 项目 {{projectName}},予以保留',
660
+ SHARED_TLS_PROJECT_DELETED: '已删除未使用的共享 TLS 项目 {{projectName}}',
661
+ TLS_SHARED_PROJECT_NOT_OWNED: '共享 TLS 项目 {{projectName}} 已存在但不属于当前应用(缺少或持有非本应用的所有权标签),拒绝采用或删除',
662
+ TLS_TOPIC_FOREIGN_OWNED: 'TLS 主题 {{topicName}} 已存在但属于其他栈,拒绝采用',
646
663
  TLS_TOPIC_ALREADY_EXISTS: 'TLS 主题 {{topicName}} 已存在,复用现有主题',
647
664
  TLS_TOPIC_TIMEOUT: '等待 TLS 主题 {{topicName}} 就绪超时',
648
665
  TLS_INDEX_CREATED: 'TLS 主题 {{topicName}} 索引创建成功',
@@ -657,6 +674,17 @@ exports.zhCN = {
657
674
  DELETING_TLS_TOPIC: '正在删除 TLS 主题:{{id}}',
658
675
  DELETING_TLS_INDEX: '正在删除 TLS 索引:{{id}}',
659
676
  WAITING_FOR_TLS_RESOURCES: '等待 TLS 资源就绪:{{projectName}}/{{topicName}}',
677
+ // Tencent CLS(云日志服务)消息
678
+ SHARED_CLS_LOGSET_IN_USE: '仍有 {{count}} 个主题引用共享 CLS 日志集 {{logsetName}},予以保留',
679
+ SHARED_CLS_LOGSET_DELETED: '已删除未使用的共享 CLS 日志集 {{logsetName}}',
680
+ CLS_TOPIC_FOREIGN_OWNED: 'CLS 主题 {{topicName}} 已存在但属于其他栈,拒绝采用',
681
+ CLS_LOGSET_FOREIGN_OWNED: 'CLS 日志集 {{logsetName}} 已存在但不属于本应用,拒绝采用',
682
+ CREATING_CLS_LOGSET: '正在创建 CLS 日志集:{{logsetName}}',
683
+ CREATING_CLS_TOPIC: '正在创建 CLS 主题:{{topicName}}',
684
+ CREATING_CLS_INDEX: '正在为 CLS 主题创建索引:{{topicName}}',
685
+ DELETING_CLS_TOPIC: '正在删除 CLS 主题:{{id}}',
686
+ DELETING_CLS_INDEX: '正在删除 CLS 主题索引:{{topicName}}',
687
+ CLS_LOG_DISABLED: '已为函数 {{functionName}} 关闭 CLS 日志投递',
660
688
  // Volcengine veFaaS dependent resources
661
689
  VEFAAS_DEPENDENT_RESOURCES_TRACKED: '依赖资源(TLS、IAM)已在状态中跟踪',
662
690
  VEFAAS_CAN_RETRY_DEPLOYMENT: '您可以重试部署 - 系统将复用现有的依赖资源',
@@ -12,6 +12,7 @@ const validator_1 = require("../validator");
12
12
  const bucketParser_1 = require("./bucketParser");
13
13
  const tableParser_1 = require("./tableParser");
14
14
  const common_1 = require("../common");
15
+ const lang_1 = require("../lang");
15
16
  const validateExistence = (path) => {
16
17
  if (!(0, node_fs_1.existsSync)(path)) {
17
18
  throw new Error(`File does not exist at path: ${path}`);
@@ -26,7 +27,7 @@ const parseBackend = (raw) => {
26
27
  const type = stateManager.type?.toUpperCase();
27
28
  if (type === types_1.StateBackendType.BUCKET_STORE) {
28
29
  if (!stateManager.bucket || !stateManager.key) {
29
- throw new Error('Backend type BUCKET_STORE requires both "bucket" and "key" fields');
30
+ throw new Error(lang_1.lang.__('PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED'));
30
31
  }
31
32
  return {
32
33
  type: types_1.StateBackendType.BUCKET_STORE,
@@ -34,6 +34,7 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
34
34
  const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
35
35
  const client = (0, aliyunClient_1.createAliyunClient)(context);
36
36
  // Build desired definition including triggers
37
+ const logSnapshot = (0, apigwTypes_1.buildEventLogSnapshot)(event, context);
37
38
  const desiredDefinition = {
38
39
  ...groupDefinition,
39
40
  triggers: event.triggers.map((t) => ({
@@ -42,6 +43,7 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
42
43
  backend: t.backend,
43
44
  })),
44
45
  domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
46
+ ...(logSnapshot ? { log: logSnapshot } : {}),
45
47
  };
46
48
  if (!currentState || currentState.status === 'tainted') {
47
49
  // No usable local state: probe the provider before planning create.
@@ -13,6 +13,7 @@ const domainUtils_1 = require("../../common/domainUtils");
13
13
  const hashUtils_1 = require("../../common/hashUtils");
14
14
  const ownershipTag_1 = require("../ownershipTag");
15
15
  const alreadyExists_1 = require("../alreadyExists");
16
+ const sharedLogProject_1 = require("./sharedLogProject");
16
17
  const getCdnConfig = (event) => {
17
18
  const domainCdn = event.domain?.cdn;
18
19
  if (domainCdn == null) {
@@ -265,6 +266,78 @@ const buildApigwDeploymentInstance = (groupId, apiId, stageName, stage) => {
265
266
  stageName,
266
267
  };
267
268
  };
269
+ const buildLogConfigInstance = (context, slsProject, slsLogStore) => ({
270
+ sid: (0, common_1.buildSid)('aliyun', 'apigw-log-config', context.stage, `${context.region}:PROVIDER`),
271
+ type: 'ALIYUN_APIGW_LOG_CONFIG',
272
+ id: `${context.region}:PROVIDER`,
273
+ attributes: { slsProject, slsLogStore },
274
+ });
275
+ const ensureGatewayLogConfig = async (context, client, state) => {
276
+ const slsLogStore = `${context.service}-${context.stage}-apigw-logs`;
277
+ const ours = { slsProject: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage), slsLogStore };
278
+ const existing = await client.apigw.describeGatewayLogConfig();
279
+ const matchesOurs = existing &&
280
+ existing.slsProject === ours.slsProject &&
281
+ existing.slsLogStore === ours.slsLogStore;
282
+ if (matchesOurs) {
283
+ // The PROVIDER singleton already targets our shared project. Enforce the
284
+ // app-ownership invariant on both the tracked and untracked paths: only an
285
+ // app-owned project is reused or adopted; a foreign/untagged one is refused
286
+ // and a missing project (stale config) falls through to (re)creation.
287
+ const project = await client.sls.getProject(ours.slsProject);
288
+ if (project) {
289
+ if (!(await (0, sharedLogProject_1.isSharedProjectOwnedByApp)(context, client, ours.slsProject))) {
290
+ throw new Error(lang_1.lang.__('SLS_PROJECT_FOREIGN_OWNED', { projectName: ours.slsProject }));
291
+ }
292
+ const known = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY);
293
+ return {
294
+ instance: buildLogConfigInstance(context, ours.slsProject, ours.slsLogStore),
295
+ sharedProject: known ?? (0, sharedLogProject_1.adoptSharedSlsProjectState)(context, ours.slsProject),
296
+ };
297
+ }
298
+ }
299
+ else if (existing) {
300
+ logger_1.logger.warn(lang_1.lang.__('SLS_LOG_CONFIG_FOREIGN', {
301
+ slsProject: existing.slsProject ?? '',
302
+ slsLogStore: existing.slsLogStore ?? '',
303
+ }));
304
+ return {};
305
+ }
306
+ const shared = await (0, sharedLogProject_1.ensureSharedSlsProject)(context, client, state);
307
+ const sharedProject = (0, sharedLogProject_1.buildSharedProjectResourceState)(context, shared);
308
+ await (0, sharedLogProject_1.ensureGatewayLogstore)(context, client, shared.projectName);
309
+ await client.apigw.createGatewayLogConfig({
310
+ slsProject: shared.projectName,
311
+ slsLogStore,
312
+ });
313
+ return {
314
+ instance: buildLogConfigInstance(context, shared.projectName, slsLogStore),
315
+ sharedProject,
316
+ };
317
+ };
318
+ const releaseGatewayLogstoreIfNeeded = async (client, attrs) => {
319
+ const { slsProject, slsLogStore } = (attrs ?? {});
320
+ if (!slsProject || !slsLogStore) {
321
+ return;
322
+ }
323
+ const currentConfig = await client.apigw.describeGatewayLogConfig();
324
+ if (currentConfig?.slsLogStore === slsLogStore && currentConfig?.slsProject === slsProject) {
325
+ logger_1.logger.warn(lang_1.lang.__('APIGW_LOG_CONFIG_STILL_REFERENCES_STORE', { slsLogStore }));
326
+ return;
327
+ }
328
+ try {
329
+ await client.sls.deleteIndex(slsProject, slsLogStore);
330
+ }
331
+ catch {
332
+ // logstore already gone — index deletion is best-effort
333
+ }
334
+ try {
335
+ await client.sls.deleteLogstore(slsProject, slsLogStore);
336
+ }
337
+ catch {
338
+ // logstore already gone
339
+ }
340
+ };
268
341
  const resolveDomainCertificate = async (domain, serviceName, eventKey, stage, client) => {
269
342
  if (domain.certificate_id) {
270
343
  const certId = domain.certificate_id;
@@ -312,6 +385,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
312
385
  ];
313
386
  const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
314
387
  let groupId;
388
+ const logSnapshot = (0, apigwTypes_1.buildEventLogSnapshot)(event, context);
315
389
  const buildResourceDefinition = () => ({
316
390
  ...groupDefinition,
317
391
  triggers: event.triggers.map((t) => ({
@@ -320,6 +394,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
320
394
  backend: t.backend,
321
395
  })),
322
396
  domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
397
+ ...(logSnapshot ? { log: logSnapshot } : {}),
323
398
  });
324
399
  // Persist a tainted state BEFORE any cloud side-effect so a group created
325
400
  // in cloud but not yet tracked stays tracked if a later step fails.
@@ -382,6 +457,18 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
382
457
  status: 'tainted',
383
458
  });
384
459
  let currentState = stateAfterDependents;
460
+ if (event.log) {
461
+ const logResult = await ensureGatewayLogConfig(context, client, stateAfterDependents);
462
+ if (logResult?.sharedProject) {
463
+ stateAfterDependents = (0, stateManager_1.setSharedResource)(stateAfterDependents, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY, logResult.sharedProject);
464
+ // Keep currentState in sync so the shared project survives into the
465
+ // final returned state (the create path returns from currentState).
466
+ currentState = stateAfterDependents;
467
+ }
468
+ if (logResult?.instance) {
469
+ instances.push(logResult.instance);
470
+ }
471
+ }
385
472
  // Create APIs and deployments for each trigger
386
473
  for (const trigger of event.triggers) {
387
474
  const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
@@ -411,6 +498,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
411
498
  backend: t.backend,
412
499
  })),
413
500
  domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
501
+ ...(logSnapshot ? { log: logSnapshot } : {}),
414
502
  },
415
503
  instances,
416
504
  lastUpdated: new Date().toISOString(),
@@ -476,6 +564,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
476
564
  backend: t.backend,
477
565
  })),
478
566
  domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
567
+ ...(logSnapshot ? { log: logSnapshot } : {}),
479
568
  },
480
569
  instances,
481
570
  lastUpdated: new Date().toISOString(),
@@ -648,6 +737,23 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
648
737
  }
649
738
  }
650
739
  }
740
+ const logSnapshot = (0, apigwTypes_1.buildEventLogSnapshot)(event, context);
741
+ let sharedProjectState;
742
+ if (event.log) {
743
+ const logResult = await ensureGatewayLogConfig(context, client, state);
744
+ if (logResult?.sharedProject) {
745
+ sharedProjectState = logResult.sharedProject;
746
+ }
747
+ if (logResult?.instance) {
748
+ instances.push(logResult.instance);
749
+ }
750
+ }
751
+ else {
752
+ const previousLogInstance = (existingState?.instances ?? []).find((i) => i.type === 'ALIYUN_APIGW_LOG_CONFIG');
753
+ if (previousLogInstance) {
754
+ await releaseGatewayLogstoreIfNeeded(client, previousLogInstance.attributes);
755
+ }
756
+ }
651
757
  if (event.domain) {
652
758
  const desiredDomainDef = (0, apigwTypes_1.extractEventDomainDefinition)(event.domain);
653
759
  const previousDomainDef = existingState?.definition?.domain;
@@ -805,11 +911,15 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
805
911
  backend: t.backend,
806
912
  })),
807
913
  domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
914
+ ...(logSnapshot ? { log: logSnapshot } : {}),
808
915
  },
809
916
  instances,
810
917
  lastUpdated: new Date().toISOString(),
811
918
  };
812
- return (0, stateManager_1.setResource)(state, logicalId, resourceState);
919
+ const finalState = sharedProjectState
920
+ ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY, sharedProjectState)
921
+ : state;
922
+ return (0, stateManager_1.setResource)(finalState, logicalId, resourceState);
813
923
  };
814
924
  exports.updateApigwResource = updateApigwResource;
815
925
  const deleteApigwResource = async (context, logicalId, state) => {
@@ -904,6 +1014,13 @@ const deleteApigwResource = async (context, logicalId, state) => {
904
1014
  name: groupId,
905
1015
  }));
906
1016
  }
1017
+ // The PROVIDER log configuration is a regional singleton — never deleted.
1018
+ // Tear down the per-service gateway logstore only when the singleton no
1019
+ // longer references it; otherwise it must be retained.
1020
+ const logConfigInstance = existingInstances.find((i) => i.type === 'ALIYUN_APIGW_LOG_CONFIG');
1021
+ if (logConfigInstance) {
1022
+ await releaseGatewayLogstoreIfNeeded(client, logConfigInstance.attributes);
1023
+ }
907
1024
  return (0, stateManager_1.removeResource)(state, logicalId);
908
1025
  };
909
1026
  exports.deleteApigwResource = deleteApigwResource;
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractEventDomainDefinition = exports.inferProtocolConfig = exports.extractApigwDeploymentDefinition = exports.extractApigwApiDefinition = exports.extractApigwGroupDefinition = exports.triggerToApigwApiConfig = exports.generateApiKey = exports.eventToApigwGroupConfig = void 0;
3
+ exports.extractEventDomainDefinition = exports.buildEventLogSnapshot = exports.inferProtocolConfig = exports.extractApigwDeploymentDefinition = exports.extractApigwApiDefinition = exports.extractApigwGroupDefinition = exports.triggerToApigwApiConfig = exports.eventToApigwGroupConfig = exports.generateApiKey = exports.buildAliyunApigwApiName = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const lang_1 = require("../../lang");
6
6
  const ownershipTag_1 = require("../ownershipTag");
7
+ var common_2 = require("../../common");
8
+ Object.defineProperty(exports, "buildAliyunApigwApiName", { enumerable: true, get: function () { return common_2.buildAliyunApigwApiName; } });
9
+ Object.defineProperty(exports, "generateApiKey", { enumerable: true, get: function () { return common_2.generateApiKey; } });
7
10
  /**
8
11
  * Convert EventDomain to API Gateway group config
9
12
  *
@@ -14,7 +17,14 @@ const ownershipTag_1 = require("../ownershipTag");
14
17
  */
15
18
  const eventToApigwGroupConfig = (event, serviceName, stage, context, logicalId) => {
16
19
  const groupConfig = {
17
- groupName: `${serviceName}-${stage}-agw-group`.replace(/_/g, '-'),
20
+ // Per-event group: each API_GATEWAY event owns its group so the
21
+ // single-owner adoption tag stays exact. 4-50 chars per Aliyun
22
+ // ALIYUN::ApiGateway::Group docs; charset proven in this repo (hyphens).
23
+ groupName: (0, common_1.buildConstrainedName)({
24
+ parts: [serviceName, stage, event.key ?? '', 'agw_group'],
25
+ maxLength: common_1.CONSTRAINT_NAME_LIMITS.ALIYUN_API_GROUP_NAME,
26
+ charset: 'hyphen',
27
+ }),
18
28
  description: `API Gateway group for ${serviceName}`,
19
29
  };
20
30
  if (context && logicalId) {
@@ -25,21 +35,6 @@ const eventToApigwGroupConfig = (event, serviceName, stage, context, logicalId)
25
35
  return groupConfig;
26
36
  };
27
37
  exports.eventToApigwGroupConfig = eventToApigwGroupConfig;
28
- /**
29
- * Generate a unique API key from method and path
30
- * Uses URL encoding to preserve path structure and avoid collisions
31
- */
32
- const generateApiKey = (method, path) => {
33
- // Replace slashes with double underscores to preserve path structure
34
- // Replace other non-alphanumeric chars with single underscore
35
- const sanitizedPath = path
36
- .replace(/\//g, '__')
37
- .replace(/[^a-zA-Z0-9_]/g, '_')
38
- .replace(/^__/, '') // Remove leading double underscore
39
- .replace(/__$/, ''); // Remove trailing double underscore
40
- return `${method}_${sanitizedPath}`;
41
- };
42
- exports.generateApiKey = generateApiKey;
43
38
  /**
44
39
  * Resolves a function reference like ${functions.xxx} to the actual function name
45
40
  */
@@ -69,12 +64,11 @@ const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, s
69
64
  const path = trigger.path;
70
65
  const backend = trigger.backend;
71
66
  const resolvedFunctionName = resolveFunctionReference(backend);
72
- const apiKey = (0, exports.generateApiKey)(method, path);
67
+ const apiKey = (0, common_1.generateApiKey)(method, path);
73
68
  const protocolConfig = (0, exports.inferProtocolConfig)(event.domain?.protocol);
74
69
  return {
75
70
  groupId,
76
- // Aliyun CreateApi requires 4-50 chars of [A-Za-z0-9_] — no hyphens.
77
- apiName: `${event.name.replace(/-/g, '_')}_${stage}_agw_api_${apiKey}`.slice(0, 50),
71
+ apiName: (0, common_1.buildAliyunApigwApiName)(event.name, stage, apiKey),
78
72
  visibility: 'PRIVATE',
79
73
  authType: 'ANONYMOUS',
80
74
  requestConfig: {
@@ -202,6 +196,24 @@ const getDomainCdnConfig = (domain) => {
202
196
  : {}),
203
197
  };
204
198
  };
199
+ /**
200
+ * Snapshot of the event-level access-log wiring (issue #214): the app-scoped
201
+ * shared SLS project plus the service-scoped gateway logstore. Omitted when the
202
+ * event does not opt into logging so existing state definitions stay identical.
203
+ */
204
+ const buildEventLogSnapshot = (event, context) => {
205
+ if (!event.log) {
206
+ return undefined;
207
+ }
208
+ return {
209
+ logEnabled: event.log === true || event.log === 'true',
210
+ logConfig: {
211
+ project: `${context.app}-${context.stage}-sls`,
212
+ logstore: `${context.service}-${context.stage}-apigw-logs`,
213
+ },
214
+ };
215
+ };
216
+ exports.buildEventLogSnapshot = buildEventLogSnapshot;
205
217
  const extractEventDomainDefinition = (domain) => {
206
218
  if (!domain) {
207
219
  return null;
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.destroyAliyunStack = void 0;
4
4
  const common_1 = require("../../common");
5
+ const stateManager_1 = require("../../common/stateManager");
6
+ const aliyunClient_1 = require("../../common/aliyunClient");
5
7
  const lang_1 = require("../../lang");
6
8
  const fc3Planner_1 = require("./fc3Planner");
7
9
  const fc3Executor_1 = require("./fc3Executor");
@@ -13,6 +15,7 @@ const tablestorePlanner_1 = require("./tablestorePlanner");
13
15
  const tablestoreExecutor_1 = require("./tablestoreExecutor");
14
16
  const apigwPlanner_1 = require("./apigwPlanner");
15
17
  const apigwExecutor_1 = require("./apigwExecutor");
18
+ const sharedLogProject_1 = require("./sharedLogProject");
16
19
  const createSaveStateFn = (backend, app, service, stage) => async (state) => {
17
20
  await backend.saveState(state, app, service, stage);
18
21
  };
@@ -117,6 +120,28 @@ const destroyAliyunStack = async (backend) => {
117
120
  ],
118
121
  });
119
122
  }
123
+ // Release the shared SLS project once nothing references it anymore. The
124
+ // per-resource teardowns above deleted their own logstores; the shared
125
+ // project is retained while the regional PROVIDER gateway log config (or a
126
+ // retained ALIYUN_APIGW_LOG_CONFIG instance) still points at it.
127
+ const shared = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY);
128
+ if (shared) {
129
+ const sharedName = (0, sharedLogProject_1.resolveSharedProjectName)(shared);
130
+ const client = (0, aliyunClient_1.createAliyunClient)(context);
131
+ const gatewayConfig = await client.apigw.describeGatewayLogConfig();
132
+ const retainedByGateway = Boolean(sharedName && gatewayConfig?.slsProject === sharedName);
133
+ const retainedByApigwState = Object.values(state.resources ?? {}).some((resourceState) => resourceState.instances?.some((instance) => instance.type === 'ALIYUN_APIGW_LOG_CONFIG' &&
134
+ instance.attributes?.slsProject === sharedName));
135
+ if (retainedByGateway || retainedByApigwState) {
136
+ common_1.logger.info(lang_1.lang.__('SHARED_SLS_PROJECT_IN_USE', { projectName: sharedName ?? '', count: '1' }));
137
+ }
138
+ else {
139
+ const releaseResult = await (0, sharedLogProject_1.releaseSharedSlsProjectIfUnused)(context, client, shared);
140
+ if (releaseResult === 'deleted') {
141
+ state = (0, stateManager_1.removeSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY);
142
+ }
143
+ }
144
+ }
120
145
  await backend.saveState(state, context.app, context.service, context.stage);
121
146
  };
122
147
  exports.destroyAliyunStack = destroyAliyunStack;