@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
@@ -11,11 +11,83 @@ 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
+ /**
17
+ * Build the Function URL trigger description for Tencent CreateTrigger
18
+ * (Type: 'http'). Format per official docs (创建函数 URL / Creating a Function
19
+ * URL): { AuthType, NetConfig: { EnableIntranet, EnableExtranet } }.
20
+ * AuthType is the mapAuthType result ('NONE' = no auth, 'CAM' = CAM auth);
21
+ * the API Gateway trigger format ({ api/service/release }) is obsolete —
22
+ * Tencent shut down new API Gateway triggers on 2024-07-01.
23
+ */
24
+ const buildTencentTriggerDesc = (authType, netConfig) => JSON.stringify({
25
+ AuthType: authType,
26
+ NetConfig: {
27
+ EnableIntranet: netConfig.enableIntranet ?? false,
28
+ EnableExtranet: netConfig.enableExtranet ?? true,
29
+ },
30
+ });
31
+ // Tencent names Function URL triggers with a random id (e.g. "5obtzwwxw1"), not
32
+ // our ${fn.key}-http-trigger, so name-based matching never finds them. A
33
+ // Function URL trigger is identified by Type 'http' + a TriggerDesc carrying
34
+ // the NetConfig field (the API Gateway flavor uses api/service/release instead).
35
+ const isFunctionUrlTrigger = (t) => t.Type === 'http' && typeof t.TriggerDesc === 'string' && t.TriggerDesc.includes('NetConfig');
36
+ /**
37
+ * Best-effort extraction of a cloud-SDK error's useful details. Tencent SDK
38
+ * errors carry `code`/`message`/`requestId` (and may throw with an empty
39
+ * `message`), so we compose them into a non-empty, diagnosable string —
40
+ * otherwise a PartialResourceError surfaces as a blank failure line.
41
+ */
42
+ const toErrorMessage = (error) => {
43
+ if (error instanceof Error && error.message) {
44
+ return error.message;
45
+ }
46
+ if (error && typeof error === 'object') {
47
+ const parts = [];
48
+ const rec = error;
49
+ if (typeof rec.code === 'string' && rec.code)
50
+ parts.push(rec.code);
51
+ if (typeof rec.message === 'string' && rec.message)
52
+ parts.push(rec.message);
53
+ if (typeof rec.requestId === 'string' && rec.requestId)
54
+ parts.push(`requestId=${rec.requestId}`);
55
+ if (parts.length > 0)
56
+ return parts.join(' · ');
57
+ }
58
+ return String(error) || 'unknown error';
59
+ };
14
60
  const delay = async (ms) => {
15
61
  await new Promise((resolve) => {
16
62
  setTimeout(resolve, ms);
17
63
  });
18
64
  };
65
+ // Delay before probing the provider after a recoverable create error — the
66
+ // platform may still be propagating a just-created function.
67
+ const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
68
+ // Create errors recoverable by reconciling with provider state. Deliberately
69
+ // limited to timeout/network conditions. A create-time "already exists" (Tencent
70
+ // reports ResourceInUse with a localized message "指定的Function已存在,请勿重复创建")
71
+ // is NOT recoverable on the non-tainted path: the cloud resource may not be owned
72
+ // by this stack, so it must propagate as PartialResourceError (persisting tainted
73
+ // state) for the user to resolve manually — no auto-adopt (product decision D1).
74
+ // Only the tainted pre-flight path may adopt a pre-existing function.
75
+ const isRecoverableCreateError = (error) => {
76
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
77
+ ? error.code.toLowerCase()
78
+ : '';
79
+ const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
80
+ return (code === 'readtimeout' ||
81
+ code === 'timeout' ||
82
+ code === 'requesttimeout' ||
83
+ code === 'econnreset' ||
84
+ code === 'etimedout' ||
85
+ message.includes('readtimeout') ||
86
+ message.includes('timeout') ||
87
+ message.includes('socket hang up') ||
88
+ message.includes('econnreset') ||
89
+ message.includes('etimedout'));
90
+ };
19
91
  const buildScfInstanceFromProvider = (info, sid) => {
20
92
  const envMap = info.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
21
93
  const triggersArray = info.Triggers?.map((t) => ({
@@ -41,6 +113,15 @@ const buildScfInstanceFromProvider = (info, sid) => {
41
113
  layerName: l.LayerName ?? null,
42
114
  layerVersion: l.LayerVersion ?? null,
43
115
  compatibleRuntimes: l.CompatibleRuntimes ?? [],
116
+ addTime: l.AddTime ?? null,
117
+ description: l.Description ?? null,
118
+ licenseInfo: l.LicenseInfo ?? null,
119
+ status: l.Status ?? null,
120
+ stamp: l.Stamp ?? null,
121
+ tags: l.Tags?.map((t) => ({
122
+ key: t.Key,
123
+ value: t.Value,
124
+ })) ?? [],
44
125
  }));
45
126
  return {
46
127
  sid,
@@ -140,6 +221,12 @@ const buildScfInstanceFromProvider = (info, sid) => {
140
221
  ? {
141
222
  imageType: info.ImageConfig.ImageType ?? null,
142
223
  imageUri: info.ImageConfig.ImageUri ?? null,
224
+ registryId: info.ImageConfig.RegistryId ?? null,
225
+ entryPoint: info.ImageConfig.EntryPoint ?? null,
226
+ command: info.ImageConfig.Command ?? null,
227
+ args: info.ImageConfig.Args ?? null,
228
+ containerImageAccelerate: info.ImageConfig.ContainerImageAccelerate ?? null,
229
+ imagePort: info.ImageConfig.ImagePort ?? null,
143
230
  }
144
231
  : {},
145
232
  protocolType: info.ProtocolType ?? null,
@@ -156,6 +243,17 @@ const buildScfInstanceFromProvider = (info, sid) => {
156
243
  intranetConfig: info.IntranetConfig
157
244
  ? {
158
245
  ipFixed: info.IntranetConfig.IpFixed ?? null,
246
+ ipAddress: info.IntranetConfig.IpAddress ?? [],
247
+ }
248
+ : {},
249
+ instanceConcurrencyConfig: info.InstanceConcurrencyConfig
250
+ ? {
251
+ dynamicEnabled: info.InstanceConcurrencyConfig.DynamicEnabled ?? null,
252
+ maxConcurrency: info.InstanceConcurrencyConfig.MaxConcurrency ?? null,
253
+ instanceIsolationEnabled: info.InstanceConcurrencyConfig.InstanceIsolationEnabled ?? null,
254
+ type: info.InstanceConcurrencyConfig.Type ?? null,
255
+ mixNodeConfig: info.InstanceConcurrencyConfig.MixNodeConfig ?? [],
256
+ sessionConfig: info.InstanceConcurrencyConfig.SessionConfig ?? {},
159
257
  }
160
258
  : {},
161
259
  };
@@ -183,7 +281,7 @@ const createDependentResources = async (context, fn, existingInstances = []) =>
183
281
  return { role: { roleName, arn: roleName } };
184
282
  }
185
283
  // Create new CAM role
186
- const trustedServices = ['scf.tencentcloudapi.com'];
284
+ const trustedServices = ['scf.qcloud.com'];
187
285
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
188
286
  const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies);
189
287
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
@@ -207,10 +305,16 @@ const deleteDependentResources = async (context, instances) => {
207
305
  };
208
306
  const createResource = async (context, fn, state) => {
209
307
  const logicalId = `functions.${fn.key}`;
308
+ // Fail config validation BEFORE any cloud operation or tainted-state write,
309
+ // so an invalid trigger config can never strand a partially-created resource.
310
+ if (fn.triggers?.http && !fn.triggers.http.auth_type) {
311
+ throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
312
+ }
210
313
  const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
211
314
  const existingDependentInstances = (existingResourceState?.instances ?? []).filter((i) => i.type !== undefined);
212
315
  const dependentResources = await createDependentResources(context, fn, existingDependentInstances);
213
316
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
317
+ config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
214
318
  if (dependentResources.role) {
215
319
  config = {
216
320
  ...config,
@@ -219,7 +323,7 @@ const createResource = async (context, fn, state) => {
219
323
  }
220
324
  const codePath = fn.code.path;
221
325
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
222
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
326
+ const codeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
223
327
  const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
224
328
  const dependentInstances = [];
225
329
  if (dependentResources.role) {
@@ -244,11 +348,144 @@ const createResource = async (context, fn, state) => {
244
348
  };
245
349
  const stateAfterDependents = (0, stateManager_1.setResource)(state, logicalId, taintedResourceState);
246
350
  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);
351
+ const isTainted = existingResourceState?.status === 'tainted';
352
+ const existingFunctionOnRetry = isTainted ? await client.scf.getFunction(fn.name) : null;
353
+ // Provider info of a function adopted from a previous partial run (tainted
354
+ // retry or reconciled after a create error) — used to skip already-attached
355
+ // triggers below.
356
+ let adoptedInfo = existingFunctionOnRetry;
357
+ if (existingFunctionOnRetry) {
358
+ logger_1.logger.info(`Function ${fn.name} already exists in provider (tainted recovery), skipping create and refreshing state`);
359
+ }
360
+ try {
361
+ if (!existingFunctionOnRetry) {
362
+ // createFunction internally polls until the function is Active (see
363
+ // scfOperations) — triggers/domains below are safe to attach immediately.
364
+ await client.scf.createFunction(config, codeBase64);
365
+ }
366
+ }
367
+ catch (error) {
368
+ if (isRecoverableCreateError(error)) {
369
+ logger_1.logger.warn(`Create function returned recoverable error for ${fn.name}, reconciling with provider state: ${String(error)}`);
370
+ await delay(RECOVERY_GET_FUNCTION_DELAY_MS);
371
+ const afterError = await client.scf.getFunction(fn.name);
372
+ if (afterError) {
373
+ adoptedInfo = afterError;
374
+ logger_1.logger.info(`Function ${fn.name} found after create error reconciliation, continuing deployment flow`);
375
+ }
376
+ else {
377
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
378
+ }
379
+ }
380
+ else if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
381
+ // Idempotent adoption: the function already exists in the provider.
382
+ // Adopt it ONLY if it carries our ownership tag (proves a previous run
383
+ // of THIS stack created it — e.g. state was reset). An untagged
384
+ // same-named function may belong to another project, so it must fail
385
+ // loudly rather than silently taking it over (destroy would then remove
386
+ // a resource that was never ours).
387
+ const probe = await client.scf.getFunction(fn.name);
388
+ if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
389
+ adoptedInfo = probe;
390
+ logger_1.logger.info(`Function ${fn.name} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
391
+ }
392
+ else {
393
+ 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.`));
394
+ }
395
+ }
396
+ else {
397
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
398
+ }
399
+ }
400
+ // Create HTTP trigger if configured
401
+ if (fn.triggers?.http) {
402
+ const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, fn.triggers.http.auth_type);
403
+ const access = (0, common_1.mapAccess)(fn.triggers.http.access);
404
+ const triggerName = `${fn.key}-http-trigger`;
405
+ const triggerDesc = buildTencentTriggerDesc(authType, access);
406
+ // Probe the provider for an already-attached trigger BEFORE attempting to
407
+ // create it. A leftover trigger from a previous partial run (function exists
408
+ // in cloud, state blank) would otherwise collide with CreateTrigger and
409
+ // surface as a confusing empty error. Applies to both fresh creates (function
410
+ // just created — Triggers from the createFunction flow) and tainted retries.
411
+ let providerTriggers = adoptedInfo?.Triggers ?? [];
412
+ if (providerTriggers.length === 0) {
413
+ const probe = await client.scf.getFunction(fn.name);
414
+ if (probe) {
415
+ providerTriggers = probe.Triggers ?? [];
416
+ }
417
+ }
418
+ const triggerAlreadyAttached = providerTriggers.some(isFunctionUrlTrigger);
419
+ if (triggerAlreadyAttached) {
420
+ logger_1.logger.info(`HTTP trigger ${triggerName} already attached to ${fn.name}, skipping creation`);
421
+ }
422
+ else {
423
+ logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
424
+ try {
425
+ await client.scf.createTrigger({
426
+ FunctionName: fn.name,
427
+ TriggerName: triggerName,
428
+ Type: 'http',
429
+ TriggerDesc: triggerDesc,
430
+ Qualifier: '$DEFAULT',
431
+ Enable: 'OPEN',
432
+ });
433
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
434
+ }
435
+ catch (error) {
436
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
437
+ logger_1.logger.warn(`HTTP trigger ${triggerName} already exists on ${fn.name}, continuing: ${String(error)}`);
438
+ }
439
+ else {
440
+ // The function exists in the cloud but the trigger failed to attach —
441
+ // persist the tainted state so a re-run reconciles instead of losing it.
442
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
443
+ }
444
+ }
445
+ }
446
+ }
447
+ // Create custom domain if configured
448
+ if (fn.domain) {
449
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
450
+ try {
451
+ await client.scf.createCustomDomain({
452
+ Domain: fn.domain.domain_name,
453
+ Protocol: fn.domain.protocol,
454
+ EndpointsConfig: [
455
+ {
456
+ Namespace: 'default',
457
+ FunctionName: fn.name,
458
+ Qualifier: '$DEFAULT',
459
+ PathMatch: '/*',
460
+ },
461
+ ],
462
+ ...(fn.domain.certificate_id
463
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
464
+ : {}),
465
+ });
466
+ }
467
+ catch (error) {
468
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
469
+ }
470
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
471
+ const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
472
+ dependentInstances.push({
473
+ sid: domainSid,
474
+ type: 'TENCENT_SCF_CUSTOM_DOMAIN',
475
+ id: fn.domain.domain_name,
476
+ protocol: fn.domain.protocol,
477
+ });
478
+ }
479
+ // Refresh state from provider to get all attributes (including triggers)
480
+ let functionInfo;
481
+ try {
482
+ functionInfo = await client.scf.getFunction(fn.name);
483
+ }
484
+ catch (error) {
485
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
486
+ }
250
487
  if (!functionInfo) {
251
- throw new Error(`Failed to refresh state for function: ${fn.name}`);
488
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(`Failed to refresh state for function: ${fn.name}`));
252
489
  }
253
490
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
254
491
  const resourceState = {
@@ -274,6 +511,7 @@ const updateResource = async (context, fn, state) => {
274
511
  const logicalId = `functions.${fn.key}`;
275
512
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
276
513
  const existingInstances = (existingState?.instances ?? []);
514
+ const existingFnInstance = existingInstances.find((i) => i.type === undefined);
277
515
  const hasCamRole = existingInstances.some((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE);
278
516
  const client = (0, tencentClient_1.createTencentClient)(context);
279
517
  const newIamRole = fn.iam?.role;
@@ -326,21 +564,196 @@ const updateResource = async (context, fn, state) => {
326
564
  }
327
565
  const codePath = fn.code.path;
328
566
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
329
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
330
- // Update configuration
331
- await client.scf.updateFunctionConfiguration(config);
567
+ const codeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
568
+ // Only push configuration when the mutable config fields actually changed —
569
+ // Tencent's UpdateFunctionConfiguration rejects Handler/Runtime (immutable at
570
+ // creation) and we don't want to re-send unchanged values. Handler/Runtime
571
+ // changes are a hard error: the platform cannot apply them on update.
572
+ const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
573
+ const existingDefinition = (existingState?.definition ?? {});
574
+ const CONFIG_DIFF_KEYS = ['runtime', 'handler', 'memorySize', 'timeout', 'environment', 'role'];
575
+ const mutableKeys = CONFIG_DIFF_KEYS.filter((k) => k !== 'runtime' && k !== 'handler');
576
+ if (desiredDefinition.handler &&
577
+ existingDefinition.handler &&
578
+ desiredDefinition.handler !== existingDefinition.handler) {
579
+ 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.`);
580
+ }
581
+ if (desiredDefinition.runtime &&
582
+ existingDefinition.runtime &&
583
+ desiredDefinition.runtime !== existingDefinition.runtime) {
584
+ 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.`);
585
+ }
586
+ const configChanged = mutableKeys.some((k) => desiredDefinition[k] !== existingDefinition[k]);
587
+ if (configChanged) {
588
+ await client.scf.updateFunctionConfiguration(config);
589
+ }
332
590
  // Update code
333
591
  await client.scf.updateFunctionCode(fn.name, codeBase64);
334
- // Refresh state from provider to get all attributes
592
+ const existingHttpTrigger = existingFnInstance?.triggers?.find((t) => t.type === 'http');
593
+ const desiredHttpConfig = fn.triggers?.http;
594
+ if (desiredHttpConfig) {
595
+ if (!desiredHttpConfig.auth_type) {
596
+ throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
597
+ }
598
+ const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, desiredHttpConfig.auth_type);
599
+ const access = (0, common_1.mapAccess)(desiredHttpConfig.access);
600
+ const triggerName = `${fn.key}-http-trigger`;
601
+ const desiredTriggerDesc = buildTencentTriggerDesc(authType, access);
602
+ if (existingHttpTrigger) {
603
+ if (existingHttpTrigger.triggerDesc !== desiredTriggerDesc) {
604
+ logger_1.logger.info(lang_1.lang.__('UPDATING_HTTP_TRIGGER', { functionName: fn.name }));
605
+ try {
606
+ await client.scf.deleteTrigger({
607
+ FunctionName: fn.name,
608
+ TriggerName: existingHttpTrigger.triggerName,
609
+ Type: 'http',
610
+ });
611
+ }
612
+ catch (err) {
613
+ const errorCode = err?.code;
614
+ if (errorCode !== 'ResourceNotFound.TriggerName' && errorCode !== 'ResourceNotFound') {
615
+ throw err;
616
+ }
617
+ }
618
+ await client.scf.createTrigger({
619
+ FunctionName: fn.name,
620
+ TriggerName: triggerName,
621
+ Type: 'http',
622
+ TriggerDesc: desiredTriggerDesc,
623
+ Qualifier: '$DEFAULT',
624
+ Enable: 'OPEN',
625
+ });
626
+ }
627
+ }
628
+ else {
629
+ // No trigger recorded in state — but a leftover trigger may still exist
630
+ // in the provider (e.g. adopted function whose state lacked trigger
631
+ // records). Probe before creating to stay idempotent.
632
+ const probe = await client.scf.getFunction(fn.name);
633
+ const providerTriggerAttached = (probe?.Triggers ?? []).some(isFunctionUrlTrigger);
634
+ if (providerTriggerAttached) {
635
+ logger_1.logger.info(`HTTP trigger ${triggerName} already attached to ${fn.name}, skipping creation`);
636
+ }
637
+ else {
638
+ logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
639
+ try {
640
+ await client.scf.createTrigger({
641
+ FunctionName: fn.name,
642
+ TriggerName: triggerName,
643
+ Type: 'http',
644
+ TriggerDesc: desiredTriggerDesc,
645
+ Qualifier: '$DEFAULT',
646
+ Enable: 'OPEN',
647
+ });
648
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
649
+ }
650
+ catch (error) {
651
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
652
+ logger_1.logger.warn(`HTTP trigger ${triggerName} already exists on ${fn.name}, continuing: ${String(error)}`);
653
+ }
654
+ else {
655
+ throw error;
656
+ }
657
+ }
658
+ }
659
+ }
660
+ }
661
+ else if (existingHttpTrigger) {
662
+ const tName = existingHttpTrigger.triggerName;
663
+ logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: tName, functionName: fn.name }));
664
+ try {
665
+ await client.scf.deleteTrigger({
666
+ FunctionName: fn.name,
667
+ TriggerName: tName,
668
+ Type: 'http',
669
+ });
670
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName: tName }));
671
+ }
672
+ catch (err) {
673
+ const errorCode = err?.code;
674
+ if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
675
+ logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: tName }));
676
+ }
677
+ else {
678
+ throw err;
679
+ }
680
+ }
681
+ }
682
+ // Reconcile custom domain
683
+ const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
684
+ if (fn.domain && !existingCustomDomain) {
685
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
686
+ await client.scf.createCustomDomain({
687
+ Domain: fn.domain.domain_name,
688
+ Protocol: fn.domain.protocol,
689
+ EndpointsConfig: [
690
+ {
691
+ Namespace: 'default',
692
+ FunctionName: fn.name,
693
+ Qualifier: '$DEFAULT',
694
+ PathMatch: '/*',
695
+ },
696
+ ],
697
+ ...(fn.domain.certificate_id
698
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
699
+ : {}),
700
+ });
701
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
702
+ }
703
+ else if (!fn.domain && existingCustomDomain) {
704
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
705
+ try {
706
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
707
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
708
+ }
709
+ catch (err) {
710
+ const errorCode = err?.code;
711
+ if (errorCode === 'ResourceNotFound') {
712
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
713
+ resourceType: 'Custom Domain',
714
+ name: existingCustomDomain.id,
715
+ }));
716
+ }
717
+ else {
718
+ throw err;
719
+ }
720
+ }
721
+ }
722
+ else if (fn.domain && existingCustomDomain) {
723
+ const domainChanged = fn.domain.domain_name !== existingCustomDomain.id ||
724
+ fn.domain.protocol !== existingCustomDomain.protocol;
725
+ if (domainChanged) {
726
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
727
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
728
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
729
+ await client.scf.createCustomDomain({
730
+ Domain: fn.domain.domain_name,
731
+ Protocol: fn.domain.protocol,
732
+ EndpointsConfig: [
733
+ {
734
+ Namespace: 'default',
735
+ FunctionName: fn.name,
736
+ Qualifier: '$DEFAULT',
737
+ PathMatch: '/*',
738
+ },
739
+ ],
740
+ ...(fn.domain.certificate_id
741
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
742
+ : {}),
743
+ });
744
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
745
+ }
746
+ }
747
+ // Refresh state from provider to get all attributes (including triggers)
335
748
  const functionInfo = await client.scf.getFunction(fn.name);
336
749
  if (!functionInfo) {
337
750
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
338
751
  }
339
752
  const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
340
753
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
341
- // Rebuild dependent instances list
342
754
  const existingDependentInstances = existingInstances
343
- .filter((i) => i.type !== undefined)
755
+ .filter((i) => i.type !== undefined &&
756
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN')
344
757
  .map((i) => {
345
758
  const { type, id, sid, roleArn, external } = i;
346
759
  return {
@@ -361,6 +774,15 @@ const updateResource = async (context, fn, state) => {
361
774
  ...(role.arn ? { roleArn: role.arn } : {}),
362
775
  });
363
776
  }
777
+ if (fn.domain) {
778
+ const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
779
+ newDependentInstances.push({
780
+ sid: domainSid,
781
+ type: 'TENCENT_SCF_CUSTOM_DOMAIN',
782
+ id: fn.domain.domain_name,
783
+ protocol: fn.domain.protocol,
784
+ });
785
+ }
364
786
  const resourceState = {
365
787
  mode: 'managed',
366
788
  region: context.region,
@@ -378,8 +800,55 @@ exports.updateResource = updateResource;
378
800
  const deleteResource = async (context, functionName, logicalId, state) => {
379
801
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
380
802
  const existingInstances = (existingState?.instances ?? []);
381
- const hasFunction = existingInstances.some((i) => i.type === undefined);
382
803
  const client = (0, tencentClient_1.createTencentClient)(context);
804
+ // Delete HTTP trigger before deleting function
805
+ const fnInstance = existingInstances.find((i) => i.type === undefined);
806
+ const httpTrigger = fnInstance?.triggers?.find((t) => t.type === 'http');
807
+ if (httpTrigger) {
808
+ try {
809
+ const triggerName = httpTrigger.triggerName;
810
+ logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName, functionName }));
811
+ await client.scf.deleteTrigger({
812
+ FunctionName: functionName,
813
+ TriggerName: triggerName,
814
+ Type: 'http',
815
+ });
816
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName }));
817
+ }
818
+ catch (err) {
819
+ const errorCode = err?.code;
820
+ if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
821
+ logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', {
822
+ triggerName: httpTrigger.triggerName,
823
+ }));
824
+ }
825
+ else {
826
+ throw err;
827
+ }
828
+ }
829
+ }
830
+ // Delete custom domain before deleting function
831
+ const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
832
+ if (existingCustomDomain) {
833
+ try {
834
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
835
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
836
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
837
+ }
838
+ catch (err) {
839
+ const errorCode = err?.code;
840
+ if (errorCode === 'ResourceNotFound') {
841
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
842
+ resourceType: 'Custom Domain',
843
+ name: existingCustomDomain.id,
844
+ }));
845
+ }
846
+ else {
847
+ throw err;
848
+ }
849
+ }
850
+ }
851
+ const hasFunction = existingInstances.some((i) => i.type === undefined);
383
852
  if (hasFunction) {
384
853
  try {
385
854
  await client.scf.deleteFunction(functionName);
@@ -394,7 +863,8 @@ const deleteResource = async (context, functionName, logicalId, state) => {
394
863
  }
395
864
  }
396
865
  }
397
- const dependentInstances = existingInstances.filter((i) => i.type !== undefined);
866
+ const dependentInstances = existingInstances.filter((i) => i.type !== undefined &&
867
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN');
398
868
  if (dependentInstances.length > 0) {
399
869
  await deleteDependentResources(context, dependentInstances);
400
870
  }
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeDatabasePlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const tdsqlcResource_1 = require("./tdsqlcResource");
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) => {
@@ -75,13 +77,26 @@ const executeDatabasePlan = async (context, plan, databases, initialState, onSta
75
77
  const successfulItems = [];
76
78
  let currentState = initialState;
77
79
  for (const item of plan.items) {
80
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
81
+ type: 'resource_pre',
82
+ logicalId: item.logicalId,
83
+ resourceType: item.resourceType,
84
+ action: item.action,
85
+ ...(item.drifted ? { message: 'resource drifted' } : {}),
86
+ });
87
+ const __siStartedAt = Date.now();
78
88
  try {
79
89
  const newState = await executeSingleItem(context, item, databasesMap, currentState);
80
90
  if (newState !== null) {
81
91
  currentState = newState;
82
92
  successfulItems.push(item);
93
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
94
+ type: 'resource_complete',
95
+ logicalId: item.logicalId,
96
+ durationMs: Date.now() - __siStartedAt,
97
+ });
83
98
  if (onStateChange) {
84
- onStateChange(currentState);
99
+ await onStateChange(currentState);
85
100
  common_1.logger.debug(lang_1.lang.__('STATE_PERSISTED_AFTER_OPERATION', {
86
101
  action: item.action,
87
102
  resourceId: item.logicalId,
@@ -90,6 +105,29 @@ const executeDatabasePlan = async (context, plan, databases, initialState, onSta
90
105
  }
91
106
  }
92
107
  catch (error) {
108
+ (0, reportResourceEvent_1.reportResourceEvent)(context, {
109
+ type: 'resource_failed',
110
+ logicalId: item.logicalId,
111
+ severity: 'error',
112
+ durationMs: Date.now() - __siStartedAt,
113
+ error: {
114
+ message: error instanceof Error ? error.message : String(error),
115
+ },
116
+ });
117
+ if (error instanceof types_1.PartialResourceError) {
118
+ const updatedState = error.updatedState;
119
+ if (onStateChange) {
120
+ await onStateChange(updatedState);
121
+ }
122
+ return {
123
+ state: updatedState,
124
+ partialFailure: {
125
+ failedItem: item,
126
+ error: error.cause,
127
+ successfulItems,
128
+ },
129
+ };
130
+ }
93
131
  return {
94
132
  state: currentState,
95
133
  partialFailure: {