@geek-fun/serverlessinsight 0.8.8 → 0.9.0

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 (52) 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 +2 -2
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +123 -0
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  8. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +93 -0
  9. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +148 -0
  10. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  11. package/CHANGELOG.md +29 -0
  12. package/dist/package.json +1 -1
  13. package/dist/src/commands/deploy.js +3 -1
  14. package/dist/src/commands/index.js +25 -0
  15. package/dist/src/common/aliyunClient/fc3Operations.js +5 -0
  16. package/dist/src/common/aliyunClient/index.js +44 -35
  17. package/dist/src/common/constants.js +5 -1
  18. package/dist/src/common/imsClient.js +2 -2
  19. package/dist/src/common/nameBuilder.js +13 -1
  20. package/dist/src/common/planCompare.js +31 -1
  21. package/dist/src/common/planFormatter.js +69 -54
  22. package/dist/src/common/refreshPlanner.js +31 -8
  23. package/dist/src/lang/en.js +20 -6
  24. package/dist/src/lang/zh-CN.js +20 -6
  25. package/dist/src/stack/aliyunStack/apigwPlanner.js +26 -5
  26. package/dist/src/stack/aliyunStack/databasePlanner.js +6 -1
  27. package/dist/src/stack/aliyunStack/databaseResource.js +10 -2
  28. package/dist/src/stack/aliyunStack/deployer.js +30 -13
  29. package/dist/src/stack/aliyunStack/fc3Planner.js +46 -25
  30. package/dist/src/stack/aliyunStack/fc3Resource.js +137 -87
  31. package/dist/src/stack/aliyunStack/ossPlanner.js +6 -1
  32. package/dist/src/stack/aliyunStack/ossResource.js +9 -2
  33. package/dist/src/stack/aliyunStack/tablestorePlanner.js +2 -1
  34. package/dist/src/stack/aliyunStack/tablestoreResource.js +2 -1
  35. package/dist/src/stack/deploy.js +10 -4
  36. package/dist/src/stack/scfStack/cosPlanner.js +6 -1
  37. package/dist/src/stack/scfStack/cosResource.js +6 -2
  38. package/dist/src/stack/scfStack/deployer.js +21 -6
  39. package/dist/src/stack/scfStack/esServerlessPlanner.js +6 -1
  40. package/dist/src/stack/scfStack/esServerlessResource.js +5 -1
  41. package/dist/src/stack/scfStack/scfPlanner.js +26 -27
  42. package/dist/src/stack/scfStack/scfResource.js +6 -2
  43. package/dist/src/stack/scfStack/tdsqlcPlanner.js +6 -1
  44. package/dist/src/stack/scfStack/tdsqlcResource.js +5 -1
  45. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  46. package/dist/src/stack/volcengineStack/deployer.js +15 -4
  47. package/dist/src/stack/volcengineStack/tosPlanner.js +6 -1
  48. package/dist/src/stack/volcengineStack/tosResource.js +10 -3
  49. package/dist/src/stack/volcengineStack/vefaasPlanner.js +39 -11
  50. package/dist/src/stack/volcengineStack/vefaasResource.js +5 -1
  51. package/dist/src/validator/semanticValidation.js +24 -0
  52. package/package.json +1 -1
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateApigwPlan = void 0;
4
4
  const aliyunClient_1 = require("../../common/aliyunClient");
5
+ const logger_1 = require("../../common/logger");
5
6
  const apigwTypes_1 = require("./apigwTypes");
6
7
  const stateManager_1 = require("../../common/stateManager");
7
8
  const hashUtils_1 = require("../../common/hashUtils");
@@ -10,6 +11,7 @@ const planCompare_1 = require("../../common/planCompare");
10
11
  const refreshCache_1 = require("../../common/refreshCache");
11
12
  const concurrency_1 = require("../../common/concurrency");
12
13
  const ownershipTag_1 = require("../ownershipTag");
14
+ const lang_1 = require("../../lang");
13
15
  const DNS_SUB_RESOURCE_SUFFIXES = ['.dns_verification', '.dns_txt_verification'];
14
16
  const isDnsSubResource = (logicalId) => DNS_SUB_RESOURCE_SUFFIXES.some((suffix) => logicalId.endsWith(suffix));
15
17
  const planEventDeletion = (logicalId, definition) => ({
@@ -68,7 +70,11 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
68
70
  const remoteGroup = await (0, refreshCache_1.cachedRefreshRead)(context, `apigw.findApiGroupByName:${groupConfig.groupName}`, () => client.apigw.findApiGroupByName(groupConfig.groupName));
69
71
  if (remoteGroup?.groupId) {
70
72
  if (!(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteGroup.tags)) {
71
- throw new Error(`API group ${groupConfig.groupName} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
73
+ throw new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED', {
74
+ resourceType: 'API group',
75
+ resourceName: groupConfig.groupName,
76
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
77
+ }));
72
78
  }
73
79
  if (!currentState) {
74
80
  // Resource exists remotely (and is ours) but not in state — drift:
@@ -96,6 +102,10 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
96
102
  const definitionChanged = !(0, hashUtils_1.attributesEqual)(currentDefinition, desiredDefinition);
97
103
  let groupRemoteDiffers = false;
98
104
  let triggersDiffer = false;
105
+ // Issue #246: live group attributes become the diff baseline when the
106
+ // group was readable; trigger-level drift has no attribute mapping and
107
+ // is surfaced as a drift reason instead.
108
+ let liveGroupAttrs;
99
109
  if (groupInstance) {
100
110
  const remoteGroup = await (0, refreshCache_1.cachedRefreshRead)(context, `apigw.getApiGroup:${groupInstance.id}`, () => client.apigw.getApiGroup(groupInstance.id));
101
111
  if (!remoteGroup) {
@@ -113,9 +123,9 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
113
123
  // to the group/trigger then surfaces as update + drifted, and a read
114
124
  // failure cannot degrade a config-driven update into a create.
115
125
  // Domain/log stay existence-only in Phase 0-2 — never compared live.
126
+ liveGroupAttrs = (0, apigwTypes_1.cloudApigwGroupToDefinition)(remoteGroup);
116
127
  if (!definitionChanged) {
117
- const remoteGroupAttrs = (0, apigwTypes_1.cloudApigwGroupToDefinition)(remoteGroup);
118
- groupRemoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(remoteGroupAttrs, desiredDefinition);
128
+ groupRemoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(liveGroupAttrs, desiredDefinition);
119
129
  if (event.triggers.length > 0) {
120
130
  const desiredApis = new Map(event.triggers.map((trigger) => {
121
131
  const apiName = buildDesiredTriggerApiName(event, trigger, context.stage);
@@ -164,18 +174,29 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
164
174
  logicalId,
165
175
  action: 'update',
166
176
  resourceType: 'ALIYUN_APIGW',
167
- changes: { before: currentDefinition, after: desiredDefinition },
177
+ changes: {
178
+ before: liveGroupAttrs
179
+ ? (0, planCompare_1.mergeLiveBefore)(currentDefinition, liveGroupAttrs)
180
+ : currentDefinition,
181
+ after: desiredDefinition,
182
+ },
168
183
  drifted: true,
184
+ ...(triggersDiffer ? { driftReasons: ['PLAN_DRIFT_TRIGGERS'] } : {}),
169
185
  };
170
186
  }
171
187
  return { logicalId, action: 'noop', resourceType: 'ALIYUN_APIGW' };
172
188
  }
173
- catch {
189
+ catch (error) {
190
+ logger_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
191
+ logicalId,
192
+ error: error instanceof Error ? error.message : String(error),
193
+ }));
174
194
  return {
175
195
  logicalId,
176
196
  action: 'create',
177
197
  resourceType: 'ALIYUN_APIGW',
178
198
  changes: { before: currentState.definition, after: desiredDefinition },
199
+ drifted: true,
179
200
  };
180
201
  }
181
202
  });
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateDatabasePlan = void 0;
4
+ const lang_1 = require("../../lang");
4
5
  const aliyunClient_1 = require("../../common/aliyunClient");
5
6
  const refreshCache_1 = require("../../common/refreshCache");
6
7
  const concurrency_1 = require("../../common/concurrency");
@@ -85,7 +86,11 @@ const generateDatabasePlan = async (context, state, databases) => {
85
86
  ? (0, refreshCache_1.cachedRefreshRead)(context, `es.getApp:${instanceId}`, () => client.es.getApp(instanceId))
86
87
  : (0, refreshCache_1.cachedRefreshRead)(context, `rds.getInstance:${instanceId}`, () => client.rds.getInstance(instanceId)),
87
88
  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
+ foreignError: () => new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED', {
90
+ resourceType,
91
+ resourceName: database.name,
92
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
93
+ })),
89
94
  cloudToDefinition: (remote) => isEs ? (0, esServerlessTypes_1.cloudEsToDefinition)(remote) : (0, rdsTypes_1.cloudRdsToDefinition)(remote),
90
95
  refresh: context.refresh,
91
96
  });
@@ -184,7 +184,11 @@ const createDatabaseResource = async (context, database, state) => {
184
184
  logger_1.logger.info(`ES app ${config.appName} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
185
185
  }
186
186
  else {
187
- throw new Error(`ES app ${config.appName} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to adopt — resolve manually.`, { cause: error });
187
+ throw new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED_ADOPT', {
188
+ resourceType: 'ES app',
189
+ resourceName: config.appName,
190
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
191
+ }), { cause: error });
188
192
  }
189
193
  }
190
194
  else {
@@ -214,7 +218,11 @@ const createDatabaseResource = async (context, database, state) => {
214
218
  logger_1.logger.info(`RDS instance ${config.dbInstanceDescription} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
215
219
  }
216
220
  else {
217
- throw new Error(`RDS instance ${config.dbInstanceDescription} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to adopt — resolve manually.`, { cause: error });
221
+ throw new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED_ADOPT', {
222
+ resourceType: 'RDS instance',
223
+ resourceName: config.dbInstanceDescription,
224
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
225
+ }), { cause: error });
218
226
  }
219
227
  }
220
228
  else {
@@ -73,7 +73,12 @@ const buildRoleArnResolver = (state, functions) => {
73
73
  };
74
74
  };
75
75
  exports.buildRoleArnResolver = buildRoleArnResolver;
76
- const deployAliyunStack = async (iac, backend) => {
76
+ // Issue #246: when the approved plan is passed through, the executor runs
77
+ // exactly the displayed items — partitioned by resourceType, no re-probe.
78
+ const partitionPlan = (plan, types) => ({
79
+ items: plan.items.filter((item) => types.includes(item.resourceType)),
80
+ });
81
+ const deployAliyunStack = async (iac, backend, approvedPlan) => {
77
82
  const context = (0, common_1.getContext)();
78
83
  // Cache IAC for access throughout the deployment
79
84
  (0, common_1.setIac)(iac);
@@ -81,18 +86,30 @@ const deployAliyunStack = async (iac, backend) => {
81
86
  let state = await backend.loadState(iac.provider.name, iac.app, iac.service, context.stage);
82
87
  const onStateChange = createSaveStateFn(backend, iac, context.stage);
83
88
  common_1.logger.info(lang_1.lang.__('GENERATING_PLAN'));
84
- const functionPlan = await (0, fc3Planner_1.generateFunctionPlan)(context, state, iac.functions);
85
- const bucketPlan = await (0, ossPlanner_1.generateBucketPlan)(context, state, iac.buckets);
86
- const databasePlan = await (0, databasePlanner_1.generateDatabasePlan)(context, state, iac.databases);
87
- const tablePlan = await (0, tablestorePlanner_1.generateTablePlan)(context, state, iac.tables);
88
- const eventPlan = await (0, apigwPlanner_1.generateApigwPlan)(context, state, iac.events, iac.service);
89
- const allItems = [
90
- ...functionPlan.items,
91
- ...bucketPlan.items,
92
- ...databasePlan.items,
93
- ...tablePlan.items,
94
- ...eventPlan.items,
95
- ];
89
+ const functionPlan = approvedPlan
90
+ ? partitionPlan(approvedPlan, ['ALIYUN_FC3'])
91
+ : await (0, fc3Planner_1.generateFunctionPlan)(context, state, iac.functions);
92
+ const bucketPlan = approvedPlan
93
+ ? partitionPlan(approvedPlan, ['ALIYUN_OSS_BUCKET'])
94
+ : await (0, ossPlanner_1.generateBucketPlan)(context, state, iac.buckets);
95
+ const databasePlan = approvedPlan
96
+ ? partitionPlan(approvedPlan, ['ALIYUN_RDS_SERVERLESS', 'ALIYUN_ES_SERVERLESS'])
97
+ : await (0, databasePlanner_1.generateDatabasePlan)(context, state, iac.databases);
98
+ const tablePlan = approvedPlan
99
+ ? partitionPlan(approvedPlan, ['ALIYUN_TABLESTORE_TABLE'])
100
+ : await (0, tablestorePlanner_1.generateTablePlan)(context, state, iac.tables);
101
+ const eventPlan = approvedPlan
102
+ ? partitionPlan(approvedPlan, ['ALIYUN_APIGW'])
103
+ : await (0, apigwPlanner_1.generateApigwPlan)(context, state, iac.events, iac.service);
104
+ const allItems = approvedPlan
105
+ ? [...approvedPlan.items]
106
+ : [
107
+ ...functionPlan.items,
108
+ ...bucketPlan.items,
109
+ ...databasePlan.items,
110
+ ...tablePlan.items,
111
+ ...eventPlan.items,
112
+ ];
96
113
  // Build dependency graph for validation (e.g. cycle detection) and logging
97
114
  const dependencyInfo = (0, common_1.getDependencyInfo)(allItems);
98
115
  if (dependencyInfo.cycleError) {
@@ -124,19 +124,21 @@ const parseRolePolicyDocument = (raw) => {
124
124
  * - logConfig must be derivable from state: with logging on but no recorded
125
125
  * logstore instance the executor creates one during update and derives the
126
126
  * grant from that new logstore, which the planner cannot know → skip.
127
+ * Returns an i18n drift-reason key (issue #246) instead of a boolean so the
128
+ * plan can say WHICH dimension drifted; null means no drift.
127
129
  */
128
130
  const detectRolePolicyDrift = async (context, state, fn, currentState, roleName, cloudRole) => {
129
131
  const client = (0, aliyunClient_1.createAliyunClient)(context);
130
132
  const logicalId = `functions.${fn.key}`;
131
133
  const iamRole = fn.iam?.role;
132
134
  if (!iamRole || typeof iamRole === 'string') {
133
- return false;
135
+ return null;
134
136
  }
135
137
  const roleInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE' &&
136
138
  i.id === roleName &&
137
139
  !i.external);
138
140
  if (!roleInstance) {
139
- return false;
141
+ return null;
140
142
  }
141
143
  // Conservative ownership scan (mirrors collectRolePeers semantics without
142
144
  // requiring context.iac): any OTHER function in state recording the same
@@ -147,13 +149,13 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
147
149
  i.id === roleName &&
148
150
  !i.external));
149
151
  if (sharedRole) {
150
- return false;
152
+ return null;
151
153
  }
152
154
  let logConfig;
153
155
  if (fn.log) {
154
156
  const logstoreInstance = currentState.instances?.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
155
157
  if (!logstoreInstance?.id) {
156
- return false;
158
+ return null;
157
159
  }
158
160
  const [project, logstore] = logstoreInstance.id.split('/');
159
161
  logConfig = { project, logstore };
@@ -172,7 +174,7 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
172
174
  ],
173
175
  };
174
176
  if (cloudTrust && !(0, common_1.attributesEqual)(cloudTrust, desiredTrust)) {
175
- return true;
177
+ return 'PLAN_DRIFT_ROLE_POLICY';
176
178
  }
177
179
  // b. execution + custom policy (the `<roleName>-policy` custom document). An
178
180
  // absent/unreadable cloud document is drift: the executor recreates it on
@@ -183,7 +185,7 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
183
185
  if (!cloudPolicy ||
184
186
  !desiredPolicyDocument ||
185
187
  !(0, common_1.attributesEqual)(cloudPolicy, desiredPolicyDocument)) {
186
- return true;
188
+ return 'PLAN_DRIFT_ROLE_POLICY';
187
189
  }
188
190
  // c. managed (system) policies as sorted name sets; desired ARNs strip the
189
191
  // `acs:ram::<uid>:policy/` prefix.
@@ -191,15 +193,16 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
191
193
  const cloudManagedNames = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.listAttachedRolePolicies:${roleName}`, () => client.ram.listAttachedRolePolicies(roleName));
192
194
  const asSortedSetKey = (names) => [...names].sort().join(',');
193
195
  if (asSortedSetKey(desiredManagedNames) !== asSortedSetKey(cloudManagedNames ?? [])) {
194
- return true;
196
+ return 'PLAN_DRIFT_ROLE_POLICY';
195
197
  }
196
- return false;
198
+ return null;
197
199
  };
198
200
  /**
199
201
  * Issue #234 M1: nested log-drift probe — logstore ttl/shards and index
200
202
  * presence for functions that declare logging. The logstore is per-function
201
203
  * (buildFunctionLogstoreName), so this lives in the function flow. Aliyun
202
204
  * cannot shrink shards, so only a shard deficit counts as drift.
205
+ * Returns an i18n drift-reason key (issue #246); null means no drift.
203
206
  */
204
207
  const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
205
208
  // Each declared dimension contributes its own probe; undeclared dimensions
@@ -211,18 +214,18 @@ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
211
214
  if (projectName && logstoreName) {
212
215
  const logstore = await (0, refreshCache_1.cachedRefreshRead)(context, `sls.getLogstore:${projectName}:${logstoreName}`, () => client.sls.getLogstore(projectName, logstoreName));
213
216
  if (!logstore) {
214
- return true; // logstore deleted out-of-band
217
+ return 'PLAN_DRIFT_LOGSTORE'; // logstore deleted out-of-band
215
218
  }
216
219
  if (logstore.ttl !== slsOperations_1.SLS_LOGSTORE_TTL) {
217
- return true;
220
+ return 'PLAN_DRIFT_LOGSTORE';
218
221
  }
219
222
  // Aliyun cannot shrink shards — only a deficit counts as drift.
220
223
  if ((logstore.shardCount ?? 0) < slsOperations_1.SLS_LOGSTORE_SHARDS) {
221
- return true;
224
+ return 'PLAN_DRIFT_LOGSTORE';
222
225
  }
223
226
  const index = await (0, refreshCache_1.cachedRefreshRead)(context, `sls.getIndex:${projectName}:${logstoreName}`, () => client.sls.getIndex(projectName, logstoreName));
224
227
  if (!index) {
225
- return true; // index deleted out-of-band
228
+ return 'PLAN_DRIFT_LOGSTORE'; // index deleted out-of-band
226
229
  }
227
230
  }
228
231
  }
@@ -256,7 +259,7 @@ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
256
259
  liveIngress.some((l) => !desired.ingress.includes(l)) ||
257
260
  desired.egress.some((d) => !liveEgress.includes(d)) ||
258
261
  liveEgress.some((l) => !desired.egress.includes(l))) {
259
- return true;
262
+ return 'PLAN_DRIFT_SG_RULES';
260
263
  }
261
264
  }
262
265
  }
@@ -271,11 +274,11 @@ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
271
274
  }
272
275
  const targets = await (0, refreshCache_1.cachedRefreshRead)(context, `nas.listMountTargets:${fsId}`, () => client.nas.listMountTargets(fsId));
273
276
  if (!targets || targets.length === 0) {
274
- return true; // mount target deleted out-of-band
277
+ return 'PLAN_DRIFT_NAS_MOUNT'; // mount target deleted out-of-band
275
278
  }
276
279
  }
277
280
  }
278
- return false;
281
+ return null;
279
282
  };
280
283
  const generateFunctionPlan = async (context, state, functions) => {
281
284
  if (!functions || functions.length === 0) {
@@ -302,7 +305,11 @@ const generateFunctionPlan = async (context, state, functions) => {
302
305
  const client = (0, aliyunClient_1.createAliyunClient)(context);
303
306
  const remoteFunction = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name));
304
307
  if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.tags)) {
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.`);
308
+ throw new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED', {
309
+ resourceType: 'Function',
310
+ resourceName: fn.name,
311
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
312
+ }));
306
313
  }
307
314
  return {
308
315
  logicalId,
@@ -346,15 +353,21 @@ const generateFunctionPlan = async (context, state, functions) => {
346
353
  // (memory/timeout/env/...). One-directional: only mapper-emitted keys
347
354
  // the desired definition declares are compared, so cloud-only extras
348
355
  // the config never asked for are ignored (desired-declared contract).
356
+ // Issue #246: the diff baseline is cloud reality — live attributes
357
+ // merged over the stored definition — and revertKeys marks the fields
358
+ // whose difference is purely an out-of-config cloud edit.
349
359
  const remoteAttributes = (0, fc3Types_1.cloudFc3ToDefinition)(remoteFunction);
350
360
  const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(remoteAttributes, desiredDefinition);
361
+ const liveBefore = normalizeDefinitionForComparison((0, planCompare_1.mergeLiveBefore)(currentState.definition || {}, remoteAttributes));
362
+ const revertKeys = (0, planCompare_1.computeRevertKeys)(normalizedCurrent, normalizeDefinitionForComparison(remoteAttributes), normalizedDesired);
351
363
  if (definitionChanged || remoteDiffers) {
352
364
  return {
353
365
  logicalId,
354
366
  action: 'update',
355
367
  resourceType: 'ALIYUN_FC3',
356
- changes: { before: normalizedCurrent, after: normalizedDesired },
368
+ changes: { before: liveBefore, after: normalizedDesired },
357
369
  drifted: true,
370
+ ...(revertKeys.length ? { revertKeys } : {}),
358
371
  };
359
372
  }
360
373
  const roleProbe = resolveManagedRoleProbe(context, fn, currentState);
@@ -370,18 +383,20 @@ const generateFunctionPlan = async (context, state, functions) => {
370
383
  logicalId,
371
384
  action: 'update',
372
385
  resourceType: 'ALIYUN_FC3',
373
- changes: { before: normalizedCurrent, after: normalizedDesired },
386
+ changes: { before: liveBefore, after: normalizedDesired },
374
387
  drifted: true,
388
+ driftReasons: ['PLAN_DRIFT_ROLE_MISSING'],
375
389
  };
376
390
  }
377
- const rolePolicyDrifted = await detectRolePolicyDrift(context, state, fn, currentState, roleProbe.roleName, cloudRole);
378
- if (rolePolicyDrifted) {
391
+ const roleDriftReason = await detectRolePolicyDrift(context, state, fn, currentState, roleProbe.roleName, cloudRole);
392
+ if (roleDriftReason) {
379
393
  return {
380
394
  logicalId,
381
395
  action: 'update',
382
396
  resourceType: 'ALIYUN_FC3',
383
- changes: { before: normalizedCurrent, after: normalizedDesired },
397
+ changes: { before: liveBefore, after: normalizedDesired },
384
398
  drifted: true,
399
+ driftReasons: [roleDriftReason],
385
400
  };
386
401
  }
387
402
  }
@@ -396,14 +411,15 @@ const generateFunctionPlan = async (context, state, functions) => {
396
411
  // Issue #234 M1/M2: nested drift probe — the probe itself skips
397
412
  // dimensions the config does not declare.
398
413
  try {
399
- const nestedDrifted = await detectFunctionNestedDrift(context, client, fn, currentState);
400
- if (nestedDrifted) {
414
+ const nestedDriftReason = await detectFunctionNestedDrift(context, client, fn, currentState);
415
+ if (nestedDriftReason) {
401
416
  return {
402
417
  logicalId,
403
418
  action: 'update',
404
419
  resourceType: 'ALIYUN_FC3',
405
- changes: { before: normalizedCurrent, after: normalizedDesired },
420
+ changes: { before: liveBefore, after: normalizedDesired },
406
421
  drifted: true,
422
+ driftReasons: [nestedDriftReason],
407
423
  };
408
424
  }
409
425
  }
@@ -415,7 +431,11 @@ const generateFunctionPlan = async (context, state, functions) => {
415
431
  }
416
432
  return { logicalId, action: 'noop', resourceType: 'ALIYUN_FC3' };
417
433
  }
418
- catch {
434
+ catch (error) {
435
+ common_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
436
+ logicalId,
437
+ error: error instanceof Error ? error.message : String(error),
438
+ }));
419
439
  return {
420
440
  logicalId,
421
441
  action: 'create',
@@ -424,6 +444,7 @@ const generateFunctionPlan = async (context, state, functions) => {
424
444
  before: normalizeDefinitionForComparison(currentState.definition),
425
445
  after: normalizeDefinitionForComparison(desiredDefinition),
426
446
  },
447
+ drifted: true,
427
448
  };
428
449
  }
429
450
  });