@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
@@ -11,11 +11,94 @@ const constants_1 = require("../../common/constants");
11
11
  const hashUtils_1 = require("../../common/hashUtils");
12
12
  const logger_1 = require("../../common/logger");
13
13
  const lang_1 = require("../../lang");
14
+ const ownershipTag_1 = require("../ownershipTag");
15
+ const alreadyExists_1 = require("../alreadyExists");
16
+ const sharedLogset_1 = require("./sharedLogset");
17
+ /**
18
+ * Build the Function URL trigger description for Tencent CreateTrigger
19
+ * (Type: 'http'). Format per official docs (创建函数 URL / Creating a Function
20
+ * URL): { AuthType, NetConfig: { EnableIntranet, EnableExtranet } }.
21
+ * AuthType is the mapAuthType result ('NONE' = no auth, 'CAM' = CAM auth);
22
+ * the API Gateway trigger format ({ api/service/release }) is obsolete —
23
+ * Tencent shut down new API Gateway triggers on 2024-07-01.
24
+ */
25
+ const buildTencentTriggerDesc = (authType, netConfig) => JSON.stringify({
26
+ AuthType: authType,
27
+ NetConfig: {
28
+ EnableIntranet: netConfig.enableIntranet ?? false,
29
+ EnableExtranet: netConfig.enableExtranet ?? true,
30
+ },
31
+ });
32
+ // Tencent names Function URL triggers with a random id (e.g. "5obtzwwxw1"), not
33
+ // our ${fn.key}-http-trigger, so name-based matching never finds them. A
34
+ // Function URL trigger is identified by Type 'http' + a TriggerDesc carrying
35
+ // the NetConfig field (the API Gateway flavor uses api/service/release instead).
36
+ const isFunctionUrlTrigger = (t) => t.Type === 'http' && typeof t.TriggerDesc === 'string' && t.TriggerDesc.includes('NetConfig');
37
+ /**
38
+ * Best-effort extraction of a cloud-SDK error's useful details. Tencent SDK
39
+ * errors carry `code`/`message`/`requestId` (and may throw with an empty
40
+ * `message`), so we compose them into a non-empty, diagnosable string —
41
+ * otherwise a PartialResourceError surfaces as a blank failure line.
42
+ */
43
+ const toErrorMessage = (error) => {
44
+ if (error instanceof Error && error.message) {
45
+ return error.message;
46
+ }
47
+ if (error && typeof error === 'object') {
48
+ const parts = [];
49
+ const rec = error;
50
+ if (typeof rec.code === 'string' && rec.code)
51
+ parts.push(rec.code);
52
+ if (typeof rec.message === 'string' && rec.message)
53
+ parts.push(rec.message);
54
+ if (typeof rec.requestId === 'string' && rec.requestId)
55
+ parts.push(`requestId=${rec.requestId}`);
56
+ if (parts.length > 0)
57
+ return parts.join(' · ');
58
+ }
59
+ return String(error) || 'unknown error';
60
+ };
14
61
  const delay = async (ms) => {
15
62
  await new Promise((resolve) => {
16
63
  setTimeout(resolve, ms);
17
64
  });
18
65
  };
66
+ // Delay before probing the provider after a recoverable create error — the
67
+ // platform may still be propagating a just-created function.
68
+ const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
69
+ // Create errors recoverable by reconciling with provider state. Deliberately
70
+ // limited to timeout/network conditions. A create-time "already exists" (Tencent
71
+ // reports ResourceInUse with a localized message "指定的Function已存在,请勿重复创建")
72
+ // is NOT recoverable on the non-tainted path: the cloud resource may not be owned
73
+ // by this stack, so it must propagate as PartialResourceError (persisting tainted
74
+ // state) for the user to resolve manually — no auto-adopt (product decision D1).
75
+ // Only the tainted pre-flight path may adopt a pre-existing function.
76
+ const isRecoverableCreateError = (error) => {
77
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
78
+ ? error.code.toLowerCase()
79
+ : '';
80
+ const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
81
+ return (code === 'readtimeout' ||
82
+ code === 'timeout' ||
83
+ code === 'requesttimeout' ||
84
+ code === 'econnreset' ||
85
+ code === 'etimedout' ||
86
+ message.includes('readtimeout') ||
87
+ message.includes('timeout') ||
88
+ message.includes('socket hang up') ||
89
+ message.includes('econnreset') ||
90
+ message.includes('etimedout'));
91
+ };
92
+ // CLS destination drift is only meaningful when the desired config carries one —
93
+ // a log-enabled function whose stable destination names differ from state must
94
+ // re-push configuration so UpdateFunctionConfiguration rebinds the function.
95
+ const isLogConfigChanged = (desiredDefinition, existingDefinition) => {
96
+ const desiredLogConfig = desiredDefinition.logConfig;
97
+ if (!desiredLogConfig) {
98
+ return false;
99
+ }
100
+ return !(0, common_1.attributesEqual)(desiredLogConfig, existingDefinition.logConfig ?? {});
101
+ };
19
102
  const buildScfInstanceFromProvider = (info, sid) => {
20
103
  const envMap = info.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
21
104
  const triggersArray = info.Triggers?.map((t) => ({
@@ -41,6 +124,15 @@ const buildScfInstanceFromProvider = (info, sid) => {
41
124
  layerName: l.LayerName ?? null,
42
125
  layerVersion: l.LayerVersion ?? null,
43
126
  compatibleRuntimes: l.CompatibleRuntimes ?? [],
127
+ addTime: l.AddTime ?? null,
128
+ description: l.Description ?? null,
129
+ licenseInfo: l.LicenseInfo ?? null,
130
+ status: l.Status ?? null,
131
+ stamp: l.Stamp ?? null,
132
+ tags: l.Tags?.map((t) => ({
133
+ key: t.Key,
134
+ value: t.Value,
135
+ })) ?? [],
44
136
  }));
45
137
  return {
46
138
  sid,
@@ -140,6 +232,12 @@ const buildScfInstanceFromProvider = (info, sid) => {
140
232
  ? {
141
233
  imageType: info.ImageConfig.ImageType ?? null,
142
234
  imageUri: info.ImageConfig.ImageUri ?? null,
235
+ registryId: info.ImageConfig.RegistryId ?? null,
236
+ entryPoint: info.ImageConfig.EntryPoint ?? null,
237
+ command: info.ImageConfig.Command ?? null,
238
+ args: info.ImageConfig.Args ?? null,
239
+ containerImageAccelerate: info.ImageConfig.ContainerImageAccelerate ?? null,
240
+ imagePort: info.ImageConfig.ImagePort ?? null,
143
241
  }
144
242
  : {},
145
243
  protocolType: info.ProtocolType ?? null,
@@ -156,23 +254,88 @@ const buildScfInstanceFromProvider = (info, sid) => {
156
254
  intranetConfig: info.IntranetConfig
157
255
  ? {
158
256
  ipFixed: info.IntranetConfig.IpFixed ?? null,
257
+ ipAddress: info.IntranetConfig.IpAddress ?? [],
258
+ }
259
+ : {},
260
+ instanceConcurrencyConfig: info.InstanceConcurrencyConfig
261
+ ? {
262
+ dynamicEnabled: info.InstanceConcurrencyConfig.DynamicEnabled ?? null,
263
+ maxConcurrency: info.InstanceConcurrencyConfig.MaxConcurrency ?? null,
264
+ instanceIsolationEnabled: info.InstanceConcurrencyConfig.InstanceIsolationEnabled ?? null,
265
+ type: info.InstanceConcurrencyConfig.Type ?? null,
266
+ mixNodeConfig: info.InstanceConcurrencyConfig.MixNodeConfig ?? [],
267
+ sessionConfig: info.InstanceConcurrencyConfig.SessionConfig ?? {},
159
268
  }
160
269
  : {},
161
270
  };
162
271
  };
163
- const createDependentResources = async (context, fn, existingInstances = []) => {
272
+ const createDependentResources = async (context, fn, existingInstances = [], state) => {
164
273
  const client = (0, tencentClient_1.createTencentClient)(context);
274
+ const clsInstances = [];
275
+ let clsConfig;
276
+ let sharedInstance;
277
+ if (fn.log) {
278
+ const topicInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC);
279
+ const logsetInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET);
280
+ if (topicInstance && logsetInstance) {
281
+ clsConfig = {
282
+ logsetId: logsetInstance.logsetId ?? '',
283
+ logsetName: logsetInstance.id,
284
+ topicId: topicInstance.id,
285
+ topicName: topicInstance.topicName ?? topicInstance.id,
286
+ };
287
+ clsInstances.push(logsetInstance, topicInstance);
288
+ }
289
+ else {
290
+ const legacyFn = existingInstances.find((i) => i.type === undefined);
291
+ if (legacyFn?.clsLogsetId && legacyFn?.clsTopicId) {
292
+ clsConfig = {
293
+ logsetId: legacyFn.clsLogsetId,
294
+ logsetName: (0, sharedLogset_1.buildSharedLogsetName)(context.app, context.stage),
295
+ topicId: legacyFn.clsTopicId,
296
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
297
+ };
298
+ }
299
+ else {
300
+ const shared = await (0, sharedLogset_1.ensureSharedLogset)(context, client, state);
301
+ sharedInstance = (0, sharedLogset_1.buildSharedLogsetResourceState)(context, shared);
302
+ const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
303
+ logsetId: shared.logsetId,
304
+ logsetName: shared.logsetName,
305
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
306
+ logicalId: `functions.${fn.key}`,
307
+ });
308
+ clsInstances.push({
309
+ sid: (0, common_1.buildSid)('tencent', 'cls-logset', context.stage, shared.logsetName),
310
+ type: types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET,
311
+ id: shared.logsetName,
312
+ logsetId: shared.logsetId,
313
+ }, {
314
+ sid: (0, common_1.buildSid)('tencent', 'cls-topic', context.stage, topic.topicName),
315
+ type: types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC,
316
+ id: topic.topicId,
317
+ topicName: topic.topicName,
318
+ });
319
+ clsConfig = {
320
+ logsetId: shared.logsetId,
321
+ logsetName: shared.logsetName,
322
+ topicId: topic.topicId,
323
+ topicName: topic.topicName,
324
+ };
325
+ }
326
+ }
327
+ }
165
328
  const iamConfig = fn.iam?.role;
166
329
  // No IAM role configured - skip
167
330
  if (!iamConfig) {
168
- return {};
331
+ return { clsConfig, clsInstances, sharedInstance };
169
332
  }
170
333
  const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
171
334
  const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
172
335
  const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
173
336
  // External role (string) - skip creation, use ARN directly
174
337
  if (typeof iamConfig === 'string') {
175
- return { role: { roleName: '', arn: iamConfig } };
338
+ return { role: { roleName: '', arn: iamConfig }, clsConfig, clsInstances, sharedInstance };
176
339
  }
177
340
  const hasCamRole = existingInstances.some((i) => i.type === 'TENCENT_SCF_ROLE');
178
341
  const serviceName = `${context.app}-${context.service}`;
@@ -180,14 +343,19 @@ const createDependentResources = async (context, fn, existingInstances = []) =>
180
343
  const roleName = customRoleName ?? defaultRoleName;
181
344
  if (hasCamRole) {
182
345
  // Role already exists - reuse it
183
- return { role: { roleName, arn: roleName } };
346
+ return { role: { roleName, arn: roleName }, clsConfig, clsInstances, sharedInstance };
184
347
  }
185
348
  // Create new CAM role
186
- const trustedServices = ['scf.tencentcloudapi.com'];
349
+ const trustedServices = ['scf.qcloud.com'];
187
350
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
188
351
  const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies);
189
352
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
190
- return { role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName } };
353
+ return {
354
+ role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName },
355
+ clsConfig,
356
+ clsInstances,
357
+ sharedInstance,
358
+ };
191
359
  };
192
360
  const deleteDependentResources = async (context, instances) => {
193
361
  const client = (0, tencentClient_1.createTencentClient)(context);
@@ -200,6 +368,15 @@ const deleteDependentResources = async (context, instances) => {
200
368
  await client.cam.deleteRole(instance.id);
201
369
  break;
202
370
  }
371
+ case types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC: {
372
+ logger_1.logger.info(lang_1.lang.__('DELETING_CLS_TOPIC', { id: instance.id }));
373
+ await client.cls.deleteTopic(instance.id);
374
+ break;
375
+ }
376
+ case types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET: {
377
+ // The shared CLS logset is released by the destroyer once no topics remain.
378
+ break;
379
+ }
203
380
  default:
204
381
  logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
205
382
  }
@@ -207,21 +384,35 @@ const deleteDependentResources = async (context, instances) => {
207
384
  };
208
385
  const createResource = async (context, fn, state) => {
209
386
  const logicalId = `functions.${fn.key}`;
387
+ // Fail config validation BEFORE any cloud operation or tainted-state write,
388
+ // so an invalid trigger config can never strand a partially-created resource.
389
+ if (fn.triggers?.http && !fn.triggers.http.auth_type) {
390
+ throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
391
+ }
210
392
  const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
211
- const existingDependentInstances = (existingResourceState?.instances ?? []).filter((i) => i.type !== undefined);
212
- const dependentResources = await createDependentResources(context, fn, existingDependentInstances);
393
+ const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state);
213
394
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
395
+ config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
214
396
  if (dependentResources.role) {
215
397
  config = {
216
398
  ...config,
217
399
  Role: dependentResources.role.arn,
218
400
  };
219
401
  }
402
+ if (dependentResources.clsConfig) {
403
+ config = {
404
+ ...config,
405
+ ClsLogsetId: dependentResources.clsConfig.logsetId,
406
+ ClsTopicId: dependentResources.clsConfig.topicId,
407
+ ClsLogsetName: dependentResources.clsConfig.logsetName,
408
+ ClsTopicName: dependentResources.clsConfig.topicName,
409
+ };
410
+ }
220
411
  const codePath = fn.code.path;
221
412
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
222
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
413
+ const codeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
223
414
  const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
224
- const dependentInstances = [];
415
+ const dependentInstances = [...dependentResources.clsInstances];
225
416
  if (dependentResources.role) {
226
417
  const iamConfig = fn.iam?.role;
227
418
  const isExternalRole = typeof iamConfig === 'string';
@@ -242,13 +433,149 @@ const createResource = async (context, fn, state) => {
242
433
  lastUpdated: new Date().toISOString(),
243
434
  status: 'tainted',
244
435
  };
245
- const stateAfterDependents = (0, stateManager_1.setResource)(state, logicalId, taintedResourceState);
436
+ const stateWithShared = dependentResources.sharedInstance
437
+ ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY, dependentResources.sharedInstance)
438
+ : state;
439
+ const stateAfterDependents = (0, stateManager_1.setResource)(stateWithShared, logicalId, taintedResourceState);
246
440
  const client = (0, tencentClient_1.createTencentClient)(context);
247
- await client.scf.createFunction(config, codeBase64);
248
- // Refresh state from provider to get all attributes
249
- const functionInfo = await client.scf.getFunction(fn.name);
441
+ const isTainted = existingResourceState?.status === 'tainted';
442
+ const existingFunctionOnRetry = isTainted ? await client.scf.getFunction(fn.name) : null;
443
+ // Provider info of a function adopted from a previous partial run (tainted
444
+ // retry or reconciled after a create error) — used to skip already-attached
445
+ // triggers below.
446
+ let adoptedInfo = existingFunctionOnRetry;
447
+ if (existingFunctionOnRetry) {
448
+ logger_1.logger.info(`Function ${fn.name} already exists in provider (tainted recovery), skipping create and refreshing state`);
449
+ }
450
+ try {
451
+ if (!existingFunctionOnRetry) {
452
+ // createFunction internally polls until the function is Active (see
453
+ // scfOperations) — triggers/domains below are safe to attach immediately.
454
+ await client.scf.createFunction(config, codeBase64);
455
+ }
456
+ }
457
+ catch (error) {
458
+ if (isRecoverableCreateError(error)) {
459
+ logger_1.logger.warn(`Create function returned recoverable error for ${fn.name}, reconciling with provider state: ${String(error)}`);
460
+ await delay(RECOVERY_GET_FUNCTION_DELAY_MS);
461
+ const afterError = await client.scf.getFunction(fn.name);
462
+ if (afterError) {
463
+ adoptedInfo = afterError;
464
+ logger_1.logger.info(`Function ${fn.name} found after create error reconciliation, continuing deployment flow`);
465
+ }
466
+ else {
467
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
468
+ }
469
+ }
470
+ else if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
471
+ // Idempotent adoption: the function already exists in the provider.
472
+ // Adopt it ONLY if it carries our ownership tag (proves a previous run
473
+ // of THIS stack created it — e.g. state was reset). An untagged
474
+ // same-named function may belong to another project, so it must fail
475
+ // loudly rather than silently taking it over (destroy would then remove
476
+ // a resource that was never ours).
477
+ const probe = await client.scf.getFunction(fn.name);
478
+ if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
479
+ adoptedInfo = probe;
480
+ logger_1.logger.info(`Function ${fn.name} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
481
+ }
482
+ else {
483
+ throw new types_1.PartialResourceError(stateAfterDependents, 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 adopt — resolve manually.`));
484
+ }
485
+ }
486
+ else {
487
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
488
+ }
489
+ }
490
+ // Create HTTP trigger if configured
491
+ if (fn.triggers?.http) {
492
+ const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, fn.triggers.http.auth_type);
493
+ const access = (0, common_1.mapAccess)(fn.triggers.http.access);
494
+ const triggerName = `${fn.key}-http-trigger`;
495
+ const triggerDesc = buildTencentTriggerDesc(authType, access);
496
+ // Probe the provider for an already-attached trigger BEFORE attempting to
497
+ // create it. A leftover trigger from a previous partial run (function exists
498
+ // in cloud, state blank) would otherwise collide with CreateTrigger and
499
+ // surface as a confusing empty error. Applies to both fresh creates (function
500
+ // just created — Triggers from the createFunction flow) and tainted retries.
501
+ let providerTriggers = adoptedInfo?.Triggers ?? [];
502
+ if (providerTriggers.length === 0) {
503
+ const probe = await client.scf.getFunction(fn.name);
504
+ if (probe) {
505
+ providerTriggers = probe.Triggers ?? [];
506
+ }
507
+ }
508
+ const triggerAlreadyAttached = providerTriggers.some(isFunctionUrlTrigger);
509
+ if (triggerAlreadyAttached) {
510
+ logger_1.logger.info(`HTTP trigger ${triggerName} already attached to ${fn.name}, skipping creation`);
511
+ }
512
+ else {
513
+ logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
514
+ try {
515
+ await client.scf.createTrigger({
516
+ FunctionName: fn.name,
517
+ TriggerName: triggerName,
518
+ Type: 'http',
519
+ TriggerDesc: triggerDesc,
520
+ Qualifier: '$DEFAULT',
521
+ Enable: 'OPEN',
522
+ });
523
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
524
+ }
525
+ catch (error) {
526
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
527
+ logger_1.logger.warn(`HTTP trigger ${triggerName} already exists on ${fn.name}, continuing: ${String(error)}`);
528
+ }
529
+ else {
530
+ // The function exists in the cloud but the trigger failed to attach —
531
+ // persist the tainted state so a re-run reconciles instead of losing it.
532
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
533
+ }
534
+ }
535
+ }
536
+ }
537
+ // Create custom domain if configured
538
+ if (fn.domain) {
539
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
540
+ try {
541
+ await client.scf.createCustomDomain({
542
+ Domain: fn.domain.domain_name,
543
+ Protocol: fn.domain.protocol,
544
+ EndpointsConfig: [
545
+ {
546
+ Namespace: 'default',
547
+ FunctionName: fn.name,
548
+ Qualifier: '$DEFAULT',
549
+ PathMatch: '/*',
550
+ },
551
+ ],
552
+ ...(fn.domain.certificate_id
553
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
554
+ : {}),
555
+ });
556
+ }
557
+ catch (error) {
558
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
559
+ }
560
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
561
+ const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
562
+ dependentInstances.push({
563
+ sid: domainSid,
564
+ type: 'TENCENT_SCF_CUSTOM_DOMAIN',
565
+ id: fn.domain.domain_name,
566
+ protocol: fn.domain.protocol,
567
+ });
568
+ }
569
+ // Refresh state from provider to get all attributes (including triggers)
570
+ let functionInfo;
571
+ try {
572
+ functionInfo = await client.scf.getFunction(fn.name);
573
+ }
574
+ catch (error) {
575
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
576
+ }
250
577
  if (!functionInfo) {
251
- throw new Error(`Failed to refresh state for function: ${fn.name}`);
578
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(`Failed to refresh state for function: ${fn.name}`));
252
579
  }
253
580
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
254
581
  const resourceState = {
@@ -274,6 +601,15 @@ const updateResource = async (context, fn, state) => {
274
601
  const logicalId = `functions.${fn.key}`;
275
602
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
276
603
  const existingInstances = (existingState?.instances ?? []);
604
+ const existingFnInstance = existingInstances.find((i) => i.type === undefined);
605
+ const existingClsTopicInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC);
606
+ const existingDefinition = (existingState?.definition ?? {});
607
+ const legacyLogsetId = existingFnInstance?.clsLogsetId;
608
+ const legacyTopicId = existingFnInstance?.clsTopicId;
609
+ // Log is bound via the unified flow (definition.logConfig) or legacy CLS ids
610
+ // stored directly on the function instance.
611
+ const wasLogEnabled = Boolean(existingDefinition.logConfig?.logset ||
612
+ (legacyLogsetId && legacyTopicId));
277
613
  const hasCamRole = existingInstances.some((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE);
278
614
  const client = (0, tencentClient_1.createTencentClient)(context);
279
615
  const newIamRole = fn.iam?.role;
@@ -324,23 +660,284 @@ const updateResource = async (context, fn, state) => {
324
660
  Role: role.arn,
325
661
  };
326
662
  }
663
+ let clsConfig;
664
+ let clsTopicInstance;
665
+ let clsSharedInstance;
666
+ const disableLog = !fn.log && wasLogEnabled;
667
+ let topicToDelete;
668
+ let topicNameToDelete;
669
+ let sharedLogsetReleased = false;
670
+ if (fn.log) {
671
+ if (legacyLogsetId && legacyTopicId) {
672
+ clsConfig = {
673
+ logsetId: legacyLogsetId,
674
+ logsetName: (0, sharedLogset_1.buildSharedLogsetName)(context.app, context.stage),
675
+ topicId: legacyTopicId,
676
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
677
+ };
678
+ }
679
+ else {
680
+ const sharedBefore = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY);
681
+ const logset = await (0, sharedLogset_1.ensureSharedLogset)(context, client, state);
682
+ if (!sharedBefore) {
683
+ clsSharedInstance = (0, sharedLogset_1.buildSharedLogsetResourceState)(context, logset);
684
+ }
685
+ const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
686
+ logsetId: logset.logsetId,
687
+ logsetName: logset.logsetName,
688
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
689
+ logicalId,
690
+ });
691
+ clsConfig = {
692
+ logsetId: logset.logsetId,
693
+ logsetName: logset.logsetName,
694
+ topicId: topic.topicId,
695
+ topicName: topic.topicName,
696
+ };
697
+ clsTopicInstance = {
698
+ sid: (0, common_1.buildSid)('tencent', 'cls-topic', context.stage, topic.topicName),
699
+ type: types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC,
700
+ id: topic.topicId,
701
+ topicName: topic.topicName,
702
+ };
703
+ }
704
+ }
705
+ else if (disableLog) {
706
+ // Log was enabled and is now disabled: clear the CLS binding so
707
+ // UpdateFunctionConfiguration unbinds the function, and tear down the
708
+ // function's CLS topic (index first, then topic) below.
709
+ config = {
710
+ ...config,
711
+ ClsLogsetId: '',
712
+ ClsTopicId: '',
713
+ };
714
+ topicToDelete = existingClsTopicInstance?.id ?? legacyTopicId;
715
+ topicNameToDelete = existingClsTopicInstance?.topicName ?? (0, sharedLogset_1.buildFunctionTopicName)(context);
716
+ }
717
+ if (clsConfig) {
718
+ config = {
719
+ ...config,
720
+ ClsLogsetId: clsConfig.logsetId,
721
+ ClsTopicId: clsConfig.topicId,
722
+ ClsLogsetName: clsConfig.logsetName,
723
+ ClsTopicName: clsConfig.topicName,
724
+ };
725
+ }
327
726
  const codePath = fn.code.path;
328
727
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
329
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
330
- // Update configuration
331
- await client.scf.updateFunctionConfiguration(config);
728
+ const codeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
729
+ // Only push configuration when the mutable config fields actually changed —
730
+ // Tencent's UpdateFunctionConfiguration rejects Handler/Runtime (immutable at
731
+ // creation) and we don't want to re-send unchanged values. Handler/Runtime
732
+ // changes are a hard error: the platform cannot apply them on update.
733
+ const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
734
+ const CONFIG_DIFF_KEYS = ['runtime', 'handler', 'memorySize', 'timeout', 'environment', 'role'];
735
+ const mutableKeys = CONFIG_DIFF_KEYS.filter((k) => k !== 'runtime' && k !== 'handler');
736
+ if (desiredDefinition.handler &&
737
+ existingDefinition.handler &&
738
+ desiredDefinition.handler !== existingDefinition.handler) {
739
+ throw new Error(`Handler is immutable in Tencent SCF and cannot be changed on update (${String(existingDefinition.handler)} -> ${String(desiredDefinition.handler)}). Delete and recreate the function instead.`);
740
+ }
741
+ if (desiredDefinition.runtime &&
742
+ existingDefinition.runtime &&
743
+ desiredDefinition.runtime !== existingDefinition.runtime) {
744
+ throw new Error(`Runtime is immutable in Tencent SCF and cannot be changed on update (${String(existingDefinition.runtime)} -> ${String(desiredDefinition.runtime)}). Delete and recreate the function instead.`);
745
+ }
746
+ const configChanged = mutableKeys.some((k) => desiredDefinition[k] !== existingDefinition[k]) ||
747
+ isLogConfigChanged(desiredDefinition, existingDefinition) ||
748
+ // Disabling log always re-pushes config so the empty Cls ids reach the
749
+ // UpdateFunctionConfiguration unbind contract.
750
+ disableLog;
751
+ if (configChanged) {
752
+ await client.scf.updateFunctionConfiguration(config);
753
+ }
754
+ if (disableLog) {
755
+ // Unbind (above), then delete index before topic so the logset releases.
756
+ if (topicToDelete) {
757
+ logger_1.logger.info(lang_1.lang.__('DELETING_CLS_INDEX', { topicName: topicNameToDelete ?? topicToDelete }));
758
+ await client.cls.deleteIndex(topicToDelete);
759
+ logger_1.logger.info(lang_1.lang.__('DELETING_CLS_TOPIC', { id: topicToDelete }));
760
+ await client.cls.deleteTopic(topicToDelete);
761
+ }
762
+ const sharedBefore = (0, stateManager_1.getSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY);
763
+ if (sharedBefore) {
764
+ const release = await (0, sharedLogset_1.releaseSharedLogsetIfUnused)(context, client, sharedBefore);
765
+ if (release === 'deleted') {
766
+ sharedLogsetReleased = true;
767
+ }
768
+ }
769
+ logger_1.logger.info(lang_1.lang.__('CLS_LOG_DISABLED', { functionName: fn.name }));
770
+ }
332
771
  // Update code
333
772
  await client.scf.updateFunctionCode(fn.name, codeBase64);
334
- // Refresh state from provider to get all attributes
773
+ const existingHttpTrigger = existingFnInstance?.triggers?.find((t) => t.type === 'http');
774
+ const desiredHttpConfig = fn.triggers?.http;
775
+ if (desiredHttpConfig) {
776
+ if (!desiredHttpConfig.auth_type) {
777
+ throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
778
+ }
779
+ const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, desiredHttpConfig.auth_type);
780
+ const access = (0, common_1.mapAccess)(desiredHttpConfig.access);
781
+ const triggerName = `${fn.key}-http-trigger`;
782
+ const desiredTriggerDesc = buildTencentTriggerDesc(authType, access);
783
+ if (existingHttpTrigger) {
784
+ if (existingHttpTrigger.triggerDesc !== desiredTriggerDesc) {
785
+ logger_1.logger.info(lang_1.lang.__('UPDATING_HTTP_TRIGGER', { functionName: fn.name }));
786
+ try {
787
+ await client.scf.deleteTrigger({
788
+ FunctionName: fn.name,
789
+ TriggerName: existingHttpTrigger.triggerName,
790
+ Type: 'http',
791
+ });
792
+ }
793
+ catch (err) {
794
+ const errorCode = err?.code;
795
+ if (errorCode !== 'ResourceNotFound.TriggerName' && errorCode !== 'ResourceNotFound') {
796
+ throw err;
797
+ }
798
+ }
799
+ await client.scf.createTrigger({
800
+ FunctionName: fn.name,
801
+ TriggerName: triggerName,
802
+ Type: 'http',
803
+ TriggerDesc: desiredTriggerDesc,
804
+ Qualifier: '$DEFAULT',
805
+ Enable: 'OPEN',
806
+ });
807
+ }
808
+ }
809
+ else {
810
+ // No trigger recorded in state — but a leftover trigger may still exist
811
+ // in the provider (e.g. adopted function whose state lacked trigger
812
+ // records). Probe before creating to stay idempotent.
813
+ const probe = await client.scf.getFunction(fn.name);
814
+ const providerTriggerAttached = (probe?.Triggers ?? []).some(isFunctionUrlTrigger);
815
+ if (providerTriggerAttached) {
816
+ logger_1.logger.info(`HTTP trigger ${triggerName} already attached to ${fn.name}, skipping creation`);
817
+ }
818
+ else {
819
+ logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
820
+ try {
821
+ await client.scf.createTrigger({
822
+ FunctionName: fn.name,
823
+ TriggerName: triggerName,
824
+ Type: 'http',
825
+ TriggerDesc: desiredTriggerDesc,
826
+ Qualifier: '$DEFAULT',
827
+ Enable: 'OPEN',
828
+ });
829
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
830
+ }
831
+ catch (error) {
832
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
833
+ logger_1.logger.warn(`HTTP trigger ${triggerName} already exists on ${fn.name}, continuing: ${String(error)}`);
834
+ }
835
+ else {
836
+ throw error;
837
+ }
838
+ }
839
+ }
840
+ }
841
+ }
842
+ else if (existingHttpTrigger) {
843
+ const tName = existingHttpTrigger.triggerName;
844
+ logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: tName, functionName: fn.name }));
845
+ try {
846
+ await client.scf.deleteTrigger({
847
+ FunctionName: fn.name,
848
+ TriggerName: tName,
849
+ Type: 'http',
850
+ });
851
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName: tName }));
852
+ }
853
+ catch (err) {
854
+ const errorCode = err?.code;
855
+ if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
856
+ logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: tName }));
857
+ }
858
+ else {
859
+ throw err;
860
+ }
861
+ }
862
+ }
863
+ // Reconcile custom domain
864
+ const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
865
+ if (fn.domain && !existingCustomDomain) {
866
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
867
+ await client.scf.createCustomDomain({
868
+ Domain: fn.domain.domain_name,
869
+ Protocol: fn.domain.protocol,
870
+ EndpointsConfig: [
871
+ {
872
+ Namespace: 'default',
873
+ FunctionName: fn.name,
874
+ Qualifier: '$DEFAULT',
875
+ PathMatch: '/*',
876
+ },
877
+ ],
878
+ ...(fn.domain.certificate_id
879
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
880
+ : {}),
881
+ });
882
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
883
+ }
884
+ else if (!fn.domain && existingCustomDomain) {
885
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
886
+ try {
887
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
888
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
889
+ }
890
+ catch (err) {
891
+ const errorCode = err?.code;
892
+ if (errorCode === 'ResourceNotFound') {
893
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
894
+ resourceType: 'Custom Domain',
895
+ name: existingCustomDomain.id,
896
+ }));
897
+ }
898
+ else {
899
+ throw err;
900
+ }
901
+ }
902
+ }
903
+ else if (fn.domain && existingCustomDomain) {
904
+ const domainChanged = fn.domain.domain_name !== existingCustomDomain.id ||
905
+ fn.domain.protocol !== existingCustomDomain.protocol;
906
+ if (domainChanged) {
907
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
908
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
909
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
910
+ await client.scf.createCustomDomain({
911
+ Domain: fn.domain.domain_name,
912
+ Protocol: fn.domain.protocol,
913
+ EndpointsConfig: [
914
+ {
915
+ Namespace: 'default',
916
+ FunctionName: fn.name,
917
+ Qualifier: '$DEFAULT',
918
+ PathMatch: '/*',
919
+ },
920
+ ],
921
+ ...(fn.domain.certificate_id
922
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
923
+ : {}),
924
+ });
925
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
926
+ }
927
+ }
928
+ // Refresh state from provider to get all attributes (including triggers)
335
929
  const functionInfo = await client.scf.getFunction(fn.name);
336
930
  if (!functionInfo) {
337
931
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
338
932
  }
339
933
  const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
340
934
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
341
- // Rebuild dependent instances list
342
935
  const existingDependentInstances = existingInstances
343
- .filter((i) => i.type !== undefined)
936
+ .filter((i) => i.type !== undefined &&
937
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
938
+ !((clsTopicInstance || disableLog) &&
939
+ (i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC ||
940
+ i.type === types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET)))
344
941
  .map((i) => {
345
942
  const { type, id, sid, roleArn, external } = i;
346
943
  return {
@@ -361,6 +958,18 @@ const updateResource = async (context, fn, state) => {
361
958
  ...(role.arn ? { roleArn: role.arn } : {}),
362
959
  });
363
960
  }
961
+ if (fn.domain) {
962
+ const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
963
+ newDependentInstances.push({
964
+ sid: domainSid,
965
+ type: 'TENCENT_SCF_CUSTOM_DOMAIN',
966
+ id: fn.domain.domain_name,
967
+ protocol: fn.domain.protocol,
968
+ });
969
+ }
970
+ if (clsTopicInstance) {
971
+ newDependentInstances.push(clsTopicInstance);
972
+ }
364
973
  const resourceState = {
365
974
  mode: 'managed',
366
975
  region: context.region,
@@ -372,14 +981,66 @@ const updateResource = async (context, fn, state) => {
372
981
  ],
373
982
  lastUpdated: new Date().toISOString(),
374
983
  };
375
- return (0, stateManager_1.setResource)(state, logicalId, resourceState);
984
+ const stateWithShared = clsSharedInstance
985
+ ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY, clsSharedInstance)
986
+ : sharedLogsetReleased
987
+ ? (0, stateManager_1.removeSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY)
988
+ : state;
989
+ return (0, stateManager_1.setResource)(stateWithShared, logicalId, resourceState);
376
990
  };
377
991
  exports.updateResource = updateResource;
378
992
  const deleteResource = async (context, functionName, logicalId, state) => {
379
993
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
380
994
  const existingInstances = (existingState?.instances ?? []);
381
- const hasFunction = existingInstances.some((i) => i.type === undefined);
382
995
  const client = (0, tencentClient_1.createTencentClient)(context);
996
+ // Delete HTTP trigger before deleting function
997
+ const fnInstance = existingInstances.find((i) => i.type === undefined);
998
+ const httpTrigger = fnInstance?.triggers?.find((t) => t.type === 'http');
999
+ if (httpTrigger) {
1000
+ try {
1001
+ const triggerName = httpTrigger.triggerName;
1002
+ logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName, functionName }));
1003
+ await client.scf.deleteTrigger({
1004
+ FunctionName: functionName,
1005
+ TriggerName: triggerName,
1006
+ Type: 'http',
1007
+ });
1008
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName }));
1009
+ }
1010
+ catch (err) {
1011
+ const errorCode = err?.code;
1012
+ if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
1013
+ logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', {
1014
+ triggerName: httpTrigger.triggerName,
1015
+ }));
1016
+ }
1017
+ else {
1018
+ throw err;
1019
+ }
1020
+ }
1021
+ }
1022
+ // Delete custom domain before deleting function
1023
+ const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
1024
+ if (existingCustomDomain) {
1025
+ try {
1026
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1027
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
1028
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
1029
+ }
1030
+ catch (err) {
1031
+ const errorCode = err?.code;
1032
+ if (errorCode === 'ResourceNotFound') {
1033
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
1034
+ resourceType: 'Custom Domain',
1035
+ name: existingCustomDomain.id,
1036
+ }));
1037
+ }
1038
+ else {
1039
+ throw err;
1040
+ }
1041
+ }
1042
+ }
1043
+ const hasFunction = existingInstances.some((i) => i.type === undefined);
383
1044
  if (hasFunction) {
384
1045
  try {
385
1046
  await client.scf.deleteFunction(functionName);
@@ -394,7 +1055,8 @@ const deleteResource = async (context, functionName, logicalId, state) => {
394
1055
  }
395
1056
  }
396
1057
  }
397
- const dependentInstances = existingInstances.filter((i) => i.type !== undefined);
1058
+ const dependentInstances = existingInstances.filter((i) => i.type !== undefined &&
1059
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN');
398
1060
  if (dependentInstances.length > 0) {
399
1061
  await deleteDependentResources(context, dependentInstances);
400
1062
  }