@geek-fun/serverlessinsight 0.9.4 → 0.9.6

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 (79) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +44 -0
  3. package/README.md +26 -6
  4. package/README.zh-CN.md +26 -6
  5. package/codecov +0 -0
  6. package/codecov.SHA256SUM +1 -1
  7. package/codecov.SHA256SUM.sig +13 -13
  8. package/dist/package.json +1 -1
  9. package/dist/src/commands/deploy.js +7 -2
  10. package/dist/src/commands/destroy.js +6 -3
  11. package/dist/src/commands/forceUnlock.js +16 -21
  12. package/dist/src/commands/index.js +14 -4
  13. package/dist/src/commands/migrate.js +105 -132
  14. package/dist/src/commands/plan.js +2 -2
  15. package/dist/src/commands/show.js +17 -6
  16. package/dist/src/common/aggregateState.js +185 -0
  17. package/dist/src/common/aggregateStore.js +247 -0
  18. package/dist/src/common/apiClient.js +35 -12
  19. package/dist/src/common/constants.js +2 -1
  20. package/dist/src/common/context.js +22 -15
  21. package/dist/src/common/effectiveConfig.js +48 -0
  22. package/dist/src/common/iacHelper.js +2 -2
  23. package/dist/src/common/index.js +5 -0
  24. package/dist/src/common/jsonOutput.js +2 -13
  25. package/dist/src/common/migrationMarker.js +0 -7
  26. package/dist/src/common/nameBuilder.js +2 -3
  27. package/dist/src/common/regionalMigration.js +261 -0
  28. package/dist/src/common/saasProtocol.js +41 -0
  29. package/dist/src/common/stateBackend/cosStateBackend.js +88 -8
  30. package/dist/src/common/stateBackend/index.js +42 -18
  31. package/dist/src/common/stateBackend/localStateBackend.js +61 -26
  32. package/dist/src/common/stateBackend/ossStateBackend.js +62 -9
  33. package/dist/src/common/stateBackend/remoteStateBackend.js +94 -94
  34. package/dist/src/common/stateBackend/saasStateBackend.js +327 -92
  35. package/dist/src/common/stateBackend/types.js +9 -0
  36. package/dist/src/common/stateManager.js +38 -11
  37. package/dist/src/common/stateScope.js +34 -0
  38. package/dist/src/common/stateStorageIO.js +31 -0
  39. package/dist/src/lang/en.js +43 -2
  40. package/dist/src/lang/zh-CN.js +43 -2
  41. package/dist/src/parser/index.js +33 -8
  42. package/dist/src/parser/templateValues.js +31 -0
  43. package/dist/src/stack/aliyunStack/deployer.js +5 -5
  44. package/dist/src/stack/aliyunStack/destroyer.js +5 -5
  45. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  46. package/dist/src/stack/aliyunStack/fc3Resource.js +2 -2
  47. package/dist/src/stack/aliyunStack/planner.js +1 -1
  48. package/dist/src/stack/aliyunStack/sharedLogProject.js +2 -2
  49. package/dist/src/stack/ownershipTag.js +34 -26
  50. package/dist/src/stack/scfStack/deployer.js +5 -5
  51. package/dist/src/stack/scfStack/destroyer.js +5 -6
  52. package/dist/src/stack/scfStack/planner.js +1 -1
  53. package/dist/src/stack/scfStack/scfResource.js +1 -1
  54. package/dist/src/stack/scfStack/sharedLogset.js +5 -2
  55. package/dist/src/stack/volcengineStack/deployer.js +3 -3
  56. package/dist/src/stack/volcengineStack/destroyer.js +2 -3
  57. package/dist/src/stack/volcengineStack/planner.js +1 -1
  58. package/dist/src/stack/volcengineStack/sharedLogProject.js +4 -4
  59. package/dist/src/stack/volcengineStack/vefaasResource.js +1 -1
  60. package/dist/src/types/domains/state.js +28 -2
  61. package/dist/src/validator/index.js +3 -1
  62. package/dist/src/validator/rootSchema.js +8 -0
  63. package/dist/tsconfig.tsbuildinfo +1 -1
  64. package/package.json +1 -1
  65. package/release-notes.md +8 -36
  66. package/samples/README_TENCENT_COS.md +65 -23
  67. package/samples/README_TENCENT_SCF.md +44 -26
  68. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +0 -14
  69. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +0 -32
  70. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +0 -90
  71. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +0 -118
  72. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +0 -215
  73. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +0 -14
  74. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +0 -132
  75. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +0 -55
  76. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +0 -1
  77. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +0 -93
  78. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +0 -163
  79. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +0 -148
@@ -32,13 +32,9 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
36
  exports.migrate = void 0;
40
37
  const readline = __importStar(require("node:readline"));
41
- const node_crypto_1 = __importDefault(require("node:crypto"));
42
38
  const common_1 = require("../common");
43
39
  const stateBackend_1 = require("../common/stateBackend");
44
40
  const credentialStore_1 = require("../common/credentialStore");
@@ -102,7 +98,7 @@ const migrate = async (options) => {
102
98
  // Purely local to the source backend, so it needs NO Console credentials.
103
99
  if (options.rollback) {
104
100
  await sourceBackend.withLock('migrate-rollback', async () => {
105
- const state = await sourceBackend.loadState(iac.provider.name, iac.app, iac.service, options.stage ?? 'default');
101
+ const state = await sourceBackend.loadState();
106
102
  if (!(0, migrationMarker_1.isMigratedToSaas)(state)) {
107
103
  common_1.logger.info(lang_1.lang.__('MIGRATE_ROLLBACK_NO_MARKER'));
108
104
  return;
@@ -118,165 +114,142 @@ const migrate = async (options) => {
118
114
  }
119
115
  const creds = (0, credentialStore_1.loadCredentials)();
120
116
  const apiKey = options.siApiKey ?? creds?.apiKey;
121
- if (!apiKey) {
117
+ if (!apiKey)
122
118
  throw new Error(lang_1.lang.__('MIGRATE_NEED_CREDENTIALS'));
123
- }
124
119
  const baseUrl = (0, credentialStore_1.getConsoleUrl)();
125
120
  const identity = await (0, apiClient_1.validateApiKey)(apiKey, baseUrl);
126
121
  const orgId = identity.orgId;
127
- common_1.logger.info(lang_1.lang.__('MIGRATE_PREFLIGHT_OK', { orgName: identity.orgName, orgId }));
122
+ if (iac.org && identity.orgSlug && iac.org !== identity.orgSlug) {
123
+ throw new Error(lang_1.lang.__('SAAS_ORG_MISMATCH', { declared: iac.org, actual: identity.orgSlug }));
124
+ }
128
125
  const client = (0, apiClient_1.createApiClient)({ apiKey, baseUrl, orgId });
126
+ if (!(0, common_1.supportsRegionalSaas)(await client.get('/api/v1/capabilities'))) {
127
+ throw new Error(lang_1.lang.__('SAAS_REGIONAL_SCOPE_UNSUPPORTED', { consoleUrl: baseUrl }));
128
+ }
129
+ const scope = (0, common_1.normalizeScope)({
130
+ provider: context.provider,
131
+ app: iac.app,
132
+ service: iac.service,
133
+ stage: context.stage,
134
+ region: context.region,
135
+ });
136
+ common_1.logger.info(lang_1.lang.__('MIGRATE_PREFLIGHT_OK', { orgName: identity.orgName, orgId }));
129
137
  await sourceBackend.withLock('migrate', async () => {
130
- // ③ pull + normalize (loadState applies registered state migrations)
131
- const hydrateStage = options.stage ?? Object.keys(iac.stages ?? {})[0] ?? 'default';
132
- const state = await sourceBackend.loadState(iac.provider.name, iac.app, iac.service, hydrateStage);
138
+ await sourceBackend.upgradeLegacyState?.({
139
+ bindUnknownRegion: options.bindUnknownRegion,
140
+ dryRun: options.dryRun,
141
+ });
142
+ const state = await sourceBackend.loadState();
133
143
  if ((0, migrationMarker_1.isMigratedToSaas)(state)) {
134
144
  common_1.logger.warn(lang_1.lang.__('MIGRATE_ALREADY_MARKED'));
145
+ return;
135
146
  }
136
- if (state.provider && state.provider !== iac.provider.name) {
137
- throw new Error(lang_1.lang.__('MIGRATE_PROVIDER_MISMATCH', {
138
- stateProvider: state.provider,
139
- ymlProvider: iac.provider.name,
140
- }));
147
+ if (!state.scope || state.version !== '4.0') {
148
+ throw new Error(lang_1.lang.__('MIGRATE_SOURCE_FORMAT_INVALID'));
141
149
  }
142
- // ④ mapping plan — only stages holding deployed resources migrate
143
- const allStageKeys = Object.keys(state.stages ?? {});
144
- if (options.stage && !allStageKeys.includes(options.stage)) {
145
- throw new Error(lang_1.lang.__('MIGRATE_STAGE_NOT_FOUND', { stage: options.stage }));
150
+ (0, common_1.validateScopedDocument)((0, common_1.toPersistedState)(state), scope);
151
+ if (!options.noMarker && !sourceBackend.patchPersisted)
152
+ throw new Error(lang_1.lang.__('MIGRATE_NO_BACKEND_SOURCE'));
153
+ if (Object.entries(state.stages).some(([stage, entry]) => stage !== scope.stage &&
154
+ (Object.keys(entry.resources ?? {}).length > 0 ||
155
+ Object.keys(entry.shared ?? {}).length > 0))) {
156
+ throw new Error(lang_1.lang.__('MIGRATE_SOURCE_MULTIPLE_SCOPES'));
146
157
  }
147
- const stageKeys = (options.stage ? [options.stage] : allStageKeys).filter((stageKey) => Object.keys(state.stages?.[stageKey]?.resources ?? {}).length > 0);
148
- if (stageKeys.length === 0) {
158
+ const selected = state.stages[scope.stage];
159
+ if (!Object.keys(selected?.resources ?? {}).length &&
160
+ !Object.keys(selected?.shared ?? {}).length) {
149
161
  throw new Error(lang_1.lang.__('MIGRATE_NOTHING_TO_MIGRATE'));
150
162
  }
151
- // ④ mapping plan — resolve which Console targets already exist (mapped by
152
- // name) and which would be auto-created, so the dry-run/confirm screen
153
- // keeps the user in control of the destination (pre-create in Console to
154
- // adopt existing apps/services/membership settings).
155
- const targets = await client.get(`/api/v1/state/migrate/targets?app_name=${encodeURIComponent(iac.app)}&service_name=${encodeURIComponent(iac.service)}&stages=${encodeURIComponent(stageKeys.join(','))}`);
156
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGETS_HEADER', { orgName: identity.orgName }));
157
- if (targets.app.exists) {
158
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_APP_EXISTS', {
159
- app: targets.app.name,
160
- appId: targets.app.id ?? '',
161
- }));
162
- }
163
- else {
164
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_APP_CREATE', { app: targets.app.name }));
163
+ const resourceCount = Object.keys(selected.resources).length;
164
+ const targets = await client.get(`/api/v1/state/migrate/targets?app_name=${encodeURIComponent(scope.app)}&service_name=${encodeURIComponent(scope.service)}&stages=${encodeURIComponent(scope.stage)}&region=${encodeURIComponent(scope.region)}&provider=${encodeURIComponent(scope.provider)}`);
165
+ if (targets.service.exists &&
166
+ (targets.service.regionalScopeEnabled !== true ||
167
+ targets.service.scopeProtocol !== common_1.SCOPE_PROTOCOL_VERSION)) {
168
+ throw new Error(lang_1.lang.__('MIGRATE_TARGET_REGIONAL_REQUIRED'));
165
169
  }
166
- if (targets.service.exists) {
167
- if (targets.service.provider && targets.service.provider !== iac.provider.name) {
168
- throw new Error(lang_1.lang.__('MIGRATE_PROVIDER_MISMATCH_TARGET', {
169
- service: iac.service,
170
- existingProvider: targets.service.provider,
171
- ymlProvider: iac.provider.name,
172
- }));
173
- }
174
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_SERVICE_EXISTS', {
175
- service: targets.service.name,
170
+ const report = targets.stages.find((entry) => entry.name === scope.stage);
171
+ if (report?.hasState && !report.contentHash)
172
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
173
+ common_1.logger.info(lang_1.lang.__('MIGRATE_TARGETS_HEADER', { orgName: identity.orgName }));
174
+ common_1.logger.info(targets.app.exists
175
+ ? lang_1.lang.__('MIGRATE_TARGET_APP_EXISTS', { app: scope.app, appId: targets.app.id ?? '' })
176
+ : lang_1.lang.__('MIGRATE_TARGET_APP_CREATE', { app: scope.app }));
177
+ common_1.logger.info(targets.service.exists
178
+ ? lang_1.lang.__('MIGRATE_TARGET_SERVICE_EXISTS', {
179
+ service: scope.service,
176
180
  serviceId: targets.service.id ?? '',
177
- provider: targets.service.provider ?? '',
178
- }));
179
- }
180
- else {
181
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_SERVICE_CREATE', {
182
- service: targets.service.name,
183
- provider: iac.provider.name,
181
+ provider: scope.provider,
182
+ })
183
+ : lang_1.lang.__('MIGRATE_TARGET_SERVICE_CREATE', {
184
+ service: scope.service,
185
+ provider: scope.provider,
184
186
  }));
185
- }
186
- for (const stageKey of stageKeys) {
187
- const count = String(Object.keys(state.stages?.[stageKey]?.resources ?? {}).length);
188
- const report = targets.stages.find((s) => s.name === stageKey);
189
- if (report?.hasState) {
190
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_STAGE_EXISTS', {
191
- stage: stageKey,
192
- count,
193
- version: String(report.latestVersion ?? 1),
194
- }));
195
- }
196
- else if (report?.registered) {
197
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_STAGE_EMPTY', { stage: stageKey, count }));
198
- }
199
- else {
200
- common_1.logger.info(lang_1.lang.__('MIGRATE_TARGET_STAGE_NEW', { stage: stageKey, count }));
201
- }
202
- }
187
+ common_1.logger.info(lang_1.lang.__(report?.hasState
188
+ ? 'MIGRATE_TARGET_STAGE_EXISTS'
189
+ : report?.registered
190
+ ? 'MIGRATE_TARGET_STAGE_EMPTY'
191
+ : 'MIGRATE_TARGET_STAGE_NEW', {
192
+ stage: `${scope.stage} / ${scope.region}`,
193
+ count: String(resourceCount),
194
+ version: String(report?.latestVersion ?? 1),
195
+ }));
203
196
  common_1.logger.info(lang_1.lang.__('MIGRATE_TARGETS_HINT'));
204
197
  if (options.dryRun) {
205
198
  common_1.logger.info(lang_1.lang.__('MIGRATE_DRY_RUN_NOTICE'));
206
199
  return;
207
200
  }
208
- // ⑤ confirm — the writer-upgrade question is the §4.5 runbook gate
209
201
  if (!options.autoApprove) {
210
- if (!(await askConfirmation(lang_1.lang.__('MIGRATE_WRITER_CONFIRMATION')))) {
202
+ if (!(await askConfirmation(lang_1.lang.__('MIGRATE_WRITER_CONFIRMATION'))))
211
203
  return;
212
- }
213
- if (!(await askConfirmation(lang_1.lang.__('MIGRATE_CONFIRMATION')))) {
204
+ if (!(await askConfirmation(lang_1.lang.__('MIGRATE_CONFIRMATION'))))
214
205
  return;
215
- }
216
206
  }
217
- // ⑥ upload — same full-persisted-state contract as the SaaS backend save.
218
- // The imported version carries the owning org id immediately (D-6 identity
219
- // anchor), so the first post-cutover loadState can verify it without
220
- // waiting for a fresh deploy save.
221
- const persisted = { ...(0, common_1.toPersistedState)(state), orgId };
222
- const contentHash = node_crypto_1.default.createHash('sha256').update(JSON.stringify(persisted)).digest('hex');
223
- const results = [];
224
- for (const stageKey of stageKeys) {
225
- common_1.logger.info(lang_1.lang.__('MIGRATE_UPLOADING', { stage: stageKey }));
226
- const resourceCount = Object.keys(state.stages?.[stageKey]?.resources ?? {}).length;
227
- let uploadResult;
228
- try {
229
- uploadResult = await client.post('/api/v1/state/migrate', {
230
- appName: iac.app,
231
- serviceName: iac.service,
232
- provider: iac.provider.name,
233
- stage: stageKey,
234
- stateJson: persisted,
235
- contentHash,
236
- resourceCount,
237
- origin: backendType === types_1.StateBackendType.LOCAL ? 'local' : 'bucket',
238
- conflict: options.force ? 'overwrite' : 'reject',
239
- });
240
- }
241
- catch (error) {
242
- if (error instanceof apiClient_1.ApiError && error.status === 409) {
243
- throw new Error(lang_1.lang.__('MIGRATE_CONFLICT'), { cause: error });
244
- }
245
- throw error;
246
- }
247
- // ⑦ read-back verification — the stored version must be ours. The server
248
- // echoes the hash it stored, so no JSON re-serialization is involved
249
- // (Postgres jsonb would reorder keys and break a naive string compare).
250
- const remote = await client.get(`/api/v1/apps/${uploadResult.appId}/services/${uploadResult.serviceId}/state/current?stage=${encodeURIComponent(stageKey)}`);
251
- const verified = remote.contentHash === contentHash &&
252
- remote.versionNumber === uploadResult.versionNumber &&
253
- (uploadResult.deduped || remote.resourceCount === resourceCount);
254
- if (!verified) {
255
- throw new Error(lang_1.lang.__('MIGRATE_VERIFY_FAILED', { stage: stageKey }));
256
- }
257
- results.push({ stage: stageKey, ...uploadResult });
258
- common_1.logger.info(lang_1.lang.__('MIGRATE_UPLOADED', {
259
- stage: stageKey,
260
- version: String(uploadResult.versionNumber),
261
- deduped: uploadResult.deduped ? lang_1.lang.__('MIGRATE_UPLOADED_DEDUPLICATED') : '',
262
- appId: uploadResult.appId,
263
- serviceId: uploadResult.serviceId,
264
- }));
207
+ const persisted = { ...(0, common_1.toPersistedState)(state), stages: { [scope.stage]: selected }, orgId };
208
+ const contentHash = (0, common_1.hashSaasState)(persisted);
209
+ common_1.logger.info(lang_1.lang.__('MIGRATE_UPLOADING', { stage: scope.stage }));
210
+ const uploaded = await client.post('/api/v1/state/migrate', {
211
+ appName: scope.app,
212
+ serviceName: scope.service,
213
+ provider: scope.provider,
214
+ stage: scope.stage,
215
+ region: scope.region,
216
+ scopeProtocol: common_1.SCOPE_PROTOCOL_VERSION,
217
+ baseContentHash: report?.contentHash ?? '',
218
+ stateJson: persisted,
219
+ contentHash,
220
+ resourceCount,
221
+ origin: backendType === types_1.StateBackendType.LOCAL ? 'local' : 'bucket',
222
+ conflict: options.force ? 'overwrite' : 'reject',
223
+ });
224
+ const remote = await client.get(`/api/v1/apps/${uploaded.appId}/services/${uploaded.serviceId}/state/current?stage=${encodeURIComponent(scope.stage)}&region=${encodeURIComponent(scope.region)}&provider=${encodeURIComponent(scope.provider)}`);
225
+ if (!(0, common_1.isRegionalSaasSnapshot)(remote, scope) ||
226
+ remote.serviceId !== uploaded.serviceId ||
227
+ remote.id !== uploaded.stateId ||
228
+ remote.stageId !== uploaded.stageId ||
229
+ uploaded.scopeProtocol !== common_1.SCOPE_PROTOCOL_VERSION ||
230
+ uploaded.provider !== scope.provider ||
231
+ uploaded.region !== scope.region ||
232
+ remote.contentHash !== contentHash ||
233
+ remote.versionNumber !== uploaded.versionNumber ||
234
+ (!uploaded.deduped && remote.resourceCount !== resourceCount)) {
235
+ throw new Error(lang_1.lang.__('MIGRATE_VERIFY_FAILED', { stage: scope.stage }));
265
236
  }
266
- // ⑧⑨ backfill console UUIDs + write the migration marker as one new
267
- // persisted version. Only reached when every stage verified.
268
- const first = results[0];
237
+ (0, common_1.validateScopedDocument)(remote.stateJson, scope);
238
+ common_1.logger.info(lang_1.lang.__('MIGRATE_UPLOADED', {
239
+ stage: scope.stage,
240
+ version: String(uploaded.versionNumber),
241
+ deduped: uploaded.deduped ? lang_1.lang.__('MIGRATE_UPLOADED_DEDUPLICATED') : '',
242
+ appId: uploaded.appId,
243
+ serviceId: uploaded.serviceId,
244
+ }));
269
245
  if (options.noMarker) {
270
246
  common_1.logger.warn(lang_1.lang.__('MIGRATE_MARKER_SKIPPED'));
271
247
  }
272
248
  else {
273
- if (!sourceBackend.patchPersisted) {
274
- throw new Error(lang_1.lang.__('MIGRATE_NO_BACKEND_SOURCE'));
275
- }
276
249
  await sourceBackend.patchPersisted({
277
250
  orgId,
278
- appId: first.appId,
279
- serviceId: first.serviceId,
251
+ appId: uploaded.appId,
252
+ serviceId: uploaded.serviceId,
280
253
  managedBy: 'saas',
281
254
  });
282
255
  common_1.logger.info(lang_1.lang.__('MIGRATE_MARKER_WRITTEN'));
@@ -34,12 +34,11 @@ const plan = async (options) => {
34
34
  };
35
35
  const providerDisplayName = providerDisplayNames[iac.provider.name] ?? iac.provider.name;
36
36
  common_1.logger.info(lang_1.lang.__('GENERATING_PLAN_FOR_PROVIDER', { provider: providerDisplayName }));
37
- // Read-only command: a migrated state only warns here (window-period
38
- // reconciliation still needs plan against the legacy copy).
39
37
  const backend = (0, stateBackend_1.createStateBackend)(iac.backend, {
40
38
  ...context,
41
39
  declaredOrg: iac.org,
42
40
  migrationMarker: 'warn',
41
+ mode: 'read-only',
43
42
  });
44
43
  let planResult;
45
44
  if (iac.provider.name === common_1.ProviderEnum.TENCENT) {
@@ -61,6 +60,7 @@ const plan = async (options) => {
61
60
  app: iac.app,
62
61
  service: iac.service,
63
62
  stage: context.stage,
63
+ region: context.region,
64
64
  }));
65
65
  }
66
66
  else {
@@ -181,8 +181,10 @@ const formatResourceOutput = (logicalId, resource) => {
181
181
  }
182
182
  return [];
183
183
  };
184
- const loadLocalState = (provider, app, service, stage, baseDir) => {
185
- return (0, common_1.loadState)(provider, app, service, stage, baseDir);
184
+ const loadLocalState = async (provider, app, service, stage, baseDir) => {
185
+ const backend = (0, stateBackend_1.createLocalStateBackend)({ provider, app, service, stage, region: (0, common_1.getContext)().region }, { baseDir, markerAction: 'off' });
186
+ const state = await backend.loadState();
187
+ return { state, source: backend.readStateSource() };
186
188
  };
187
189
  const readLocalLock = (app, service, baseDir) => {
188
190
  const statePath = (0, common_1.getStatePath)(app, service, baseDir);
@@ -206,19 +208,22 @@ const show = async (options) => {
206
208
  let stateLocation;
207
209
  let stateLocationDisplay;
208
210
  let usingRemoteBackend = false;
211
+ let stateSource;
209
212
  const backendType = options.iac?.backend?.type;
210
213
  const shouldUseRemoteBackend = backendType === backend_1.StateBackendType.BUCKET_STORE ||
211
214
  backendType === backend_1.StateBackendType.SAAS ||
212
215
  !backendType;
213
216
  if (shouldUseRemoteBackend) {
214
217
  try {
215
- // Read-only command: a migrated state only warns here.
216
218
  const backend = (0, stateBackend_1.createStateBackend)(options.iac.backend, {
217
219
  ...context,
220
+ stage,
218
221
  declaredOrg: options.iac.org,
219
222
  migrationMarker: 'warn',
223
+ mode: 'read-only',
220
224
  });
221
- state = await backend.loadState(context.provider, context.app, context.service, stage);
225
+ state = await backend.loadState();
226
+ stateSource = backend.readStateSource();
222
227
  lockInfo = await backend.readLock();
223
228
  usingRemoteBackend = true;
224
229
  stateLocation =
@@ -233,7 +238,9 @@ const show = async (options) => {
233
238
  else {
234
239
  logger_1.logger.warn(lang_1.lang.__('SHOW_REMOTE_BACKEND_FALLBACK', { error: String(error) }));
235
240
  }
236
- state = loadLocalState(context.provider, context.app, context.service, stage, baseDir);
241
+ const local = await loadLocalState(context.provider, context.app, context.service, stage, baseDir);
242
+ state = local.state;
243
+ stateSource = local.source;
237
244
  // A local copy of a MIGRATED state is stale by definition — showing it
238
245
  // after a remote failure would mislead the user (decision D-3/D-4).
239
246
  if ((0, migrationMarker_1.isMigratedToSaas)(state)) {
@@ -246,7 +253,9 @@ const show = async (options) => {
246
253
  stateLocation === SAAS_STATE_LOCATION ? lang_1.lang.__('SHOW_BACKEND_SAAS') : stateLocation;
247
254
  }
248
255
  else {
249
- state = loadLocalState(context.provider, context.app, context.service, stage, baseDir);
256
+ const local = await loadLocalState(context.provider, context.app, context.service, stage, baseDir);
257
+ state = local.state;
258
+ stateSource = local.source;
250
259
  lockInfo = readLocalLock(context.app, context.service, baseDir);
251
260
  stateLocation = (0, common_1.getStatePath)(context.app, context.service, baseDir);
252
261
  stateLocationDisplay = stateLocation;
@@ -265,11 +274,13 @@ const show = async (options) => {
265
274
  app: state.app,
266
275
  service: state.service,
267
276
  stage,
277
+ region: context.region,
268
278
  ...(state.serial !== undefined ? { serial: state.serial } : {}),
269
279
  ...(state.lineage !== undefined ? { lineage: state.lineage } : {}),
270
280
  ...(state.managedBy !== undefined ? { managedBy: state.managedBy } : {}),
271
281
  stateLocation,
272
282
  backend: backendKind,
283
+ stateSource,
273
284
  locked: !!lockInfo,
274
285
  lock: lockInfo ? { ...lockInfo } : null,
275
286
  resources: resources,
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deploymentStateHash = exports.patchAggregateScope = exports.mergeAggregateScope = exports.assertDeploymentState = exports.projectAggregateScope = exports.aggregatePartition = exports.readAggregateDocument = exports.emptyDeploymentState = exports.aggregateStateCorruptError = exports.AGGREGATE_STATE_VERSION = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const types_1 = require("../types");
9
+ const lang_1 = require("../lang");
10
+ const stateScope_1 = require("./stateScope");
11
+ const saasProtocol_1 = require("./saasProtocol");
12
+ exports.AGGREGATE_STATE_VERSION = types_1.CURRENT_STATE_VERSION;
13
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ const aggregateStateCorruptError = (location, cause) => Object.assign(new types_1.StateCorruptError(location, cause), {
15
+ message: lang_1.lang.__('STATE_AGGREGATE_INVALID'),
16
+ });
17
+ exports.aggregateStateCorruptError = aggregateStateCorruptError;
18
+ const corrupt = (location) => {
19
+ throw (0, exports.aggregateStateCorruptError)(location);
20
+ };
21
+ const ownEntry = (values, key) => values && Object.prototype.hasOwnProperty.call(values, key) ? values[key] : undefined;
22
+ const emptyDeploymentState = (scope) => {
23
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
24
+ return {
25
+ version: types_1.CURRENT_STATE_VERSION,
26
+ provider: normalized.provider,
27
+ app: normalized.app,
28
+ service: normalized.service,
29
+ scope: { stage: normalized.stage, region: normalized.region },
30
+ stages: { [normalized.stage]: { resources: {}, shared: {} } },
31
+ resources: {},
32
+ };
33
+ };
34
+ exports.emptyDeploymentState = emptyDeploymentState;
35
+ const readAggregateDocument = (raw, scope, location) => {
36
+ if (!record(raw))
37
+ return corrupt(location);
38
+ if (raw.version !== exports.AGGREGATE_STATE_VERSION) {
39
+ throw new types_1.StateVersionError(String(raw.version ?? ''), exports.AGGREGATE_STATE_VERSION);
40
+ }
41
+ if (raw.app !== scope.app || raw.service !== scope.service) {
42
+ throw Object.assign(new types_1.StateCorruptError(location, undefined), {
43
+ message: lang_1.lang.__('STATE_SCOPED_IDENTITY_MISMATCH'),
44
+ });
45
+ }
46
+ if (!record(raw.stages) || 'provider' in raw || 'resources' in raw)
47
+ return corrupt(location);
48
+ Object.entries(raw.stages).forEach(([stage, entry]) => {
49
+ (0, stateScope_1.validateScopeKeyPart)(stage, 'stage');
50
+ if (!record(entry) || !record(entry.providers))
51
+ return corrupt(location);
52
+ Object.entries(entry.providers).forEach(([provider, providerEntry]) => {
53
+ (0, stateScope_1.validateScopeKeyPart)(provider, 'provider');
54
+ if (!record(providerEntry) || !record(providerEntry.regions))
55
+ return corrupt(location);
56
+ Object.entries(providerEntry.regions).forEach(([region, partition]) => {
57
+ (0, stateScope_1.validateScopeKeyPart)(region, 'region');
58
+ if (region !== region.toLowerCase() ||
59
+ !record(partition) ||
60
+ !record(partition.resources) ||
61
+ (partition.shared !== undefined && !record(partition.shared)) ||
62
+ ['app', 'service', 'provider', 'scope', 'version', 'stages'].some((key) => key in partition) ||
63
+ typeof partition.lineage !== 'string' ||
64
+ partition.lineage.length === 0 ||
65
+ !Number.isInteger(partition.serial) ||
66
+ Number(partition.serial) < 1) {
67
+ return corrupt(location);
68
+ }
69
+ });
70
+ });
71
+ });
72
+ return raw;
73
+ };
74
+ exports.readAggregateDocument = readAggregateDocument;
75
+ const aggregatePartition = (document, scope) => {
76
+ const stage = ownEntry(document?.stages, scope.stage);
77
+ const provider = ownEntry(stage?.providers, scope.provider);
78
+ return ownEntry(provider?.regions, scope.region);
79
+ };
80
+ exports.aggregatePartition = aggregatePartition;
81
+ const projectAggregateScope = (document, scope) => {
82
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
83
+ const partition = (0, exports.aggregatePartition)(document, normalized);
84
+ const empty = (0, exports.emptyDeploymentState)(normalized);
85
+ if (!partition)
86
+ return empty;
87
+ const { resources, shared = {}, ...metadata } = partition;
88
+ return {
89
+ ...empty,
90
+ ...metadata,
91
+ stages: { [normalized.stage]: { resources, shared } },
92
+ resources,
93
+ };
94
+ };
95
+ exports.projectAggregateScope = projectAggregateScope;
96
+ const assertDeploymentState = (state, scope) => {
97
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
98
+ if (state.version !== types_1.CURRENT_STATE_VERSION) {
99
+ throw new types_1.StateVersionError(state.version, types_1.CURRENT_STATE_VERSION);
100
+ }
101
+ if (state.app !== normalized.app ||
102
+ state.service !== normalized.service ||
103
+ state.provider !== normalized.provider ||
104
+ (state.scope &&
105
+ (state.scope.stage !== normalized.stage ||
106
+ state.scope.region.toLowerCase() !== normalized.region))) {
107
+ throw new types_1.StateScopeMismatchError(normalized, {
108
+ app: state.app,
109
+ service: state.service,
110
+ provider: state.provider,
111
+ stage: state.scope?.stage,
112
+ region: state.scope?.region,
113
+ });
114
+ }
115
+ };
116
+ exports.assertDeploymentState = assertDeploymentState;
117
+ const METADATA_KEYS = ['orgId', 'appId', 'serviceId', 'managedBy', 'migration'];
118
+ const mergeAggregateScope = (document, scope, state, options = {}) => {
119
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
120
+ (0, exports.assertDeploymentState)(state, normalized);
121
+ const previous = (0, exports.aggregatePartition)(document, normalized);
122
+ const metadata = Object.fromEntries(METADATA_KEYS.flatMap((key) => {
123
+ const value = previous ? previous[key] : state[key];
124
+ return value === undefined ? [] : [[key, value]];
125
+ }));
126
+ const partition = {
127
+ ...metadata,
128
+ lineage: previous?.lineage ?? state.lineage ?? node_crypto_1.default.randomUUID(),
129
+ serial: options.preserveRevision ? (state.serial ?? 1) : (previous?.serial ?? 0) + 1,
130
+ resources: state.resources,
131
+ shared: state.stages[normalized.stage]?.shared ?? previous?.shared ?? {},
132
+ };
133
+ const stages = document?.stages ?? {};
134
+ const providers = ownEntry(stages, normalized.stage)?.providers ?? {};
135
+ const regions = ownEntry(providers, normalized.provider)?.regions ?? {};
136
+ return {
137
+ ...document,
138
+ version: exports.AGGREGATE_STATE_VERSION,
139
+ app: normalized.app,
140
+ service: normalized.service,
141
+ stages: {
142
+ ...stages,
143
+ [normalized.stage]: {
144
+ providers: {
145
+ ...providers,
146
+ [normalized.provider]: { regions: { ...regions, [normalized.region]: partition } },
147
+ },
148
+ },
149
+ },
150
+ };
151
+ };
152
+ exports.mergeAggregateScope = mergeAggregateScope;
153
+ const patchAggregateScope = (document, selected, patch) => {
154
+ const scope = (0, stateScope_1.normalizeScope)(selected);
155
+ if (Object.keys(patch).some((key) => !METADATA_KEYS.includes(key))) {
156
+ throw new Error(lang_1.lang.__('STATE_PARTITION_PATCH_INVALID'));
157
+ }
158
+ const current = (0, exports.projectAggregateScope)(document, scope);
159
+ const next = (0, exports.mergeAggregateScope)(document, scope, current);
160
+ const partition = (0, exports.aggregatePartition)(next, scope);
161
+ const patched = Object.fromEntries(Object.entries({ ...partition, ...patch }).filter(([, value]) => value !== undefined));
162
+ return {
163
+ ...next,
164
+ stages: {
165
+ ...next.stages,
166
+ [scope.stage]: {
167
+ providers: {
168
+ ...next.stages[scope.stage].providers,
169
+ [scope.provider]: {
170
+ regions: {
171
+ ...next.stages[scope.stage].providers[scope.provider].regions,
172
+ [scope.region]: patched,
173
+ },
174
+ },
175
+ },
176
+ },
177
+ },
178
+ };
179
+ };
180
+ exports.patchAggregateScope = patchAggregateScope;
181
+ const deploymentStateHash = (state) => {
182
+ const { resources: _projection, ...persisted } = state;
183
+ return (0, saasProtocol_1.hashSaasState)(persisted);
184
+ };
185
+ exports.deploymentStateHash = deploymentStateHash;