@geek-fun/serverlessinsight 0.9.2 → 0.9.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 (101) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +4 -8
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -8
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +28 -5
  8. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  9. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +3 -3
  10. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +20 -5
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/AGENTS.md +10 -0
  13. package/CHANGELOG.md +34 -0
  14. package/README.md +29 -15
  15. package/README.zh-CN.md +7 -14
  16. package/dist/package.json +1 -1
  17. package/dist/src/commands/index.js +19 -3
  18. package/dist/src/commands/local.js +16 -3
  19. package/dist/src/commands/plan.js +10 -3
  20. package/dist/src/common/aliyunClient/apigwOperations.js +17 -1
  21. package/dist/src/common/aliyunClient/fc3Operations.js +7 -1
  22. package/dist/src/common/aliyunClient/ossOperations.js +214 -221
  23. package/dist/src/common/bucketPolicy.js +63 -0
  24. package/dist/src/common/domainUtils.js +4 -1
  25. package/dist/src/common/functionDefinition.js +25 -0
  26. package/dist/src/common/index.js +4 -0
  27. package/dist/src/common/jsonOutput.js +6 -1
  28. package/dist/src/common/nameBuilder.js +3 -1
  29. package/dist/src/common/planCapabilities.js +119 -0
  30. package/dist/src/common/planCompare.js +119 -66
  31. package/dist/src/common/planFormatter.js +22 -14
  32. package/dist/src/common/planRedaction.js +26 -0
  33. package/dist/src/common/refreshPlanner.js +66 -21
  34. package/dist/src/common/tencentClient/cosOperations.js +326 -322
  35. package/dist/src/common/tencentClient/scfOperations.js +9 -2
  36. package/dist/src/common/tencentClient/tdsqlcOperations.js +6 -11
  37. package/dist/src/common/triggerMapper.js +16 -1
  38. package/dist/src/common/volcengineClient/apigwOperations.js +82 -0
  39. package/dist/src/common/volcengineClient/iamOperations.js +27 -3
  40. package/dist/src/common/volcengineClient/tosOperations.js +62 -56
  41. package/dist/src/lang/en.js +28 -4
  42. package/dist/src/lang/zh-CN.js +28 -4
  43. package/dist/src/parser/eventParser.js +1 -0
  44. package/dist/src/parser/functionParser.js +1 -1
  45. package/dist/src/stack/aliyunStack/apigwExecutor.js +1 -1
  46. package/dist/src/stack/aliyunStack/apigwPlanner.js +103 -23
  47. package/dist/src/stack/aliyunStack/apigwResource.js +4 -3
  48. package/dist/src/stack/aliyunStack/apigwTypes.js +3 -7
  49. package/dist/src/stack/aliyunStack/deployer.js +2 -0
  50. package/dist/src/stack/aliyunStack/esServerlessTypes.js +8 -4
  51. package/dist/src/stack/aliyunStack/fc3Executor.js +7 -3
  52. package/dist/src/stack/aliyunStack/fc3Planner.js +124 -155
  53. package/dist/src/stack/aliyunStack/fc3Resource.js +48 -52
  54. package/dist/src/stack/aliyunStack/fc3Types.js +30 -16
  55. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  56. package/dist/src/stack/aliyunStack/ossResource.js +113 -102
  57. package/dist/src/stack/aliyunStack/ossTypes.js +20 -20
  58. package/dist/src/stack/localStack/aliyunFc.js +1 -6
  59. package/dist/src/stack/localStack/event.js +31 -60
  60. package/dist/src/stack/localStack/function.js +24 -65
  61. package/dist/src/stack/localStack/functionRunner.js +10 -2
  62. package/dist/src/stack/localStack/httpAdapter.js +54 -0
  63. package/dist/src/stack/localStack/httpError.js +5 -0
  64. package/dist/src/stack/localStack/legacyLambda.js +26 -0
  65. package/dist/src/stack/localStack/localContext.js +29 -0
  66. package/dist/src/stack/localStack/localRoute.js +12 -0
  67. package/dist/src/stack/localStack/localRuntimes.js +22 -0
  68. package/dist/src/stack/localStack/localServer.js +8 -3
  69. package/dist/src/stack/localStack/requestBody.js +24 -0
  70. package/dist/src/stack/localStack/requestId.js +18 -0
  71. package/dist/src/stack/localStack/tencent.js +147 -0
  72. package/dist/src/stack/localStack/timer.js +23 -2
  73. package/dist/src/stack/localStack/volcengine.js +68 -0
  74. package/dist/src/stack/scfStack/cosPlanner.js +9 -14
  75. package/dist/src/stack/scfStack/cosResource.js +42 -50
  76. package/dist/src/stack/scfStack/cosTypes.js +19 -14
  77. package/dist/src/stack/scfStack/deployer.js +2 -0
  78. package/dist/src/stack/scfStack/scfExecutor.js +7 -3
  79. package/dist/src/stack/scfStack/scfHttpTrigger.js +106 -0
  80. package/dist/src/stack/scfStack/scfPlanner.js +67 -16
  81. package/dist/src/stack/scfStack/scfResource.js +170 -321
  82. package/dist/src/stack/scfStack/scfTypes.js +4 -3
  83. package/dist/src/stack/scfStack/tdsqlcPlanner.js +10 -13
  84. package/dist/src/stack/volcengineStack/apigwDomains.js +64 -0
  85. package/dist/src/stack/volcengineStack/apigwPlanner.js +71 -15
  86. package/dist/src/stack/volcengineStack/apigwResource.js +60 -24
  87. package/dist/src/stack/volcengineStack/apigwTypes.js +5 -1
  88. package/dist/src/stack/volcengineStack/deployer.js +6 -0
  89. package/dist/src/stack/volcengineStack/tosPlanner.js +8 -13
  90. package/dist/src/stack/volcengineStack/tosResource.js +22 -35
  91. package/dist/src/stack/volcengineStack/tosTypes.js +5 -8
  92. package/dist/src/stack/volcengineStack/vefaasPlanner.js +142 -49
  93. package/dist/src/stack/volcengineStack/vefaasResource.js +17 -12
  94. package/dist/src/stack/volcengineStack/vefaasTypes.js +6 -3
  95. package/dist/tsconfig.tsbuildinfo +1 -1
  96. package/package.json +1 -1
  97. package/release-notes.md +79 -0
  98. package/samples/tencent-local/index.js +13 -0
  99. package/samples/tencent-local/serverlessinsight.yml +23 -0
  100. package/samples/volcengine-local/index.js +13 -0
  101. package/samples/volcengine-local/serverlessinsight.yml +28 -0
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveScfExecutionStatements = void 0;
4
+ const functionDefinition_1 = require("../../common/functionDefinition");
5
+ const planCompare_1 = require("../../common/planCompare");
6
+ const scfHttpTrigger_1 = require("./scfHttpTrigger");
4
7
  const types_1 = require("../../types");
5
8
  const siCron_1 = require("../../common/siCron");
6
9
  const tencentClient_1 = require("../../common/tencentClient");
@@ -16,26 +19,6 @@ const ownershipTag_1 = require("../ownershipTag");
16
19
  const alreadyExists_1 = require("../alreadyExists");
17
20
  const sharedLogset_1 = require("./sharedLogset");
18
21
  const clsOperations_1 = require("../../common/tencentClient/clsOperations");
19
- /**
20
- * Build the Function URL trigger description for Tencent CreateTrigger
21
- * (Type: 'http'). Format per official docs (创建函数 URL / Creating a Function
22
- * URL): { AuthType, NetConfig: { EnableIntranet, EnableExtranet } }.
23
- * AuthType is the mapAuthType result ('NONE' = no auth, 'CAM' = CAM auth);
24
- * the API Gateway trigger format ({ api/service/release }) is obsolete —
25
- * Tencent shut down new API Gateway triggers on 2024-07-01.
26
- */
27
- const buildTencentTriggerDesc = (authType, netConfig) => JSON.stringify({
28
- AuthType: authType,
29
- NetConfig: {
30
- EnableIntranet: netConfig.enableIntranet ?? false,
31
- EnableExtranet: netConfig.enableExtranet ?? true,
32
- },
33
- });
34
- // Tencent names Function URL triggers with a random id (e.g. "5obtzwwxw1"), not
35
- // our ${fn.key}-http-trigger, so name-based matching never finds them. A
36
- // Function URL trigger is identified by Type 'http' + a TriggerDesc carrying
37
- // the NetConfig field (the API Gateway flavor uses api/service/release instead).
38
- const isFunctionUrlTrigger = (t) => t.Type === 'http' && typeof t.TriggerDesc === 'string' && t.TriggerDesc.includes('NetConfig');
39
22
  const TIMER_TRIGGER_INSTANCE_TYPE = 'TENCENT_SCF_TIMER_TRIGGER';
40
23
  /** Tencent timer dialect: 7-field cron (UTC+8, `*` year), payload → CustomArgument. */
41
24
  const buildScfTimerTriggerConfig = (timer) => ({
@@ -243,13 +226,15 @@ const isLogConfigChanged = (desiredDefinition, existingDefinition) => {
243
226
  }
244
227
  return !(0, common_1.attributesEqual)(desiredLogConfig, existingDefinition.logConfig ?? {});
245
228
  };
246
- const buildScfInstanceFromProvider = (info, sid) => {
229
+ const isScfFunctionInstance = (instance) => typeof instance.functionName === 'string' || instance.type == null;
230
+ const buildScfInstanceFromProvider = (info, sid, ownedHttpIds = []) => {
247
231
  const envMap = info.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
248
232
  const triggersArray = info.Triggers?.map((t) => ({
249
233
  modTime: t.ModTime,
250
234
  type: t.Type,
251
235
  triggerDesc: t.TriggerDesc,
252
236
  triggerName: t.TriggerName,
237
+ ...(t.Type === 'http' ? { owned: ownedHttpIds.includes(t.TriggerName) } : {}),
253
238
  addTime: t.AddTime,
254
239
  enable: t.Enable,
255
240
  customArgument: t.CustomArgument ?? null,
@@ -473,7 +458,7 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
473
458
  clsInstances.push(logsetInstance, topicInstance);
474
459
  }
475
460
  else {
476
- const legacyFn = existingInstances.find((i) => i.type === undefined);
461
+ const legacyFn = existingInstances.find((i) => isScfFunctionInstance(i));
477
462
  if (legacyFn?.clsLogsetId && legacyFn?.clsTopicId) {
478
463
  clsConfig = {
479
464
  logsetId: legacyFn.clsLogsetId,
@@ -617,7 +602,7 @@ const createResource = async (context, fn, state) => {
617
602
  const codePath = fn.code.path;
618
603
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
619
604
  const codeHash = await (0, hashUtils_1.computeZipContentHash)(codePath);
620
- const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
605
+ const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam, fn);
621
606
  const dependentInstances = [...dependentResources.clsInstances];
622
607
  if (dependentResources.role) {
623
608
  const iamConfig = fn.iam?.role;
@@ -642,14 +627,10 @@ const createResource = async (context, fn, state) => {
642
627
  const stateWithShared = dependentResources.sharedInstance
643
628
  ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY, dependentResources.sharedInstance)
644
629
  : state;
645
- const stateAfterDependents = (0, stateManager_1.setResource)(stateWithShared, logicalId, taintedResourceState);
630
+ let stateAfterDependents = (0, stateManager_1.setResource)(stateWithShared, logicalId, taintedResourceState);
646
631
  const client = (0, tencentClient_1.createTencentClient)(context);
647
632
  const isTainted = existingResourceState?.status === 'tainted';
648
633
  const existingFunctionOnRetry = isTainted ? await client.scf.getFunction(fn.name) : null;
649
- // Provider info of a function adopted from a previous partial run (tainted
650
- // retry or reconciled after a create error) — used to skip already-attached
651
- // triggers below.
652
- let adoptedInfo = existingFunctionOnRetry;
653
634
  if (existingFunctionOnRetry) {
654
635
  logger_1.logger.info(lang_1.lang.__('TAINTED_RECOVERY_SKIP_CREATE', { resourceType: 'Function', resourceName: fn.name }));
655
636
  }
@@ -669,7 +650,6 @@ const createResource = async (context, fn, state) => {
669
650
  await delay(RECOVERY_GET_FUNCTION_DELAY_MS);
670
651
  const afterError = await client.scf.getFunction(fn.name);
671
652
  if (afterError) {
672
- adoptedInfo = afterError;
673
653
  logger_1.logger.info(lang_1.lang.__('FC3_FOUND_AFTER_CREATE_RECONCILE', { functionName: fn.name }));
674
654
  }
675
655
  else {
@@ -685,7 +665,6 @@ const createResource = async (context, fn, state) => {
685
665
  // a resource that was never ours).
686
666
  const probe = await client.scf.getFunction(fn.name);
687
667
  if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
688
- adoptedInfo = probe;
689
668
  logger_1.logger.info(lang_1.lang.__('RESOURCE_OWNERSHIP_TAG_ADOPT', {
690
669
  resourceType: 'Function',
691
670
  name: fn.name,
@@ -704,56 +683,17 @@ const createResource = async (context, fn, state) => {
704
683
  throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
705
684
  }
706
685
  }
707
- // Create HTTP trigger if configured
708
- if (fn.triggers?.http) {
709
- const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, fn.triggers.http.auth_type);
710
- const access = (0, common_1.mapAccess)(fn.triggers.http.access);
711
- const triggerName = `${fn.key}-http-trigger`;
712
- const triggerDesc = buildTencentTriggerDesc(authType, access);
713
- // Probe the provider for an already-attached trigger BEFORE attempting to
714
- // create it. A leftover trigger from a previous partial run (function exists
715
- // in cloud, state blank) would otherwise collide with CreateTrigger and
716
- // surface as a confusing empty error. Applies to both fresh creates (function
717
- // just created — Triggers from the createFunction flow) and tainted retries.
718
- let providerTriggers = adoptedInfo?.Triggers ?? [];
719
- if (providerTriggers.length === 0) {
720
- const probe = await client.scf.getFunction(fn.name);
721
- if (probe) {
722
- providerTriggers = probe.Triggers ?? [];
723
- }
724
- }
725
- const triggerAlreadyAttached = providerTriggers.some(isFunctionUrlTrigger);
726
- if (triggerAlreadyAttached) {
727
- logger_1.logger.info(lang_1.lang.__('SCF_HTTP_TRIGGER_ALREADY_ATTACHED', { triggerName, functionName: fn.name }));
728
- }
729
- else {
730
- logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
731
- try {
732
- await client.scf.createTrigger({
733
- FunctionName: fn.name,
734
- TriggerName: triggerName,
735
- Type: 'http',
736
- TriggerDesc: triggerDesc,
737
- Qualifier: '$DEFAULT',
738
- Enable: 'OPEN',
739
- });
740
- logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
741
- }
742
- catch (error) {
743
- if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
744
- logger_1.logger.warn(lang_1.lang.__('SCF_HTTP_TRIGGER_ALREADY_EXISTS', {
745
- triggerName,
746
- functionName: fn.name,
747
- error: String(error),
748
- }));
749
- }
750
- else {
751
- // The function exists in the cloud but the trigger failed to attach —
752
- // persist the tainted state so a re-run reconciles instead of losing it.
753
- throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
754
- }
755
- }
756
- }
686
+ try {
687
+ const httpInstances = await (0, scfHttpTrigger_1.reconcileScfHttpTrigger)(context, fn, existingResourceState?.instances ?? [], existingResourceState?.definition ?? {}, client, false, existingResourceState?.status === 'tainted');
688
+ dependentInstances.push(...httpInstances);
689
+ if (httpInstances.length)
690
+ stateAfterDependents = (0, stateManager_1.setResource)(stateAfterDependents, logicalId, {
691
+ ...taintedResourceState,
692
+ instances: [...dependentInstances],
693
+ });
694
+ }
695
+ catch (error) {
696
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
757
697
  }
758
698
  // Create timer triggers if configured — a failure mid-way persists the
759
699
  // tainted state so a re-run reconciles instead of duplicating triggers.
@@ -816,7 +756,9 @@ const createResource = async (context, fn, state) => {
816
756
  region: context.region,
817
757
  definition,
818
758
  instances: [
819
- buildScfInstanceFromProvider(functionInfo, sid),
759
+ buildScfInstanceFromProvider(functionInfo, sid, dependentInstances
760
+ .filter((instance) => instance.type === scfHttpTrigger_1.SCF_HTTP_TRIGGER_TYPE)
761
+ .map((instance) => instance.id)),
820
762
  ...dependentInstances,
821
763
  ],
822
764
  lastUpdated: new Date().toISOString(),
@@ -830,11 +772,12 @@ const readResource = async (context, functionName) => {
830
772
  return await client.scf.getFunction(functionName);
831
773
  };
832
774
  exports.readResource = readResource;
833
- const updateResource = async (context, fn, state, options) => {
834
- const logicalId = `functions.${fn.key}`;
775
+ const updateResource = async (context, providedFn, state, options) => {
776
+ const logicalId = `functions.${providedFn.key}`;
835
777
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
778
+ const fn = (0, functionDefinition_1.withStoredFunctionIam)(providedFn, existingState?.definition);
836
779
  const existingInstances = (existingState?.instances ?? []);
837
- const existingFnInstance = existingInstances.find((i) => i.type === undefined);
780
+ const existingFnInstance = existingInstances.find((i) => isScfFunctionInstance(i));
838
781
  const existingClsTopicInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC);
839
782
  const existingDefinition = (existingState?.definition ?? {});
840
783
  const legacyLogsetId = existingFnInstance?.clsLogsetId;
@@ -927,7 +870,7 @@ const updateResource = async (context, fn, state, options) => {
927
870
  let clsConfig;
928
871
  let clsTopicInstance;
929
872
  let clsSharedInstance;
930
- const disableLog = !fn.log && wasLogEnabled;
873
+ const disableLog = fn.log === false && wasLogEnabled;
931
874
  let topicToDelete;
932
875
  let topicNameToDelete;
933
876
  let sharedLogsetReleased = false;
@@ -994,7 +937,7 @@ const updateResource = async (context, fn, state, options) => {
994
937
  // Tencent's UpdateFunctionConfiguration rejects Handler/Runtime (immutable at
995
938
  // creation) and we don't want to re-send unchanged values. Handler/Runtime
996
939
  // changes are a hard error: the platform cannot apply them on update.
997
- const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
940
+ const desiredDefinition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam, fn);
998
941
  const CONFIG_DIFF_KEYS = ['runtime', 'handler', 'memorySize', 'timeout', 'environment', 'role'];
999
942
  const mutableKeys = CONFIG_DIFF_KEYS.filter((k) => k !== 'runtime' && k !== 'handler');
1000
943
  if (desiredDefinition.handler &&
@@ -1013,7 +956,7 @@ const updateResource = async (context, fn, state, options) => {
1013
956
  newRuntime: String(desiredDefinition.runtime),
1014
957
  }));
1015
958
  }
1016
- const configChanged = mutableKeys.some((k) => desiredDefinition[k] !== existingDefinition[k]) ||
959
+ const configChanged = mutableKeys.some((k) => (0, planCompare_1.definitionsDiffer)({ [k]: existingDefinition[k] }, { [k]: desiredDefinition[k] })) ||
1017
960
  isLogConfigChanged(desiredDefinition, existingDefinition) ||
1018
961
  // Disabling log always re-pushes config so the empty Cls ids reach the
1019
962
  // UpdateFunctionConfiguration unbind contract.
@@ -1043,149 +986,26 @@ const updateResource = async (context, fn, state, options) => {
1043
986
  }
1044
987
  // Update code
1045
988
  await client.scf.updateFunctionCode(fn.name, codeBase64);
1046
- const existingHttpTrigger = existingFnInstance?.triggers?.find((t) => t.type === 'http');
1047
- const desiredHttpConfig = fn.triggers?.http;
1048
- if (desiredHttpConfig) {
1049
- if (!desiredHttpConfig.auth_type) {
1050
- throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
1051
- }
1052
- const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.TENCENT, desiredHttpConfig.auth_type);
1053
- const access = (0, common_1.mapAccess)(desiredHttpConfig.access);
1054
- const triggerName = `${fn.key}-http-trigger`;
1055
- const desiredTriggerDesc = buildTencentTriggerDesc(authType, access);
1056
- if (existingHttpTrigger) {
1057
- if (existingHttpTrigger.triggerDesc !== desiredTriggerDesc) {
1058
- logger_1.logger.info(lang_1.lang.__('UPDATING_HTTP_TRIGGER', { functionName: fn.name }));
1059
- try {
1060
- await client.scf.deleteTrigger({
1061
- FunctionName: fn.name,
1062
- TriggerName: existingHttpTrigger.triggerName,
1063
- Type: 'http',
1064
- });
1065
- }
1066
- catch (err) {
1067
- const errorCode = err?.code;
1068
- if (errorCode !== 'ResourceNotFound.TriggerName' && errorCode !== 'ResourceNotFound') {
1069
- throw err;
1070
- }
1071
- }
1072
- await client.scf.createTrigger({
1073
- FunctionName: fn.name,
1074
- TriggerName: triggerName,
1075
- Type: 'http',
1076
- TriggerDesc: desiredTriggerDesc,
1077
- Qualifier: '$DEFAULT',
1078
- Enable: 'OPEN',
1079
- });
1080
- }
1081
- }
1082
- else {
1083
- // No trigger recorded in state — but a leftover trigger may still exist
1084
- // in the provider (e.g. adopted function whose state lacked trigger
1085
- // records). Probe before creating to stay idempotent.
1086
- const probe = await client.scf.getFunction(fn.name);
1087
- const providerTriggerAttached = (probe?.Triggers ?? []).some(isFunctionUrlTrigger);
1088
- if (providerTriggerAttached) {
1089
- logger_1.logger.info(lang_1.lang.__('SCF_HTTP_TRIGGER_ALREADY_ATTACHED', { triggerName, functionName: fn.name }));
1090
- }
1091
- else {
1092
- logger_1.logger.info(lang_1.lang.__('CREATING_HTTP_TRIGGER', { triggerName, functionName: fn.name }));
1093
- try {
1094
- await client.scf.createTrigger({
1095
- FunctionName: fn.name,
1096
- TriggerName: triggerName,
1097
- Type: 'http',
1098
- TriggerDesc: desiredTriggerDesc,
1099
- Qualifier: '$DEFAULT',
1100
- Enable: 'OPEN',
1101
- });
1102
- logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName, functionName: fn.name }));
1103
- }
1104
- catch (error) {
1105
- if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
1106
- logger_1.logger.warn(lang_1.lang.__('SCF_HTTP_TRIGGER_ALREADY_EXISTS', {
1107
- triggerName,
1108
- functionName: fn.name,
1109
- error: String(error),
1110
- }));
1111
- }
1112
- else {
1113
- throw error;
1114
- }
1115
- }
1116
- }
1117
- }
1118
- }
1119
- else if (existingHttpTrigger) {
1120
- const tName = existingHttpTrigger.triggerName;
1121
- logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: tName, functionName: fn.name }));
1122
- try {
1123
- await client.scf.deleteTrigger({
1124
- FunctionName: fn.name,
1125
- TriggerName: tName,
1126
- Type: 'http',
1127
- });
1128
- logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName: tName }));
1129
- }
1130
- catch (err) {
1131
- const errorCode = err?.code;
1132
- if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
1133
- logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: tName }));
1134
- }
1135
- else {
1136
- throw err;
1137
- }
1138
- }
1139
- }
1140
- // Reconcile timer triggers against the provider (issue #258) — the live
1141
- // GetFunction trigger list is the baseline so console edits converge.
1142
- const timerInstances = await reconcileScfTimerTriggers(context, fn, existingInstances, client);
1143
- // Reconcile custom domain
1144
- const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
1145
- if (fn.domain && !existingCustomDomain) {
1146
- logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
1147
- await client.scf.createCustomDomain({
1148
- Domain: fn.domain.domain_name,
1149
- Protocol: fn.domain.protocol,
1150
- EndpointsConfig: [
1151
- {
1152
- Namespace: 'default',
1153
- FunctionName: fn.name,
1154
- Qualifier: '$DEFAULT',
1155
- PathMatch: '/*',
1156
- },
1157
- ],
1158
- ...(fn.domain.certificate_id
1159
- ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
1160
- : {}),
1161
- });
1162
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
1163
- }
1164
- else if (!fn.domain && existingCustomDomain) {
1165
- logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1166
- try {
1167
- await client.scf.deleteCustomDomain(existingCustomDomain.id);
1168
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
1169
- }
1170
- catch (err) {
1171
- const errorCode = err?.code;
1172
- if (errorCode === 'ResourceNotFound') {
1173
- logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
1174
- resourceType: 'Custom Domain',
1175
- name: existingCustomDomain.id,
1176
- }));
1177
- }
1178
- else {
1179
- throw err;
1180
- }
1181
- }
1182
- }
1183
- else if (fn.domain && existingCustomDomain) {
1184
- const domainChanged = fn.domain.domain_name !== existingCustomDomain.id ||
1185
- fn.domain.protocol !== existingCustomDomain.protocol;
1186
- if (domainChanged) {
1187
- logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1188
- await client.scf.deleteCustomDomain(existingCustomDomain.id);
989
+ const httpInstances = await (0, scfHttpTrigger_1.reconcileScfHttpTrigger)(context, fn, existingInstances, existingState?.definition ?? {}, client, options?.repairHttp);
990
+ const stateAfterHttp = (0, stateManager_1.setResource)(state, logicalId, {
991
+ ...(existingState ?? {
992
+ mode: 'managed',
993
+ region: context.region,
994
+ definition: existingDefinition,
995
+ lastUpdated: new Date().toISOString(),
996
+ }),
997
+ instances: [
998
+ ...(existingState?.instances ?? []).filter((instance) => instance.type !== scfHttpTrigger_1.SCF_HTTP_TRIGGER_TYPE),
999
+ ...httpInstances,
1000
+ ],
1001
+ });
1002
+ try {
1003
+ // Reconcile timer triggers against the provider (issue #258) — the live
1004
+ // GetFunction trigger list is the baseline so console edits converge.
1005
+ const timerInstances = await reconcileScfTimerTriggers(context, fn, existingInstances, client);
1006
+ // Reconcile custom domain
1007
+ const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
1008
+ if (fn.domain && !existingCustomDomain) {
1189
1009
  logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
1190
1010
  await client.scf.createCustomDomain({
1191
1011
  Domain: fn.domain.domain_name,
@@ -1204,103 +1024,131 @@ const updateResource = async (context, fn, state, options) => {
1204
1024
  });
1205
1025
  logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
1206
1026
  }
1207
- }
1208
- // Refresh state from provider to get all attributes (including triggers)
1209
- const functionInfo = await client.scf.getFunction(fn.name);
1210
- if (!functionInfo) {
1211
- throw new Error(lang_1.lang.__('REFRESH_STATE_FUNCTION', { name: fn.name }));
1212
- }
1213
- const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
1214
- const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
1215
- const existingDependentInstances = existingInstances
1216
- .filter((i) => i.type !== undefined &&
1217
- i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
1218
- // timers are fully rebuilt from the reconcile result below
1219
- i.type !== TIMER_TRIGGER_INSTANCE_TYPE &&
1220
- !((clsTopicInstance || disableLog) &&
1221
- (i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC ||
1222
- i.type === types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET)))
1223
- .map((i) => {
1224
- const { type, id, sid, roleArn, external } = i;
1225
- return {
1226
- sid: sid ?? (0, common_1.buildSid)('tencent', 'scf-role', context.stage, id),
1227
- type,
1228
- id,
1229
- ...(roleArn ? { roleArn } : {}),
1230
- ...(external ? { external } : {}),
1231
- };
1232
- });
1233
- const newDependentInstances = [];
1234
- if (role && !hasCamRole && typeof newIamRole !== 'string') {
1235
- const newRoleSid = (0, common_1.buildSid)('tencent', 'scf-role', context.stage, role.roleName ?? '');
1236
- newDependentInstances.push({
1237
- sid: newRoleSid,
1238
- type: types_1.ResourceTypeEnum.TENCENT_SCF_ROLE,
1239
- id: role.roleName ?? '',
1240
- ...(role.arn ? { roleArn: role.arn } : {}),
1241
- });
1242
- }
1243
- if (fn.domain) {
1244
- const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
1245
- newDependentInstances.push({
1246
- sid: domainSid,
1247
- type: 'TENCENT_SCF_CUSTOM_DOMAIN',
1248
- id: fn.domain.domain_name,
1249
- protocol: fn.domain.protocol,
1027
+ else if (!fn.domain && existingCustomDomain) {
1028
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1029
+ try {
1030
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
1031
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
1032
+ }
1033
+ catch (err) {
1034
+ const errorCode = err?.code;
1035
+ if (errorCode !== 'ResourceNotFound')
1036
+ throw err;
1037
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
1038
+ resourceType: 'Custom Domain',
1039
+ name: existingCustomDomain.id,
1040
+ }));
1041
+ }
1042
+ }
1043
+ else if (fn.domain && existingCustomDomain) {
1044
+ const domainChanged = options?.repairDomain ||
1045
+ !(0, common_1.attributesEqual)(existingState?.definition?.domain ?? {}, fn.domain) ||
1046
+ fn.domain.domain_name !== existingCustomDomain.id ||
1047
+ fn.domain.protocol !== existingCustomDomain.protocol;
1048
+ if (domainChanged) {
1049
+ logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1050
+ await client.scf.deleteCustomDomain(existingCustomDomain.id);
1051
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
1052
+ await client.scf.createCustomDomain({
1053
+ Domain: fn.domain.domain_name,
1054
+ Protocol: fn.domain.protocol,
1055
+ EndpointsConfig: [
1056
+ {
1057
+ Namespace: 'default',
1058
+ FunctionName: fn.name,
1059
+ Qualifier: '$DEFAULT',
1060
+ PathMatch: '/*',
1061
+ },
1062
+ ],
1063
+ ...(fn.domain.certificate_id
1064
+ ? { CertConfig: { CertificateId: fn.domain.certificate_id } }
1065
+ : {}),
1066
+ });
1067
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
1068
+ }
1069
+ }
1070
+ // Refresh state from provider to get all attributes (including triggers)
1071
+ const functionInfo = await client.scf.getFunction(fn.name);
1072
+ if (!functionInfo) {
1073
+ throw new Error(lang_1.lang.__('REFRESH_STATE_FUNCTION', { name: fn.name }));
1074
+ }
1075
+ const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam, fn);
1076
+ const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
1077
+ const existingDependentInstances = existingInstances
1078
+ .filter((i) => !isScfFunctionInstance(i) &&
1079
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
1080
+ // timers are fully rebuilt from the reconcile result below
1081
+ i.type !== TIMER_TRIGGER_INSTANCE_TYPE &&
1082
+ i.type !== scfHttpTrigger_1.SCF_HTTP_TRIGGER_TYPE &&
1083
+ !((clsTopicInstance || disableLog) &&
1084
+ (i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC ||
1085
+ i.type === types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET)))
1086
+ .map((i) => {
1087
+ const { type, id, sid, roleArn, external } = i;
1088
+ return {
1089
+ sid: sid ?? (0, common_1.buildSid)('tencent', 'scf-role', context.stage, id),
1090
+ type,
1091
+ id,
1092
+ ...(roleArn ? { roleArn } : {}),
1093
+ ...(external ? { external } : {}),
1094
+ };
1250
1095
  });
1096
+ const newDependentInstances = [];
1097
+ if (role && !hasCamRole && typeof newIamRole !== 'string') {
1098
+ const newRoleSid = (0, common_1.buildSid)('tencent', 'scf-role', context.stage, role.roleName ?? '');
1099
+ newDependentInstances.push({
1100
+ sid: newRoleSid,
1101
+ type: types_1.ResourceTypeEnum.TENCENT_SCF_ROLE,
1102
+ id: role.roleName ?? '',
1103
+ ...(role.arn ? { roleArn: role.arn } : {}),
1104
+ });
1105
+ }
1106
+ if (fn.domain) {
1107
+ const domainSid = (0, common_1.buildSid)('tencent', 'scf-custom-domain', context.stage, fn.domain.domain_name);
1108
+ newDependentInstances.push({
1109
+ sid: domainSid,
1110
+ type: 'TENCENT_SCF_CUSTOM_DOMAIN',
1111
+ id: fn.domain.domain_name,
1112
+ protocol: fn.domain.protocol,
1113
+ });
1114
+ }
1115
+ if (clsTopicInstance) {
1116
+ newDependentInstances.push(clsTopicInstance);
1117
+ }
1118
+ const resourceState = {
1119
+ mode: 'managed',
1120
+ region: context.region,
1121
+ definition: (0, functionDefinition_1.withLifecycleIntent)((0, planCompare_1.mergeManagedIntent)(existingState?.definition ?? {}, definition), definition, ['http', 'domain', 'timers']),
1122
+ instances: [
1123
+ buildScfInstanceFromProvider(functionInfo, sid, httpInstances.map((instance) => instance.id)),
1124
+ ...existingDependentInstances,
1125
+ ...newDependentInstances,
1126
+ ...timerInstances,
1127
+ ...httpInstances,
1128
+ ],
1129
+ lastUpdated: new Date().toISOString(),
1130
+ };
1131
+ const stateWithShared = clsSharedInstance
1132
+ ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY, clsSharedInstance)
1133
+ : sharedLogsetReleased
1134
+ ? (0, stateManager_1.removeSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY)
1135
+ : state;
1136
+ return (0, stateManager_1.setResource)(stateWithShared, logicalId, resourceState);
1251
1137
  }
1252
- if (clsTopicInstance) {
1253
- newDependentInstances.push(clsTopicInstance);
1138
+ catch (error) {
1139
+ if (error instanceof types_1.PartialResourceError)
1140
+ throw error;
1141
+ throw new types_1.PartialResourceError(stateAfterHttp, new Error(toErrorMessage(error)));
1254
1142
  }
1255
- const resourceState = {
1256
- mode: 'managed',
1257
- region: context.region,
1258
- definition,
1259
- instances: [
1260
- buildScfInstanceFromProvider(functionInfo, sid),
1261
- ...existingDependentInstances,
1262
- ...newDependentInstances,
1263
- ...timerInstances,
1264
- ],
1265
- lastUpdated: new Date().toISOString(),
1266
- };
1267
- const stateWithShared = clsSharedInstance
1268
- ? (0, stateManager_1.setSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY, clsSharedInstance)
1269
- : sharedLogsetReleased
1270
- ? (0, stateManager_1.removeSharedResource)(state, context.stage, sharedLogset_1.SHARED_LOGSET_KEY)
1271
- : state;
1272
- return (0, stateManager_1.setResource)(stateWithShared, logicalId, resourceState);
1273
1143
  };
1274
1144
  exports.updateResource = updateResource;
1275
1145
  const deleteResource = async (context, functionName, logicalId, state) => {
1276
1146
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
1277
1147
  const existingInstances = (existingState?.instances ?? []);
1278
1148
  const client = (0, tencentClient_1.createTencentClient)(context);
1279
- // Delete HTTP trigger before deleting function
1280
- const fnInstance = existingInstances.find((i) => i.type === undefined);
1281
- const httpTrigger = fnInstance?.triggers?.find((t) => t.type === 'http');
1282
- if (httpTrigger) {
1283
- try {
1284
- const triggerName = httpTrigger.triggerName;
1285
- logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName, functionName }));
1286
- await client.scf.deleteTrigger({
1287
- FunctionName: functionName,
1288
- TriggerName: triggerName,
1289
- Type: 'http',
1290
- });
1291
- logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName }));
1292
- }
1293
- catch (err) {
1294
- const errorCode = err?.code;
1295
- if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
1296
- logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', {
1297
- triggerName: httpTrigger.triggerName,
1298
- }));
1299
- }
1300
- else {
1301
- throw err;
1302
- }
1303
- }
1149
+ const ownedHttp = (0, scfHttpTrigger_1.ownedScfHttpTrigger)(existingInstances, existingState?.definition ?? {});
1150
+ if (ownedHttp) {
1151
+ await (0, scfHttpTrigger_1.reconcileScfHttpTrigger)(context, { name: functionName }, existingInstances, existingState?.definition ?? {}, client);
1304
1152
  }
1305
1153
  // Delete timer triggers before deleting function
1306
1154
  const timerTriggerInstances = existingInstances.filter((i) => i.type === TIMER_TRIGGER_INSTANCE_TYPE);
@@ -1329,7 +1177,7 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1329
1177
  }
1330
1178
  }
1331
1179
  }
1332
- const hasFunction = existingInstances.some((i) => i.type === undefined);
1180
+ const hasFunction = existingInstances.some((i) => isScfFunctionInstance(i));
1333
1181
  if (hasFunction) {
1334
1182
  try {
1335
1183
  await client.scf.deleteFunction(functionName);
@@ -1344,10 +1192,11 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1344
1192
  }
1345
1193
  }
1346
1194
  }
1347
- const dependentInstances = existingInstances.filter((i) => i.type !== undefined &&
1195
+ const dependentInstances = existingInstances.filter((i) => !isScfFunctionInstance(i) &&
1348
1196
  i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
1349
1197
  // timers were deleted explicitly above
1350
- i.type !== TIMER_TRIGGER_INSTANCE_TYPE);
1198
+ i.type !== TIMER_TRIGGER_INSTANCE_TYPE &&
1199
+ i.type !== scfHttpTrigger_1.SCF_HTTP_TRIGGER_TYPE);
1351
1200
  if (dependentInstances.length > 0) {
1352
1201
  await deleteDependentResources(context, dependentInstances);
1353
1202
  }