@geek-fun/serverlessinsight 0.8.7 → 0.8.9

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 (65) 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 +36 -16
  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/dist/package.json +1 -1
  9. package/dist/src/commands/deploy.js +1 -0
  10. package/dist/src/commands/index.js +6 -2
  11. package/dist/src/commands/plan.js +1 -0
  12. package/dist/src/common/aliyunClient/ecsOperations.js +70 -1
  13. package/dist/src/common/aliyunClient/index.js +44 -35
  14. package/dist/src/common/aliyunClient/nasOperations.js +21 -0
  15. package/dist/src/common/aliyunClient/ramOperations.js +32 -20
  16. package/dist/src/common/aliyunClient/slsOperations.js +16 -3
  17. package/dist/src/common/concurrency.js +30 -0
  18. package/dist/src/common/constants.js +5 -1
  19. package/dist/src/common/context.js +3 -0
  20. package/dist/src/common/dependencyGraph/graph.js +5 -0
  21. package/dist/src/common/imsClient.js +2 -2
  22. package/dist/src/common/index.js +5 -0
  23. package/dist/src/common/planCompare.js +62 -0
  24. package/dist/src/common/planFormatter.js +15 -3
  25. package/dist/src/common/refreshCache.js +32 -0
  26. package/dist/src/common/refreshPlanner.js +105 -0
  27. package/dist/src/common/tencentClient/clsOperations.js +27 -3
  28. package/dist/src/common/tencentClient/tdsqlcOperations.js +22 -0
  29. package/dist/src/common/throttleRetry.js +56 -0
  30. package/dist/src/common/volcengineClient/tlsOperations.js +12 -4
  31. package/dist/src/lang/en.js +16 -0
  32. package/dist/src/lang/zh-CN.js +16 -0
  33. package/dist/src/stack/aliyunStack/apigwPlanner.js +75 -7
  34. package/dist/src/stack/aliyunStack/apigwTypes.js +67 -1
  35. package/dist/src/stack/aliyunStack/databasePlanner.js +26 -62
  36. package/dist/src/stack/aliyunStack/esServerlessTypes.js +50 -1
  37. package/dist/src/stack/aliyunStack/fc3Executor.js +5 -3
  38. package/dist/src/stack/aliyunStack/fc3Planner.js +299 -12
  39. package/dist/src/stack/aliyunStack/fc3Resource.js +221 -30
  40. package/dist/src/stack/aliyunStack/fc3Types.js +61 -1
  41. package/dist/src/stack/aliyunStack/ossPlanner.js +21 -63
  42. package/dist/src/stack/aliyunStack/ossTypes.js +25 -1
  43. package/dist/src/stack/aliyunStack/rdsTypes.js +38 -1
  44. package/dist/src/stack/aliyunStack/tablestorePlanner.js +20 -74
  45. package/dist/src/stack/aliyunStack/tablestoreTypes.js +33 -1
  46. package/dist/src/stack/scfStack/cosPlanner.js +30 -50
  47. package/dist/src/stack/scfStack/cosTypes.js +29 -1
  48. package/dist/src/stack/scfStack/esServerlessPlanner.js +21 -54
  49. package/dist/src/stack/scfStack/esServerlessTypes.js +13 -1
  50. package/dist/src/stack/scfStack/scfExecutor.js +5 -3
  51. package/dist/src/stack/scfStack/scfPlanner.js +71 -50
  52. package/dist/src/stack/scfStack/scfResource.js +37 -2
  53. package/dist/src/stack/scfStack/scfTypes.js +35 -1
  54. package/dist/src/stack/scfStack/sharedLogset.js +3 -2
  55. package/dist/src/stack/scfStack/tdsqlcPlanner.js +37 -55
  56. package/dist/src/stack/scfStack/tdsqlcTypes.js +21 -1
  57. package/dist/src/stack/volcengineStack/apigwPlanner.js +54 -7
  58. package/dist/src/stack/volcengineStack/apigwTypes.js +26 -1
  59. package/dist/src/stack/volcengineStack/tosPlanner.js +28 -55
  60. package/dist/src/stack/volcengineStack/tosTypes.js +18 -1
  61. package/dist/src/stack/volcengineStack/vefaasExecutor.js +5 -3
  62. package/dist/src/stack/volcengineStack/vefaasPlanner.js +114 -6
  63. package/dist/src/stack/volcengineStack/vefaasResource.js +40 -5
  64. package/dist/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +1 -1
@@ -2,10 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateDatabasePlan = void 0;
4
4
  const aliyunClient_1 = require("../../common/aliyunClient");
5
+ const refreshCache_1 = require("../../common/refreshCache");
6
+ const concurrency_1 = require("../../common/concurrency");
5
7
  const rdsTypes_1 = require("./rdsTypes");
6
8
  const esServerlessTypes_1 = require("./esServerlessTypes");
7
9
  const stateManager_1 = require("../../common/stateManager");
8
- const hashUtils_1 = require("../../common/hashUtils");
10
+ const refreshPlanner_1 = require("../../common/refreshPlanner");
9
11
  const ownershipTag_1 = require("../ownershipTag");
10
12
  const toOwnershipTagShape = (tags) => tags?.map((t) => ({ Key: t.key, Value: t.value }));
11
13
  const planDatabaseDeletion = (logicalId, definition, resourceType) => ({
@@ -61,71 +63,33 @@ const generateDatabasePlan = async (context, state, databases) => {
61
63
  }
62
64
  const desiredLogicalIds = new Set(aliyunDatabases.map((db) => `databases.${db.key}`));
63
65
  const client = (0, aliyunClient_1.createAliyunClient)(context);
64
- const databaseItems = await Promise.all(aliyunDatabases.map(async (database) => {
66
+ const databaseItems = await (0, concurrency_1.mapWithConcurrency)(aliyunDatabases, concurrency_1.PLAN_READ_CONCURRENCY, async (database) => {
65
67
  const logicalId = `databases.${database.key}`;
66
68
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
67
69
  const resourceType = getResourceType(database);
68
70
  const desiredDefinition = getDesiredDefinition(database);
69
- if (!currentState || currentState.status === 'tainted') {
70
- // No usable local state: probe the provider before planning create.
71
- // If a same-named resource already exists WITHOUT our ownership tag it
72
- // may belong to another project — fail fast in the plan instead of
73
- // letting the executor discover it mid-deploy.
74
- const remote = resourceType === 'ALIYUN_ES_SERVERLESS'
75
- ? await client.es.getApp(database.name)
76
- : await client.rds.getInstanceByName(database.name);
77
- if (remote && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, toOwnershipTagShape(remote.tags))) {
78
- throw new Error(`${resourceType} ${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.`);
79
- }
80
- return {
81
- logicalId,
82
- action: 'create',
83
- resourceType,
84
- changes: { after: desiredDefinition },
85
- };
86
- }
87
- const instanceId = currentState.metadata?.instanceId ||
88
- currentState.instances?.[0]?.id;
89
- try {
90
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
- let remoteInstance = null;
92
- if (resourceType === 'ALIYUN_ES_SERVERLESS') {
93
- remoteInstance = instanceId ? await client.es.getApp(instanceId) : null;
94
- }
95
- else if (resourceType === 'ALIYUN_RDS_SERVERLESS') {
96
- remoteInstance = instanceId ? await client.rds.getInstance(instanceId) : null;
97
- }
98
- if (!remoteInstance) {
99
- return {
100
- logicalId,
101
- action: 'create',
102
- resourceType,
103
- changes: { before: currentState.definition, after: desiredDefinition },
104
- drifted: true,
105
- };
106
- }
107
- const currentDefinition = currentState.definition || {};
108
- const definitionChanged = !(0, hashUtils_1.attributesEqual)(currentDefinition, desiredDefinition);
109
- if (definitionChanged) {
110
- return {
111
- logicalId,
112
- action: 'update',
113
- resourceType,
114
- changes: { before: currentDefinition, after: desiredDefinition },
115
- drifted: true,
116
- };
117
- }
118
- return { logicalId, action: 'noop', resourceType };
119
- }
120
- catch {
121
- return {
122
- logicalId,
123
- action: 'create',
124
- resourceType,
125
- changes: { before: currentState.definition, after: desiredDefinition },
126
- };
127
- }
128
- }));
71
+ const instanceId = currentState?.metadata?.instanceId ||
72
+ currentState?.instances?.[0]?.id;
73
+ const isEs = resourceType === 'ALIYUN_ES_SERVERLESS';
74
+ return (0, refreshPlanner_1.planRefreshedResource)({
75
+ logicalId,
76
+ resourceType,
77
+ currentState,
78
+ desiredDefinition,
79
+ probeRead: () => isEs
80
+ ? (0, refreshCache_1.cachedRefreshRead)(context, `es.getApp:${database.name}`, () => client.es.getApp(database.name))
81
+ : (0, refreshCache_1.cachedRefreshRead)(context, `rds.getInstanceByName:${database.name}`, () => client.rds.getInstanceByName(database.name)),
82
+ read: () => !instanceId
83
+ ? Promise.resolve(null)
84
+ : isEs
85
+ ? (0, refreshCache_1.cachedRefreshRead)(context, `es.getApp:${instanceId}`, () => client.es.getApp(instanceId))
86
+ : (0, refreshCache_1.cachedRefreshRead)(context, `rds.getInstance:${instanceId}`, () => client.rds.getInstance(instanceId)),
87
+ isOwned: (remote) => (0, ownershipTag_1.isOwnedByStack)(context, logicalId, toOwnershipTagShape(remote.tags)),
88
+ foreignError: () => new Error(`${resourceType} ${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.`),
89
+ cloudToDefinition: (remote) => isEs ? (0, esServerlessTypes_1.cloudEsToDefinition)(remote) : (0, rdsTypes_1.cloudRdsToDefinition)(remote),
90
+ refresh: context.refresh,
91
+ });
92
+ });
129
93
  const allStates = (0, stateManager_1.getAllResources)(state);
130
94
  const deletionItems = Object.entries(allStates)
131
95
  .filter(([logicalId, resourceState]) => {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractEsDefinition = exports.databaseToEsConfig = void 0;
3
+ exports.cloudEsToDefinition = exports.extractEsDefinition = exports.databaseToEsConfig = void 0;
4
4
  // Map database versions to ES versions
5
5
  const esVersionMap = new Map([
6
6
  [
@@ -139,3 +139,52 @@ const extractEsDefinition = (config) => {
139
139
  };
140
140
  };
141
141
  exports.extractEsDefinition = extractEsDefinition;
142
+ const cloudEsToDefinition = (info) => ({
143
+ ...(info.appName === undefined ? {} : { appName: info.appName }),
144
+ ...(info.version === undefined ? {} : { appVersion: info.version }),
145
+ ...(info.description === undefined ? {} : { description: info.description }),
146
+ ...(info.chargeType === undefined ? {} : { chargeType: info.chargeType }),
147
+ ...(info.network === undefined
148
+ ? {}
149
+ : {
150
+ network: info.network.map((network) => ({
151
+ type: network.type ?? null,
152
+ enabled: network.enabled ?? null,
153
+ domain: network.domain ?? null,
154
+ port: network.port ?? null,
155
+ whiteIpGroup: network.whiteIpGroup
156
+ ? network.whiteIpGroup.map((group) => ({
157
+ groupName: group.groupName ?? null,
158
+ ips: group.ips ?? [],
159
+ }))
160
+ : null,
161
+ })),
162
+ }),
163
+ ...(info.privateNetwork === undefined
164
+ ? {}
165
+ : {
166
+ privateNetwork: info.privateNetwork.map((network) => ({
167
+ type: network.type ?? null,
168
+ enabled: network.enabled ?? null,
169
+ domain: network.domain ?? null,
170
+ port: network.port ?? null,
171
+ vpcId: network.vpcId ?? null,
172
+ pvlEndpointId: network.pvlEndpointId ?? null,
173
+ whiteIpGroup: network.whiteIpGroup
174
+ ? network.whiteIpGroup.map((group) => ({
175
+ groupName: group.groupName ?? null,
176
+ ips: group.ips ?? [],
177
+ }))
178
+ : null,
179
+ })),
180
+ }),
181
+ ...(info.tags === undefined
182
+ ? {}
183
+ : {
184
+ tags: info.tags.map((tag) => ({
185
+ key: tag.key ?? null,
186
+ value: tag.value ?? null,
187
+ })),
188
+ }),
189
+ });
190
+ exports.cloudEsToDefinition = cloudEsToDefinition;
@@ -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, fc3Resource_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, fc3Resource_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);
@@ -3,7 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateFunctionPlan = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const aliyunClient_1 = require("../../common/aliyunClient");
6
+ const ramOperations_1 = require("../../common/aliyunClient/ramOperations");
7
+ const slsOperations_1 = require("../../common/aliyunClient/slsOperations");
8
+ const ecsOperations_1 = require("../../common/aliyunClient/ecsOperations");
9
+ const refreshCache_1 = require("../../common/refreshCache");
10
+ const planCompare_1 = require("../../common/planCompare");
11
+ const concurrency_1 = require("../../common/concurrency");
6
12
  const fc3Types_1 = require("./fc3Types");
13
+ const fc3Resource_1 = require("./fc3Resource");
7
14
  const lang_1 = require("../../lang");
8
15
  const ownershipTag_1 = require("../ownershipTag");
9
16
  /**
@@ -38,7 +45,7 @@ const resolveSecurityGroupId = async (context, securityGroupName, vpcId) => {
38
45
  return securityGroupName;
39
46
  }
40
47
  const client = (0, aliyunClient_1.createAliyunClient)(context);
41
- const sg = await client.ecs.getSecurityGroupByName(securityGroupName, vpcId);
48
+ const sg = await (0, refreshCache_1.cachedRefreshRead)(context, `ecs.getSecurityGroupByName:${securityGroupName}:${vpcId ?? ''}`, () => client.ecs.getSecurityGroupByName(securityGroupName, vpcId));
42
49
  if (!sg) {
43
50
  throw new Error(lang_1.lang.__('SECURITY_GROUP_NOT_FOUND', { sgName: securityGroupName, vpcId: vpcId ?? 'default' }));
44
51
  }
@@ -63,6 +70,213 @@ const planFunctionDeletion = (logicalId, definition) => ({
63
70
  resourceType: 'ALIYUN_FC3',
64
71
  changes: { before: normalizeDefinitionForComparison(definition) },
65
72
  });
73
+ // Issue #234: recorded role instance governs (stored-first); explicit managed
74
+ // iam.role derives the executor's name. External (string) roles and functions
75
+ // without role config are deliberately not probed.
76
+ const resolveManagedRoleProbe = (context, fn, currentState) => {
77
+ const iamRole = fn.iam?.role;
78
+ if (typeof iamRole === 'string') {
79
+ return undefined;
80
+ }
81
+ const roleInstance = currentState?.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
82
+ if (roleInstance?.id) {
83
+ return { roleName: roleInstance.id };
84
+ }
85
+ if (iamRole && typeof iamRole === 'object') {
86
+ const serviceName = `${context.app}-${context.service}`;
87
+ return {
88
+ roleName: iamRole.name ?? (0, common_1.buildFunctionRoleName)(serviceName, context.stage, fn.key),
89
+ };
90
+ }
91
+ return undefined;
92
+ };
93
+ /**
94
+ * Parse a cloud RAM trust/policy document. Aliyun returns these URL-encoded
95
+ * (GetRole / GetPolicyVersion) while mocks return plain JSON — accept both.
96
+ * Unparseable/absent yields `undefined` so the caller treats the dimension as
97
+ * unreadable instead of phantom-drifting on garbage.
98
+ */
99
+ const parseRolePolicyDocument = (raw) => {
100
+ if (!raw) {
101
+ return undefined;
102
+ }
103
+ const tryParse = (candidate) => {
104
+ try {
105
+ const parsed = JSON.parse(candidate);
106
+ return parsed && typeof parsed === 'object' ? parsed : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ };
112
+ return tryParse(raw) ?? tryParse(decodeURIComponent(raw));
113
+ };
114
+ /**
115
+ * Live RAM role policy drift against the grant the executor would write via
116
+ * resolveRoleGrant (the very call updateResource uses), so the planner never
117
+ * diverges from the executor. Scoped to avoid false drift:
118
+ * - Only functions declaring a managed `iam.role` object: legacy recorded roles
119
+ * without one carry older si-written documents whose baseline differs from
120
+ * today's derivation — flagging them would fabricate drift with no console
121
+ * edit behind them (the existence probe still covers them).
122
+ * - Only single-owner roles; shared roles need an executor peer-union the
123
+ * planner cannot reproduce → probe-only (coverage gap accepted).
124
+ * - logConfig must be derivable from state: with logging on but no recorded
125
+ * logstore instance the executor creates one during update and derives the
126
+ * grant from that new logstore, which the planner cannot know → skip.
127
+ */
128
+ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName, cloudRole) => {
129
+ const client = (0, aliyunClient_1.createAliyunClient)(context);
130
+ const logicalId = `functions.${fn.key}`;
131
+ const iamRole = fn.iam?.role;
132
+ if (!iamRole || typeof iamRole === 'string') {
133
+ return false;
134
+ }
135
+ const roleInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE' &&
136
+ i.id === roleName &&
137
+ !i.external);
138
+ if (!roleInstance) {
139
+ return false;
140
+ }
141
+ // Conservative ownership scan (mirrors collectRolePeers semantics without
142
+ // requiring context.iac): any OTHER function in state recording the same
143
+ // managed role instance makes the role shared → executor uses a peer union.
144
+ const sharedRole = Object.entries((0, common_1.getAllResources)(state)).some(([peerLogicalId, peerState]) => peerLogicalId !== logicalId &&
145
+ peerLogicalId.startsWith('functions.') &&
146
+ (peerState.instances ?? []).some((i) => i.type === 'ALIYUN_RAM_ROLE' &&
147
+ i.id === roleName &&
148
+ !i.external));
149
+ if (sharedRole) {
150
+ return false;
151
+ }
152
+ let logConfig;
153
+ if (fn.log) {
154
+ const logstoreInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
155
+ if (!logstoreInstance?.id) {
156
+ return false;
157
+ }
158
+ const [project, logstore] = logstoreInstance.id.split('/');
159
+ logConfig = { project, logstore };
160
+ }
161
+ const roleGrant = (0, fc3Resource_1.resolveRoleGrant)(context, state, fn, logConfig, roleName);
162
+ // a. trust policy — console edits to the assume-role principals.
163
+ const cloudTrust = parseRolePolicyDocument(cloudRole?.assumeRolePolicyDocument);
164
+ const desiredTrust = {
165
+ Version: '1',
166
+ Statement: [
167
+ {
168
+ Action: 'sts:AssumeRole',
169
+ Effect: 'Allow',
170
+ Principal: { Service: [...roleGrant.trustedServices] },
171
+ },
172
+ ],
173
+ };
174
+ if (cloudTrust && !(0, common_1.attributesEqual)(cloudTrust, desiredTrust)) {
175
+ return true;
176
+ }
177
+ // b. execution + custom policy (the `<roleName>-policy` custom document). An
178
+ // absent/unreadable cloud document is drift: the executor recreates it on
179
+ // update, so leaving it unread would mask a deleted policy.
180
+ const cloudPolicyDocument = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.getExecutionPolicyDocument:${roleName}`, () => client.ram.getExecutionPolicyDocument(roleName));
181
+ const cloudPolicy = parseRolePolicyDocument(cloudPolicyDocument);
182
+ const desiredPolicyDocument = parseRolePolicyDocument((0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
183
+ if (!cloudPolicy ||
184
+ !desiredPolicyDocument ||
185
+ !(0, common_1.attributesEqual)(cloudPolicy, desiredPolicyDocument)) {
186
+ return true;
187
+ }
188
+ // c. managed (system) policies as sorted name sets; desired ARNs strip the
189
+ // `acs:ram::<uid>:policy/` prefix.
190
+ const desiredManagedNames = (iamRole.managed_policies ?? []).map((policyArn) => policyArn.split('/').pop() ?? '');
191
+ const cloudManagedNames = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.listAttachedRolePolicies:${roleName}`, () => client.ram.listAttachedRolePolicies(roleName));
192
+ const asSortedSetKey = (names) => [...names].sort().join(',');
193
+ if (asSortedSetKey(desiredManagedNames) !== asSortedSetKey(cloudManagedNames ?? [])) {
194
+ return true;
195
+ }
196
+ return false;
197
+ };
198
+ /**
199
+ * Issue #234 M1: nested log-drift probe — logstore ttl/shards and index
200
+ * presence for functions that declare logging. The logstore is per-function
201
+ * (buildFunctionLogstoreName), so this lives in the function flow. Aliyun
202
+ * cannot shrink shards, so only a shard deficit counts as drift.
203
+ */
204
+ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
205
+ // Each declared dimension contributes its own probe; undeclared dimensions
206
+ // fall through so later dimensions still run.
207
+ if (fn.log) {
208
+ const slsLogstoreInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
209
+ if (slsLogstoreInstance?.id) {
210
+ const [projectName, logstoreName] = slsLogstoreInstance.id.split('/');
211
+ if (projectName && logstoreName) {
212
+ const logstore = await (0, refreshCache_1.cachedRefreshRead)(context, `sls.getLogstore:${projectName}:${logstoreName}`, () => client.sls.getLogstore(projectName, logstoreName));
213
+ if (!logstore) {
214
+ return true; // logstore deleted out-of-band
215
+ }
216
+ if (logstore.ttl !== slsOperations_1.SLS_LOGSTORE_TTL) {
217
+ return true;
218
+ }
219
+ // Aliyun cannot shrink shards — only a deficit counts as drift.
220
+ if ((logstore.shardCount ?? 0) < slsOperations_1.SLS_LOGSTORE_SHARDS) {
221
+ return true;
222
+ }
223
+ const index = await (0, refreshCache_1.cachedRefreshRead)(context, `sls.getIndex:${projectName}:${logstoreName}`, () => client.sls.getIndex(projectName, logstoreName));
224
+ if (!index) {
225
+ return true; // index deleted out-of-band
226
+ }
227
+ }
228
+ }
229
+ }
230
+ // SG rules are function-owned (created from fn.network.security_group) —
231
+ // console edits to the rule set are function drift (issue #234 M2).
232
+ if (fn.network) {
233
+ const sgInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
234
+ if (sgInstance?.id) {
235
+ const sgId = sgInstance.id;
236
+ const live = await (0, refreshCache_1.cachedRefreshRead)(context, `ecs.getSecurityGroupRules:${sgId}`, () => client.ecs.getSecurityGroupRules(sgId));
237
+ const desiredRules = (ingress, egress) => {
238
+ const parse = (rule) => {
239
+ try {
240
+ const parsed = (0, ecsOperations_1.parseSecurityGroupRule)(rule);
241
+ return (0, ecsOperations_1.canonicalSecurityGroupRule)(parsed.protocol, parsed.portRange, parsed.cidr);
242
+ }
243
+ catch {
244
+ return null; // invalid rules are skipped at create time too
245
+ }
246
+ };
247
+ return {
248
+ ingress: (ingress ?? []).map(parse).filter((r) => Boolean(r)),
249
+ egress: (egress ?? []).map(parse).filter((r) => Boolean(r)),
250
+ };
251
+ };
252
+ const desired = desiredRules(fn.network.security_group.ingress ?? [], fn.network.security_group.egress ?? []);
253
+ const liveIngress = (live?.ingressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.sourceCidrIp ?? ''));
254
+ const liveEgress = (live?.egressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.destCidrIp ?? ''));
255
+ if (desired.ingress.some((d) => !liveIngress.includes(d)) ||
256
+ liveIngress.some((l) => !desired.ingress.includes(l)) ||
257
+ desired.egress.some((d) => !liveEgress.includes(d)) ||
258
+ liveEgress.some((l) => !desired.egress.includes(l))) {
259
+ return true;
260
+ }
261
+ }
262
+ }
263
+ // Issue #234 M4: NAS mount targets are function-owned — a file system with
264
+ // no live mount targets means the console deleted it out-of-band.
265
+ if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network) {
266
+ const fsInstances = currentState.instances?.filter((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
267
+ for (const fs of fsInstances) {
268
+ const fsId = fs.id;
269
+ if (!fsId) {
270
+ continue;
271
+ }
272
+ const targets = await (0, refreshCache_1.cachedRefreshRead)(context, `nas.listMountTargets:${fsId}`, () => client.nas.listMountTargets(fsId));
273
+ if (!targets || targets.length === 0) {
274
+ return true; // mount target deleted out-of-band
275
+ }
276
+ }
277
+ }
278
+ return false;
279
+ };
66
280
  const generateFunctionPlan = async (context, state, functions) => {
67
281
  if (!functions || functions.length === 0) {
68
282
  const allStates = (0, common_1.getAllResources)(state);
@@ -72,13 +286,12 @@ const generateFunctionPlan = async (context, state, functions) => {
72
286
  return { items };
73
287
  }
74
288
  const desiredLogicalIds = new Set(functions.map((fn) => `functions.${fn.key}`));
75
- const functionItems = await Promise.all(functions.map(async (fn) => {
289
+ const functionItems = await (0, concurrency_1.mapWithConcurrency)(functions, concurrency_1.PLAN_READ_CONCURRENCY, async (fn) => {
76
290
  const logicalId = `functions.${fn.key}`;
77
291
  const currentState = (0, common_1.getResource)(state, logicalId);
78
292
  const rawConfig = (0, fc3Types_1.functionToFc3Config)(fn);
79
293
  const config = await resolveVpcConfigSecurityGroup(context, rawConfig);
80
- const codePath = fn.code.path;
81
- const desiredCodeHash = await (0, common_1.computeZipContentHash)(codePath);
294
+ const desiredCodeHash = fn.code ? await (0, common_1.computeZipContentHash)(fn.code.path) : null;
82
295
  const baseDefinition = (0, fc3Types_1.extractFc3Definition)(config, desiredCodeHash);
83
296
  const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
84
297
  if (!currentState || currentState.status === 'tainted') {
@@ -87,7 +300,7 @@ const generateFunctionPlan = async (context, state, functions) => {
87
300
  // may belong to another project — fail fast in the plan instead of
88
301
  // letting the executor discover it mid-deploy.
89
302
  const client = (0, aliyunClient_1.createAliyunClient)(context);
90
- const remoteFunction = await client.fc3.getFunction(fn.name);
303
+ const remoteFunction = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name));
91
304
  if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.tags)) {
92
305
  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.`);
93
306
  }
@@ -100,7 +313,22 @@ const generateFunctionPlan = async (context, state, functions) => {
100
313
  }
101
314
  try {
102
315
  const client = (0, aliyunClient_1.createAliyunClient)(context);
103
- const remoteFunction = await client.fc3.getFunction(fn.name);
316
+ const normalizedCurrent = normalizeDefinitionForComparison(currentState.definition || {});
317
+ const normalizedDesired = normalizeDefinitionForComparison(desiredDefinition);
318
+ const definitionChanged = !(0, common_1.attributesEqual)(normalizedCurrent, normalizedDesired);
319
+ // --no-refresh: no live read, no drift claims — intent-diff only.
320
+ if (context.refresh === false) {
321
+ if (!definitionChanged) {
322
+ return { logicalId, action: 'noop', resourceType: 'ALIYUN_FC3' };
323
+ }
324
+ return {
325
+ logicalId,
326
+ action: 'update',
327
+ resourceType: 'ALIYUN_FC3',
328
+ changes: { before: normalizedCurrent, after: normalizedDesired },
329
+ };
330
+ }
331
+ const remoteFunction = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name));
104
332
  if (!remoteFunction) {
105
333
  return {
106
334
  logicalId,
@@ -113,11 +341,14 @@ const generateFunctionPlan = async (context, state, functions) => {
113
341
  drifted: true,
114
342
  };
115
343
  }
116
- const currentDefinition = currentState.definition || {};
117
- const normalizedCurrent = normalizeDefinitionForComparison(currentDefinition);
118
- const normalizedDesired = normalizeDefinitionForComparison(desiredDefinition);
119
- const definitionChanged = !(0, common_1.attributesEqual)(normalizedCurrent, normalizedDesired);
120
- if (definitionChanged) {
344
+ // Issue #234 phase 1: live attribute drift. The stored definition can
345
+ // be untouched while the console edited the deployed function
346
+ // (memory/timeout/env/...). One-directional: only mapper-emitted keys
347
+ // the desired definition declares are compared, so cloud-only extras
348
+ // the config never asked for are ignored (desired-declared contract).
349
+ const remoteAttributes = (0, fc3Types_1.cloudFc3ToDefinition)(remoteFunction);
350
+ const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(remoteAttributes, desiredDefinition);
351
+ if (definitionChanged || remoteDiffers) {
121
352
  return {
122
353
  logicalId,
123
354
  action: 'update',
@@ -126,6 +357,62 @@ const generateFunctionPlan = async (context, state, functions) => {
126
357
  drifted: true,
127
358
  };
128
359
  }
360
+ const roleProbe = resolveManagedRoleProbe(context, fn, currentState);
361
+ if (roleProbe) {
362
+ try {
363
+ const cloudRole = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.getRole:${roleProbe.roleName}`, () => client.ram.getRole(roleProbe.roleName));
364
+ if (!cloudRole) {
365
+ common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_ROLE_MISSING', {
366
+ roleName: roleProbe.roleName,
367
+ functionName: fn.name,
368
+ }));
369
+ return {
370
+ logicalId,
371
+ action: 'update',
372
+ resourceType: 'ALIYUN_FC3',
373
+ changes: { before: normalizedCurrent, after: normalizedDesired },
374
+ drifted: true,
375
+ };
376
+ }
377
+ const rolePolicyDrifted = await detectRolePolicyDrift(context, state, fn, currentState, roleProbe.roleName, cloudRole);
378
+ if (rolePolicyDrifted) {
379
+ return {
380
+ logicalId,
381
+ action: 'update',
382
+ resourceType: 'ALIYUN_FC3',
383
+ changes: { before: normalizedCurrent, after: normalizedDesired },
384
+ drifted: true,
385
+ };
386
+ }
387
+ }
388
+ catch (error) {
389
+ common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_ROLE_PROBE_FAILED', {
390
+ roleName: roleProbe.roleName,
391
+ functionName: fn.name,
392
+ error: String(error),
393
+ }));
394
+ }
395
+ }
396
+ // Issue #234 M1/M2: nested drift probe — the probe itself skips
397
+ // dimensions the config does not declare.
398
+ try {
399
+ const nestedDrifted = await detectFunctionNestedDrift(context, client, fn, currentState);
400
+ if (nestedDrifted) {
401
+ return {
402
+ logicalId,
403
+ action: 'update',
404
+ resourceType: 'ALIYUN_FC3',
405
+ changes: { before: normalizedCurrent, after: normalizedDesired },
406
+ drifted: true,
407
+ };
408
+ }
409
+ }
410
+ catch (error) {
411
+ common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_NESTED_PROBE_FAILED', {
412
+ functionName: fn.name,
413
+ error: String(error),
414
+ }));
415
+ }
129
416
  return { logicalId, action: 'noop', resourceType: 'ALIYUN_FC3' };
130
417
  }
131
418
  catch {
@@ -139,7 +426,7 @@ const generateFunctionPlan = async (context, state, functions) => {
139
426
  },
140
427
  };
141
428
  }
142
- }));
429
+ });
143
430
  const allStates = (0, common_1.getAllResources)(state);
144
431
  const deletionItems = Object.entries(allStates)
145
432
  .filter(([logicalId]) => logicalId.startsWith('functions.') && !desiredLogicalIds.has(logicalId))