@geek-fun/serverlessinsight 0.8.2 → 0.8.4

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 (124) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +15 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +33 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +359 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +15 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +154 -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 +5 -2
  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 +363 -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 +90 -28
  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 +13 -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 +10 -4
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +186 -14
  43. package/dist/src/common/tencentClient/clsOperations.js +137 -0
  44. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  45. package/dist/src/common/tencentClient/esOperations.js +110 -46
  46. package/dist/src/common/tencentClient/index.js +43 -2
  47. package/dist/src/common/tencentClient/scfOperations.js +266 -133
  48. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  49. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  50. package/dist/src/common/triggerMapper.js +36 -0
  51. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  52. package/dist/src/common/volcengineClient/iamOperations.js +91 -48
  53. package/dist/src/common/volcengineClient/index.js +46 -21
  54. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  55. package/dist/src/common/volcengineClient/tlsOperations.js +305 -171
  56. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  57. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  58. package/dist/src/lang/en.js +107 -1
  59. package/dist/src/lang/zh-CN.js +107 -1
  60. package/dist/src/parser/eventParser.js +2 -0
  61. package/dist/src/parser/functionParser.js +96 -65
  62. package/dist/src/parser/index.js +7 -4
  63. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  64. package/dist/src/stack/aliyunStack/apigwPlanner.js +16 -10
  65. package/dist/src/stack/aliyunStack/apigwResource.js +334 -125
  66. package/dist/src/stack/aliyunStack/apigwTypes.js +35 -4
  67. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  68. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  69. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  70. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  71. package/dist/src/stack/aliyunStack/destroyer.js +27 -2
  72. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  73. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  74. package/dist/src/stack/aliyunStack/fc3Resource.js +416 -94
  75. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  76. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  77. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  78. package/dist/src/stack/aliyunStack/sharedLogProject.js +137 -0
  79. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  80. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  81. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  82. package/dist/src/stack/alreadyExists.js +26 -0
  83. package/dist/src/stack/ownershipTag.js +58 -0
  84. package/dist/src/stack/rfsStack/index.js +3 -1
  85. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  86. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  87. package/dist/src/stack/scfStack/cosResource.js +167 -64
  88. package/dist/src/stack/scfStack/deployer.js +2 -2
  89. package/dist/src/stack/scfStack/destroyer.js +15 -2
  90. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  91. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  92. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  93. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  94. package/dist/src/stack/scfStack/scfPlanner.js +21 -3
  95. package/dist/src/stack/scfStack/scfResource.js +686 -24
  96. package/dist/src/stack/scfStack/scfTypes.js +6 -0
  97. package/dist/src/stack/scfStack/sharedLogset.js +126 -0
  98. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  99. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  100. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  101. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  102. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  103. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  104. package/dist/src/stack/volcengineStack/apigwResource.js +434 -222
  105. package/dist/src/stack/volcengineStack/apigwTypes.js +85 -66
  106. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  107. package/dist/src/stack/volcengineStack/destroyer.js +13 -1
  108. package/dist/src/stack/volcengineStack/index.js +1 -2
  109. package/dist/src/stack/volcengineStack/sharedLogProject.js +190 -0
  110. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  111. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  112. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  113. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  114. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  115. package/dist/src/stack/volcengineStack/vefaasPlanner.js +78 -2
  116. package/dist/src/stack/volcengineStack/vefaasResource.js +194 -144
  117. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  118. package/dist/src/types/domains/backend.js +1 -0
  119. package/dist/src/types/domains/state.js +32 -1
  120. package/dist/src/validator/eventSchema.js +10 -0
  121. package/dist/src/validator/functionSchema.js +37 -12
  122. package/dist/src/validator/iacSchema.js +1 -0
  123. package/dist/tsconfig.tsbuildinfo +1 -1
  124. package/package.json +5 -2
@@ -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;
@@ -11,8 +11,11 @@ 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, app, service, stage) => (state) => {
15
- backend.saveState(state, app, service, stage);
14
+ const tencentClient_1 = require("../../common/tencentClient");
15
+ const stateManager_1 = require("../../common/stateManager");
16
+ const sharedLogset_1 = require("./sharedLogset");
17
+ const createSaveStateFn = (backend, app, service, stage) => async (state) => {
18
+ await backend.saveState(state, app, service, stage);
16
19
  };
17
20
  const handlePartialFailure = (failure) => {
18
21
  const error = failure.error;
@@ -86,6 +89,16 @@ const destroyTencentStack = async (backend) => {
86
89
  ],
87
90
  });
88
91
  }
92
+ // Release the shared CLS logset once no topics reference it anymore. The
93
+ // per-function teardowns above deleted their own topics, so a logset with
94
+ // zero remaining topics is safe to delete.
95
+ const sharedLogset = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY);
96
+ if (sharedLogset) {
97
+ const releaseResult = await (0, sharedLogset_1.releaseSharedLogsetIfUnused)(context, (0, tencentClient_1.createTencentClient)(context), sharedLogset);
98
+ if (releaseResult === 'deleted') {
99
+ state = (0, stateManager_1.removeSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY);
100
+ }
101
+ }
89
102
  await backend.saveState(state, context.app, context.service, context.stage);
90
103
  };
91
104
  exports.destroyTencentStack = destroyTencentStack;
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeEsPlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const esServerlessResource_1 = require("./esServerlessResource");
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, database, currentState) => {
@@ -87,13 +89,26 @@ const executeEsPlan = async (context, plan, databases, initialState, onStateChan
87
89
  const successfulItems = [];
88
90
  let currentState = initialState;
89
91
  for (const item of plan.items) {
92
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
93
+ type: 'resource_pre',
94
+ logicalId: item.logicalId,
95
+ resourceType: item.resourceType,
96
+ action: item.action,
97
+ ...(item.drifted ? { message: 'resource drifted' } : {}),
98
+ });
99
+ const __siStartedAt = Date.now();
90
100
  try {
91
101
  const newState = await executeSingleItem(context, item, databasesMap, currentState);
92
102
  if (newState !== null) {
93
103
  currentState = newState;
94
104
  successfulItems.push(item);
105
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
106
+ type: 'resource_complete',
107
+ logicalId: item.logicalId,
108
+ durationMs: Date.now() - __siStartedAt,
109
+ });
95
110
  if (onStateChange) {
96
- onStateChange(currentState);
111
+ await onStateChange(currentState);
97
112
  common_1.logger.debug(lang_1.lang.__('STATE_PERSISTED_AFTER_OPERATION', {
98
113
  action: item.action,
99
114
  resourceId: item.logicalId,
@@ -102,6 +117,29 @@ const executeEsPlan = async (context, plan, databases, initialState, onStateChan
102
117
  }
103
118
  }
104
119
  catch (error) {
120
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
121
+ type: 'resource_failed',
122
+ logicalId: item.logicalId,
123
+ severity: 'error',
124
+ durationMs: Date.now() - __siStartedAt,
125
+ error: {
126
+ message: error instanceof Error ? error.message : String(error),
127
+ },
128
+ });
129
+ if (error instanceof types_1.PartialResourceError) {
130
+ const updatedState = error.updatedState;
131
+ if (onStateChange) {
132
+ await onStateChange(updatedState);
133
+ }
134
+ return {
135
+ state: updatedState,
136
+ partialFailure: {
137
+ failedItem: item,
138
+ error: error.cause,
139
+ successfulItems,
140
+ },
141
+ };
142
+ }
105
143
  return {
106
144
  state: currentState,
107
145
  partialFailure: {
@@ -5,6 +5,7 @@ const tencentClient_1 = require("../../common/tencentClient");
5
5
  const esServerlessTypes_1 = require("./esServerlessTypes");
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 planEsDeletion = (logicalId, definition) => ({
9
10
  logicalId,
10
11
  action: 'delete',
@@ -29,7 +30,16 @@ const generateEsPlan = async (context, state, databases) => {
29
30
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
30
31
  const config = (0, esServerlessTypes_1.databaseToTencentEsConfig)(database);
31
32
  const desiredDefinition = (0, esServerlessTypes_1.extractTencentEsDefinition)(config);
32
- if (!currentState) {
33
+ if (!currentState || currentState.status === 'tainted') {
34
+ // No usable local state: probe the provider before planning create.
35
+ // If a same-named space already exists WITHOUT our ownership tag it may
36
+ // belong to another project — fail fast in the plan instead of letting
37
+ // the executor discover it mid-deploy.
38
+ const client = (0, tencentClient_1.createTencentClient)(context);
39
+ const remoteSpace = await client.es.getSpaceByName(config.SpaceName);
40
+ if (remoteSpace && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteSpace.Tags)) {
41
+ throw new Error(`ES space ${config.SpaceName} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
42
+ }
33
43
  return {
34
44
  logicalId,
35
45
  action: 'create',
@@ -1,12 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteEsResource = exports.updateEsResource = exports.readEsResource = exports.createEsResource = void 0;
4
+ const types_1 = require("../../types");
4
5
  const tencentClient_1 = require("../../common/tencentClient");
5
6
  const esServerlessTypes_1 = require("./esServerlessTypes");
6
7
  const stateManager_1 = require("../../common/stateManager");
7
8
  const common_1 = require("../../common");
8
9
  const logger_1 = require("../../common/logger");
9
10
  const lang_1 = require("../../lang");
11
+ const ownershipTag_1 = require("../ownershipTag");
12
+ const alreadyExists_1 = require("../alreadyExists");
13
+ // CreateServerlessSpaceV2 reports a duplicate space name with this error code
14
+ // (腾讯云官方文档: 空间名已存在).
15
+ const ES_SPACE_NAME_EXISTS_CODE = 'InvalidParameter.SpaceNameExist';
10
16
  const buildEsSpaceFromProvider = (info, sid) => {
11
17
  return {
12
18
  sid,
@@ -18,40 +24,99 @@ const buildEsSpaceFromProvider = (info, sid) => {
18
24
  indexCount: info.IndexCount ?? null,
19
25
  kibanaUrl: info.KibanaUrl ?? null,
20
26
  kibanaPrivateUrl: info.KibanaPrivateUrl ?? null,
27
+ indexAccessUrl: info.IndexAccessUrl ?? null,
28
+ kibanaPublicAcl: info.KibanaPublicAcl
29
+ ? {
30
+ blackIpList: info.KibanaPublicAcl.BlackIpList ?? [],
31
+ whiteIpList: info.KibanaPublicAcl.WhiteIpList ?? [],
32
+ }
33
+ : {},
34
+ kibanaEmbedUrl: info.KibanaEmbedUrl ?? null,
35
+ diDataList: info.DiDataList ?? [],
36
+ vpcInfo: info.VpcInfo?.map((v) => ({
37
+ vpcId: v.VpcId ?? null,
38
+ subnetId: v.SubnetId ?? null,
39
+ vpcUid: v.VpcUid ?? null,
40
+ subnetUid: v.SubnetUid ?? null,
41
+ availableIpAddressCount: v.AvailableIpAddressCount ?? null,
42
+ })) ?? [],
43
+ region: info.Region ?? null,
44
+ zone: info.Zone ?? null,
45
+ enableKibanaPublicAccess: info.EnableKibanaPublicAccess ?? null,
46
+ enableKibanaPrivateAccess: info.EnableKibanaPrivateAccess ?? null,
47
+ appId: info.AppId ?? null,
48
+ kibanaLanguage: info.KibanaLanguage ?? null,
49
+ clusterType: info.ClusterType ?? null,
50
+ enableMcpAccess: info.EnableMcpAccess ?? null,
51
+ mcpAccess: info.McpAccess ?? null,
52
+ tags: info.Tags?.map((t) => ({
53
+ key: t.Key,
54
+ value: t.Value,
55
+ })) ?? [],
21
56
  };
22
57
  };
23
58
  const createEsResource = async (context, database, state) => {
24
59
  const config = (0, esServerlessTypes_1.databaseToTencentEsConfig)(database);
25
60
  const client = (0, tencentClient_1.createTencentClient)(context);
26
- const spaceId = await client.es.createSpace({
27
- SpaceName: config.SpaceName,
28
- VpcInfo: config.VpcId && config.SubnetId
29
- ? [{ VpcId: config.VpcId, SubnetId: config.SubnetId }]
30
- : undefined,
31
- Zone: config.Zone,
32
- KibanaWhiteIpList: config.KibanaWhiteIpList,
33
- });
34
- // Refresh state from provider to get all attributes
35
- const spaceInfo = await client.es.getSpace(spaceId);
36
- if (!spaceInfo) {
37
- throw new Error(`Failed to refresh state for ES space: ${spaceId}`);
38
- }
39
61
  const definition = (0, esServerlessTypes_1.extractTencentEsDefinition)(config);
40
- const sid = (0, common_1.buildSid)('tencent', 'es', context.stage, spaceId);
41
- const resourceState = {
62
+ const logicalId = `databases.${database.key}`;
63
+ const taintedResourceState = {
42
64
  mode: 'managed',
43
65
  region: context.region,
44
66
  definition,
45
- instances: [buildEsSpaceFromProvider(spaceInfo, sid)],
67
+ instances: [],
46
68
  lastUpdated: new Date().toISOString(),
47
- metadata: {
48
- spaceName: database.name,
49
- spaceId,
50
- resourceType: 'TENCENT_ES_SERVERLESS',
51
- },
69
+ status: 'tainted',
52
70
  };
53
- const logicalId = `databases.${database.key}`;
54
- return (0, stateManager_1.setResource)(state, logicalId, resourceState);
71
+ const stateAfterDependents = (0, stateManager_1.setResource)(state, logicalId, taintedResourceState);
72
+ const buildResourceState = (info) => {
73
+ const sid = (0, common_1.buildSid)('tencent', 'es', context.stage, info.SpaceId);
74
+ return {
75
+ mode: 'managed',
76
+ region: context.region,
77
+ definition,
78
+ instances: [buildEsSpaceFromProvider(info, sid)],
79
+ lastUpdated: new Date().toISOString(),
80
+ metadata: {
81
+ spaceName: database.name,
82
+ spaceId: info.SpaceId,
83
+ resourceType: 'TENCENT_ES_SERVERLESS',
84
+ },
85
+ };
86
+ };
87
+ try {
88
+ const spaceId = await client.es.createSpace({
89
+ SpaceName: config.SpaceName,
90
+ VpcInfo: config.VpcId && config.SubnetId
91
+ ? [{ VpcId: config.VpcId, SubnetId: config.SubnetId }]
92
+ : undefined,
93
+ Zone: config.Zone,
94
+ KibanaWhiteIpList: config.KibanaWhiteIpList,
95
+ Tags: [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }],
96
+ });
97
+ // Refresh state from provider to get all attributes
98
+ const spaceInfo = await client.es.getSpace(spaceId);
99
+ if (!spaceInfo) {
100
+ throw new Error(`Failed to refresh state for ES space: ${spaceId}`);
101
+ }
102
+ return (0, stateManager_1.setResource)(state, logicalId, buildResourceState(spaceInfo));
103
+ }
104
+ catch (error) {
105
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error, [ES_SPACE_NAME_EXISTS_CODE])) {
106
+ // Idempotent adoption: a space with this name already exists in the
107
+ // provider. Adopt it ONLY if it carries our ownership tag (proves a
108
+ // previous run of THIS stack created it — e.g. state was reset). An
109
+ // untagged same-named space may belong to another project, so it must
110
+ // fail loudly rather than silently taking it over.
111
+ const probe = await client.es.getSpaceByName(config.SpaceName);
112
+ if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
113
+ logger_1.logger.info(`ES space ${config.SpaceName} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
114
+ return (0, stateManager_1.setResource)(state, logicalId, buildResourceState(probe));
115
+ }
116
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(`ES space ${config.SpaceName} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to adopt — resolve manually.`));
117
+ }
118
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
119
+ }
55
120
  };
56
121
  exports.createEsResource = createEsResource;
57
122
  const readEsResource = async (context, spaceId) => {
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeFunctionPlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const scfResource_1 = require("./scfResource");
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, fn, currentState) => {
@@ -61,13 +63,26 @@ const executeFunctionPlan = async (context, plan, functions, initialState, onSta
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, functionsMap, 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 executeFunctionPlan = async (context, plan, functions, initialState, onSta
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,8 @@ const tencentClient_1 = require("../../common/tencentClient");
5
5
  const scfTypes_1 = require("./scfTypes");
6
6
  const stateManager_1 = require("../../common/stateManager");
7
7
  const hashUtils_1 = require("../../common/hashUtils");
8
+ const ownershipTag_1 = require("../ownershipTag");
9
+ const sharedLogset_1 = require("./sharedLogset");
8
10
  const planFunctionDeletion = (logicalId, definition) => ({
9
11
  logicalId,
10
12
  action: 'delete',
@@ -23,11 +25,27 @@ const generateFunctionPlan = async (context, state, functions) => {
23
25
  const functionItems = await Promise.all(functions.map(async (fn) => {
24
26
  const logicalId = `functions.${fn.key}`;
25
27
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
26
- const config = (0, scfTypes_1.functionToScfConfig)(fn);
28
+ let config = (0, scfTypes_1.functionToScfConfig)(fn);
29
+ if (fn.log) {
30
+ config = {
31
+ ...config,
32
+ ClsLogsetName: (0, sharedLogset_1.buildSharedLogsetName)(context.app, context.stage),
33
+ ClsTopicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
34
+ };
35
+ }
27
36
  const codePath = fn.code.path;
28
- const desiredCodeHash = (0, hashUtils_1.computeFileHash)(codePath);
37
+ const desiredCodeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
29
38
  const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, desiredCodeHash, fn.iam);
30
- if (!currentState) {
39
+ if (!currentState || currentState.status === 'tainted') {
40
+ // No usable local state: probe the provider before planning create.
41
+ // If a same-named function already exists WITHOUT our ownership tag it
42
+ // may belong to another project — fail fast in the plan instead of
43
+ // letting the executor discover it mid-deploy.
44
+ const client = (0, tencentClient_1.createTencentClient)(context);
45
+ const remoteFunction = await client.scf.getFunction(fn.name);
46
+ if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.Tags)) {
47
+ throw new Error(`Function ${fn.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
48
+ }
31
49
  return {
32
50
  logicalId,
33
51
  action: 'create',