@geek-fun/serverlessinsight 0.8.2 → 0.8.3

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 (119) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +14 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +14 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +348 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +14 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +114 -0
  6. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +1 -0
  7. package/README.md +26 -18
  8. package/README.zh-CN.md +19 -6
  9. package/dist/package.json +3 -1
  10. package/dist/src/commands/deploy.js +87 -4
  11. package/dist/src/commands/destroy.js +61 -10
  12. package/dist/src/commands/forceUnlock.js +8 -0
  13. package/dist/src/commands/index.js +34 -2
  14. package/dist/src/commands/login.js +195 -0
  15. package/dist/src/commands/logout.js +17 -0
  16. package/dist/src/commands/show.js +15 -7
  17. package/dist/src/commands/whoami.js +20 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +327 -30
  19. package/dist/src/common/aliyunClient/esOperations.js +43 -29
  20. package/dist/src/common/aliyunClient/fc3Operations.js +481 -207
  21. package/dist/src/common/aliyunClient/ossOperations.js +165 -13
  22. package/dist/src/common/aliyunClient/rdsOperations.js +143 -39
  23. package/dist/src/common/aliyunClient/slsOperations.js +56 -26
  24. package/dist/src/common/aliyunClient/tablestoreOperations.js +25 -22
  25. package/dist/src/common/apiClient.js +102 -0
  26. package/dist/src/common/constants.js +9 -4
  27. package/dist/src/common/credentialStore.js +94 -0
  28. package/dist/src/common/credentials.js +2 -0
  29. package/dist/src/common/eventQueue.js +208 -0
  30. package/dist/src/common/hashUtils.js +87 -11
  31. package/dist/src/common/imsClient.js +1 -0
  32. package/dist/src/common/index.js +3 -0
  33. package/dist/src/common/lockManager.js +61 -54
  34. package/dist/src/common/logger.js +2 -0
  35. package/dist/src/common/polling.js +54 -0
  36. package/dist/src/common/reportResourceEvent.js +8 -0
  37. package/dist/src/common/runtimeMapper.js +11 -12
  38. package/dist/src/common/stateBackend/index.js +10 -1
  39. package/dist/src/common/stateBackend/localStateBackend.js +4 -1
  40. package/dist/src/common/stateBackend/remoteStateBackend.js +6 -3
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +135 -13
  43. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  44. package/dist/src/common/tencentClient/esOperations.js +110 -46
  45. package/dist/src/common/tencentClient/index.js +22 -1
  46. package/dist/src/common/tencentClient/scfOperations.js +255 -133
  47. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  48. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  49. package/dist/src/common/triggerMapper.js +36 -0
  50. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  51. package/dist/src/common/volcengineClient/iamOperations.js +58 -48
  52. package/dist/src/common/volcengineClient/index.js +46 -21
  53. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  54. package/dist/src/common/volcengineClient/tlsOperations.js +229 -178
  55. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  56. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  57. package/dist/src/lang/en.js +84 -0
  58. package/dist/src/lang/zh-CN.js +84 -0
  59. package/dist/src/parser/eventParser.js +2 -0
  60. package/dist/src/parser/functionParser.js +96 -65
  61. package/dist/src/parser/index.js +7 -4
  62. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  63. package/dist/src/stack/aliyunStack/apigwPlanner.js +14 -10
  64. package/dist/src/stack/aliyunStack/apigwResource.js +216 -124
  65. package/dist/src/stack/aliyunStack/apigwTypes.js +16 -3
  66. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  67. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  68. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  69. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  70. package/dist/src/stack/aliyunStack/destroyer.js +2 -2
  71. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  72. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  73. package/dist/src/stack/aliyunStack/fc3Resource.js +327 -64
  74. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  75. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  76. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  77. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  78. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  79. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  80. package/dist/src/stack/alreadyExists.js +26 -0
  81. package/dist/src/stack/ownershipTag.js +40 -0
  82. package/dist/src/stack/rfsStack/index.js +3 -1
  83. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  84. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  85. package/dist/src/stack/scfStack/cosResource.js +167 -64
  86. package/dist/src/stack/scfStack/deployer.js +2 -2
  87. package/dist/src/stack/scfStack/destroyer.js +2 -2
  88. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  89. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  90. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  91. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  92. package/dist/src/stack/scfStack/scfPlanner.js +12 -2
  93. package/dist/src/stack/scfStack/scfResource.js +484 -14
  94. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  95. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  96. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  97. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  98. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  99. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  100. package/dist/src/stack/volcengineStack/apigwResource.js +418 -222
  101. package/dist/src/stack/volcengineStack/apigwTypes.js +76 -66
  102. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  103. package/dist/src/stack/volcengineStack/destroyer.js +1 -1
  104. package/dist/src/stack/volcengineStack/index.js +1 -2
  105. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  106. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  107. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  108. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  109. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  110. package/dist/src/stack/volcengineStack/vefaasPlanner.js +71 -2
  111. package/dist/src/stack/volcengineStack/vefaasResource.js +148 -98
  112. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  113. package/dist/src/types/domains/backend.js +1 -0
  114. package/dist/src/types/domains/state.js +29 -1
  115. package/dist/src/validator/eventSchema.js +10 -0
  116. package/dist/src/validator/functionSchema.js +37 -12
  117. package/dist/src/validator/iacSchema.js +1 -0
  118. package/dist/tsconfig.tsbuildinfo +1 -1
  119. package/package.json +3 -1
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeTablePlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const tablestoreResource_1 = require("./tablestoreResource");
5
6
  const common_1 = require("../../common");
7
+ const reportResourceEvent_1 = require("../../common/reportResourceEvent");
6
8
  const stateManager_1 = require("../../common/stateManager");
7
9
  const lang_1 = require("../../lang");
8
10
  const executeCreateAction = async (context, table, currentState) => {
@@ -74,13 +76,26 @@ const executeTablePlan = async (context, plan, tables, initialState, onStateChan
74
76
  const successfulItems = [];
75
77
  let currentState = initialState;
76
78
  for (const item of plan.items) {
79
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
80
+ type: 'resource_pre',
81
+ logicalId: item.logicalId,
82
+ resourceType: item.resourceType,
83
+ action: item.action,
84
+ ...(item.drifted ? { message: 'resource drifted' } : {}),
85
+ });
86
+ const __siStartedAt = Date.now();
77
87
  try {
78
88
  const newState = await executeSingleItem(context, item, tablesMap, currentState);
79
89
  if (newState !== null) {
80
90
  currentState = newState;
81
91
  successfulItems.push(item);
92
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
93
+ type: 'resource_complete',
94
+ logicalId: item.logicalId,
95
+ durationMs: Date.now() - __siStartedAt,
96
+ });
82
97
  if (onStateChange) {
83
- onStateChange(currentState);
98
+ await onStateChange(currentState);
84
99
  common_1.logger.debug(lang_1.lang.__('STATE_PERSISTED_AFTER_OPERATION', {
85
100
  action: item.action,
86
101
  resourceId: item.logicalId,
@@ -89,6 +104,29 @@ const executeTablePlan = async (context, plan, tables, initialState, onStateChan
89
104
  }
90
105
  }
91
106
  catch (error) {
107
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
108
+ type: 'resource_failed',
109
+ logicalId: item.logicalId,
110
+ severity: 'error',
111
+ durationMs: Date.now() - __siStartedAt,
112
+ error: {
113
+ message: error instanceof Error ? error.message : String(error),
114
+ },
115
+ });
116
+ if (error instanceof types_1.PartialResourceError) {
117
+ const updatedState = error.updatedState;
118
+ if (onStateChange) {
119
+ await onStateChange(updatedState);
120
+ }
121
+ return {
122
+ state: updatedState,
123
+ partialFailure: {
124
+ failedItem: item,
125
+ error: error.cause,
126
+ successfulItems,
127
+ },
128
+ };
129
+ }
92
130
  return {
93
131
  state: currentState,
94
132
  partialFailure: {
@@ -25,7 +25,19 @@ const generateTablePlan = async (context, state, tables) => {
25
25
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
26
26
  const config = (0, tablestoreTypes_1.tableToTableStoreConfig)(table);
27
27
  const desiredDefinition = (0, tablestoreTypes_1.extractTableStoreDefinition)(config);
28
- if (!currentState) {
28
+ if (!currentState || currentState.status === 'tainted') {
29
+ // No usable local state: probe the provider before planning create.
30
+ // Aliyun Tablestore (OTS) supports only instance-level tags — table
31
+ // ownership cannot be verified, so tag-based adoption is IMPOSSIBLE.
32
+ // If a same-named table already exists it may belong to another
33
+ // project: fail fast in the plan instead of letting the executor
34
+ // discover the collision mid-deploy.
35
+ const client = (0, aliyunClient_1.createAliyunClient)(context);
36
+ const tablestoreClient = client.tablestore(config.instanceName);
37
+ const remoteTable = await tablestoreClient.getTable(config.tableName);
38
+ if (remoteTable) {
39
+ throw new Error(`Table ${config.tableName} already exists in provider but ownership cannot be verified (no table-level tags). Refusing to adopt — resolve manually.`);
40
+ }
29
41
  return {
30
42
  logicalId,
31
43
  action: 'create',
@@ -3,7 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteTableResource = exports.updateTableResource = exports.readTableResource = exports.createTableResource = void 0;
4
4
  const aliyunClient_1 = require("../../common/aliyunClient");
5
5
  const common_1 = require("../../common");
6
+ const types_1 = require("../../types");
6
7
  const tablestoreTypes_1 = require("./tablestoreTypes");
8
+ const alreadyExists_1 = require("../alreadyExists");
7
9
  const logger_1 = require("../../common/logger");
8
10
  const buildTableStoreInstanceFromProvider = (info, sid, instanceName, clusterType) => {
9
11
  return {
@@ -27,6 +29,8 @@ const buildTableStoreInstanceFromProvider = (info, sid, instanceName, clusterTyp
27
29
  maxVersions: info.tableOptions.maxVersions ?? null,
28
30
  maxTimeDeviation: info.tableOptions.maxTimeDeviation ?? null,
29
31
  allowUpdate: info.tableOptions.allowUpdate ?? null,
32
+ bloomFilterType: info.tableOptions.bloomFilterType ?? null,
33
+ blockSize: info.tableOptions.blockSize ?? null,
30
34
  }
31
35
  : undefined,
32
36
  streamDetails: info.streamDetails
@@ -37,39 +41,69 @@ const buildTableStoreInstanceFromProvider = (info, sid, instanceName, clusterTyp
37
41
  lastEnableTime: info.streamDetails.lastEnableTime ?? null,
38
42
  }
39
43
  : undefined,
44
+ tableStatus: info.tableStatus ?? null,
45
+ definedColumn: info.definedColumn ?? [],
46
+ indexMetas: info.indexMetas ?? [],
47
+ shardSplits: info.shardSplits ?? [],
40
48
  };
41
49
  };
42
50
  const createTableResource = async (context, table, state) => {
43
51
  const config = (0, tablestoreTypes_1.tableToTableStoreConfig)(table);
44
52
  const client = (0, aliyunClient_1.createAliyunClient)(context);
45
53
  const tablestoreClient = client.tablestore(config.instanceName);
46
- // Create table
47
- await tablestoreClient.createTable({
48
- tableName: config.tableName,
49
- primaryKey: config.primaryKey,
50
- reservedThroughput: config.reservedThroughput,
51
- tableOptions: config.tableOptions,
52
- });
53
- // Wait for table to be ready
54
- await tablestoreClient.waitForTableReady(config.tableName);
55
- // Refresh state from provider to get all attributes
56
- const tableInfo = await tablestoreClient.getTable(config.tableName);
57
- if (!tableInfo) {
58
- throw new Error(`Failed to refresh state for table: ${config.tableName}`);
59
- }
54
+ const logicalId = `tables.${table.key}`;
60
55
  const definition = (0, tablestoreTypes_1.extractTableStoreDefinition)(config);
61
56
  const sid = (0, common_1.buildSid)('aliyun', 'ots', context.stage, `${config.instanceName}/${config.tableName}`);
62
- const resourceState = {
57
+ const taintedResourceState = {
63
58
  mode: 'managed',
64
59
  region: context.region,
65
60
  definition,
66
- instances: [
67
- buildTableStoreInstanceFromProvider(tableInfo, sid, config.instanceName, config.clusterType),
68
- ],
61
+ instances: [],
69
62
  lastUpdated: new Date().toISOString(),
63
+ status: 'tainted',
70
64
  };
71
- const logicalId = `tables.${table.key}`;
72
- return (0, common_1.setResource)(state, logicalId, resourceState);
65
+ const stateAfterDependents = (0, common_1.setResource)(state, logicalId, taintedResourceState);
66
+ try {
67
+ // Create table
68
+ await tablestoreClient.createTable({
69
+ tableName: config.tableName,
70
+ primaryKey: config.primaryKey,
71
+ reservedThroughput: config.reservedThroughput,
72
+ tableOptions: config.tableOptions,
73
+ });
74
+ // Wait for table to be ready
75
+ await tablestoreClient.waitForTableReady(config.tableName);
76
+ // Refresh state from provider to get all attributes
77
+ const tableInfo = await tablestoreClient.getTable(config.tableName);
78
+ if (!tableInfo) {
79
+ throw new Error(`Failed to refresh state for table: ${config.tableName}`);
80
+ }
81
+ const resourceState = {
82
+ mode: 'managed',
83
+ region: context.region,
84
+ definition,
85
+ instances: [
86
+ buildTableStoreInstanceFromProvider(tableInfo, sid, config.instanceName, config.clusterType),
87
+ ],
88
+ lastUpdated: new Date().toISOString(),
89
+ };
90
+ return (0, common_1.setResource)(stateAfterDependents, logicalId, resourceState);
91
+ }
92
+ catch (error) {
93
+ // Aliyun Tablestore (OTS) does NOT support table-level tags — only
94
+ // instance-level. Without a tag, ownership of a pre-existing table cannot
95
+ // be verified, so tag-based idempotent adoption is IMPOSSIBLE. On a create
96
+ // collision we therefore ALWAYS refuse to adopt (never take over a table
97
+ // that may belong to another project): persist the tainted state and let
98
+ // the user resolve manually.
99
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error, ['OTSObjectAlreadyExist', 'OTSInstanceAlreadyExist'])) {
100
+ const existingTable = await tablestoreClient.getTable(config.tableName);
101
+ if (existingTable) {
102
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(`Table ${config.tableName} already exists in provider but ownership cannot be verified (Tablestore does not support table-level tags). Refusing to adopt — resolve manually.`));
103
+ }
104
+ }
105
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
106
+ }
73
107
  };
74
108
  exports.createTableResource = createTableResource;
75
109
  const readTableResource = async (context, instanceName, tableName) => {
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isResourceAlreadyExistsError = void 0;
4
+ /**
5
+ * Generic "resource already exists" detector for create-time errors, shared
6
+ * across all providers. Cloud SDKs report collisions with different shapes:
7
+ * - Tencent: code ResourceInUse, message "指定的Function已存在,请勿重复创建"
8
+ * - Aliyun: code...AlreadyExists / message "already exists" / ResourceExhausted
9
+ * - Volcengine: code...Conflict / message "already exist"
10
+ *
11
+ * Deliberately does NOT match timeouts/network errors — those must propagate so
12
+ * a missing resource is never silently swallowed. Callers can pass provider-
13
+ * specific extra codes that only their SDK emits.
14
+ */
15
+ const isResourceAlreadyExistsError = (error, extraCodes = []) => {
16
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
17
+ ? error.code.toLowerCase()
18
+ : '';
19
+ const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
20
+ const providerCodes = extraCodes.map((c) => c.toLowerCase());
21
+ return (code.includes('resourceinuse') ||
22
+ message.includes('已存在') ||
23
+ message.includes('already exist') ||
24
+ providerCodes.some((c) => code.includes(c)));
25
+ };
26
+ exports.isResourceAlreadyExistsError = isResourceAlreadyExistsError;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOwnedByStack = exports.parseOwnershipTagValue = exports.buildOwnershipTagValue = exports.OWNERSHIP_TAG_KEY = void 0;
4
+ /**
5
+ * Ownership tag stamped on provider resources at create time so a deploy can
6
+ * idempotently adopt a resource that exists in the cloud but is missing from
7
+ * local state (e.g. state was reset or a previous run failed mid-way).
8
+ *
9
+ * The value encodes BOTH the owning stack and the logical id:
10
+ * `${app}-${service}:${logicalId}` e.g. "fn-url-probe:functions.probe"
11
+ *
12
+ * A single tag is enough because the cloud resource name is already globally
13
+ * unique per provider; the tag only needs to prove ownership so an unrelated
14
+ * same-named resource is never adopted (that would corrupt state and let a
15
+ * later destroy remove a resource that was never ours).
16
+ */
17
+ exports.OWNERSHIP_TAG_KEY = 'si-owned-by';
18
+ const buildOwnershipTagValue = (context, logicalId) => `${context.app}-${context.service}:${logicalId}`;
19
+ exports.buildOwnershipTagValue = buildOwnershipTagValue;
20
+ const parseOwnershipTagValue = (value) => {
21
+ if (!value)
22
+ return null;
23
+ const idx = value.indexOf(':');
24
+ if (idx <= 0)
25
+ return null;
26
+ return { stack: value.slice(0, idx), logicalId: value.slice(idx + 1) };
27
+ };
28
+ exports.parseOwnershipTagValue = parseOwnershipTagValue;
29
+ const isOwnedByStack = (context, logicalId, tags) => {
30
+ if (!tags)
31
+ return false;
32
+ const tag = tags.find((t) => t.Key === exports.OWNERSHIP_TAG_KEY);
33
+ if (!tag?.Value)
34
+ return false;
35
+ const parsed = (0, exports.parseOwnershipTagValue)(tag.Value);
36
+ if (!parsed)
37
+ return false;
38
+ return parsed.stack === `${context.app}-${context.service}` && parsed.logicalId === logicalId;
39
+ };
40
+ exports.isOwnedByStack = isOwnedByStack;
@@ -23,10 +23,12 @@ provider "huaweicloud" {
23
23
  stack.appendHcl(hcl);
24
24
  };
25
25
  class RfsStack {
26
+ iac;
27
+ context;
28
+ hcl = '';
26
29
  constructor(iac, context = (0, common_1.getContext)()) {
27
30
  this.iac = iac;
28
31
  this.context = context;
29
- this.hcl = '';
30
32
  provider(this, context);
31
33
  (0, function_1.resolveFunction)(this, iac.functions, context, `${iac.app}-${iac.service}`);
32
34
  }
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeBucketPlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const cosResource_1 = require("./cosResource");
5
6
  const common_1 = require("../../common");
7
+ const reportResourceEvent_1 = require("../../common/reportResourceEvent");
6
8
  const stateManager_1 = require("../../common/stateManager");
7
9
  const lang_1 = require("../../lang");
8
10
  const executeCreateAction = async (context, bucket, currentState) => {
@@ -61,13 +63,26 @@ const executeBucketPlan = async (context, plan, buckets, initialState, onStateCh
61
63
  const successfulItems = [];
62
64
  let currentState = initialState;
63
65
  for (const item of plan.items) {
66
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
67
+ type: 'resource_pre',
68
+ logicalId: item.logicalId,
69
+ resourceType: item.resourceType,
70
+ action: item.action,
71
+ ...(item.drifted ? { message: 'resource drifted' } : {}),
72
+ });
73
+ const __siStartedAt = Date.now();
64
74
  try {
65
75
  const newState = await executeSingleItem(context, item, bucketsMap, currentState);
66
76
  if (newState !== null) {
67
77
  currentState = newState;
68
78
  successfulItems.push(item);
79
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
80
+ type: 'resource_complete',
81
+ logicalId: item.logicalId,
82
+ durationMs: Date.now() - __siStartedAt,
83
+ });
69
84
  if (onStateChange) {
70
- onStateChange(currentState);
85
+ await onStateChange(currentState);
71
86
  common_1.logger.debug(lang_1.lang.__('STATE_PERSISTED_AFTER_OPERATION', {
72
87
  action: item.action,
73
88
  resourceId: item.logicalId,
@@ -76,6 +91,29 @@ const executeBucketPlan = async (context, plan, buckets, initialState, onStateCh
76
91
  }
77
92
  }
78
93
  catch (error) {
94
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
95
+ type: 'resource_failed',
96
+ logicalId: item.logicalId,
97
+ severity: 'error',
98
+ durationMs: Date.now() - __siStartedAt,
99
+ error: {
100
+ message: error instanceof Error ? error.message : String(error),
101
+ },
102
+ });
103
+ if (error instanceof types_1.PartialResourceError) {
104
+ const updatedState = error.updatedState;
105
+ if (onStateChange) {
106
+ await onStateChange(updatedState);
107
+ }
108
+ return {
109
+ state: updatedState,
110
+ partialFailure: {
111
+ failedItem: item,
112
+ error: error.cause,
113
+ successfulItems,
114
+ },
115
+ };
116
+ }
79
117
  return {
80
118
  state: currentState,
81
119
  partialFailure: {
@@ -5,6 +5,7 @@ const tencentClient_1 = require("../../common/tencentClient");
5
5
  const cosTypes_1 = require("./cosTypes");
6
6
  const stateManager_1 = require("../../common/stateManager");
7
7
  const hashUtils_1 = require("../../common/hashUtils");
8
+ const ownershipTag_1 = require("../ownershipTag");
8
9
  const planBucketDeletion = (logicalId, definition) => ({
9
10
  logicalId,
10
11
  action: 'delete',
@@ -25,7 +26,16 @@ const generateBucketPlan = async (context, state, buckets) => {
25
26
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
26
27
  const config = (0, cosTypes_1.bucketToCosBucketConfig)(bucket, context.region);
27
28
  const desiredDefinition = (0, cosTypes_1.extractCosBucketDefinition)(config);
28
- if (!currentState) {
29
+ if (!currentState || currentState.status === 'tainted') {
30
+ // No usable local state: probe the provider before planning create.
31
+ // If a same-named bucket already exists WITHOUT our ownership tag it
32
+ // may belong to another project — fail fast in the plan instead of
33
+ // letting the executor discover it mid-deploy.
34
+ const client = (0, tencentClient_1.createTencentClient)(context);
35
+ const remoteBucket = await client.cos.getBucket(bucket.name, context.region);
36
+ if (remoteBucket && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteBucket.Tags)) {
37
+ throw new Error(`Bucket ${bucket.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
38
+ }
29
39
  return {
30
40
  logicalId,
31
41
  action: 'create',
@@ -9,6 +9,8 @@ const certUtils_1 = require("../../common/certUtils");
9
9
  const logger_1 = require("../../common/logger");
10
10
  const lang_1 = require("../../lang");
11
11
  const domainUtils_1 = require("../../common/domainUtils");
12
+ const ownershipTag_1 = require("../ownershipTag");
13
+ const alreadyExists_1 = require("../alreadyExists");
12
14
  const toCosStatement = (stmt) => {
13
15
  const s = {
14
16
  effect: stmt.effect.toLowerCase(),
@@ -47,8 +49,14 @@ const deleteBucketPolicy = async (client, bucketName, region) => {
47
49
  await client.cos.deleteBucketPolicy(bucketName, region);
48
50
  logger_1.logger.info(lang_1.lang.__('BUCKET_POLICY_DELETED', { bucketName }));
49
51
  }
50
- catch {
51
- // Best effort cleanup
52
+ catch (err) {
53
+ const errorCode = err?.code;
54
+ const statusCode = err?.statusCode;
55
+ if (errorCode === 'NoSuchBucket' || statusCode === 404) {
56
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Bucket', name: bucketName }));
57
+ return;
58
+ }
59
+ throw err;
52
60
  }
53
61
  };
54
62
  const resolveBucketDomainCertificate = (bucket) => {
@@ -157,86 +165,181 @@ const buildCosInstanceFromProvider = (info, sid) => {
157
165
  })) ?? [],
158
166
  }
159
167
  : {},
168
+ tags: info.Tags?.map((t) => ({
169
+ key: t.Key,
170
+ value: t.Value,
171
+ })) ?? [],
172
+ lifecycleConfiguration: info.LifecycleConfiguration
173
+ ? {
174
+ rules: info.LifecycleConfiguration.rules?.map((r) => ({
175
+ id: r.id ?? null,
176
+ status: r.status ?? null,
177
+ prefix: r.prefix ?? null,
178
+ expiration: r.expiration
179
+ ? {
180
+ days: r.expiration.days ?? null,
181
+ date: r.expiration.date ?? null,
182
+ expiredObjectDeleteMarker: r.expiration.expiredObjectDeleteMarker ?? null,
183
+ }
184
+ : {},
185
+ transition: r.transition
186
+ ? {
187
+ days: r.transition.days ?? null,
188
+ date: r.transition.date ?? null,
189
+ storageClass: r.transition.storageClass ?? null,
190
+ }
191
+ : {},
192
+ })) ?? [],
193
+ }
194
+ : {},
195
+ loggingConfiguration: info.LoggingConfiguration
196
+ ? {
197
+ targetBucket: info.LoggingConfiguration.targetBucket ?? null,
198
+ targetPrefix: info.LoggingConfiguration.targetPrefix ?? null,
199
+ }
200
+ : {},
201
+ replicationConfiguration: info.ReplicationConfiguration
202
+ ? {
203
+ role: info.ReplicationConfiguration.role ?? null,
204
+ rules: info.ReplicationConfiguration.rules?.map((r) => ({
205
+ id: r.id ?? null,
206
+ status: r.status ?? null,
207
+ prefix: r.prefix ?? null,
208
+ destination: r.destination
209
+ ? {
210
+ bucket: r.destination.bucket ?? null,
211
+ storageClass: r.destination.storageClass ?? null,
212
+ }
213
+ : {},
214
+ })) ?? [],
215
+ }
216
+ : {},
217
+ sseConfiguration: info.SseConfiguration
218
+ ? {
219
+ sseAlgorithm: info.SseConfiguration.sseAlgorithm ?? null,
220
+ sseKmsMasterKeyId: info.SseConfiguration.sseKmsMasterKeyId ?? null,
221
+ }
222
+ : {},
223
+ policy: info.Policy ?? null,
160
224
  };
161
225
  };
162
226
  const createBucketResource = async (context, bucket, state) => {
163
227
  const config = (0, cosTypes_1.bucketToCosBucketConfig)(bucket, context.region);
164
228
  const client = (0, tencentClient_1.createTencentClient)(context);
165
- await client.cos.createBucket(config);
166
- const bucketInfo = await client.cos.getBucket(bucket.name, context.region);
167
- if (!bucketInfo) {
168
- throw new Error(`Failed to refresh state for bucket: ${bucket.name}`);
169
- }
170
229
  const definition = (0, cosTypes_1.extractCosBucketDefinition)(config);
171
- const sid = (0, common_1.buildSid)('tencent', 'cos', context.stage, bucket.name);
172
230
  const logicalId = `buckets.${bucket.key}`;
173
- const instances = [
174
- buildCosInstanceFromProvider(bucketInfo, sid),
175
- ];
176
- let cnameInfo;
177
- if (bucket.website?.domain) {
178
- const resolved = resolveBucketDomainCertificate(bucket);
179
- const primaryDomain = bucket.website.domain;
180
- const wwwBindApex = bucket.website.www_bind_apex ?? false;
181
- logger_1.logger.info(lang_1.lang.__('BINDING_CUSTOM_DOMAIN_TO_BUCKET', {
182
- domain: primaryDomain,
183
- bucketName: bucket.name,
184
- }));
185
- cnameInfo = await client.cos.bindCustomDomain(bucket.name, primaryDomain);
186
- if (cnameInfo) {
187
- const instanceId = cnameInfo.dnsRecordId ?? primaryDomain;
188
- const dnsInstance = {
189
- sid: (0, common_1.buildSid)('tencent', 'dnspod', context.stage, instanceId),
190
- id: instanceId,
191
- type: types_1.ResourceTypeEnum.COS_DNS_CNAME,
192
- domain: primaryDomain,
193
- cname: cnameInfo.cname,
194
- ...(cnameInfo.dnsRecordId ? { dnsRecordId: cnameInfo.dnsRecordId } : {}),
195
- };
196
- instances.push(dnsInstance);
197
- if (resolved && cnameInfo.bucketDomainBound) {
198
- await deployCertificateToCosDomain(client, resolved, bucket.name, primaryDomain, context.region);
231
+ // Stamp the ownership tag (sent as the x-cos-tagging header on PutBucket) so
232
+ // a later run can idempotently adopt this bucket, and an unrelated same-named
233
+ // bucket is never adopted.
234
+ config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
235
+ const taintedResourceState = {
236
+ mode: 'managed',
237
+ region: context.region,
238
+ definition,
239
+ instances: [],
240
+ lastUpdated: new Date().toISOString(),
241
+ status: 'tainted',
242
+ };
243
+ const stateAfterDependents = (0, common_1.setResource)(state, logicalId, taintedResourceState);
244
+ try {
245
+ try {
246
+ await client.cos.createBucket(config);
247
+ }
248
+ catch (error) {
249
+ // COS PutBucket is idempotent for the same region/owner, so a collision
250
+ // surfaces only for a different region/owner (BucketAlreadyExists /
251
+ // BucketAlreadyOwnedByYou) — treat it as non-fatal and fall through to
252
+ // the ownership probe below. Any other error propagates (outer catch
253
+ // persists the tainted state).
254
+ if (!(0, alreadyExists_1.isResourceAlreadyExistsError)(error, ['BucketAlreadyExists', 'BucketAlreadyOwnedByYou'])) {
255
+ throw error;
199
256
  }
257
+ logger_1.logger.info(`Bucket ${bucket.name} already exists in provider, verifying ownership tag before adopting`);
200
258
  }
201
- const wwwDomain = wwwBindApex ? (0, domainUtils_1.deriveWwwDomain)(primaryDomain) : null;
202
- if (wwwDomain) {
259
+ const bucketInfo = await client.cos.getBucket(bucket.name, context.region);
260
+ if (!bucketInfo) {
261
+ throw new Error(`Failed to refresh state for bucket: ${bucket.name}`);
262
+ }
263
+ // PutBucket succeeding does NOT prove the bucket is ours: a pre-existing
264
+ // bucket is returned idempotently. Only a bucket carrying our ownership tag
265
+ // (stamped at create time via x-cos-tagging) may be adopted; an untagged
266
+ // one may belong to another project and must fail loudly rather than be
267
+ // silently taken over (destroy would then remove a resource never ours).
268
+ if (!(0, ownershipTag_1.isOwnedByStack)(context, logicalId, bucketInfo.Tags)) {
269
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(`Bucket ${bucket.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to adopt — resolve manually.`));
270
+ }
271
+ const sid = (0, common_1.buildSid)('tencent', 'cos', context.stage, bucket.name);
272
+ const instances = [
273
+ buildCosInstanceFromProvider(bucketInfo, sid),
274
+ ];
275
+ let cnameInfo;
276
+ if (bucket.website?.domain) {
277
+ const resolved = resolveBucketDomainCertificate(bucket);
278
+ const primaryDomain = bucket.website.domain;
279
+ const wwwBindApex = bucket.website.www_bind_apex ?? false;
203
280
  logger_1.logger.info(lang_1.lang.__('BINDING_CUSTOM_DOMAIN_TO_BUCKET', {
204
- domain: wwwDomain,
281
+ domain: primaryDomain,
205
282
  bucketName: bucket.name,
206
283
  }));
207
- const wwwCnameInfo = await client.cos.bindCustomDomain(bucket.name, wwwDomain);
208
- if (wwwCnameInfo) {
209
- const wwwInstanceId = wwwCnameInfo.dnsRecordId ?? wwwDomain;
210
- const wwwDnsInstance = {
211
- sid: (0, common_1.buildSid)('tencent', 'dnspod', context.stage, wwwInstanceId),
212
- id: wwwInstanceId,
284
+ cnameInfo = await client.cos.bindCustomDomain(bucket.name, primaryDomain);
285
+ if (cnameInfo) {
286
+ const instanceId = cnameInfo.dnsRecordId ?? primaryDomain;
287
+ const dnsInstance = {
288
+ sid: (0, common_1.buildSid)('tencent', 'dnspod', context.stage, instanceId),
289
+ id: instanceId,
213
290
  type: types_1.ResourceTypeEnum.COS_DNS_CNAME,
214
- domain: wwwDomain,
215
- cname: wwwCnameInfo.cname,
216
- isWwwVariant: true,
217
- ...(wwwCnameInfo.dnsRecordId ? { dnsRecordId: wwwCnameInfo.dnsRecordId } : {}),
291
+ domain: primaryDomain,
292
+ cname: cnameInfo.cname,
293
+ ...(cnameInfo.dnsRecordId ? { dnsRecordId: cnameInfo.dnsRecordId } : {}),
218
294
  };
219
- instances.push(wwwDnsInstance);
220
- if (resolved && wwwCnameInfo.bucketDomainBound) {
221
- await deployCertificateToCosDomain(client, resolved, bucket.name, wwwDomain, context.region);
295
+ instances.push(dnsInstance);
296
+ if (resolved && cnameInfo.bucketDomainBound) {
297
+ await deployCertificateToCosDomain(client, resolved, bucket.name, primaryDomain, context.region);
222
298
  }
223
299
  }
300
+ const wwwDomain = wwwBindApex ? (0, domainUtils_1.deriveWwwDomain)(primaryDomain) : null;
301
+ if (wwwDomain) {
302
+ logger_1.logger.info(lang_1.lang.__('BINDING_CUSTOM_DOMAIN_TO_BUCKET', {
303
+ domain: wwwDomain,
304
+ bucketName: bucket.name,
305
+ }));
306
+ const wwwCnameInfo = await client.cos.bindCustomDomain(bucket.name, wwwDomain);
307
+ if (wwwCnameInfo) {
308
+ const wwwInstanceId = wwwCnameInfo.dnsRecordId ?? wwwDomain;
309
+ const wwwDnsInstance = {
310
+ sid: (0, common_1.buildSid)('tencent', 'dnspod', context.stage, wwwInstanceId),
311
+ id: wwwInstanceId,
312
+ type: types_1.ResourceTypeEnum.COS_DNS_CNAME,
313
+ domain: wwwDomain,
314
+ cname: wwwCnameInfo.cname,
315
+ isWwwVariant: true,
316
+ ...(wwwCnameInfo.dnsRecordId ? { dnsRecordId: wwwCnameInfo.dnsRecordId } : {}),
317
+ };
318
+ instances.push(wwwDnsInstance);
319
+ if (resolved && wwwCnameInfo.bucketDomainBound) {
320
+ await deployCertificateToCosDomain(client, resolved, bucket.name, wwwDomain, context.region);
321
+ }
322
+ }
323
+ }
324
+ const refreshedInfo = await client.cos.getBucket(bucket.name, context.region);
325
+ if (refreshedInfo) {
326
+ instances[0] = buildCosInstanceFromProvider(refreshedInfo, sid);
327
+ }
224
328
  }
225
- const refreshedInfo = await client.cos.getBucket(bucket.name, context.region);
226
- if (refreshedInfo) {
227
- instances[0] = buildCosInstanceFromProvider(refreshedInfo, sid);
228
- }
329
+ // Apply IAM bucket policy if configured
330
+ await applyBucketPolicy(client, bucket, context.region);
331
+ const resourceState = {
332
+ mode: 'managed',
333
+ region: context.region,
334
+ definition,
335
+ instances,
336
+ lastUpdated: new Date().toISOString(),
337
+ };
338
+ return (0, common_1.setResource)(state, logicalId, resourceState);
339
+ }
340
+ catch (error) {
341
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
229
342
  }
230
- // Apply IAM bucket policy if configured
231
- await applyBucketPolicy(client, bucket, context.region);
232
- const resourceState = {
233
- mode: 'managed',
234
- region: context.region,
235
- definition,
236
- instances,
237
- lastUpdated: new Date().toISOString(),
238
- };
239
- return (0, common_1.setResource)(state, logicalId, resourceState);
240
343
  };
241
344
  exports.createBucketResource = createBucketResource;
242
345
  const readBucketResource = async (context, bucketName, region) => {
@@ -11,8 +11,8 @@ const tdsqlcPlanner_1 = require("./tdsqlcPlanner");
11
11
  const tdsqlcExecutor_1 = require("./tdsqlcExecutor");
12
12
  const esServerlessPlanner_1 = require("./esServerlessPlanner");
13
13
  const esServerlessExecutor_1 = require("./esServerlessExecutor");
14
- const createSaveStateFn = (backend, iac, stage) => (state) => {
15
- backend.saveState(state, iac.app, iac.service, stage);
14
+ const createSaveStateFn = (backend, iac, stage) => async (state) => {
15
+ await backend.saveState(state, iac.app, iac.service, stage);
16
16
  };
17
17
  const handlePartialFailure = (failure) => {
18
18
  const error = failure.error;