@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
@@ -1,27 +1,19 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.createSaasStateBackend = void 0;
7
4
  const apiClient_1 = require("../apiClient");
8
5
  const credentialStore_1 = require("../credentialStore");
9
6
  const logger_1 = require("../logger");
10
- const types_1 = require("../../types");
11
7
  const stateManager_1 = require("../stateManager");
8
+ const stateScope_1 = require("../stateScope");
12
9
  const eventQueue_1 = require("../eventQueue");
13
10
  const lang_1 = require("../../lang");
14
- const node_crypto_1 = __importDefault(require("node:crypto"));
15
- const getDefaultState = (provider, app, service) => ({
16
- version: types_1.CURRENT_STATE_VERSION,
17
- provider,
18
- app,
19
- service,
20
- stages: {},
21
- resources: {},
22
- });
11
+ const saasProtocol_1 = require("../saasProtocol");
12
+ const types_1 = require("../../types");
23
13
  const createSaasStateBackend = (context, options) => {
24
- const creds = (0, credentialStore_1.loadCredentials)();
14
+ const normalized = (0, stateScope_1.normalizeScope)(context.scope);
15
+ const mode = options?.mode ?? 'mutating';
16
+ const creds = options?.apiKey ? null : (0, credentialStore_1.loadCredentials)();
25
17
  const apiKey = options?.apiKey || creds?.apiKey;
26
18
  const consoleUrl = (0, credentialStore_1.getConsoleUrl)();
27
19
  let knownOrgId = creds?.orgId ?? '';
@@ -45,12 +37,49 @@ const createSaasStateBackend = (context, options) => {
45
37
  orgId: knownOrgId,
46
38
  });
47
39
  let currentDeploymentId = null;
48
- let currentStage = null;
49
40
  let resolvedAppId = null;
50
41
  let resolvedServiceId = null;
42
+ let resolvedStageId = null;
43
+ let resolvedReadProtocol;
51
44
  let provisioned = false;
52
45
  let eventQueue = null;
53
46
  let sequenceCounter = 0;
47
+ let lastSource = 'empty';
48
+ let probedCapabilities = null;
49
+ // Only the server-acknowledged hash is a CAS base; never reconstruct it
50
+ // from JSONB or from a document-local serial/lineage.
51
+ let acknowledgedHash = null;
52
+ let acknowledgedSnapshot = null;
53
+ let running = false;
54
+ const retryRequest = async (send) => {
55
+ try {
56
+ return await send();
57
+ }
58
+ catch (error) {
59
+ if (error instanceof apiClient_1.ApiError && error.status < 500)
60
+ throw error;
61
+ return send();
62
+ }
63
+ };
64
+ const capabilities = { conditionalCreate: true };
65
+ const probeCapabilities = async () => {
66
+ if (probedCapabilities) {
67
+ return probedCapabilities;
68
+ }
69
+ try {
70
+ const caps = await client.get('/api/v1/capabilities');
71
+ probedCapabilities = { regionalScope: (0, saasProtocol_1.supportsRegionalSaas)(caps) };
72
+ }
73
+ catch (error) {
74
+ if (error instanceof apiClient_1.ApiError && (error.status === 404 || error.status === 405)) {
75
+ probedCapabilities = { regionalScope: false };
76
+ }
77
+ else {
78
+ throw error;
79
+ }
80
+ }
81
+ return probedCapabilities;
82
+ };
54
83
  /** ADR-005: enqueue a typed event for the active deployment (durable JSONL + batch flush). */
55
84
  const reportEvent = (event) => {
56
85
  ensureEventQueue();
@@ -68,6 +97,7 @@ const createSaasStateBackend = (context, options) => {
68
97
  return;
69
98
  eventQueue = new eventQueue_1.EventQueue({
70
99
  deploymentId: currentDeploymentId,
100
+ queueDir: options?.eventQueueDir,
71
101
  sendBatch: async (events) => {
72
102
  await client.patch(`/api/v1/deployments/${currentDeploymentId}`, {
73
103
  phase: 'event',
@@ -114,10 +144,16 @@ const createSaasStateBackend = (context, options) => {
114
144
  }
115
145
  return resolvedIdentity;
116
146
  };
117
- /**
118
- * Provision the deployment by calling the unified POST endpoint.
119
- * This resolves YAML names to Console UUIDs and caches them.
120
- */
147
+ const resolveReadOnlyIdentity = async () => {
148
+ const targets = await client.get(`/api/v1/state/migrate/targets?app_name=${encodeURIComponent(normalized.app)}&service_name=${encodeURIComponent(normalized.service)}&stages=${encodeURIComponent(normalized.stage)}&region=${encodeURIComponent(normalized.region)}&provider=${encodeURIComponent(normalized.provider)}`);
149
+ if (!targets.app.exists || !targets.service.exists) {
150
+ return false;
151
+ }
152
+ resolvedAppId = targets.app.id;
153
+ resolvedServiceId = targets.service.id;
154
+ resolvedReadProtocol = targets.service.scopeProtocol;
155
+ return true;
156
+ };
121
157
  const provision = async (provider, stage) => {
122
158
  // D-6: the org declaration must match the key's org BEFORE provisioning —
123
159
  // this POST is what auto-creates app/service, i.e. the wrong-org write.
@@ -130,34 +166,111 @@ const createSaasStateBackend = (context, options) => {
130
166
  }));
131
167
  }
132
168
  }
169
+ const caps = await probeCapabilities();
170
+ if (!caps.regionalScope) {
171
+ throw new Error(lang_1.lang.__('SAAS_REGIONAL_SCOPE_UNSUPPORTED', { consoleUrl }));
172
+ }
133
173
  const result = await client.post('/api/v1/deployments/', {
134
- appName: context.app,
135
- serviceName: context.service,
174
+ appName: normalized.app,
175
+ serviceName: normalized.service,
136
176
  provider,
137
177
  stage,
178
+ region: normalized.region,
179
+ scopeProtocol: saasProtocol_1.SCOPE_PROTOCOL_VERSION,
138
180
  spec: { operation: 'init' },
139
181
  source: 'cli',
140
182
  });
183
+ if (result.scopeProtocol !== saasProtocol_1.SCOPE_PROTOCOL_VERSION ||
184
+ result.provider !== normalized.provider ||
185
+ result.stage !== normalized.stage ||
186
+ result.region !== normalized.region ||
187
+ [result.id, result.appId, result.serviceId, result.stageId].some((id) => typeof id !== 'string' || id.length === 0)) {
188
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
189
+ }
141
190
  resolvedAppId = result.appId;
191
+ knownOrgId = result.orgId ?? knownOrgId;
142
192
  resolvedServiceId = result.serviceId;
193
+ resolvedStageId = result.stageId;
143
194
  currentDeploymentId = result.id;
144
195
  provisioned = true;
145
196
  };
146
- /**
147
- * Ensure the backend is provisioned — calls provision() if not already done.
148
- */
149
- const ensureProvisioned = async (provider, stage) => {
150
- if (!provisioned) {
151
- await provision(provider, stage);
197
+ const ensureResolved = async (provider, stage) => {
198
+ if (provisioned) {
199
+ return;
200
+ }
201
+ if (mode === 'read-only') {
202
+ const exists = await resolveReadOnlyIdentity();
203
+ if (!exists) {
204
+ lastSource = 'empty';
205
+ return;
206
+ }
207
+ provisioned = true;
208
+ return;
209
+ }
210
+ await provision(provider, stage);
211
+ };
212
+ const validateReturnedScope = (stateJson) => {
213
+ if (stateJson.provider !== normalized.provider ||
214
+ stateJson.app !== normalized.app ||
215
+ stateJson.service !== normalized.service) {
216
+ throw new Error(lang_1.lang.__('SAAS_STATE_SCOPE_MISMATCH', {
217
+ storedStage: stateJson.scope?.stage ?? 'unknown',
218
+ storedRegion: stateJson.scope?.region ?? 'unknown',
219
+ stage: normalized.stage,
220
+ region: normalized.region,
221
+ }));
222
+ }
223
+ if (stateJson.scope) {
224
+ const stored = {
225
+ provider: stateJson.provider,
226
+ app: stateJson.app,
227
+ service: stateJson.service,
228
+ stage: stateJson.scope.stage,
229
+ region: stateJson.scope.region,
230
+ };
231
+ const matches = stored.stage === normalized.stage &&
232
+ (stored.region ?? '').toLowerCase() === normalized.region;
233
+ if (!matches) {
234
+ throw new Error(lang_1.lang.__('SAAS_STATE_SCOPE_MISMATCH', {
235
+ storedStage: stored.stage ?? 'unknown',
236
+ storedRegion: stored.region ?? 'unknown',
237
+ stage: normalized.stage,
238
+ region: normalized.region,
239
+ }));
240
+ }
241
+ }
242
+ return stateJson;
243
+ };
244
+ const assertDeploymentAck = (value, status) => {
245
+ const ack = value;
246
+ if (!ack ||
247
+ ack.id !== currentDeploymentId ||
248
+ ack.serviceId !== resolvedServiceId ||
249
+ ack.stageId !== resolvedStageId ||
250
+ ack.stage !== normalized.stage ||
251
+ ack.provider !== normalized.provider ||
252
+ ack.region !== normalized.region ||
253
+ ack.scopeProtocol !== saasProtocol_1.SCOPE_PROTOCOL_VERSION ||
254
+ ack.status !== status) {
255
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
152
256
  }
153
257
  };
154
258
  return {
155
- loadState: async (provider, app, service, stage) => {
156
- currentStage = stage;
157
- await ensureProvisioned(provider, stage);
259
+ scope: normalized,
260
+ capabilities,
261
+ loadState: async () => {
262
+ await ensureResolved(normalized.provider, normalized.stage);
263
+ if (!resolvedAppId || !resolvedServiceId) {
264
+ lastSource = 'empty';
265
+ return (0, stateManager_1.emptyScopedState)(normalized);
266
+ }
158
267
  try {
159
- const state = await client.get(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/current?stage=${encodeURIComponent(stage)}`);
160
- const migrated = (0, stateManager_1.migrateState)(state.stateJson);
268
+ const state = await client.get(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/current?stage=${encodeURIComponent(normalized.stage)}&region=${encodeURIComponent(normalized.region)}&provider=${encodeURIComponent(normalized.provider)}`);
269
+ if (!state || !state.stateJson || typeof state.stateJson !== 'object') {
270
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
271
+ }
272
+ const validated = validateReturnedScope(state.stateJson);
273
+ const migrated = (0, stateManager_1.migrateState)(validated);
161
274
  // D-6 identity anchor: the state records the org id that owns this
162
275
  // service (persisted on every SaaS save / migrate backfill). A mismatch
163
276
  // with the current key's org means a wrong key — or an org deleted and
@@ -172,10 +285,20 @@ const createSaasStateBackend = (context, options) => {
172
285
  }));
173
286
  }
174
287
  }
288
+ // The server's activated lifecycle binding authorizes projection of
289
+ // historical documents; the JSON scope block alone is not authority.
290
+ const regional = (0, saasProtocol_1.isRegionalSaasSnapshot)(state, normalized) && state.serviceId === resolvedServiceId;
291
+ if (state.scopeProtocol === saasProtocol_1.SCOPE_PROTOCOL_VERSION &&
292
+ (!regional || (resolvedStageId && state.stageId !== resolvedStageId))) {
293
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
294
+ }
295
+ lastSource = regional ? 'scoped' : 'legacy';
296
+ acknowledgedHash = regional ? state.contentHash : null;
297
+ acknowledgedSnapshot = regional ? state : null;
175
298
  // Legacy Console states hold fresh resources only in the top-level
176
299
  // field (pre-stage-syncing saves) — prefer the stage store, fall back.
177
- const stageResources = migrated.stages?.[stage]?.resources;
178
- const resources = stageResources && Object.keys(stageResources).length > 0
300
+ const stageResources = migrated.stages?.[normalized.stage]?.resources;
301
+ const resources = stageResources !== undefined
179
302
  ? stageResources
180
303
  : migrated.resources && Object.keys(migrated.resources).length > 0
181
304
  ? migrated.resources
@@ -183,6 +306,15 @@ const createSaasStateBackend = (context, options) => {
183
306
  // Attach console metadata so subsequent deploys have the UUIDs
184
307
  return {
185
308
  ...migrated,
309
+ ...(regional
310
+ ? {
311
+ version: types_1.CURRENT_STATE_VERSION,
312
+ scope: { stage: normalized.stage, region: normalized.region },
313
+ stages: {
314
+ [normalized.stage]: { ...migrated.stages?.[normalized.stage], resources },
315
+ },
316
+ }
317
+ : {}),
186
318
  resources,
187
319
  orgId: knownOrgId,
188
320
  appId: resolvedAppId,
@@ -190,49 +322,106 @@ const createSaasStateBackend = (context, options) => {
190
322
  };
191
323
  }
192
324
  catch (error) {
193
- // Only a genuine 404 ("no state yet for this service+stage") may start
194
- // from an empty state. Network/5xx failures must surface — treating
195
- // them as empty would make the next plan propose full re-creation.
196
325
  if (!(error instanceof apiClient_1.ApiError && error.status === 404)) {
197
326
  throw error;
198
327
  }
199
- const defaultState = getDefaultState(provider, app, service);
328
+ lastSource = 'empty';
329
+ acknowledgedHash = '';
330
+ acknowledgedSnapshot = null;
200
331
  return {
201
- ...defaultState,
332
+ ...(0, stateManager_1.emptyScopedState)(normalized),
202
333
  orgId: knownOrgId,
203
- appId: resolvedAppId,
204
- serviceId: resolvedServiceId,
334
+ ...(resolvedAppId ? { appId: resolvedAppId } : {}),
335
+ ...(resolvedServiceId ? { serviceId: resolvedServiceId } : {}),
205
336
  };
206
337
  }
207
338
  },
208
- saveState: async (state, app, service, stage) => {
209
- // If not provisioned yet, use the state's provider for provisioning
210
- await ensureProvisioned(state.provider, stage);
339
+ saveState: async (state) => {
340
+ if (mode !== 'mutating') {
341
+ throw new Error(lang_1.lang.__('SAAS_READ_ONLY_WRITE_REFUSED'));
342
+ }
343
+ if (state.provider !== normalized.provider ||
344
+ state.app !== normalized.app ||
345
+ state.service !== normalized.service ||
346
+ (state.scope &&
347
+ (state.scope.stage !== normalized.stage || state.scope.region !== normalized.region))) {
348
+ throw new Error(lang_1.lang.__('SAAS_STATE_SCOPE_MISMATCH', {
349
+ storedStage: state.scope?.stage ?? state.provider,
350
+ storedRegion: state.scope?.region ?? `${state.app}/${state.service}`,
351
+ stage: normalized.stage,
352
+ region: normalized.region,
353
+ }));
354
+ }
355
+ const caps = await probeCapabilities();
356
+ if (!caps.regionalScope) {
357
+ throw new Error(lang_1.lang.__('SAAS_REGIONAL_SCOPE_UNSUPPORTED', { consoleUrl }));
358
+ }
359
+ await ensureResolved(state.provider, normalized.stage);
360
+ if (acknowledgedHash === null) {
361
+ throw new Error(lang_1.lang.__('SAAS_STATE_BASE_UNKNOWN'));
362
+ }
211
363
  // Sync the runtime projection into the stage store before stripping, so
212
364
  // stages[stage].resources carries the fresh working set (mirrors the fs
213
365
  // and remote backends' save contract)
214
366
  const stateJson = (0, stateManager_1.toPersistedState)({
215
367
  ...state,
368
+ version: types_1.CURRENT_STATE_VERSION,
369
+ scope: { stage: normalized.stage, region: normalized.region },
216
370
  stages: {
217
- ...state.stages,
218
- [stage]: {
219
- ...state.stages?.[stage],
371
+ [normalized.stage]: {
372
+ ...state.stages?.[normalized.stage],
220
373
  resources: state.resources,
221
374
  },
222
375
  },
223
376
  });
377
+ const contentHash = (0, saasProtocol_1.hashSaasState)(stateJson);
224
378
  const body = {
225
- appName: app,
226
- serviceName: service,
379
+ appName: normalized.app,
380
+ serviceName: normalized.service,
227
381
  provider: state.provider,
228
- stage,
382
+ stage: normalized.stage,
383
+ region: normalized.region,
384
+ scopeProtocol: saasProtocol_1.SCOPE_PROTOCOL_VERSION,
385
+ baseContentHash: acknowledgedHash,
386
+ ...(running ? { deploymentId: currentDeploymentId } : {}),
229
387
  stateJson,
230
- contentHash: node_crypto_1.default.createHash('sha256').update(JSON.stringify(stateJson)).digest('hex'),
388
+ contentHash,
231
389
  resourceCount: Object.keys(state.resources).length,
232
390
  };
233
- await client.post(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/sync`, body);
391
+ const response = await retryRequest(() => client.post(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/sync`, body));
392
+ if (!(0, saasProtocol_1.isRegionalSaasSnapshot)(response, normalized) ||
393
+ response.stageId !== resolvedStageId ||
394
+ response.serviceId !== resolvedServiceId ||
395
+ response.contentHash !== contentHash) {
396
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
397
+ }
398
+ acknowledgedHash = response.contentHash;
399
+ acknowledgedSnapshot = response;
400
+ lastSource = 'scoped';
401
+ },
402
+ readStateSource: () => lastSource,
403
+ probeWriteReadiness: async () => {
404
+ const caps = await probeCapabilities();
405
+ if (!caps.regionalScope) {
406
+ return {
407
+ ready: false,
408
+ source: lastSource,
409
+ reason: lang_1.lang.__('SAAS_REGIONAL_SCOPE_UNSUPPORTED', { consoleUrl }),
410
+ };
411
+ }
412
+ if (lastSource === 'legacy') {
413
+ return {
414
+ ready: false,
415
+ source: lastSource,
416
+ reason: lang_1.lang.__('SAAS_WRITE_BLOCKED_UNSCOPED_STATE', {
417
+ stage: normalized.stage,
418
+ region: normalized.region,
419
+ }),
420
+ };
421
+ }
422
+ return { ready: true, source: lastSource };
234
423
  },
235
- acquireLock: async (_operation, _options) => {
424
+ acquireLock: async (_operation, _lockOptions) => {
236
425
  return 'saas-lock-placeholder';
237
426
  },
238
427
  releaseLock: async (_lockId) => {
@@ -247,39 +436,56 @@ const createSaasStateBackend = (context, options) => {
247
436
  if (!resolvedServiceId) {
248
437
  return null;
249
438
  }
250
- try {
251
- const active = await client.get(`/api/v1/deployments/active?service_id=${resolvedServiceId}&stage=${currentStage ?? ''}`);
252
- // Backend returns data:null (not []) when no deployment is active
253
- if (Array.isArray(active) && active.length > 0) {
254
- const d = active[0];
255
- return {
256
- id: d.id,
257
- user: 'Console',
258
- processId: 0,
259
- hostname: 'console',
260
- operation: 'deploy',
261
- acquiredAt: new Date().toISOString(),
262
- path: `/api/v1/deployments/${d.id}`,
263
- };
264
- }
265
- return null;
266
- }
267
- catch {
439
+ const active = await client.get(`/api/v1/deployments/active?service_id=${encodeURIComponent(resolvedServiceId)}&stage=${encodeURIComponent(normalized.stage)}&region=${encodeURIComponent(normalized.region)}&provider=${encodeURIComponent(normalized.provider)}`);
440
+ if (active === null)
268
441
  return null;
442
+ const scopeProtocol = mode === 'read-only' && resolvedReadProtocol === 2 ? 2 : saasProtocol_1.SCOPE_PROTOCOL_VERSION;
443
+ if (!active ||
444
+ typeof active.id !== 'string' ||
445
+ !active.id ||
446
+ active.status !== 'deploying' ||
447
+ active.serviceId !== resolvedServiceId ||
448
+ active.stage !== normalized.stage ||
449
+ active.provider !== normalized.provider ||
450
+ active.region !== normalized.region ||
451
+ active.scopeProtocol !== scopeProtocol ||
452
+ typeof active.stageId !== 'string' ||
453
+ !active.stageId ||
454
+ (resolvedStageId && active.stageId !== resolvedStageId)) {
455
+ throw new Error(lang_1.lang.__('SAAS_STATE_ACK_INVALID'));
269
456
  }
457
+ return {
458
+ id: active.id,
459
+ user: 'Console',
460
+ processId: 0,
461
+ hostname: 'console',
462
+ operation: 'deploy',
463
+ acquiredAt: new Date().toISOString(),
464
+ path: `/api/v1/deployments/${active.id}`,
465
+ };
270
466
  },
271
- withLock: async (operation, fn, _options, onLockAcquired) => {
272
- if (!currentStage) {
273
- throw new Error(lang_1.lang.__('SAAS_BACKEND_SET_STAGE_FIRST'));
274
- }
467
+ withLock: async (operation, fn, _lockOptions, onLockAcquired) => {
275
468
  if (!currentDeploymentId) {
276
469
  throw new Error(lang_1.lang.__('SAAS_BACKEND_NO_DEPLOYMENT'));
277
470
  }
278
- // Acquire lock via phase:start (server checks for 409 conflicts)
279
- await client.patch(`/api/v1/deployments/${currentDeploymentId}`, { phase: 'start' });
471
+ if (mode !== 'mutating' || acknowledgedHash === null) {
472
+ throw new Error(lang_1.lang.__('SAAS_STATE_BASE_UNKNOWN'));
473
+ }
474
+ const started = await retryRequest(() => client.patch(`/api/v1/deployments/${currentDeploymentId}`, {
475
+ phase: 'start',
476
+ provider: normalized.provider,
477
+ region: normalized.region,
478
+ scopeProtocol: saasProtocol_1.SCOPE_PROTOCOL_VERSION,
479
+ baseContentHash: acknowledgedHash,
480
+ }));
481
+ assertDeploymentAck(started, 'deploying');
482
+ running = true;
280
483
  onLockAcquired?.(currentDeploymentId);
281
484
  ensureEventQueue();
282
- reportEvent({ type: 'deployment_started', message: `Deployment ${operation} started` });
485
+ reportEvent({
486
+ type: 'deployment_started',
487
+ message: lang_1.lang.__('SAAS_BACKEND_DEPLOYMENT_STARTED'),
488
+ });
283
489
  try {
284
490
  const result = await fn();
285
491
  // If the caller returned a deployment summary ({ stateJson, plan,
@@ -290,19 +496,32 @@ const createSaasStateBackend = (context, options) => {
290
496
  const isSummary = typeof result === 'object' &&
291
497
  result !== null &&
292
498
  ('stateJson' in summary || 'plan' in summary);
293
- await client.patch(`/api/v1/deployments/${currentDeploymentId}`, {
499
+ const completed = await retryRequest(() => client.patch(`/api/v1/deployments/${currentDeploymentId}`, {
294
500
  phase: 'complete',
501
+ provider: normalized.provider,
502
+ region: normalized.region,
503
+ scopeProtocol: saasProtocol_1.SCOPE_PROTOCOL_VERSION,
504
+ baseContentHash: acknowledgedHash,
505
+ ...(acknowledgedSnapshot ? { stateId: acknowledgedSnapshot.id } : {}),
295
506
  result: isSummary ? (summary['result'] ?? null) : result,
296
507
  ...(isSummary
297
508
  ? {
298
- stateJson: summary['stateJson'],
299
- contentHash: summary['contentHash'],
300
- resourceCount: summary['resourceCount'],
509
+ ...(!acknowledgedSnapshot && summary['stateJson']
510
+ ? {
511
+ stateJson: (0, stateManager_1.toPersistedState)(summary['stateJson']),
512
+ contentHash: (0, saasProtocol_1.hashSaasState)((0, stateManager_1.toPersistedState)(summary['stateJson'])),
513
+ resourceCount: summary['resourceCount'],
514
+ }
515
+ : {}),
301
516
  plan: summary['plan'],
302
517
  }
303
518
  : {}),
519
+ }));
520
+ assertDeploymentAck(completed, 'completed');
521
+ reportEvent({
522
+ type: 'deployment_completed',
523
+ message: lang_1.lang.__('SAAS_BACKEND_DEPLOYMENT_COMPLETE'),
304
524
  });
305
- reportEvent({ type: 'deployment_completed', message: `Deployment ${operation} completed` });
306
525
  await eventQueue?.flushOnExit();
307
526
  return result;
308
527
  }
@@ -314,31 +533,46 @@ const createSaasStateBackend = (context, options) => {
314
533
  try {
315
534
  const payload = {
316
535
  phase: 'fail',
536
+ provider: normalized.provider,
537
+ region: normalized.region,
538
+ scopeProtocol: saasProtocol_1.SCOPE_PROTOCOL_VERSION,
539
+ baseContentHash: acknowledgedHash,
540
+ ...(acknowledgedSnapshot ? { stateId: acknowledgedSnapshot.id } : {}),
317
541
  error: { message: err instanceof Error ? err.message : String(err) },
318
542
  ...(failure.plan ? { plan: failure.plan } : {}),
319
543
  };
320
- if (failure.stateJson) {
321
- payload['stateJson'] = failure.stateJson;
322
- payload['contentHash'] = node_crypto_1.default
323
- .createHash('sha256')
324
- .update(JSON.stringify(failure.stateJson))
325
- .digest('hex');
326
- payload['resourceCount'] = Object.keys(failure.stateJson.resources ?? {}).length;
544
+ if (failure.stateJson)
545
+ payload['stateSnapshot'] = failure.stateJson;
546
+ try {
547
+ const failed = await retryRequest(() => client.patch(`/api/v1/deployments/${currentDeploymentId}`, payload));
548
+ assertDeploymentAck(failed, 'failed');
549
+ }
550
+ catch (failureError) {
551
+ if (!(failureError instanceof apiClient_1.ApiError && failureError.status === 409))
552
+ throw failureError;
553
+ // Preserve partial diagnostics, but never replace a newer head.
554
+ const { stateId: _stateId, ...diagnostic } = payload;
555
+ const failed = await retryRequest(() => client.patch(`/api/v1/deployments/${currentDeploymentId}`, diagnostic));
556
+ assertDeploymentAck(failed, 'failed');
327
557
  }
328
- await client.patch(`/api/v1/deployments/${currentDeploymentId}`, payload);
329
558
  }
330
559
  catch {
331
560
  // Best-effort fail notification
332
561
  }
333
562
  reportEvent({
334
563
  type: 'deployment_failed',
335
- message: `Deployment ${operation} failed`,
564
+ message: lang_1.lang.__('SAAS_BACKEND_DEPLOYMENT_FAILED', {
565
+ error: err instanceof Error ? err.message : String(err),
566
+ }),
336
567
  error: { message: err instanceof Error ? err.message : String(err) },
337
568
  severity: 'error',
338
569
  });
339
570
  await eventQueue?.flushOnExit();
340
571
  throw err;
341
572
  }
573
+ finally {
574
+ running = false;
575
+ }
342
576
  },
343
577
  reportEvent,
344
578
  flushEvents: async () => {
@@ -349,6 +583,7 @@ const createSaasStateBackend = (context, options) => {
349
583
  // deploymentId, and sendBatch targets the deployment embedded in the event.
350
584
  const replayQueue = new eventQueue_1.EventQueue({
351
585
  deploymentId: 'replay',
586
+ queueDir: options?.eventQueueDir,
352
587
  sendBatch: async (events) => {
353
588
  const deploymentId = events[0]?.deploymentId;
354
589
  if (!deploymentId)
@@ -1,2 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConditionalPutUnsupportedError = void 0;
4
+ class ConditionalPutUnsupportedError extends Error {
5
+ constructor(cause) {
6
+ super('storage does not support conditional (create-only) writes');
7
+ this.name = 'ConditionalPutUnsupportedError';
8
+ this.cause = cause;
9
+ }
10
+ }
11
+ exports.ConditionalPutUnsupportedError = ConditionalPutUnsupportedError;