@geek-fun/serverlessinsight 0.8.9 → 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 (49) 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/nameBuilder.js +13 -1
  17. package/dist/src/common/planCompare.js +31 -1
  18. package/dist/src/common/planFormatter.js +69 -54
  19. package/dist/src/common/refreshPlanner.js +31 -8
  20. package/dist/src/lang/en.js +20 -6
  21. package/dist/src/lang/zh-CN.js +20 -6
  22. package/dist/src/stack/aliyunStack/apigwPlanner.js +26 -5
  23. package/dist/src/stack/aliyunStack/databasePlanner.js +6 -1
  24. package/dist/src/stack/aliyunStack/databaseResource.js +10 -2
  25. package/dist/src/stack/aliyunStack/deployer.js +30 -13
  26. package/dist/src/stack/aliyunStack/fc3Planner.js +46 -25
  27. package/dist/src/stack/aliyunStack/fc3Resource.js +49 -20
  28. package/dist/src/stack/aliyunStack/ossPlanner.js +6 -1
  29. package/dist/src/stack/aliyunStack/ossResource.js +9 -2
  30. package/dist/src/stack/aliyunStack/tablestorePlanner.js +2 -1
  31. package/dist/src/stack/aliyunStack/tablestoreResource.js +2 -1
  32. package/dist/src/stack/deploy.js +10 -4
  33. package/dist/src/stack/scfStack/cosPlanner.js +6 -1
  34. package/dist/src/stack/scfStack/cosResource.js +6 -2
  35. package/dist/src/stack/scfStack/deployer.js +21 -6
  36. package/dist/src/stack/scfStack/esServerlessPlanner.js +6 -1
  37. package/dist/src/stack/scfStack/esServerlessResource.js +5 -1
  38. package/dist/src/stack/scfStack/scfPlanner.js +26 -27
  39. package/dist/src/stack/scfStack/scfResource.js +6 -2
  40. package/dist/src/stack/scfStack/tdsqlcPlanner.js +6 -1
  41. package/dist/src/stack/scfStack/tdsqlcResource.js +5 -1
  42. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  43. package/dist/src/stack/volcengineStack/deployer.js +15 -4
  44. package/dist/src/stack/volcengineStack/tosPlanner.js +6 -1
  45. package/dist/src/stack/volcengineStack/tosResource.js +10 -3
  46. package/dist/src/stack/volcengineStack/vefaasPlanner.js +39 -11
  47. package/dist/src/stack/volcengineStack/vefaasResource.js +5 -1
  48. package/dist/src/validator/semanticValidation.js +24 -0
  49. package/package.json +1 -1
@@ -28,8 +28,6 @@ const DEFAULT_CONFIG = {
28
28
  colorize: true,
29
29
  indentSize: 4,
30
30
  keyAlignWidth: 12,
31
- showUnchangedAttributes: false,
32
- maxUnchangedHidden: 5,
33
31
  };
34
32
  const isObject = (val) => typeof val === 'object' && val !== null && !Array.isArray(val);
35
33
  const isSimpleObject = (val) => {
@@ -142,9 +140,17 @@ const computeMaxKeyWidth = (diffs, baseIndent) => diffs.reduce((maxWidth, diff)
142
140
  : 0;
143
141
  return Math.max(maxWidth, keyWidth, childWidth);
144
142
  }, 0);
145
- const formatAttributeLines = (diff, indent, config, keyWidth) => {
143
+ const formatAttributeLines = (diff, indent, config, keyWidth, revertKeys) => {
146
144
  const spaces = ' '.repeat(indent);
147
145
  const alignedKey = (diff.key + ':').padEnd(keyWidth);
146
+ // Issue #246: a field whose stored value already matched the config while
147
+ // the cloud diverged is annotated at the line level — the resource block
148
+ // stays in place, only this line explains why it appears. Only leaf lines
149
+ // reach suffix (parent cases early-return on children), so a revert key
150
+ // with nested children never carries the annotation.
151
+ const suffix = (line) => revertKeys?.has(diff.key)
152
+ ? `${line} ${colorize(lang_1.lang.__('PLAN_REVERT_ANNOTATION'), 'CYAN', config.colorize)}`
153
+ : line;
148
154
  switch (diff.action) {
149
155
  case 'add': {
150
156
  if (diff.children && diff.children.length > 0) {
@@ -157,7 +163,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
157
163
  const value = diff.isComputed
158
164
  ? colorize(lang_1.lang.__('PLAN_COMPUTED_VALUE'), 'CYAN', config.colorize)
159
165
  : formatValue(diff.after);
160
- return [colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize)];
166
+ return [suffix(colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize))];
161
167
  }
162
168
  case 'remove': {
163
169
  if (diff.children && diff.children.length > 0) {
@@ -168,7 +174,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
168
174
  ];
169
175
  }
170
176
  return [
171
- colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize),
177
+ suffix(colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize)),
172
178
  ];
173
179
  }
174
180
  case 'change': {
@@ -182,7 +188,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
182
188
  const beforeStr = formatValue(diff.before);
183
189
  const afterStr = formatValue(diff.after);
184
190
  return [
185
- colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize),
191
+ suffix(colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize)),
186
192
  ];
187
193
  }
188
194
  }
@@ -192,49 +198,68 @@ const ACTION_DESC = {
192
198
  update: 'PLAN_WILL_UPDATE',
193
199
  delete: 'PLAN_WILL_DESTROY',
194
200
  noop: 'PLAN_NO_CHANGES',
195
- refresh: 'PLAN_WILL_REFRESH',
196
201
  };
197
202
  const ACTION_SYMBOL = {
198
203
  create: '+',
199
204
  update: '~',
200
205
  delete: '-',
201
- refresh: '↻',
202
206
  };
203
207
  const ACTION_COLOR = {
204
208
  create: 'GREEN',
205
209
  update: 'YELLOW',
206
210
  delete: 'RED',
207
- refresh: 'CYAN',
208
211
  };
212
+ /**
213
+ * A create plan for a resource that also has a recorded `before` is a
214
+ * recreation (the cloud copy disappeared or was tainted) — rendered as a
215
+ * single `-/+` block showing the old→new fields, never as two separate
216
+ * add/remove blocks (issue #246 resource-paradigm invariant).
217
+ */
218
+ const isRecreate = (item) => item.action === 'create' && !!item.changes?.before;
209
219
  /* istanbul ignore next */
210
220
  const formatPlanItem = (item, config = DEFAULT_CONFIG) => {
211
- const descKey = ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES';
212
- const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
213
221
  if (item.action === 'noop') {
214
- return headerLine;
222
+ // Unchanged resources are not rendered as blocks — they only surface in
223
+ // the plan summary count (issue #246 display spec).
224
+ return '';
215
225
  }
216
- const symbol = ACTION_SYMBOL[item.action] ?? ' ';
217
- const symbolColor = ACTION_COLOR[item.action] ?? 'RESET';
226
+ const recreate = isRecreate(item);
227
+ const descKey = recreate ? 'PLAN_WILL_RECREATE' : (ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES');
228
+ const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
229
+ const symbol = recreate ? '-/+' : (ACTION_SYMBOL[item.action] ?? ' ');
230
+ const symbolColor = recreate ? 'YELLOW' : (ACTION_COLOR[item.action] ?? 'RESET');
218
231
  const resourceLine = colorize(` ${symbol} ${item.logicalId}:`, symbolColor, config.colorize);
219
- // A drifted update is caused by an out-of-config cloud edit — surface that
220
- // so it doesn't read like an ordinary config change.
221
- const driftedLine = item.drifted && item.action !== 'delete'
222
- ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
223
- : [];
232
+ // Probe-level drift (role policy, logstore, ...) has no attribute-level
233
+ // diff to show — each reason becomes its own explanatory line.
234
+ const reasonLines = (item.driftReasons ?? []).map((reason) => colorize(` # ${lang_1.lang.__(reason)}`, 'CYAN', config.colorize));
224
235
  if (!item.changes) {
225
- return [headerLine, resourceLine, ...driftedLine].join('\n');
236
+ // No changes payload at all: the drift marker is the only explanation
237
+ // available (fallback — planners normally attach changes or reasons).
238
+ const driftedLine = item.drifted && reasonLines.length === 0
239
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
240
+ : [];
241
+ return [headerLine, resourceLine, ...reasonLines, ...driftedLine].join('\n');
226
242
  }
227
243
  const { diffs, unchangedCount } = (0, exports.computeAttributeDiffs)(item.changes.before, item.changes.after);
228
244
  const keyWidth = Math.max(config.keyAlignWidth, computeMaxKeyWidth(diffs, config.indentSize));
245
+ const revertKeys = new Set(item.revertKeys ?? []);
229
246
  const attrLines = diffs.length > 0
230
- ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth))
247
+ ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth, revertKeys))
231
248
  : [];
232
- const hiddenLine = unchangedCount > 0 && !config.showUnchangedAttributes
249
+ const hiddenLine = unchangedCount > 0
233
250
  ? [
234
251
  colorize(` # ${lang_1.lang.__('PLAN_UNCHANGED_ATTRS', { count: String(unchangedCount) })}`, 'DIM', config.colorize),
235
252
  ]
236
253
  : [];
237
- return [headerLine, resourceLine, ...driftedLine, ...attrLines, ...hiddenLine].join('\n');
254
+ // Invariant backstop (issue #246): a drifted item must always explain
255
+ // itself — attribute lines, reasons, or as a last resort the generic
256
+ // marker. Planners attach at least one of these for every drifted item.
257
+ const driftedFallback = item.drifted && attrLines.length === 0 && reasonLines.length === 0
258
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
259
+ : [];
260
+ return [headerLine, resourceLine, ...reasonLines, ...attrLines, ...hiddenLine, ...driftedFallback]
261
+ .filter((line) => line.length > 0)
262
+ .join('\n');
238
263
  };
239
264
  exports.formatPlanItem = formatPlanItem;
240
265
  /* istanbul ignore next */
@@ -242,39 +267,29 @@ const formatPlan = (items, config = DEFAULT_CONFIG) => {
242
267
  if (items.length === 0) {
243
268
  return lang_1.lang.__('NO_CHANGES_INFRASTRUCTURE_UP_TO_DATE');
244
269
  }
245
- const createItems = items.filter((i) => i.action === 'create');
246
- const updateItems = items.filter((i) => i.action === 'update');
247
- const deleteItems = items.filter((i) => i.action === 'delete');
248
- const refreshItems = items.filter((i) => i.action === 'refresh');
249
- const noopItems = items.filter((i) => i.action === 'noop');
250
- const actionItems = [
251
- ...createItems,
252
- ...updateItems,
253
- ...deleteItems,
254
- ...refreshItems,
255
- ...noopItems,
256
- ];
257
- const header = [
258
- `${lang_1.lang.__('PLAN_HEADER')}\n`,
259
- colorize(lang_1.lang.__('PLAN_LEGEND_CREATE'), 'GREEN', config.colorize),
260
- colorize(lang_1.lang.__('PLAN_LEGEND_UPDATE'), 'YELLOW', config.colorize),
261
- colorize(lang_1.lang.__('PLAN_LEGEND_DESTROY'), 'RED', config.colorize),
262
- '',
263
- ];
264
- const itemLines = actionItems.flatMap((item) => [(0, exports.formatPlanItem)(item, config), '']);
265
- const driftedCount = items.filter((i) => i.drifted && i.action !== 'delete').length;
266
- const driftedSummary = driftedCount > 0
267
- ? [
268
- colorize(lang_1.lang.__('PLAN_DRIFTED_SUMMARY', { driftedCount: String(driftedCount) }), 'CYAN', config.colorize),
269
- '',
270
- ]
271
- : [];
270
+ // Resource paradigm (issue #246): render blocks in the planner's domain
271
+ // order, one block per resource, never regrouped by action. Unchanged
272
+ // resources only surface in the summary count.
273
+ const unchangedCount = items.filter((i) => i.action === 'noop').length;
274
+ const itemLines = items
275
+ .filter((i) => i.action !== 'noop')
276
+ .flatMap((item) => {
277
+ const block = (0, exports.formatPlanItem)(item, config);
278
+ return block ? [block, ''] : [];
279
+ });
280
+ const recreateCount = items.filter(isRecreate).length;
281
+ const addCount = items.filter((i) => i.action === 'create' && !isRecreate(i)).length;
282
+ const modifyCount = items.filter((i) => i.action === 'update').length;
283
+ const removeCount = items.filter((i) => i.action === 'delete').length;
284
+ const header = [`${lang_1.lang.__('PLAN_HEADER')}\n`];
272
285
  const summary = lang_1.lang.__('PLAN_SUMMARY', {
273
- createCount: String(createItems.length),
274
- updateCount: String(updateItems.length),
275
- deleteCount: String(deleteItems.length),
286
+ addCount: String(addCount),
287
+ modifyCount: String(modifyCount),
288
+ removeCount: String(removeCount),
289
+ recreateCount: String(recreateCount),
290
+ unchangedCount: String(unchangedCount),
276
291
  });
277
- return [...header, ...itemLines, ...driftedSummary, summary].join('\n');
292
+ return [...header, ...itemLines, summary].join('\n');
278
293
  };
279
294
  exports.formatPlan = formatPlan;
280
295
  /* istanbul ignore next */
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.planRefreshedResource = exports.decideRefreshedExistsAction = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
5
  const planCompare_1 = require("./planCompare");
6
+ const logger_1 = require("./logger");
7
+ const lang_1 = require("../lang");
6
8
  const decideRefreshedExistsAction = async (args) => {
7
9
  const remote = await args.read();
8
10
  if (!remote) {
@@ -14,11 +16,16 @@ const decideRefreshedExistsAction = async (args) => {
14
16
  }
15
17
  const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(attributes, args.desiredDefinition);
16
18
  if (args.definitionChanged || remoteDiffers) {
17
- return { action: 'update', drifted: true };
19
+ return { action: 'update', drifted: true, liveAttributes: attributes };
18
20
  }
19
21
  const extra = await args.extraUpdate?.();
20
22
  if (extra?.update) {
21
- return { action: 'update', drifted: extra.drifted };
23
+ return {
24
+ action: 'update',
25
+ drifted: extra.drifted,
26
+ liveAttributes: attributes,
27
+ ...(extra.reason ? { driftReasons: [extra.reason] } : {}),
28
+ };
22
29
  }
23
30
  return { action: 'noop' };
24
31
  };
@@ -28,8 +35,12 @@ exports.decideRefreshedExistsAction = decideRefreshedExistsAction;
28
35
  * no-state-probe / exists-refresh decision chain of the simple planners
29
36
  * (buckets, tables, databases). Function and gateway planners keep their
30
37
  * custom flows (role probes, trigger reconciliation, config normalization).
31
- * Read failures on the exists path degrade to a create plan — the pre-existing
32
- * planner behavior, preserved verbatim.
38
+ *
39
+ * Issue #246 display contract: a drift/intent update's `changes.before` is
40
+ * always cloud reality — live attributes merged over the stored definition
41
+ * (stored fills the keys the cloud mapper never emits) — so every update
42
+ * renders a complete live→desired field diff, and `revertKeys` marks the
43
+ * fields whose difference is purely an out-of-config cloud edit.
33
44
  */
34
45
  const planRefreshedResource = async (args) => {
35
46
  const { logicalId, resourceType, currentState, desiredDefinition } = args;
@@ -81,24 +92,36 @@ const planRefreshedResource = async (args) => {
81
92
  logicalId,
82
93
  action: 'create',
83
94
  resourceType,
84
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
95
+ changes: { before: normalizedCurrent, after: desiredDefinition },
85
96
  drifted: true,
86
97
  };
87
98
  }
99
+ const normalizedLive = normalize(decision.liveAttributes);
100
+ const revertKeys = (0, planCompare_1.computeRevertKeys)(normalizedCurrent, normalizedLive, normalizedDesired);
88
101
  return {
89
102
  logicalId,
90
103
  action: 'update',
91
104
  resourceType,
92
- changes: { before: normalizedCurrent, after: normalizedDesired },
105
+ changes: {
106
+ before: normalize((0, planCompare_1.mergeLiveBefore)(currentDefinition, normalizedLive)),
107
+ after: normalizedDesired,
108
+ },
93
109
  ...(decision.drifted ? { drifted: true } : {}),
110
+ ...(revertKeys.length ? { revertKeys } : {}),
111
+ ...(decision.driftReasons?.length ? { driftReasons: decision.driftReasons } : {}),
94
112
  };
95
113
  }
96
- catch {
114
+ catch (error) {
115
+ logger_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
116
+ logicalId,
117
+ error: error instanceof Error ? error.message : String(error),
118
+ }));
97
119
  return {
98
120
  logicalId,
99
121
  action: 'create',
100
122
  resourceType,
101
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
123
+ changes: { before: normalizedCurrent, after: normalizedDesired },
124
+ drifted: true,
102
125
  };
103
126
  }
104
127
  };
@@ -109,17 +109,29 @@ exports.en = {
109
109
  PLAN_WILL_CREATE: 'will be created',
110
110
  PLAN_WILL_UPDATE: 'will be updated in-place',
111
111
  PLAN_WILL_DESTROY: 'will be destroyed',
112
- PLAN_WILL_REFRESH: 'will be refreshed',
112
+ PLAN_WILL_RECREATE: 'will be recreated',
113
113
  PLAN_NO_CHANGES: 'no changes',
114
114
  PLAN_HEADER: 'ServerlessInsight will perform the following actions:',
115
- PLAN_LEGEND_CREATE: ' + create',
116
- PLAN_LEGEND_UPDATE: ' ~ update in-place',
117
- PLAN_LEGEND_DESTROY: ' - destroy',
118
- PLAN_SUMMARY: 'Plan: {{createCount}} to add, {{updateCount}} to change, {{deleteCount}} to destroy.',
115
+ PLAN_SUMMARY: 'Plan: {{addCount}} add, {{modifyCount}} modify, {{removeCount}} remove, {{recreateCount}} recreate, {{unchangedCount}} unchanged.',
119
116
  PLAN_UNCHANGED_ATTRS: '({{count}} unchanged attributes hidden)',
120
117
  PLAN_COMPUTED_VALUE: '(known after deploy)',
118
+ PLAN_REVERT_ANNOTATION: '(changed in the cloud, will be restored to config)',
121
119
  PLAN_DRIFTED_MARKER: '(drifted — cloud changed outside of this config, will be reconciled)',
122
- PLAN_DRIFTED_SUMMARY: 'Drift: {{driftedCount}} resource(s) changed in the cloud outside of this config.',
120
+ PLAN_LIVE_READ_FAILED: 'Failed to read live state for {{logicalId}}; planning a create instead: {{error}}',
121
+ PLAN_DRIFT_ROLE_MISSING: 'IAM role missing in the cloud',
122
+ PLAN_DRIFT_ROLE_POLICY: 'IAM role policy changed in the cloud',
123
+ PLAN_DRIFT_LOGSTORE: 'function log resources changed in the cloud',
124
+ PLAN_DRIFT_SG_RULES: 'security group rules changed in the cloud',
125
+ PLAN_DRIFT_NAS_MOUNT: 'NAS mount target deleted in the cloud',
126
+ PLAN_DRIFT_TLS_TOPIC: 'log topic configuration changed in the cloud',
127
+ PLAN_DRIFT_CLS_TOPIC: 'log topic configuration changed in the cloud',
128
+ PLAN_DRIFT_TRIGGERS: 'API triggers changed in the cloud',
129
+ RESOURCE_EXISTS_NOT_OWNED: '{{resourceType}} {{resourceName}} already exists in provider but is not owned by this stack (missing {{tagKey}} tag). Refusing to create — resolve manually.',
130
+ RESOURCE_EXISTS_NOT_OWNED_ADOPT: '{{resourceType}} {{resourceName}} already exists in provider but is not owned by this stack (missing {{tagKey}} tag). Refusing to adopt — resolve manually.',
131
+ TABLESTORE_EXISTS_UNVERIFIABLE: 'Table {{tableName}} already exists in provider but ownership cannot be verified (Tablestore does not support table-level tags). Refusing to adopt — resolve manually.',
132
+ TABLESTORE_EXISTS_UNVERIFIABLE_PROBE: 'Table {{tableName}} already exists in provider but ownership cannot be verified (no table-level tags). Refusing to adopt — resolve manually.',
133
+ TAINTED_RECOVERY_SKIP_CREATE: '{{resourceType}} {{resourceName}} already exists in provider (tainted recovery), skipping create and refreshing state',
134
+ OWNERSHIP_VERIFYING: '{{resourceType}} {{resourceName}} already exists in provider, verifying ownership tag before adopting',
123
135
  // TDSQL-C database messages
124
136
  TDSQL_CLUSTER_CREATION_INITIATED: 'TDSQL-C cluster creation initiated',
125
137
  TDSQL_CLUSTER_CREATION_FAILED: 'Failed to create TDSQL-C cluster',
@@ -426,6 +438,8 @@ exports.en = {
426
438
  // Pre-deploy semantic validation (issue #222)
427
439
  PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: 'Backend type BUCKET_STORE requires both "bucket" and "key" fields',
428
440
  SEMANTIC_DUPLICATE_TRIGGER: 'Duplicate trigger in event "{{eventKey}}": {{method}} {{path}} is defined more than once',
441
+ SEMANTIC_CONTAINER_CODE_CONFLICT: 'Function "{{fnKey}}" cannot define both "container" and "code" — they are mutually exclusive sources',
442
+ SEMANTIC_FUNCTION_SOURCE_REQUIRED: 'Function "{{fnKey}}" must define either "code" or "container"',
429
443
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: 'Generated API Gateway apiName "{{apiName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
430
444
  SEMANTIC_DUPLICATE_ROUTE_NAME: 'Generated API Gateway route name "{{routeName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
431
445
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: 'Trigger backend "{{reference}}" in event "{{eventKey}}" does not match any function definition in the configuration',
@@ -109,17 +109,29 @@ exports.zhCN = {
109
109
  PLAN_WILL_CREATE: '将被创建',
110
110
  PLAN_WILL_UPDATE: '将就地更新',
111
111
  PLAN_WILL_DESTROY: '将被销毁',
112
- PLAN_WILL_REFRESH: '将被刷新',
112
+ PLAN_WILL_RECREATE: '将被重建',
113
113
  PLAN_NO_CHANGES: '无变更',
114
114
  PLAN_HEADER: 'ServerlessInsight 将执行以下操作:',
115
- PLAN_LEGEND_CREATE: ' + 创建',
116
- PLAN_LEGEND_UPDATE: ' ~ 就地更新',
117
- PLAN_LEGEND_DESTROY: ' - 销毁',
118
- PLAN_SUMMARY: '计划: 新增 {{createCount}} 个,变更 {{updateCount}} 个,销毁 {{deleteCount}} 个。',
115
+ PLAN_SUMMARY: '计划: 新增 {{addCount}},变更 {{modifyCount}},移除 {{removeCount}},重建 {{recreateCount}},无变更 {{unchangedCount}}。',
119
116
  PLAN_UNCHANGED_ATTRS: '({{count}} 个未变更属性已隐藏)',
120
117
  PLAN_COMPUTED_VALUE: '(部署后可知)',
118
+ PLAN_REVERT_ANNOTATION: '(云端已改,将按配置恢复)',
121
119
  PLAN_DRIFTED_MARKER: '(云端已漂移——与本配置不一致,将按配置纠正)',
122
- PLAN_DRIFTED_SUMMARY: '漂移: {{driftedCount}} 个资源在云端被本配置之外的变更修改。',
120
+ PLAN_LIVE_READ_FAILED: '读取 {{logicalId}} 云端状态失败,降级为创建计划: {{error}}',
121
+ PLAN_DRIFT_ROLE_MISSING: '云端 IAM 角色缺失',
122
+ PLAN_DRIFT_ROLE_POLICY: '云端 IAM 角色策略被修改',
123
+ PLAN_DRIFT_LOGSTORE: '云端函数日志资源被修改',
124
+ PLAN_DRIFT_SG_RULES: '云端安全组规则被修改',
125
+ PLAN_DRIFT_NAS_MOUNT: '云端 NAS 挂载点被删除',
126
+ PLAN_DRIFT_TLS_TOPIC: '云端日志主题配置被修改',
127
+ PLAN_DRIFT_CLS_TOPIC: '云端日志主题配置被修改',
128
+ PLAN_DRIFT_TRIGGERS: '云端 API 触发器被修改',
129
+ RESOURCE_EXISTS_NOT_OWNED: '{{resourceType}} {{resourceName}} 已存在于云端但归属本 stack(缺少 {{tagKey}} 标签),拒绝创建——请手动处理。',
130
+ RESOURCE_EXISTS_NOT_OWNED_ADOPT: '{{resourceType}} {{resourceName}} 已存在于云端但归属本 stack(缺少 {{tagKey}} 标签),拒绝收养——请手动处理。',
131
+ TABLESTORE_EXISTS_UNVERIFIABLE: '表 {{tableName}} 已存在于云端但无法校验归属(Tablestore 不支持表级标签),拒绝收养——请手动处理。',
132
+ TABLESTORE_EXISTS_UNVERIFIABLE_PROBE: '表 {{tableName}} 已存在于云端但无法校验归属(无表级标签),拒绝收养——请手动处理。',
133
+ TAINTED_RECOVERY_SKIP_CREATE: '{{resourceType}} {{resourceName}} 已存在(tainted 恢复),跳过创建并刷新状态',
134
+ OWNERSHIP_VERIFYING: '{{resourceType}} {{resourceName}} 已存在,正在校验归属标签后收养',
123
135
  // TDSQL-C 数据库消息
124
136
  TDSQL_CLUSTER_CREATION_INITIATED: 'TDSQL-C 集群创建已启动',
125
137
  TDSQL_CLUSTER_CREATION_FAILED: '创建 TDSQL-C 集群失败',
@@ -423,6 +435,8 @@ exports.zhCN = {
423
435
  // Pre-deploy semantic validation (issue #222)
424
436
  PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: '后端类型 BUCKET_STORE 需要同时提供 "bucket" 和 "key" 字段',
425
437
  SEMANTIC_DUPLICATE_TRIGGER: '事件 "{{eventKey}}" 中存在重复触发器: {{method}} {{path}} 定义了不止一次',
438
+ SEMANTIC_CONTAINER_CODE_CONFLICT: '函数 "{{fnKey}}" 不能同时定义 "container" 与 "code"——两者互斥',
439
+ SEMANTIC_FUNCTION_SOURCE_REQUIRED: '函数 "{{fnKey}}" 必须定义 "code" 或 "container" 之一',
426
440
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: '生成的 API Gateway apiName "{{apiName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
427
441
  SEMANTIC_DUPLICATE_ROUTE_NAME: '生成的 API Gateway route name "{{routeName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
428
442
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: '事件 "{{eventKey}}" 的触发器后端 "{{reference}}" 未匹配到配置中的任何函数定义',
@@ -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) {