@geek-fun/serverlessinsight 0.8.5 → 0.8.7

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 (39) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -2
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -3
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +19 -183
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -2
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +11 -72
  6. package/AGENTS.md +29 -0
  7. package/README.md +0 -12
  8. package/README.zh-CN.md +146 -286
  9. package/dist/package.json +1 -1
  10. package/dist/src/commands/deploy.js +4 -6
  11. package/dist/src/common/aliyunClient/ramOperations.js +104 -15
  12. package/dist/src/common/iacHelper.js +3 -1
  13. package/dist/src/common/iamStatements.js +21 -1
  14. package/dist/src/common/nameBuilder.js +12 -1
  15. package/dist/src/common/stateBackend/remoteStateBackend.js +1 -3
  16. package/dist/src/common/stateBackend/saasStateBackend.js +26 -5
  17. package/dist/src/common/stateManager.js +8 -4
  18. package/dist/src/common/tencentClient/camOperations.js +24 -12
  19. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  20. package/dist/src/lang/en.js +7 -0
  21. package/dist/src/lang/zh-CN.js +6 -0
  22. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  23. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  24. package/dist/src/stack/aliyunStack/apigwTypes.js +20 -5
  25. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  26. package/dist/src/stack/aliyunStack/fc3Resource.js +172 -18
  27. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  28. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  29. package/dist/src/stack/scfStack/scfResource.js +72 -10
  30. package/dist/src/stack/scfStack/sharedLogset.js +9 -1
  31. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  32. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  33. package/dist/src/stack/volcengineStack/apigwTypes.js +18 -7
  34. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  35. package/dist/src/stack/volcengineStack/vefaasPlanner.js +5 -4
  36. package/dist/src/stack/volcengineStack/vefaasResource.js +74 -10
  37. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  38. package/dist/src/validator/semanticValidation.js +41 -0
  39. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
3
+ exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveScfExecutionStatements = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const tencentClient_1 = require("../../common/tencentClient");
6
6
  const fileUtils_1 = require("../../common/fileUtils");
@@ -269,7 +269,49 @@ const buildScfInstanceFromProvider = (info, sid) => {
269
269
  : {},
270
270
  };
271
271
  };
272
- const createDependentResources = async (context, fn, existingInstances = [], state) => {
272
+ /**
273
+ * Least-privilege SCF execution statements for a function's CAM role
274
+ * (verified against Tencent docs: product/583/38176 role split, 38177 policy
275
+ * syntax — 2026-08).
276
+ *
277
+ * - COS actions are REMOVED: deployment-package access belongs to the
278
+ * configuration role (SCF_QcsRole), not the execution role. Functions whose
279
+ * code uses COS declare it via iam.role.statements.
280
+ * - CLS: the legacy `cls:logset:*` action names are not documented CAM forms
281
+ * (the documented actions are flat, e.g. cls:UploadLog) — the old statement
282
+ * matched no real permission. One conservative grant remains:
283
+ * cls:UploadLog on this function's own topic (si creates it and knows the
284
+ * Id), covering the documented upload action in case SCF's platform log
285
+ * delivery is gated via the execution role.
286
+ * - scf:InvokeFunction is scoped to the function's QCS resource
287
+ * qcs::scf:<region>:uin/<uin>:namespace/<ns>/function/<name> (name-based;
288
+ * the namespace is part of the path) when the UIN is resolvable via CAM
289
+ * GetUserAppId, else falls back to '*' (never wrong-permissions).
290
+ */
291
+ const deriveScfExecutionStatements = (fn, context, uin, clsTopicId) => {
292
+ const namespace = context.parameters?.find((parameter) => parameter.key === 'namespace')?.value ?? 'default';
293
+ const invokeResource = uin && context.region
294
+ ? [`qcs::scf:${context.region}:uin/${uin}:namespace/${namespace}/function/${fn.name}`]
295
+ : ['*'];
296
+ const statements = [
297
+ { effect: 'Allow', action: ['scf:InvokeFunction'], resource: invokeResource },
298
+ ];
299
+ // Verified CLS facts: CAM actions are flat (cls:UploadLog targets the TOPIC
300
+ // resource; CreateLogset/CreateTopic are operation-level -> Resource "*"),
301
+ // and whether SCF's platform log delivery is gated via the execution role is
302
+ // not documented. Keep one conservative statement: UploadLog on this
303
+ // function's own topic (si creates it and knows the Id).
304
+ if (uin && context.region && clsTopicId) {
305
+ statements.push({
306
+ effect: 'Allow',
307
+ action: ['cls:UploadLog'],
308
+ resource: [`qcs::cls:${context.region}:uin/${uin}:topic/${clsTopicId}`],
309
+ });
310
+ }
311
+ return statements;
312
+ };
313
+ exports.deriveScfExecutionStatements = deriveScfExecutionStatements;
314
+ const createDependentResources = async (context, fn, existingInstances = [], state, existingDefinition) => {
273
315
  const client = (0, tencentClient_1.createTencentClient)(context);
274
316
  const clsInstances = [];
275
317
  let clsConfig;
@@ -302,7 +344,7 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
302
344
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
303
345
  logsetId: shared.logsetId,
304
346
  logsetName: shared.logsetName,
305
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
347
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
306
348
  logicalId: `functions.${fn.key}`,
307
349
  });
308
350
  clsInstances.push({
@@ -339,16 +381,36 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
339
381
  }
340
382
  const hasCamRole = existingInstances.some((i) => i.type === 'TENCENT_SCF_ROLE');
341
383
  const serviceName = `${context.app}-${context.service}`;
342
- const defaultRoleName = `${serviceName}-${context.stage}-scf-role`;
384
+ const defaultRoleName = (0, common_1.buildFunctionRoleName)(serviceName, context.stage, fn.key);
343
385
  const roleName = customRoleName ?? defaultRoleName;
386
+ const executionStatements = (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), clsConfig?.topicId);
344
387
  if (hasCamRole) {
345
- // Role already exists - reuse it
346
- return { role: { roleName, arn: roleName }, clsConfig, clsInstances, sharedInstance };
388
+ // Role already exists - reuse it. Keyed on the TENCENT_SCF_ROLE instance
389
+ // type (not the desired name), so pre-existing deployments keep the role
390
+ // they were created with even though the default name now includes fn.key.
391
+ const existingRoleInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE && !i.external);
392
+ const reusedRoleName = existingRoleInstance?.id ?? roleName;
393
+ // Propagate the inline policy (derived baseline + custom statements) only
394
+ // when the custom statements drifted from the last stored definition.
395
+ const desiredStatements = statements;
396
+ const existingRole = existingDefinition?.iam;
397
+ const existingStatements = existingRole && existingRole.role && typeof existingRole.role !== 'string'
398
+ ? existingRole.role.statements
399
+ : undefined;
400
+ if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
401
+ await client.cam.updateRolePolicy(reusedRoleName, desiredStatements, executionStatements);
402
+ }
403
+ return {
404
+ role: { roleName: reusedRoleName, arn: reusedRoleName },
405
+ clsConfig,
406
+ clsInstances,
407
+ sharedInstance,
408
+ };
347
409
  }
348
410
  // Create new CAM role
349
411
  const trustedServices = ['scf.qcloud.com'];
350
412
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
351
- const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies);
413
+ const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies, executionStatements);
352
414
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
353
415
  return {
354
416
  role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName },
@@ -390,7 +452,7 @@ const createResource = async (context, fn, state) => {
390
452
  throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
391
453
  }
392
454
  const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
393
- const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state);
455
+ const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state, existingResourceState?.definition);
394
456
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
395
457
  config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
396
458
  if (dependentResources.role) {
@@ -640,7 +702,7 @@ const updateResource = async (context, fn, state) => {
640
702
  const existingRole = existingIam?.role;
641
703
  const existingStatements = existingRole && typeof existingRole !== 'string' ? existingRole.statements : undefined;
642
704
  if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
643
- await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements);
705
+ await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements, (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), existingClsTopicInstance?.topicId));
644
706
  }
645
707
  // Check for managed policy changes
646
708
  const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
@@ -685,7 +747,7 @@ const updateResource = async (context, fn, state) => {
685
747
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
686
748
  logsetId: logset.logsetId,
687
749
  logsetName: logset.logsetName,
688
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
750
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
689
751
  logicalId,
690
752
  });
691
753
  clsConfig = {
@@ -16,7 +16,15 @@ const ownershipTag_1 = require("../ownershipTag");
16
16
  exports.SHARED_LOGSET_KEY = 'logs.project';
17
17
  const buildSharedLogsetName = (app, stage) => `${app}-${stage}-cls`;
18
18
  exports.buildSharedLogsetName = buildSharedLogsetName;
19
- const buildFunctionTopicName = (context) => `${context.service}-${context.stage}-fn-logs`;
19
+ /**
20
+ * Topic names are per-function (#214 per-owner teardown): the function key is
21
+ * part of the name. The fnKey-less legacy shape only matches topics created
22
+ * before per-function naming — used by legacy-state branches and delete
23
+ * fallbacks where the actual topic predates this scheme.
24
+ */
25
+ const buildFunctionTopicName = (context, fnKey) => fnKey
26
+ ? `${context.service}-${context.stage}-${fnKey}-fn-logs`
27
+ : `${context.service}-${context.stage}-fn-logs`;
20
28
  exports.buildFunctionTopicName = buildFunctionTopicName;
21
29
  const resolveSharedLogsetName = (shared) => {
22
30
  const instanceId = shared.instances?.[0]?.id;
@@ -25,7 +25,11 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
25
25
  const logicalId = `events.${event.key}`;
26
26
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
27
27
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
28
- const desiredDefinition = (0, apigwTypes_1.buildEventResourceDefinition)(event);
28
+ // Stored-first: an existing event keeps its recorded topic name so the
29
+ // desired definition never phantom-drifts against legacy state.
30
+ const storedTlsTopic = currentState?.instances?.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
31
+ const storedTopicName = storedTlsTopic?.id?.split('/')[1];
32
+ const desiredDefinition = (0, apigwTypes_1.buildEventResourceDefinition)(event, storedTopicName);
29
33
  if (!currentState || currentState.status === 'tainted') {
30
34
  // No usable local state: probe the provider before planning create.
31
35
  // If a same-named gateway already exists WITHOUT our ownership tag it
@@ -3,9 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteApigwResource = exports.updateApigwResource = exports.createApigwResource = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const volcengineClient_1 = require("../../common/volcengineClient");
6
+ const common_1 = require("../../common");
6
7
  const apigwTypes_1 = require("./apigwTypes");
7
8
  const stateManager_1 = require("../../common/stateManager");
8
- const common_1 = require("../../common");
9
+ const common_2 = require("../../common");
9
10
  const logger_1 = require("../../common/logger");
10
11
  const lang_1 = require("../../lang");
11
12
  const ownershipTag_1 = require("../ownershipTag");
@@ -13,7 +14,7 @@ const alreadyExists_1 = require("../alreadyExists");
13
14
  const sharedLogProject_1 = require("./sharedLogProject");
14
15
  const buildGatewayInstance = (info, stage) => ({
15
16
  type: 'VOLCENGINE_APIGW_GATEWAY',
16
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
17
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
17
18
  id: info.gatewayId ?? '',
18
19
  gatewayId: info.gatewayId ?? null,
19
20
  gatewayName: info.gatewayName ?? null,
@@ -32,7 +33,11 @@ const buildGatewayInstance = (info, stage) => ({
32
33
  logSpec: info.logSpec ?? null,
33
34
  resourceSpec: info.resourceSpec ?? null,
34
35
  });
35
- const ensureApigwLogResources = async (context, existingInstances, state, logicalId) => {
36
+ const resolveTlsTopicNameFromInstances = (instances) => {
37
+ const tlsTopic = instances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
38
+ return tlsTopic?.id?.split('/')[1];
39
+ };
40
+ const ensureApigwLogResources = async (context, existingInstances, state, logicalId, eventKey) => {
36
41
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
37
42
  const tlsProjectInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
38
43
  const tlsTopicInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
@@ -47,7 +52,7 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
47
52
  // Shared app-scoped TLS project (#214) with a per-event topic nested under it.
48
53
  const shared = await (0, sharedLogProject_1.ensureSharedLogProject)(context, client, state);
49
54
  const sharedInstance = (0, sharedLogProject_1.buildSharedProjectResourceState)(context, shared);
50
- const topicName = `${context.service}-${context.stage}-apigw-logs`;
55
+ const topicName = (0, sharedLogProject_1.buildApigwLogTopicName)(context.service, context.stage, eventKey);
51
56
  const topic = await (0, sharedLogProject_1.ensureOwnedTopic)(context, client, {
52
57
  projectName: shared.projectName,
53
58
  topicName,
@@ -59,14 +64,14 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
59
64
  instances: [
60
65
  {
61
66
  type: 'VOLCENGINE_TLS_TOPIC',
62
- sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}`),
67
+ sid: (0, common_2.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}`),
63
68
  id: `${shared.projectName}/${topic.topicName}`,
64
69
  projectId: shared.projectId,
65
70
  topicId: topic.topicId,
66
71
  },
67
72
  {
68
73
  type: 'VOLCENGINE_TLS_INDEX',
69
- sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}/index`),
74
+ sid: (0, common_2.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}/index`),
70
75
  id: `${shared.projectName}/${topic.topicName}/index`,
71
76
  },
72
77
  ],
@@ -75,7 +80,7 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
75
80
  };
76
81
  const buildServiceInstance = (serviceId, serviceName, gatewayId, stage, info) => ({
77
82
  type: 'VOLCENGINE_APIGW_SERVICE',
78
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, serviceId),
83
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, serviceId),
79
84
  id: serviceId,
80
85
  serviceId,
81
86
  serviceName,
@@ -92,7 +97,7 @@ const buildServiceInstance = (serviceId, serviceName, gatewayId, stage, info) =>
92
97
  });
93
98
  const buildUpstreamInstance = (upstreamId, upstreamName, gatewayId, functionId, stage, info) => ({
94
99
  type: 'VOLCENGINE_APIGW_UPSTREAM',
95
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, upstreamId),
100
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, upstreamId),
96
101
  id: upstreamId,
97
102
  upstreamId,
98
103
  upstreamName,
@@ -109,7 +114,7 @@ const buildUpstreamInstance = (upstreamId, upstreamName, gatewayId, functionId,
109
114
  });
110
115
  const buildRouteInstance = (routeId, routeName, serviceId, stage, info) => ({
111
116
  type: 'VOLCENGINE_APIGW_ROUTE',
112
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, routeId),
117
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, routeId),
113
118
  id: routeId,
114
119
  routeId,
115
120
  routeName,
@@ -124,18 +129,36 @@ const buildRouteInstance = (routeId, routeName, serviceId, stage, info) => ({
124
129
  ...(info?.upstreamList && { upstreamList: info.upstreamList }),
125
130
  });
126
131
  /**
127
- * Resolve the veFaaS function Id for a ${functions.xxx} backend ref from state.
128
- * The function resource must already be deployed (functions deploy before events).
132
+ * Resolve the veFaaS function Id for a backend ref. Template refs carry the
133
+ * key directly; bare values are the deployed function name — mapped to the
134
+ * template key first, then resolved from state. A bare name matching no
135
+ * template function is an EXTERNAL deployed function: its Id is resolved
136
+ * from the provider by name (same account/region, function must exist).
129
137
  */
130
- const resolveFunctionIdFromState = (state, backendRef) => {
131
- const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
132
- const fnState = (0, stateManager_1.getResource)(state, `functions.${fnKey}`);
133
- const instance = fnState?.instances?.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
134
- const functionId = instance?.functionId;
135
- if (!functionId) {
136
- throw new Error(`Cannot resolve veFaaS function Id for backend ${backendRef} (functions.${fnKey} has no functionId in state). Deploy the function first.`);
138
+ const resolveFunctionIdFromState = async (state, backendRef, client) => {
139
+ const context = (0, common_1.getContext)();
140
+ const refMatch = /^\$\{functions\.([\w.]+)\}$/.exec(String(backendRef ?? ''));
141
+ const templateKey = refMatch?.[1];
142
+ const fnKey = templateKey ?? context.iac?.functions?.find((f) => f.name === String(backendRef))?.key;
143
+ if (fnKey) {
144
+ const fnState = (0, stateManager_1.getResource)(state, `functions.${fnKey}`);
145
+ const instance = fnState?.instances?.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
146
+ const functionId = instance?.functionId;
147
+ if (functionId) {
148
+ return functionId;
149
+ }
150
+ if (templateKey) {
151
+ // Template function with no state Id: deploy failed or state is stale —
152
+ // do not mask it by adopting a same-named foreign function.
153
+ throw new Error(`Cannot resolve veFaaS function Id for backend ${backendRef} (functions.${fnKey} has no functionId in state). Deploy the function first.`);
154
+ }
155
+ }
156
+ const external = await client.vefaas.getFunction(String(backendRef ?? ''));
157
+ const externalId = external?.functionId;
158
+ if (!externalId) {
159
+ throw new Error(lang_1.lang.__('EXTERNAL_FUNCTION_NOT_FOUND_VOLCENGINE', { backendRef: String(backendRef ?? '') }));
137
160
  }
138
- return functionId;
161
+ return externalId;
139
162
  };
140
163
  const createApigwResource = async (context, event, serviceName, state) => {
141
164
  const logicalId = `events.${event.key}`;
@@ -186,7 +209,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
186
209
  if (event.log) {
187
210
  const existingEventState = (0, stateManager_1.getResource)(state, logicalId);
188
211
  const existingInstances = existingEventState?.instances ?? [];
189
- const logResources = await ensureApigwLogResources(context, existingInstances, state, logicalId);
212
+ const logResources = await ensureApigwLogResources(context, existingInstances, state, logicalId, event.key);
190
213
  if (logResources.sharedInstance) {
191
214
  state = (0, stateManager_1.setSharedResource)(state, context.stage, 'logs.project', logResources.sharedInstance);
192
215
  }
@@ -214,7 +237,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
214
237
  const partialResourceState = {
215
238
  mode: 'managed',
216
239
  region: context.region,
217
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
240
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
218
241
  instances,
219
242
  status: 'tainted',
220
243
  lastUpdated: new Date().toISOString(),
@@ -228,8 +251,8 @@ const createApigwResource = async (context, event, serviceName, state) => {
228
251
  const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
229
252
  let upstreamId = upstreamByFunction.get(fnKey);
230
253
  if (!upstreamId) {
231
- const functionId = resolveFunctionIdFromState(state, backendRef);
232
- const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
254
+ const functionId = await resolveFunctionIdFromState(state, backendRef, client);
255
+ const upstreamName = (0, apigwTypes_1.buildUpstreamName)(event, backendRef, context.stage);
233
256
  const existingUpstream = await client.apigw.findUpstreamByName(gatewayId, upstreamName);
234
257
  if (existingUpstream?.upstreamId) {
235
258
  upstreamId = existingUpstream.upstreamId;
@@ -268,7 +291,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
268
291
  });
269
292
  instances.push({
270
293
  type: 'VOLCENGINE_APIGW_DOMAIN',
271
- sid: (0, common_1.buildSid)('volcengine', 'apigw', context.stage, domainId || domainName),
294
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', context.stage, domainId || domainName),
272
295
  id: domainId || domainName,
273
296
  domainName,
274
297
  serviceId,
@@ -284,7 +307,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
284
307
  const finalResourceState = {
285
308
  mode: 'managed',
286
309
  region: context.region,
287
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
310
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
288
311
  instances,
289
312
  status: 'ready',
290
313
  lastUpdated: new Date().toISOString(),
@@ -311,7 +334,7 @@ const updateApigwResource = async (context, event, serviceName, state) => {
311
334
  i.type === 'VOLCENGINE_APIGW_UPSTREAM');
312
335
  try {
313
336
  if (event.log) {
314
- const logResources = await ensureApigwLogResources(context, existingState.instances, state, `events.${event.key}`);
337
+ const logResources = await ensureApigwLogResources(context, existingState.instances, state, `events.${event.key}`, event.key);
315
338
  if (logResources.sharedInstance) {
316
339
  state = (0, stateManager_1.setSharedResource)(state, context.stage, 'logs.project', logResources.sharedInstance);
317
340
  }
@@ -350,11 +373,10 @@ const updateApigwResource = async (context, event, serviceName, state) => {
350
373
  }
351
374
  for (const trigger of event.triggers) {
352
375
  const backendRef = String(trigger.backend);
353
- const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
354
- const functionId = resolveFunctionIdFromState(state, backendRef);
376
+ const functionId = await resolveFunctionIdFromState(state, backendRef, client);
355
377
  let upstreamId = upstreamByFunction.get(functionId);
356
378
  if (!upstreamId) {
357
- const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
379
+ const upstreamName = (0, apigwTypes_1.buildUpstreamName)(event, backendRef, context.stage);
358
380
  const existing = await client.apigw.findUpstreamByName(serviceInstance.gatewayId, upstreamName);
359
381
  if (existing?.upstreamId) {
360
382
  upstreamId = existing.upstreamId;
@@ -396,7 +418,7 @@ const updateApigwResource = async (context, event, serviceName, state) => {
396
418
  const resourceState = {
397
419
  mode: 'managed',
398
420
  region: context.region,
399
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
421
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
400
422
  instances,
401
423
  lastUpdated: new Date().toISOString(),
402
424
  };
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveFunctionReference = exports.buildEventResourceDefinition = exports.extractEventDomainDefinition = exports.triggerToApigwRouteConfig = exports.triggerToApigwUpstreamConfig = exports.eventToApigwServiceConfig = exports.eventToApigwGatewayConfig = exports.resolveFunctionKey = exports.buildRouteName = exports.buildUpstreamName = exports.buildServiceName = exports.buildGatewayName = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const lang_1 = require("../../lang");
6
+ const ownershipTag_1 = require("../ownershipTag");
7
+ const sharedLogProject_1 = require("./sharedLogProject");
6
8
  /**
7
9
  * Gateway instance name — reused for find-by-name adoption across deploys.
8
10
  */
@@ -20,6 +22,7 @@ exports.buildRouteName = buildRouteName;
20
22
  /**
21
23
  * Resolves a function reference like ${functions.xxx} to the actual function name
22
24
  */
25
+ const FUNCTION_REF_PATTERN = /^\$\{functions\.[\w.]+\}$/;
23
26
  const resolveFunctionReference = (backendRef) => {
24
27
  const context = (0, common_1.getContext)();
25
28
  if (!context.iac) {
@@ -28,7 +31,14 @@ const resolveFunctionReference = (backendRef) => {
28
31
  }
29
32
  const functionDef = (0, common_1.getIacDefinition)(context.iac, backendRef);
30
33
  if (!functionDef || !(0, common_1.isFunctionDomain)(functionDef)) {
31
- common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
34
+ // Dangling template refs fail semantic validation; a bare value that matches
35
+ // no template function is an external deployed function name (issue #227).
36
+ if (FUNCTION_REF_PATTERN.test(backendRef)) {
37
+ common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
38
+ }
39
+ else {
40
+ common_1.logger.info(lang_1.lang.__('EXTERNAL_FUNCTION_BACKEND', { backendRef }));
41
+ }
32
42
  return backendRef;
33
43
  }
34
44
  return functionDef.name;
@@ -50,7 +60,7 @@ const eventToApigwGatewayConfig = (event, serviceName, stage, ownershipValue) =>
50
60
  network: { vpcId: event.network.vpc_id, subnetIds: event.network.subnet_ids },
51
61
  }),
52
62
  logConfig: event.log ? { enable: true, projectId: '', topicId: '' } : undefined,
53
- Tags: [{ Key: 'si-owned-by', Value: ownershipValue }],
63
+ Tags: [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: ownershipValue }],
54
64
  };
55
65
  };
56
66
  exports.eventToApigwGatewayConfig = eventToApigwGatewayConfig;
@@ -83,7 +93,7 @@ const triggerToApigwRouteConfig = (event, trigger, serviceId, upstreamId) => {
83
93
  };
84
94
  };
85
95
  exports.triggerToApigwRouteConfig = triggerToApigwRouteConfig;
86
- const extractEventDomainDefinition = (event) => {
96
+ const extractEventDomainDefinition = (event, logTopicOverride) => {
87
97
  const context = (0, common_1.getContext)();
88
98
  return {
89
99
  gatewayName: event.name,
@@ -94,8 +104,9 @@ const extractEventDomainDefinition = (event) => {
94
104
  ...(event.log && context
95
105
  ? {
96
106
  logConfig: {
97
- project: `${context.app}-${context.stage}-tls`,
98
- topic: `${context.service}-${context.stage}-apigw-logs`,
107
+ project: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage),
108
+ topic: logTopicOverride ??
109
+ (0, sharedLogProject_1.buildApigwLogTopicName)(context.service, context.stage, String(event.key)),
99
110
  },
100
111
  }
101
112
  : {}),
@@ -113,7 +124,7 @@ const extractEventDomainDefinition = (event) => {
113
124
  };
114
125
  };
115
126
  exports.extractEventDomainDefinition = extractEventDomainDefinition;
116
- const buildEventResourceDefinition = (event) => {
117
- return (0, exports.extractEventDomainDefinition)(event);
127
+ const buildEventResourceDefinition = (event, logTopicOverride) => {
128
+ return (0, exports.extractEventDomainDefinition)(event, logTopicOverride);
118
129
  };
119
130
  exports.buildEventResourceDefinition = buildEventResourceDefinition;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteTlsLogResources = exports.ensureOwnedTopic = exports.releaseSharedLogProjectIfUnused = exports.buildSharedProjectResourceState = exports.ensureSharedLogProject = exports.buildSharedProjectName = exports.SHARED_LOG_PROJECT_KEY = void 0;
3
+ exports.deleteTlsLogResources = exports.ensureOwnedTopic = exports.releaseSharedLogProjectIfUnused = exports.buildSharedProjectResourceState = exports.ensureSharedLogProject = exports.buildApigwLogTopicName = exports.buildFunctionLogTopicName = exports.buildSharedProjectName = exports.SHARED_LOG_PROJECT_KEY = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const logger_1 = require("../../common/logger");
6
6
  const lang_1 = require("../../lang");
@@ -15,6 +15,12 @@ const ownershipTag_1 = require("../ownershipTag");
15
15
  exports.SHARED_LOG_PROJECT_KEY = 'logs.project';
16
16
  const buildSharedProjectName = (app, stage) => `${app}-${stage}-tls`;
17
17
  exports.buildSharedProjectName = buildSharedProjectName;
18
+ /** Per-function fn-logs topic (#214 per-owner teardown): the function key is part of the name. */
19
+ const buildFunctionLogTopicName = (service, stage, fnKey) => `${service}-${stage}-${fnKey}-fn-logs`;
20
+ exports.buildFunctionLogTopicName = buildFunctionLogTopicName;
21
+ /** Per-event apigw-logs topic (#214 per-owner teardown): the event key is part of the name. */
22
+ const buildApigwLogTopicName = (service, stage, eventKey) => `${service}-${stage}-${eventKey}-apigw-logs`;
23
+ exports.buildApigwLogTopicName = buildApigwLogTopicName;
18
24
  const resolveSharedProjectName = (shared) => {
19
25
  const instanceId = shared.instances?.[0]?.id;
20
26
  return instanceId ?? shared.definition?.projectName;
@@ -130,8 +136,8 @@ const ensureOwnedTopic = async (context, client, params) => {
130
136
  const { projectName, topicName, logicalId } = params;
131
137
  const existing = await client.tls.getTopic(projectName, topicName);
132
138
  if (existing) {
133
- // Service-scoped topics are shared across a service's functions/events, so
134
- // ownership is verified at the owning-stack level, not per logical id.
139
+ // fn-logs topics are per-function (the key is in the name); the apigw topic
140
+ // stays service-scoped. Adoption verifies the owning stack either way.
135
141
  const tag = (existing.tags ?? []).find((t) => t.Key === ownershipTag_1.OWNERSHIP_TAG_KEY);
136
142
  const parsed = (0, ownershipTag_1.parseOwnershipTagValue)(tag?.Value);
137
143
  if (parsed?.stack === `${context.app}-${context.service}`) {
@@ -5,6 +5,7 @@ const common_1 = require("../../common");
5
5
  const stateManager_1 = require("../../common/stateManager");
6
6
  const volcengineClient_1 = require("../../common/volcengineClient");
7
7
  const vefaasTypes_1 = require("./vefaasTypes");
8
+ const sharedLogProject_1 = require("./sharedLogProject");
8
9
  const ownershipTag_1 = require("../ownershipTag");
9
10
  const planFunctionDeletion = (logicalId, definition) => ({
10
11
  logicalId,
@@ -47,7 +48,7 @@ const generateFunctionPlan = async (context, state, functions) => {
47
48
  // planner would report `noop` forever, so `UpdateFunction`'s `TlsConfig`
48
49
  // never gets sent. Derive the same project/topic names the executor
49
50
  // would use (shared stage slot → tracked topic instance → deterministic
50
- // shared names `${app}-${stage}-tls` / `${service}-${stage}-fn-logs`) so
51
+ // names `${app}-${stage}-tls` / `${service}-${stage}-${fn.key}-fn-logs`) so
51
52
  // the diff can see the field change without phantom drift.
52
53
  if (fn.log) {
53
54
  const tlsTopicInstance = currentState?.instances?.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
@@ -61,14 +62,14 @@ const generateFunctionPlan = async (context, state, functions) => {
61
62
  if (projectName) {
62
63
  config.logConfig = {
63
64
  project: projectName,
64
- topic: `${context.service}-${context.stage}-fn-logs`,
65
+ topic: (0, sharedLogProject_1.buildFunctionLogTopicName)(context.service, context.stage, fn.key),
65
66
  };
66
67
  }
67
68
  }
68
69
  else {
69
70
  config.logConfig = {
70
- project: `${context.app}-${context.stage}-tls`,
71
- topic: `${context.service}-${context.stage}-fn-logs`,
71
+ project: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage),
72
+ topic: (0, sharedLogProject_1.buildFunctionLogTopicName)(context.service, context.stage, fn.key),
72
73
  };
73
74
  }
74
75
  }