@geek-fun/serverlessinsight 0.8.6 → 0.8.8

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 (76) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +94 -0
  4. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +47 -27
  5. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  6. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +35 -73
  7. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +148 -0
  8. package/AGENTS.md +29 -0
  9. package/dist/package.json +1 -1
  10. package/dist/src/commands/deploy.js +1 -0
  11. package/dist/src/commands/index.js +6 -2
  12. package/dist/src/commands/plan.js +1 -0
  13. package/dist/src/common/aliyunClient/ecsOperations.js +70 -1
  14. package/dist/src/common/aliyunClient/nasOperations.js +21 -0
  15. package/dist/src/common/aliyunClient/ramOperations.js +116 -15
  16. package/dist/src/common/aliyunClient/slsOperations.js +16 -3
  17. package/dist/src/common/concurrency.js +30 -0
  18. package/dist/src/common/context.js +3 -0
  19. package/dist/src/common/dependencyGraph/graph.js +5 -0
  20. package/dist/src/common/iacHelper.js +3 -1
  21. package/dist/src/common/iamStatements.js +21 -1
  22. package/dist/src/common/index.js +5 -0
  23. package/dist/src/common/nameBuilder.js +12 -1
  24. package/dist/src/common/planCompare.js +62 -0
  25. package/dist/src/common/planFormatter.js +15 -3
  26. package/dist/src/common/refreshCache.js +32 -0
  27. package/dist/src/common/refreshPlanner.js +105 -0
  28. package/dist/src/common/tencentClient/camOperations.js +24 -12
  29. package/dist/src/common/tencentClient/clsOperations.js +27 -3
  30. package/dist/src/common/tencentClient/tdsqlcOperations.js +22 -0
  31. package/dist/src/common/throttleRetry.js +56 -0
  32. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  33. package/dist/src/common/volcengineClient/tlsOperations.js +12 -4
  34. package/dist/src/lang/en.js +23 -0
  35. package/dist/src/lang/zh-CN.js +22 -0
  36. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  37. package/dist/src/stack/aliyunStack/apigwPlanner.js +75 -7
  38. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  39. package/dist/src/stack/aliyunStack/apigwTypes.js +86 -5
  40. package/dist/src/stack/aliyunStack/databasePlanner.js +26 -62
  41. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  42. package/dist/src/stack/aliyunStack/esServerlessTypes.js +50 -1
  43. package/dist/src/stack/aliyunStack/fc3Executor.js +5 -3
  44. package/dist/src/stack/aliyunStack/fc3Planner.js +299 -12
  45. package/dist/src/stack/aliyunStack/fc3Resource.js +358 -34
  46. package/dist/src/stack/aliyunStack/fc3Types.js +61 -1
  47. package/dist/src/stack/aliyunStack/ossPlanner.js +21 -63
  48. package/dist/src/stack/aliyunStack/ossTypes.js +25 -1
  49. package/dist/src/stack/aliyunStack/rdsTypes.js +38 -1
  50. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  51. package/dist/src/stack/aliyunStack/tablestorePlanner.js +20 -74
  52. package/dist/src/stack/aliyunStack/tablestoreTypes.js +33 -1
  53. package/dist/src/stack/scfStack/cosPlanner.js +30 -50
  54. package/dist/src/stack/scfStack/cosTypes.js +29 -1
  55. package/dist/src/stack/scfStack/esServerlessPlanner.js +21 -54
  56. package/dist/src/stack/scfStack/esServerlessTypes.js +13 -1
  57. package/dist/src/stack/scfStack/scfExecutor.js +5 -3
  58. package/dist/src/stack/scfStack/scfPlanner.js +72 -51
  59. package/dist/src/stack/scfStack/scfResource.js +109 -12
  60. package/dist/src/stack/scfStack/scfTypes.js +35 -1
  61. package/dist/src/stack/scfStack/sharedLogset.js +12 -3
  62. package/dist/src/stack/scfStack/tdsqlcPlanner.js +37 -55
  63. package/dist/src/stack/scfStack/tdsqlcTypes.js +21 -1
  64. package/dist/src/stack/volcengineStack/apigwPlanner.js +59 -8
  65. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  66. package/dist/src/stack/volcengineStack/apigwTypes.js +44 -8
  67. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  68. package/dist/src/stack/volcengineStack/tosPlanner.js +28 -55
  69. package/dist/src/stack/volcengineStack/tosTypes.js +18 -1
  70. package/dist/src/stack/volcengineStack/vefaasExecutor.js +5 -3
  71. package/dist/src/stack/volcengineStack/vefaasPlanner.js +119 -10
  72. package/dist/src/stack/volcengineStack/vefaasResource.js +112 -13
  73. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  74. package/dist/src/validator/semanticValidation.js +41 -0
  75. package/dist/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractTencentEsDefinition = exports.databaseToTencentEsConfig = void 0;
3
+ exports.cloudTencentEsToDefinition = exports.extractTencentEsDefinition = exports.databaseToTencentEsConfig = void 0;
4
4
  // Map database versions to ES versions
5
5
  const esVersionMap = new Map([
6
6
  [
@@ -46,3 +46,15 @@ const extractTencentEsDefinition = (config) => {
46
46
  };
47
47
  };
48
48
  exports.extractTencentEsDefinition = extractTencentEsDefinition;
49
+ // issue #234 phase 2: cloud-side counterpart of extractTencentEsDefinition.
50
+ // Mirrors the executor write shape key-for-key. Not refreshable (omitted so it
51
+ // can never phantom-drift): version (DescribeServerlessSpaceVCU / getSpace
52
+ // does not report the configured engine version).
53
+ const cloudTencentEsToDefinition = (info) => ({
54
+ spaceName: info.SpaceName,
55
+ vpcId: info.VpcInfo?.[0]?.VpcId ?? null,
56
+ subnetId: info.VpcInfo?.[0]?.SubnetId ?? null,
57
+ zone: info.Zone ?? null,
58
+ kibanaWhiteIpList: info.KibanaPublicAcl?.WhiteIpList ?? null,
59
+ });
60
+ exports.cloudTencentEsToDefinition = cloudTencentEsToDefinition;
@@ -13,9 +13,11 @@ const executeCreateAction = async (context, fn, currentState) => {
13
13
  common_1.logger.info(lang_1.lang.__('RESOURCE_CREATED', { resourceType: 'function', name: fn.name }));
14
14
  return newState;
15
15
  };
16
- const executeUpdateAction = async (context, fn, currentState) => {
16
+ const executeUpdateAction = async (context, fn, currentState, drifted) => {
17
17
  common_1.logger.info(lang_1.lang.__('UPDATING_RESOURCE', { resourceType: 'function', name: fn.name }));
18
- const newState = await (0, scfResource_1.updateResource)(context, fn, currentState);
18
+ // A drifted plan item means the cloud left the config: force the config
19
+ // re-push even when state-vs-desired sees no change.
20
+ const newState = await (0, scfResource_1.updateResource)(context, fn, currentState, { force: drifted === true });
19
21
  common_1.logger.info(lang_1.lang.__('RESOURCE_UPDATED', { resourceType: 'function', name: fn.name }));
20
22
  return newState;
21
23
  };
@@ -42,7 +44,7 @@ const executeSingleItem = async (context, item, functionsMap, currentState) => {
42
44
  if (!fn) {
43
45
  throw new Error(`Function not found for logical ID: ${item.logicalId}`);
44
46
  }
45
- return executeUpdateAction(context, fn, currentState);
47
+ return executeUpdateAction(context, fn, currentState, item.drifted);
46
48
  }
47
49
  case 'delete': {
48
50
  const state = (0, stateManager_1.getResource)(currentState, item.logicalId);
@@ -2,9 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateFunctionPlan = void 0;
4
4
  const tencentClient_1 = require("../../common/tencentClient");
5
+ const logger_1 = require("../../common/logger");
6
+ const lang_1 = require("../../lang");
7
+ const refreshCache_1 = require("../../common/refreshCache");
8
+ const clsOperations_1 = require("../../common/tencentClient/clsOperations");
9
+ const concurrency_1 = require("../../common/concurrency");
5
10
  const scfTypes_1 = require("./scfTypes");
6
11
  const stateManager_1 = require("../../common/stateManager");
7
12
  const hashUtils_1 = require("../../common/hashUtils");
13
+ const refreshPlanner_1 = require("../../common/refreshPlanner");
8
14
  const ownershipTag_1 = require("../ownershipTag");
9
15
  const sharedLogset_1 = require("./sharedLogset");
10
16
  const planFunctionDeletion = (logicalId, definition) => ({
@@ -22,7 +28,7 @@ const generateFunctionPlan = async (context, state, functions) => {
22
28
  return { items };
23
29
  }
24
30
  const desiredLogicalIds = new Set(functions.map((fn) => `functions.${fn.key}`));
25
- const functionItems = await Promise.all(functions.map(async (fn) => {
31
+ const functionItems = await (0, concurrency_1.mapWithConcurrency)(functions, concurrency_1.PLAN_READ_CONCURRENCY, async (fn) => {
26
32
  const logicalId = `functions.${fn.key}`;
27
33
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
28
34
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
@@ -30,63 +36,78 @@ const generateFunctionPlan = async (context, state, functions) => {
30
36
  config = {
31
37
  ...config,
32
38
  ClsLogsetName: (0, sharedLogset_1.buildSharedLogsetName)(context.app, context.stage),
33
- ClsTopicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
39
+ ClsTopicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
34
40
  };
35
41
  }
36
42
  const codePath = fn.code.path;
37
43
  const desiredCodeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
38
44
  const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, desiredCodeHash, fn.iam);
39
- if (!currentState || currentState.status === 'tainted') {
40
- // No usable local state: probe the provider before planning create.
41
- // If a same-named function already exists WITHOUT our ownership tag it
42
- // may belong to another project — fail fast in the plan instead of
43
- // letting the executor discover it mid-deploy.
44
- const client = (0, tencentClient_1.createTencentClient)(context);
45
- const remoteFunction = await client.scf.getFunction(fn.name);
46
- if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.Tags)) {
47
- throw new Error(`Function ${fn.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
45
+ const client = (0, tencentClient_1.createTencentClient)(context);
46
+ // Issue #234 M3: nested topic drift — probed only when logging is
47
+ // declared; unresolvable/unreadable topics are not drift.
48
+ if (currentState &&
49
+ currentState.status !== 'tainted' &&
50
+ fn.log &&
51
+ context.refresh !== false) {
52
+ const topicInstance = currentState.instances?.find((i) => i.type === 'TENCENT_CLS_TOPIC');
53
+ if (topicInstance?.id) {
54
+ const topicId = topicInstance.id;
55
+ try {
56
+ const liveTopic = await (0, refreshCache_1.cachedRefreshRead)(context, `cls.getTopicById:${topicId}`, () => client.cls.getTopicById(topicId));
57
+ const topicDrifted = !liveTopic ||
58
+ liveTopic.StorageType !== clsOperations_1.CLS_TOPIC_STORAGE_TYPE ||
59
+ liveTopic.Period !== clsOperations_1.CLS_TOPIC_PERIOD;
60
+ if (topicDrifted) {
61
+ return {
62
+ logicalId,
63
+ action: 'update',
64
+ resourceType: 'SCF',
65
+ changes: { before: currentState.definition || {}, after: desiredDefinition },
66
+ drifted: true,
67
+ };
68
+ }
69
+ }
70
+ catch (error) {
71
+ logger_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_NESTED_PROBE_FAILED', {
72
+ functionName: fn.name,
73
+ error: String(error),
74
+ }));
75
+ }
48
76
  }
49
- return {
50
- logicalId,
51
- action: 'create',
52
- resourceType: 'SCF',
53
- changes: { after: desiredDefinition },
54
- };
55
- }
56
- try {
57
- const client = (0, tencentClient_1.createTencentClient)(context);
58
- const remoteFunction = await client.scf.getFunction(fn.name);
59
- if (!remoteFunction) {
60
- return {
61
- logicalId,
62
- action: 'create',
63
- resourceType: 'SCF',
64
- changes: { before: currentState.definition, after: desiredDefinition },
65
- drifted: true,
66
- };
67
- }
68
- const currentDefinition = currentState.definition || {};
69
- const definitionChanged = !(0, hashUtils_1.attributesEqual)(currentDefinition, desiredDefinition);
70
- if (definitionChanged) {
71
- return {
72
- logicalId,
73
- action: 'update',
74
- resourceType: 'SCF',
75
- changes: { before: currentDefinition, after: desiredDefinition },
76
- drifted: true,
77
- };
78
- }
79
- return { logicalId, action: 'noop', resourceType: 'SCF' };
80
- }
81
- catch {
82
- return {
83
- logicalId,
84
- action: 'create',
85
- resourceType: 'SCF',
86
- changes: { before: currentState.definition, after: desiredDefinition },
87
- };
88
77
  }
89
- }));
78
+ return (0, refreshPlanner_1.planRefreshedResource)({
79
+ logicalId,
80
+ resourceType: 'SCF',
81
+ currentState,
82
+ desiredDefinition,
83
+ read: () => (0, refreshCache_1.cachedRefreshRead)(context, `scf.getFunction:${fn.name}`, () => client.scf.getFunction(fn.name)),
84
+ isOwned: (remote) => (0, ownershipTag_1.isOwnedByStack)(context, logicalId, remote.Tags),
85
+ foreignError: () => new Error(`Function ${fn.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`),
86
+ cloudToDefinition: scfTypes_1.cloudScfToDefinition,
87
+ enrichRemoteAttributes: async (remote, attributes) => {
88
+ // Resolve cloud CLS ids back to the stable names the desired
89
+ // definition uses; unresolvable ids are skipped, not fabricated into
90
+ // drift.
91
+ const desiredLog = desiredDefinition.logConfig;
92
+ if (!desiredLog || !remote.ClsLogsetId || !remote.ClsTopicId) {
93
+ return attributes;
94
+ }
95
+ try {
96
+ const logsetName = await (0, refreshCache_1.cachedRefreshRead)(context, `cls.getLogsetNameById:${remote.ClsLogsetId}`, () => client.cls.getLogsetNameById(remote.ClsLogsetId));
97
+ const topics = await (0, refreshCache_1.cachedRefreshRead)(context, `cls.listTopicsByLogset:${remote.ClsLogsetId}`, () => client.cls.listTopicsByLogset(remote.ClsLogsetId));
98
+ const topicName = topics?.find((t) => t.TopicId === remote.ClsTopicId)?.TopicName;
99
+ if (!logsetName || !topicName) {
100
+ return attributes;
101
+ }
102
+ return { ...attributes, logConfig: { logset: logsetName, topic: topicName } };
103
+ }
104
+ catch {
105
+ return attributes;
106
+ }
107
+ },
108
+ refresh: context.refresh,
109
+ });
110
+ });
90
111
  const allStates = (0, stateManager_1.getAllResources)(state);
91
112
  const deletionItems = Object.entries(allStates)
92
113
  .filter(([logicalId]) => logicalId.startsWith('functions.') && !desiredLogicalIds.has(logicalId))
@@ -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");
@@ -14,6 +14,7 @@ const lang_1 = require("../../lang");
14
14
  const ownershipTag_1 = require("../ownershipTag");
15
15
  const alreadyExists_1 = require("../alreadyExists");
16
16
  const sharedLogset_1 = require("./sharedLogset");
17
+ const clsOperations_1 = require("../../common/tencentClient/clsOperations");
17
18
  /**
18
19
  * Build the Function URL trigger description for Tencent CreateTrigger
19
20
  * (Type: 'http'). Format per official docs (创建函数 URL / Creating a Function
@@ -269,7 +270,49 @@ const buildScfInstanceFromProvider = (info, sid) => {
269
270
  : {},
270
271
  };
271
272
  };
272
- const createDependentResources = async (context, fn, existingInstances = [], state) => {
273
+ /**
274
+ * Least-privilege SCF execution statements for a function's CAM role
275
+ * (verified against Tencent docs: product/583/38176 role split, 38177 policy
276
+ * syntax — 2026-08).
277
+ *
278
+ * - COS actions are REMOVED: deployment-package access belongs to the
279
+ * configuration role (SCF_QcsRole), not the execution role. Functions whose
280
+ * code uses COS declare it via iam.role.statements.
281
+ * - CLS: the legacy `cls:logset:*` action names are not documented CAM forms
282
+ * (the documented actions are flat, e.g. cls:UploadLog) — the old statement
283
+ * matched no real permission. One conservative grant remains:
284
+ * cls:UploadLog on this function's own topic (si creates it and knows the
285
+ * Id), covering the documented upload action in case SCF's platform log
286
+ * delivery is gated via the execution role.
287
+ * - scf:InvokeFunction is scoped to the function's QCS resource
288
+ * qcs::scf:<region>:uin/<uin>:namespace/<ns>/function/<name> (name-based;
289
+ * the namespace is part of the path) when the UIN is resolvable via CAM
290
+ * GetUserAppId, else falls back to '*' (never wrong-permissions).
291
+ */
292
+ const deriveScfExecutionStatements = (fn, context, uin, clsTopicId) => {
293
+ const namespace = context.parameters?.find((parameter) => parameter.key === 'namespace')?.value ?? 'default';
294
+ const invokeResource = uin && context.region
295
+ ? [`qcs::scf:${context.region}:uin/${uin}:namespace/${namespace}/function/${fn.name}`]
296
+ : ['*'];
297
+ const statements = [
298
+ { effect: 'Allow', action: ['scf:InvokeFunction'], resource: invokeResource },
299
+ ];
300
+ // Verified CLS facts: CAM actions are flat (cls:UploadLog targets the TOPIC
301
+ // resource; CreateLogset/CreateTopic are operation-level -> Resource "*"),
302
+ // and whether SCF's platform log delivery is gated via the execution role is
303
+ // not documented. Keep one conservative statement: UploadLog on this
304
+ // function's own topic (si creates it and knows the Id).
305
+ if (uin && context.region && clsTopicId) {
306
+ statements.push({
307
+ effect: 'Allow',
308
+ action: ['cls:UploadLog'],
309
+ resource: [`qcs::cls:${context.region}:uin/${uin}:topic/${clsTopicId}`],
310
+ });
311
+ }
312
+ return statements;
313
+ };
314
+ exports.deriveScfExecutionStatements = deriveScfExecutionStatements;
315
+ const createDependentResources = async (context, fn, existingInstances = [], state, existingDefinition) => {
273
316
  const client = (0, tencentClient_1.createTencentClient)(context);
274
317
  const clsInstances = [];
275
318
  let clsConfig;
@@ -302,7 +345,7 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
302
345
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
303
346
  logsetId: shared.logsetId,
304
347
  logsetName: shared.logsetName,
305
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
348
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
306
349
  logicalId: `functions.${fn.key}`,
307
350
  });
308
351
  clsInstances.push({
@@ -339,16 +382,36 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
339
382
  }
340
383
  const hasCamRole = existingInstances.some((i) => i.type === 'TENCENT_SCF_ROLE');
341
384
  const serviceName = `${context.app}-${context.service}`;
342
- const defaultRoleName = `${serviceName}-${context.stage}-scf-role`;
385
+ const defaultRoleName = (0, common_1.buildFunctionRoleName)(serviceName, context.stage, fn.key);
343
386
  const roleName = customRoleName ?? defaultRoleName;
387
+ const executionStatements = (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), clsConfig?.topicId);
344
388
  if (hasCamRole) {
345
- // Role already exists - reuse it
346
- return { role: { roleName, arn: roleName }, clsConfig, clsInstances, sharedInstance };
389
+ // Role already exists - reuse it. Keyed on the TENCENT_SCF_ROLE instance
390
+ // type (not the desired name), so pre-existing deployments keep the role
391
+ // they were created with even though the default name now includes fn.key.
392
+ const existingRoleInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE && !i.external);
393
+ const reusedRoleName = existingRoleInstance?.id ?? roleName;
394
+ // Propagate the inline policy (derived baseline + custom statements) only
395
+ // when the custom statements drifted from the last stored definition.
396
+ const desiredStatements = statements;
397
+ const existingRole = existingDefinition?.iam;
398
+ const existingStatements = existingRole && existingRole.role && typeof existingRole.role !== 'string'
399
+ ? existingRole.role.statements
400
+ : undefined;
401
+ if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
402
+ await client.cam.updateRolePolicy(reusedRoleName, desiredStatements, executionStatements);
403
+ }
404
+ return {
405
+ role: { roleName: reusedRoleName, arn: reusedRoleName },
406
+ clsConfig,
407
+ clsInstances,
408
+ sharedInstance,
409
+ };
347
410
  }
348
411
  // Create new CAM role
349
412
  const trustedServices = ['scf.qcloud.com'];
350
413
  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);
414
+ const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies, executionStatements);
352
415
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
353
416
  return {
354
417
  role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName },
@@ -390,7 +453,7 @@ const createResource = async (context, fn, state) => {
390
453
  throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
391
454
  }
392
455
  const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
393
- const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state);
456
+ const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state, existingResourceState?.definition);
394
457
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
395
458
  config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
396
459
  if (dependentResources.role) {
@@ -597,7 +660,7 @@ const readResource = async (context, functionName) => {
597
660
  return await client.scf.getFunction(functionName);
598
661
  };
599
662
  exports.readResource = readResource;
600
- const updateResource = async (context, fn, state) => {
663
+ const updateResource = async (context, fn, state, options) => {
601
664
  const logicalId = `functions.${fn.key}`;
602
665
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
603
666
  const existingInstances = (existingState?.instances ?? []);
@@ -612,6 +675,37 @@ const updateResource = async (context, fn, state) => {
612
675
  (legacyLogsetId && legacyTopicId));
613
676
  const hasCamRole = existingInstances.some((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE);
614
677
  const client = (0, tencentClient_1.createTencentClient)(context);
678
+ // Issue #234 M3: nested repair — only on a drifted plan item (force):
679
+ // reconcile topic attributes against si's creation defaults; a deleted
680
+ // topic is recreated under the shared logset when it is still recorded.
681
+ if (options?.force && fn.log && existingClsTopicInstance) {
682
+ const liveTopic = await client.cls.getTopicById(existingClsTopicInstance.id).catch(() => null);
683
+ if (!liveTopic) {
684
+ const sharedBefore = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY);
685
+ const sharedLogsetId = sharedBefore?.instances?.[0]?.id ??
686
+ existingClsTopicInstance.logsetId;
687
+ if (sharedLogsetId) {
688
+ logger_1.logger.warn(lang_1.lang.__('NESTED_TOPIC_RECREATED', { topicId: existingClsTopicInstance.id }));
689
+ await client.cls.createTopic(sharedLogsetId, (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key), {
690
+ tags: [
691
+ {
692
+ key: ownershipTag_1.OWNERSHIP_TAG_KEY,
693
+ value: (0, ownershipTag_1.buildOwnershipTagValue)(context, `functions.${fn.key}`),
694
+ },
695
+ ],
696
+ });
697
+ await client.cls.createFulltextIndex(existingClsTopicInstance.id);
698
+ }
699
+ }
700
+ else if (liveTopic.StorageType !== clsOperations_1.CLS_TOPIC_STORAGE_TYPE ||
701
+ liveTopic.Period !== clsOperations_1.CLS_TOPIC_PERIOD) {
702
+ await client.cls.modifyTopic(existingClsTopicInstance.id, {
703
+ period: clsOperations_1.CLS_TOPIC_PERIOD,
704
+ storageType: clsOperations_1.CLS_TOPIC_STORAGE_TYPE,
705
+ });
706
+ logger_1.logger.info(lang_1.lang.__('NESTED_TOPIC_UPDATED', { topicId: existingClsTopicInstance.id }));
707
+ }
708
+ }
615
709
  const newIamRole = fn.iam?.role;
616
710
  let role;
617
711
  if (typeof newIamRole === 'string') {
@@ -640,7 +734,7 @@ const updateResource = async (context, fn, state) => {
640
734
  const existingRole = existingIam?.role;
641
735
  const existingStatements = existingRole && typeof existingRole !== 'string' ? existingRole.statements : undefined;
642
736
  if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
643
- await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements);
737
+ await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements, (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), existingClsTopicInstance?.topicId));
644
738
  }
645
739
  // Check for managed policy changes
646
740
  const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
@@ -685,7 +779,7 @@ const updateResource = async (context, fn, state) => {
685
779
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
686
780
  logsetId: logset.logsetId,
687
781
  logsetName: logset.logsetName,
688
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
782
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
689
783
  logicalId,
690
784
  });
691
785
  clsConfig = {
@@ -748,7 +842,10 @@ const updateResource = async (context, fn, state) => {
748
842
  // Disabling log always re-pushes config so the empty Cls ids reach the
749
843
  // UpdateFunctionConfiguration unbind contract.
750
844
  disableLog;
751
- if (configChanged) {
845
+ // `force` carries the plan's drifted flag: a live-drift update (state
846
+ // matches config, cloud edited in console) must re-push the config even
847
+ // though state-vs-desired sees no change.
848
+ if (configChanged || options?.force) {
752
849
  await client.scf.updateFunctionConfiguration(config);
753
850
  }
754
851
  if (disableLog) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractFunctionDomainDefinition = exports.extractScfDefinition = exports.functionToScfConfig = void 0;
3
+ exports.cloudScfToDefinition = exports.extractFunctionDomainDefinition = exports.extractScfDefinition = exports.functionToScfConfig = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const functionToScfConfig = (fn, role) => {
6
6
  const config = {
@@ -77,3 +77,37 @@ const extractFunctionDomainDefinition = (fn, codeHash) => {
77
77
  return (0, exports.extractScfDefinition)(config, codeHash, fn.iam);
78
78
  };
79
79
  exports.extractFunctionDomainDefinition = extractFunctionDomainDefinition;
80
+ // issue #234 phase 2: cloud-side counterpart of extractScfDefinition. Mirrors
81
+ // the executor write shape key-for-key. Not refreshable (omitted so they can
82
+ // never phantom-drift): logConfig (GetFunction returns ClsLogsetId/ClsTopicId
83
+ // ids while the desired definition uses stable logset/topic names — ids churn
84
+ // across redeploys), diskSize (GetFunction does not report it), iam/role
85
+ // (planner-side role grant not reproduced for tencent in this phase).
86
+ const cloudScfToDefinition = (info) => {
87
+ const envMap = info.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
88
+ const cloudVpcConfig = info.VpcConfig;
89
+ const cloudCfsConfig = info.CfsConfig;
90
+ const cloudImageConfig = info.ImageConfig;
91
+ return {
92
+ functionName: info.FunctionName ?? null,
93
+ runtime: info.Runtime ?? null,
94
+ handler: info.Handler ?? null,
95
+ memorySize: info.MemorySize ?? null,
96
+ timeout: info.Timeout ?? null,
97
+ environment: envMap,
98
+ vpcConfig: cloudVpcConfig
99
+ ? { VpcId: cloudVpcConfig.VpcId ?? null, SubnetId: cloudVpcConfig.SubnetId ?? null }
100
+ : null,
101
+ cfsConfig: cloudCfsConfig?.CfsInsList
102
+ ? {
103
+ CfsInsList: cloudCfsConfig.CfsInsList.map((i) => ({
104
+ LocalMountDir: i.LocalMountDir ?? null,
105
+ RemoteMountDir: i.RemoteMountDir ?? null,
106
+ })),
107
+ }
108
+ : null,
109
+ useGpu: info.UseGpu ?? null,
110
+ imageConfig: cloudImageConfig ? { ImageUri: cloudImageConfig.ImageUri ?? null } : null,
111
+ };
112
+ };
113
+ exports.cloudScfToDefinition = cloudScfToDefinition;
@@ -5,6 +5,7 @@ const common_1 = require("../../common");
5
5
  const types_1 = require("../../types");
6
6
  const logger_1 = require("../../common/logger");
7
7
  const lang_1 = require("../../lang");
8
+ const clsOperations_1 = require("../../common/tencentClient/clsOperations");
8
9
  const ownershipTag_1 = require("../ownershipTag");
9
10
  /**
10
11
  * Issue #214: one shared CLS logset per app×stage, tracked in the stage-level
@@ -16,7 +17,15 @@ const ownershipTag_1 = require("../ownershipTag");
16
17
  exports.SHARED_LOGSET_KEY = 'logs.project';
17
18
  const buildSharedLogsetName = (app, stage) => `${app}-${stage}-cls`;
18
19
  exports.buildSharedLogsetName = buildSharedLogsetName;
19
- const buildFunctionTopicName = (context) => `${context.service}-${context.stage}-fn-logs`;
20
+ /**
21
+ * Topic names are per-function (#214 per-owner teardown): the function key is
22
+ * part of the name. The fnKey-less legacy shape only matches topics created
23
+ * before per-function naming — used by legacy-state branches and delete
24
+ * fallbacks where the actual topic predates this scheme.
25
+ */
26
+ const buildFunctionTopicName = (context, fnKey) => fnKey
27
+ ? `${context.service}-${context.stage}-${fnKey}-fn-logs`
28
+ : `${context.service}-${context.stage}-fn-logs`;
20
29
  exports.buildFunctionTopicName = buildFunctionTopicName;
21
30
  const resolveSharedLogsetName = (shared) => {
22
31
  const instanceId = shared.instances?.[0]?.id;
@@ -115,8 +124,8 @@ const ensureFunctionTopic = async (context, client, params) => {
115
124
  }
116
125
  logger_1.logger.info(lang_1.lang.__('CREATING_CLS_TOPIC', { topicName }));
117
126
  const topic = await client.cls.createTopic(logsetId, topicName, {
118
- period: 30,
119
- storageType: 'hot',
127
+ period: clsOperations_1.CLS_TOPIC_PERIOD,
128
+ storageType: clsOperations_1.CLS_TOPIC_STORAGE_TYPE,
120
129
  tags: [{ key: ownershipTag_1.OWNERSHIP_TAG_KEY, value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }],
121
130
  });
122
131
  logger_1.logger.info(lang_1.lang.__('CREATING_CLS_INDEX', { topicName }));
@@ -2,9 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateDatabasePlan = void 0;
4
4
  const tencentClient_1 = require("../../common/tencentClient");
5
+ const refreshCache_1 = require("../../common/refreshCache");
6
+ const concurrency_1 = require("../../common/concurrency");
5
7
  const tdsqlcTypes_1 = require("./tdsqlcTypes");
6
8
  const stateManager_1 = require("../../common/stateManager");
7
- const hashUtils_1 = require("../../common/hashUtils");
9
+ const refreshPlanner_1 = require("../../common/refreshPlanner");
8
10
  const ownershipTag_1 = require("../ownershipTag");
9
11
  const planDatabaseDeletion = (logicalId, definition) => ({
10
12
  logicalId,
@@ -29,64 +31,44 @@ const generateDatabasePlan = async (context, state, databases) => {
29
31
  return { items };
30
32
  }
31
33
  const desiredLogicalIds = new Set(tdsqlcDatabases.map((db) => `databases.${db.key}`));
32
- const databaseItems = await Promise.all(tdsqlcDatabases.map(async (database) => {
34
+ const databaseItems = await (0, concurrency_1.mapWithConcurrency)(tdsqlcDatabases, concurrency_1.PLAN_READ_CONCURRENCY, async (database) => {
33
35
  const logicalId = `databases.${database.key}`;
34
36
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
35
37
  const config = (0, tdsqlcTypes_1.databaseToTdsqlcConfig)(database);
36
38
  const desiredDefinition = (0, tdsqlcTypes_1.extractTdsqlcDefinition)(config);
37
- if (!currentState || currentState.status === 'tainted') {
38
- // No usable local state: probe the provider before planning create. If a
39
- // same-named cluster already exists WITHOUT our ownership tag it may
40
- // belong to another project — fail fast in the plan instead of letting
41
- // the executor discover it mid-deploy.
42
- const client = (0, tencentClient_1.createTencentClient)(context);
43
- const remoteCluster = await client.tdsqlc.getClusterByName(database.name);
44
- if (remoteCluster &&
45
- !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, (0, tdsqlcTypes_1.tdsqlcTagsToOwnershipTags)(remoteCluster.ResourceTags))) {
46
- throw new Error(`Cluster ${database.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
47
- }
48
- return {
49
- logicalId,
50
- action: 'create',
51
- resourceType: 'TDSQL_C_SERVERLESS',
52
- changes: { after: desiredDefinition },
53
- };
54
- }
55
- const clusterId = currentState.metadata?.clusterId || currentState.instances?.[0]?.id;
56
- try {
57
- const client = (0, tencentClient_1.createTencentClient)(context);
58
- const remoteCluster = clusterId ? await client.tdsqlc.getCluster(clusterId) : null;
59
- if (!remoteCluster) {
60
- return {
61
- logicalId,
62
- action: 'create',
63
- resourceType: 'TDSQL_C_SERVERLESS',
64
- changes: { before: currentState.definition, after: desiredDefinition },
65
- drifted: true,
66
- };
67
- }
68
- const currentDefinition = currentState.definition || {};
69
- const definitionChanged = !(0, hashUtils_1.attributesEqual)(currentDefinition, desiredDefinition);
70
- if (definitionChanged) {
71
- return {
72
- logicalId,
73
- action: 'update',
74
- resourceType: 'TDSQL_C_SERVERLESS',
75
- changes: { before: currentDefinition, after: desiredDefinition },
76
- drifted: true,
77
- };
78
- }
79
- return { logicalId, action: 'noop', resourceType: 'TDSQL_C_SERVERLESS' };
80
- }
81
- catch {
82
- return {
83
- logicalId,
84
- action: 'create',
85
- resourceType: 'TDSQL_C_SERVERLESS',
86
- changes: { before: currentState.definition, after: desiredDefinition },
87
- };
88
- }
89
- }));
39
+ const client = (0, tencentClient_1.createTencentClient)(context);
40
+ const clusterId = currentState?.metadata?.clusterId ||
41
+ currentState?.instances?.[0]?.id;
42
+ return (0, refreshPlanner_1.planRefreshedResource)({
43
+ logicalId,
44
+ resourceType: 'TDSQL_C_SERVERLESS',
45
+ currentState,
46
+ desiredDefinition,
47
+ probeRead: () => (0, refreshCache_1.cachedRefreshRead)(context, `tdsqlc.getClusterByName:${database.name}`, () => client.tdsqlc.getClusterByName(database.name)),
48
+ read: () => clusterId
49
+ ? (0, refreshCache_1.cachedRefreshRead)(context, `tdsqlc.getCluster:${clusterId}`, () => client.tdsqlc.getCluster(clusterId))
50
+ : Promise.resolve(null),
51
+ isOwned: (remote) => (0, ownershipTag_1.isOwnedByStack)(context, logicalId, (0, tdsqlcTypes_1.tdsqlcTagsToOwnershipTags)(remote.ResourceTags)),
52
+ foreignError: () => new Error(`Cluster ${database.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`),
53
+ cloudToDefinition: tdsqlcTypes_1.cloudTdsqlcToDefinition,
54
+ extraUpdate: async () => {
55
+ // AutoPause needs a dedicated read: DescribeClusters reports the
56
+ // running serverless state, not the configured idle-pause switch —
57
+ // DescribeServerlessStrategy does. Unreadable strategy is not drift.
58
+ const desiredAutoPause = desiredDefinition.autoPause;
59
+ if (typeof desiredAutoPause !== 'boolean' || !clusterId) {
60
+ return { update: false, drifted: false };
61
+ }
62
+ const strategy = await (0, refreshCache_1.cachedRefreshRead)(context, `tdsqlc.getServerlessStrategy:${clusterId}`, () => client.tdsqlc.getServerlessStrategy(clusterId));
63
+ if (!strategy || strategy.autoPause === undefined) {
64
+ return { update: false, drifted: false };
65
+ }
66
+ const drifted = strategy.autoPause !== desiredAutoPause;
67
+ return { update: drifted, drifted };
68
+ },
69
+ refresh: context.refresh,
70
+ });
71
+ });
90
72
  const allStates = (0, stateManager_1.getAllResources)(state);
91
73
  const deletionItems = Object.entries(allStates)
92
74
  .filter(([logicalId, resourceState]) => {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractTdsqlcDefinition = exports.databaseToTdsqlcConfig = exports.tdsqlcTagsToOwnershipTags = void 0;
3
+ exports.cloudTdsqlcToDefinition = exports.extractTdsqlcDefinition = exports.databaseToTdsqlcConfig = exports.tdsqlcTagsToOwnershipTags = void 0;
4
4
  // TDSQL-C tags are {TagKey,TagValue}; the ownership-tag matcher expects
5
5
  // {Key,Value}. Convert once at the probe site.
6
6
  const tdsqlcTagsToOwnershipTags = (tags) => (tags ?? []).map((t) => ({ Key: t.TagKey, Value: t.TagValue }));
@@ -61,3 +61,23 @@ const extractTdsqlcDefinition = (config) => {
61
61
  };
62
62
  };
63
63
  exports.extractTdsqlcDefinition = extractTdsqlcDefinition;
64
+ // issue #234 phase 2: cloud-side counterpart of extractTdsqlcDefinition.
65
+ // Mirrors the executor write shape key-for-key. Not refreshable (omitted so
66
+ // they can never phantom-drift): autoPause/autoPauseDelay — DescribeClusters
67
+ // reports only the running serverless state; the configured switch is compared
68
+ // separately in the planner via DescribeServerlessStrategy (extraUpdate).
69
+ // port/projectId are not returned by any read API.
70
+ const cloudTdsqlcToDefinition = (info) => ({
71
+ clusterName: info.ClusterName,
72
+ dbType: info.DbType ?? null,
73
+ dbVersion: info.DbVersion ?? null,
74
+ dbMode: info.DbMode ?? null,
75
+ minCpu: info.MinCpu ?? null,
76
+ maxCpu: info.MaxCpu ?? null,
77
+ storagePayMode: info.StoragePayMode ?? null,
78
+ vpcId: info.VpcId ?? null,
79
+ subnetId: info.SubnetId ?? null,
80
+ minStorageSize: info.MinStorageSize ?? null,
81
+ maxStorageSize: info.MaxStorageSize ?? null,
82
+ });
83
+ exports.cloudTdsqlcToDefinition = cloudTdsqlcToDefinition;