@geek-fun/serverlessinsight 0.8.1 → 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 +332 -32
  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 +230 -125
  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
@@ -5,6 +5,7 @@ const common_1 = require("../../common");
5
5
  const stateManager_1 = require("../../common/stateManager");
6
6
  const volcengineClient_1 = require("../../common/volcengineClient");
7
7
  const vefaasTypes_1 = require("./vefaasTypes");
8
+ const ownershipTag_1 = require("../ownershipTag");
8
9
  const planFunctionDeletion = (logicalId, definition) => ({
9
10
  logicalId,
10
11
  action: 'delete',
@@ -25,10 +26,57 @@ const generateFunctionPlan = async (context, state, functions) => {
25
26
  const currentState = (0, common_1.getResource)(state, logicalId);
26
27
  const config = (0, vefaasTypes_1.functionToVefaasConfig)(fn);
27
28
  const codePath = fn.code.path;
28
- const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
29
+ const desiredCodeHash = await (0, common_1.computeZipContentHash)(codePath);
30
+ // Mirror the executor's auto-role behavior: when the YAML omits
31
+ // `iam.role`, the executor reuses the IAM role recorded in state
32
+ // (createDependentResources persists a VOLCENGINE_IAM_ROLE instance and
33
+ // reuses it on subsequent deploys). Deriving the same trn here keeps the
34
+ // plan's desired definition in sync with what the executor will apply —
35
+ // otherwise every plan shows a phantom `role: <trn> -> null` drift.
36
+ if (!fn.iam && currentState?.instances?.length) {
37
+ const roleInstance = currentState.instances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
38
+ if (roleInstance?.trn) {
39
+ config.role = roleInstance.trn;
40
+ }
41
+ }
42
+ // Mirror the executor's TLS log-resource behavior: functionToVefaasConfig(fn)
43
+ // never sets logConfig on its own (it's only populated via the second
44
+ // `options` argument), so without this the diff below always compares
45
+ // desiredDefinition.logConfig === undefined regardless of `fn.log` in the
46
+ // YAML — meaning `log: true` could never be detected as drift and the
47
+ // planner would report `noop` forever, so `UpdateFunction`'s `TlsConfig`
48
+ // never gets sent. Derive the same project/topic names
49
+ // createDependentResources would use (existing TLS instances in state
50
+ // take priority; otherwise the deterministic `{service}-{stage}-tls` /
51
+ // `{service}-{stage}-logs` names) so the diff can see the field change.
52
+ if (fn.log) {
53
+ if (currentState?.instances?.length) {
54
+ const tlsTopicInstance = currentState.instances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
55
+ if (tlsTopicInstance?.id) {
56
+ const [projectName, topicName] = tlsTopicInstance.id.split('/');
57
+ config.logConfig = { project: projectName, topic: topicName };
58
+ }
59
+ }
60
+ if (!config.logConfig) {
61
+ const serviceName = `${context.app}-${context.service}`;
62
+ config.logConfig = {
63
+ project: `${serviceName}-${context.stage}-tls`,
64
+ topic: `${serviceName}-${context.stage}-logs`,
65
+ };
66
+ }
67
+ }
29
68
  const baseDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
30
69
  const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
31
70
  if (!currentState || currentState.status === 'tainted') {
71
+ // No usable local state: probe the provider before planning create.
72
+ // If a same-named function already exists WITHOUT our ownership tag it
73
+ // may belong to another project — fail fast in the plan instead of
74
+ // letting the executor discover it mid-deploy.
75
+ const client = (0, volcengineClient_1.createVolcengineClient)(context);
76
+ const remoteFunction = await client.vefaas.getFunction(fn.name);
77
+ if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.Tags)) {
78
+ throw new Error(`Function ${fn.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
79
+ }
32
80
  return {
33
81
  logicalId,
34
82
  action: 'create',
@@ -53,7 +101,28 @@ const generateFunctionPlan = async (context, state, functions) => {
53
101
  }
54
102
  const currentDefinition = currentState.definition || {};
55
103
  const definitionChanged = !(0, common_1.attributesEqual)(currentDefinition, desiredDefinition);
56
- if (definitionChanged) {
104
+ // Drift detection against the LIVE provider: compare the remote
105
+ // function's actual attributes (runtime/handler/memory/timeout/env)
106
+ // against the desired definition. Console edits would otherwise go
107
+ // undetected — definitionChanged only sees local-vs-desired.
108
+ const remoteAttributes = {
109
+ runtime: remoteFunction.runtime,
110
+ handler: remoteFunction.handler,
111
+ memorySize: remoteFunction.memoryMb,
112
+ timeout: remoteFunction.requestTimeout,
113
+ environment: remoteFunction.environmentVariables,
114
+ // Provider responses carry `null` for unset fields while the desired
115
+ // definition carries `undefined` — normalize null → undefined so the
116
+ // comparison ignores the representation difference.
117
+ description: remoteFunction.description ?? undefined,
118
+ role: remoteFunction.role ?? undefined,
119
+ vpcConfig: remoteFunction.vpcConfig ?? undefined,
120
+ logConfig: remoteFunction.logConfig
121
+ ? { project: remoteFunction.logConfig.project, topic: remoteFunction.logConfig.topic }
122
+ : undefined,
123
+ };
124
+ const remoteMatchesDesired = (0, common_1.attributesEqual)(remoteAttributes, desiredDefinition);
125
+ if (definitionChanged || !remoteMatchesDesired) {
57
126
  return {
58
127
  logicalId,
59
128
  action: 'update',
@@ -1,37 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
37
4
  const volcengineClient_1 = require("../../common/volcengineClient");
@@ -40,8 +7,24 @@ const types_1 = require("../../types");
40
7
  const vefaasTypes_1 = require("./vefaasTypes");
41
8
  const logger_1 = require("../../common/logger");
42
9
  const lang_1 = require("../../lang");
10
+ const ownershipTag_1 = require("../ownershipTag");
11
+ const alreadyExists_1 = require("../alreadyExists");
43
12
  const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
13
+ // volcengine role TRN format: trn:iam::{accountId}:role/{roleName}. Prefer the
14
+ // stored TRN; else construct from the known accountId, else fetch it via STS.
15
+ const resolveRoleTrn = async (client, context, roleName, storedTrn) => {
16
+ if (storedTrn)
17
+ return storedTrn;
18
+ if (context.accountId)
19
+ return `trn:iam::${context.accountId}:role/${roleName}`;
20
+ const accountId = await client.sts.getAccountId();
21
+ return accountId ? `trn:iam::${accountId}:role/${roleName}` : undefined;
22
+ };
44
23
  const IAM_ROLE_PROPAGATION_DELAY_MS = 3000;
24
+ // Volcengine SDK surfaces "resource already exists" collisions with code
25
+ // `Conflict` (the shared isResourceAlreadyExistsError also matches the message
26
+ // "already exists" / "已存在" for the veFaaS flavor of the error).
27
+ const VEFAAS_ALREADY_EXISTS_CODES = ['Conflict'];
45
28
  const delay = async (ms) => {
46
29
  await new Promise((resolve) => {
47
30
  setTimeout(resolve, ms);
@@ -75,24 +58,48 @@ const buildVefaasInstanceFromProvider = (info, sid) => {
75
58
  memorySize: info.memoryMb ?? null,
76
59
  timeout: info.requestTimeout ?? null,
77
60
  environment: info.environmentVariables ?? {},
78
- description: info.description ?? null,
61
+ description: info.description ?? undefined,
79
62
  status: info.status ?? null,
80
63
  createdTime: info.createdTime ?? null,
81
64
  lastUpdateTime: info.lastModifiedTime ?? null,
82
- role: info.role ?? null,
65
+ role: info.role ?? undefined,
83
66
  vpcConfig: info.vpcConfig
84
67
  ? {
85
- vpcId: info.vpcConfig.vpcId ?? null,
68
+ vpcId: info.vpcConfig.vpcId ?? undefined,
86
69
  subnetIds: info.vpcConfig.subnetIds ?? [],
87
70
  securityGroupIds: info.vpcConfig.securityGroupIds ?? [],
71
+ enableVpc: info.vpcConfig.enableVpc ?? undefined,
72
+ enableSharedInternetAccess: info.vpcConfig.enableSharedInternetAccess ?? undefined,
88
73
  }
89
- : {},
74
+ : undefined,
90
75
  logConfig: info.logConfig
91
76
  ? {
92
- project: info.logConfig.project ?? null,
93
- topic: info.logConfig.topic ?? null,
77
+ project: info.logConfig.project ?? undefined,
78
+ topic: info.logConfig.topic ?? undefined,
79
+ enableLog: info.logConfig.enableLog ?? undefined,
94
80
  }
95
- : null,
81
+ : undefined,
82
+ Tags: info.Tags,
83
+ exclusiveMode: info.exclusiveMode,
84
+ maxConcurrency: info.maxConcurrency,
85
+ codeSize: info.codeSize,
86
+ codeSizeLimit: info.codeSizeLimit,
87
+ sourceLocation: info.sourceLocation,
88
+ sourceType: info.sourceType,
89
+ owner: info.owner,
90
+ triggersCount: info.triggersCount,
91
+ instanceType: info.instanceType,
92
+ initializerSec: info.initializerSec,
93
+ command: info.command,
94
+ port: info.port,
95
+ cpuStrategy: info.cpuStrategy,
96
+ projectName: info.projectName,
97
+ functionType: info.functionType,
98
+ cell: info.cell,
99
+ enableApmplus: info.enableApmplus,
100
+ nasStorage: info.nasStorage,
101
+ tosMountConfig: info.tosMountConfig,
102
+ asyncTaskConfig: info.asyncTaskConfig,
96
103
  };
97
104
  };
98
105
  const createDependentResources = async (context, fn, serviceName, existingInstances = []) => {
@@ -196,8 +203,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
196
203
  if (!iamRoleInstance) {
197
204
  throw new Error(lang_1.lang.__('IAM_ROLE_INSTANCE_NOT_FOUND', { roleName }));
198
205
  }
199
- const trn = iamRoleInstance.trn ??
200
- (context.accountId ? `trn:iam::${context.accountId}:role/${iamRoleInstance.id}` : undefined);
206
+ const trn = await resolveRoleTrn(client, context, iamRoleInstance.id, iamRoleInstance.trn);
201
207
  if (!trn) {
202
208
  throw new Error(lang_1.lang.__('IAM_ROLE_TRN_MISSING', { roleName }));
203
209
  }
@@ -214,44 +220,35 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
214
220
  const deleteDependentResources = async (context, instances) => {
215
221
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
216
222
  for (const instance of [...instances].reverse()) {
217
- try {
218
- switch (instance.type) {
219
- case 'VOLCENGINE_TLS_INDEX': {
220
- const [projectName, topicName] = instance.id.split('/');
221
- logger_1.logger.info(lang_1.lang.__('DELETING_TLS_INDEX', { id: instance.id }));
222
- await client.tls.deleteIndex(projectName, topicName);
223
- break;
224
- }
225
- case 'VOLCENGINE_TLS_TOPIC': {
226
- const [projectName, topicName] = instance.id.split('/');
227
- logger_1.logger.info(lang_1.lang.__('DELETING_TLS_TOPIC', { id: instance.id }));
228
- await client.tls.deleteTopic(projectName, topicName);
229
- break;
230
- }
231
- case 'VOLCENGINE_TLS_PROJECT':
232
- logger_1.logger.info(lang_1.lang.__('DELETING_TLS_PROJECT', { id: instance.id }));
233
- await client.tls.deleteProject(instance.id);
234
- break;
235
- case 'VOLCENGINE_IAM_ROLE': {
236
- const attrs = instance.attributes;
237
- if (attrs?.external === true) {
238
- logger_1.logger.info(`Skipping deletion of external IAM role: ${instance.id} (managed externally)`);
239
- break;
240
- }
241
- logger_1.logger.info(lang_1.lang.__('DELETING_IAM_ROLE', { id: instance.id }));
242
- await client.iam.deleteRole(instance.id);
223
+ switch (instance.type) {
224
+ case 'VOLCENGINE_TLS_INDEX': {
225
+ const [projectName, topicName] = instance.id.split('/');
226
+ logger_1.logger.info(lang_1.lang.__('DELETING_TLS_INDEX', { id: instance.id }));
227
+ await client.tls.deleteIndex(projectName, topicName);
228
+ break;
229
+ }
230
+ case 'VOLCENGINE_TLS_TOPIC': {
231
+ const [projectName, topicName] = instance.id.split('/');
232
+ logger_1.logger.info(lang_1.lang.__('DELETING_TLS_TOPIC', { id: instance.id }));
233
+ await client.tls.deleteTopic(projectName, topicName);
234
+ break;
235
+ }
236
+ case 'VOLCENGINE_TLS_PROJECT':
237
+ logger_1.logger.info(lang_1.lang.__('DELETING_TLS_PROJECT', { id: instance.id }));
238
+ await client.tls.deleteProject(instance.id);
239
+ break;
240
+ case 'VOLCENGINE_IAM_ROLE': {
241
+ const attrs = instance.attributes;
242
+ if (attrs?.external === true) {
243
+ logger_1.logger.info(`Skipping deletion of external IAM role: ${instance.id} (managed externally)`);
243
244
  break;
244
245
  }
245
- default:
246
- logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
246
+ logger_1.logger.info(lang_1.lang.__('DELETING_IAM_ROLE', { id: instance.id }));
247
+ await client.iam.deleteRole(instance.id);
248
+ break;
247
249
  }
248
- }
249
- catch (err) {
250
- logger_1.logger.error(lang_1.lang.__('FAILED_TO_DELETE_RESOURCE', {
251
- type: instance.type,
252
- id: instance.id,
253
- error: String(err),
254
- }));
250
+ default:
251
+ logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
255
252
  }
256
253
  }
257
254
  };
@@ -278,8 +275,9 @@ const createResource = async (context, fn, state) => {
278
275
  }
279
276
  : undefined,
280
277
  });
278
+ config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
281
279
  const codePath = fn.code.path;
282
- const codeHash = (0, common_1.computeFileHash)(codePath);
280
+ const codeHash = await (0, common_1.computeZipContentHash)(codePath);
283
281
  const resourceAttributes = (0, vefaasTypes_1.extractVefaasDefinition)(config, codeHash);
284
282
  const definition = fn.iam ? { ...resourceAttributes, iam: fn.iam } : resourceAttributes;
285
283
  const sid = (0, common_1.buildSid)('volcengine', context.service, context.stage, fn.name);
@@ -315,11 +313,14 @@ const createResource = async (context, fn, state) => {
315
313
  if (existingFunctionOnRetry) {
316
314
  logger_1.logger.info(lang_1.lang.__('VEFAAS_FUNCTION_EXISTS_RECOVERY', { functionName: fn.name }));
317
315
  }
316
+ let createdFunctionId;
317
+ let releaseRecordId;
318
318
  try {
319
319
  if (!existingFunctionOnRetry) {
320
- const codeContent = await Promise.resolve().then(() => __importStar(require('node:fs'))).then((fs) => fs.readFileSync(codePath));
321
- const codeBase64 = codeContent.toString('base64');
322
- await client.vefaas.createFunction(config, codeBase64);
320
+ // createFunction validates + base64-encodes the zip at codePath itself.
321
+ const created = await client.vefaas.createFunction(config, codePath);
322
+ createdFunctionId = created.functionId;
323
+ releaseRecordId = created.releaseRecordId;
323
324
  }
324
325
  }
325
326
  catch (error) {
@@ -330,15 +331,35 @@ const createResource = async (context, fn, state) => {
330
331
  throw new types_1.PartialResourceError(stateAfterDependents, error);
331
332
  }
332
333
  }
334
+ else if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error, VEFAAS_ALREADY_EXISTS_CODES)) {
335
+ // Idempotent adoption: the function already exists in the provider.
336
+ // Adopt it ONLY if it carries our ownership tag (proves a previous run
337
+ // of THIS stack created it — e.g. state was reset). An untagged
338
+ // same-named function may belong to another project, so it must fail
339
+ // loudly rather than silently taking it over (destroy would then remove
340
+ // a resource that was never ours).
341
+ const probe = await client.vefaas.getFunction(fn.name);
342
+ if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
343
+ logger_1.logger.info(`Function ${fn.name} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
344
+ }
345
+ else {
346
+ 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.`));
347
+ }
348
+ }
333
349
  else {
334
350
  throw new types_1.PartialResourceError(stateAfterDependents, error);
335
351
  }
336
352
  }
337
- const functionInfo = await client.vefaas.getFunction(fn.name);
353
+ const functionInfo = createdFunctionId
354
+ ? await client.vefaas.getFunctionById(createdFunctionId)
355
+ : await client.vefaas.getFunction(fn.name);
338
356
  if (!functionInfo) {
339
357
  throw new Error(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: fn.name }));
340
358
  }
341
359
  const vefaasInstance = buildVefaasInstanceFromProvider(functionInfo, sid);
360
+ if (releaseRecordId) {
361
+ vefaasInstance.releaseRecordId = releaseRecordId;
362
+ }
342
363
  const resourceState = {
343
364
  mode: 'managed',
344
365
  region: context.region,
@@ -375,9 +396,22 @@ const updateResource = async (context, fn, state) => {
375
396
  let logConfig;
376
397
  let role;
377
398
  if (fn.log && !hasTlsResources && !isTainted) {
378
- const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { disk: undefined, nas: undefined } }, serviceName);
379
- logConfig = deps.logConfig;
380
- newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_')));
399
+ // Persist a tainted state BEFORE creating dependent TLS resources so a
400
+ // partial failure (e.g. project created but topic creation fails) leaves a
401
+ // tainted marker for the executor instead of orphaning cloud resources
402
+ // untracked. A retry then resumes with the tainted state.
403
+ const stateAfterDependents = (0, common_1.setResource)(state, logicalId, {
404
+ ...currentState,
405
+ status: 'tainted',
406
+ });
407
+ try {
408
+ const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { disk: undefined, nas: undefined } }, serviceName);
409
+ logConfig = deps.logConfig;
410
+ newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_')));
411
+ }
412
+ catch (error) {
413
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
414
+ }
381
415
  }
382
416
  else if (hasTlsResources) {
383
417
  const tlsProjectInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
@@ -402,10 +436,7 @@ const updateResource = async (context, fn, state) => {
402
436
  else {
403
437
  const iamRoleInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
404
438
  if (iamRoleInstance) {
405
- const trn = iamRoleInstance.trn ??
406
- (context.accountId
407
- ? `trn:iam::${context.accountId}:role/${iamRoleInstance.id}`
408
- : undefined);
439
+ const trn = await resolveRoleTrn(client, context, iamRoleInstance.id, iamRoleInstance.trn);
409
440
  if (!trn) {
410
441
  throw new Error(lang_1.lang.__('IAM_ROLE_TRN_MISSING', { roleName: iamRoleInstance.id }));
411
442
  }
@@ -451,7 +482,7 @@ const updateResource = async (context, fn, state) => {
451
482
  : undefined,
452
483
  });
453
484
  const codePath = fn.code.path;
454
- const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
485
+ const desiredCodeHash = await (0, common_1.computeZipContentHash)(codePath);
455
486
  const baseDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
456
487
  const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
457
488
  const currentDefinition = currentState.definition || {};
@@ -482,20 +513,38 @@ const updateResource = async (context, fn, state) => {
482
513
  logConfig: desiredDefinition.logConfig,
483
514
  };
484
515
  const configChanged = !(0, common_1.attributesEqual)(existingConfigOnly, desiredConfigOnly);
516
+ // The instance in state carries the provider function Id — use it directly
517
+ // for all follow-up calls instead of re-resolving the name every time.
518
+ const currentFunctionId = currentInstance.functionId;
519
+ let lastReleaseRecordId;
485
520
  if (configChanged) {
486
- await client.vefaas.updateFunctionConfiguration(config);
521
+ const released = await client.vefaas.updateFunctionConfiguration(currentFunctionId ?? fn.name, config);
522
+ if (released)
523
+ lastReleaseRecordId = released;
487
524
  }
488
525
  if (codeChanged) {
489
- const codeContent = await Promise.resolve().then(() => __importStar(require('node:fs'))).then((fs) => fs.readFileSync(codePath));
490
- const codeBase64 = codeContent.toString('base64');
491
- await client.vefaas.updateFunctionCode(fn.name, codeBase64);
526
+ const updated = await client.vefaas.updateFunctionCode(currentFunctionId ?? fn.name, codePath);
527
+ lastReleaseRecordId = updated.releaseRecordId;
492
528
  }
493
- const functionInfo = await client.vefaas.getFunction(fn.name);
529
+ const functionInfo = currentFunctionId
530
+ ? await client.vefaas.getFunctionById(currentFunctionId)
531
+ : await client.vefaas.getFunction(fn.name);
494
532
  if (!functionInfo) {
495
533
  throw new Error(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: fn.name }));
496
534
  }
497
535
  const sid = currentInstance.sid ?? (0, common_1.buildSid)('volcengine', context.service, context.stage, fn.name);
498
536
  const vefaasInstance = buildVefaasInstanceFromProvider(functionInfo, sid);
537
+ if (lastReleaseRecordId) {
538
+ vefaasInstance.releaseRecordId = lastReleaseRecordId;
539
+ }
540
+ else if (!codeChanged && !configChanged) {
541
+ // Preserve the previously recorded release id when nothing changed.
542
+ const previousRelease = currentInstance
543
+ .releaseRecordId;
544
+ if (previousRelease) {
545
+ vefaasInstance.releaseRecordId = previousRelease;
546
+ }
547
+ }
499
548
  const existingDependentInstances = existingInstances
500
549
  .filter((i) => i.type !== 'VOLCENGINE_VEFAAS_FUNCTION')
501
550
  .map((i) => {
@@ -529,11 +578,12 @@ exports.updateResource = updateResource;
529
578
  const deleteResource = async (context, functionName, logicalId, state) => {
530
579
  const existingState = (0, common_1.getResource)(state, logicalId);
531
580
  const existingInstances = (existingState?.instances ?? []);
532
- const hasVefaasFunction = existingInstances.some((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
581
+ const vefaasInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
582
+ const functionId = vefaasInstance?.functionId;
533
583
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
534
- if (hasVefaasFunction) {
584
+ if (functionId) {
535
585
  try {
536
- await client.vefaas.deleteFunction(functionName);
586
+ await client.vefaas.deleteFunction(functionId);
537
587
  }
538
588
  catch (err) {
539
589
  const errorCode = err?.code;
@@ -13,9 +13,7 @@ exports.getTrustedServicesForFunction = exports.buildDefaultTrustPolicy = export
13
13
  const getTrustedServicesForFunction = (fn, context) => {
14
14
  const expectedBackendRef = `\${functions.${fn.key}}`;
15
15
  const hasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => String(trigger.backend) === expectedBackendRef));
16
- return hasApiGateway
17
- ? ['vefaas.volcengine.com', 'apigateway.volcengine.com']
18
- : ['vefaas.volcengine.com'];
16
+ return hasApiGateway ? ['vefaas', 'apigateway'] : ['vefaas'];
19
17
  };
20
18
  exports.getTrustedServicesForFunction = getTrustedServicesForFunction;
21
19
  const functionToVefaasConfig = (fn, options) => {
@@ -5,4 +5,5 @@ var StateBackendType;
5
5
  (function (StateBackendType) {
6
6
  StateBackendType["LOCAL"] = "LOCAL";
7
7
  StateBackendType["BUCKET_STORE"] = "BUCKET_STORE";
8
+ StateBackendType["SAAS"] = "SAAS";
8
9
  })(StateBackendType || (exports.StateBackendType = StateBackendType = {}));
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PartialResourceError = exports.CURRENT_STATE_VERSION = exports.ResourceTypeEnum = void 0;
3
+ exports.StateVersionError = exports.StateCorruptError = exports.PartialResourceError = exports.CURRENT_STATE_VERSION = exports.ResourceTypeEnum = void 0;
4
4
  var ResourceTypeEnum;
5
5
  (function (ResourceTypeEnum) {
6
6
  // Tencent Cloud
@@ -39,6 +39,8 @@ var ResourceTypeEnum;
39
39
  })(ResourceTypeEnum || (exports.ResourceTypeEnum = ResourceTypeEnum = {}));
40
40
  exports.CURRENT_STATE_VERSION = '3.0';
41
41
  class PartialResourceError extends Error {
42
+ updatedState;
43
+ cause;
42
44
  constructor(updatedState, cause) {
43
45
  super(`Partial resource creation failed: ${cause.message}`);
44
46
  this.name = 'PartialResourceError';
@@ -47,3 +49,29 @@ class PartialResourceError extends Error {
47
49
  }
48
50
  }
49
51
  exports.PartialResourceError = PartialResourceError;
52
+ class StateCorruptError extends Error {
53
+ path;
54
+ cause;
55
+ constructor(path, cause) {
56
+ super(`State file at "${path}" is corrupt and no valid "${path}.backup" is available to recover from. ` +
57
+ 'Restore the state file from the .backup file if it exists, or remove the corrupt file and re-run the deploy to rebuild state.', { cause });
58
+ this.name = 'StateCorruptError';
59
+ this.path = path;
60
+ this.cause = cause;
61
+ }
62
+ }
63
+ exports.StateCorruptError = StateCorruptError;
64
+ class StateVersionError extends Error {
65
+ version;
66
+ currentVersion;
67
+ cause;
68
+ constructor(version, currentVersion, cause) {
69
+ super(`State file version "${version}" is not supported by this CLI (current "${currentVersion}"). ` +
70
+ 'Upgrade the CLI to a version that understands this state format, or restore a compatible state file.', cause !== undefined ? { cause } : undefined);
71
+ this.name = 'StateVersionError';
72
+ this.version = version;
73
+ this.currentVersion = currentVersion;
74
+ this.cause = cause;
75
+ }
76
+ }
77
+ exports.StateVersionError = StateVersionError;
@@ -30,6 +30,16 @@ exports.eventSchema = {
30
30
  properties: {
31
31
  name: { type: 'string' },
32
32
  type: (0, templateRefSchema_1.resolvableEnum)(['API_GATEWAY']),
33
+ log: templateRefSchema_1.resolvableBoolean,
34
+ network: {
35
+ type: 'object',
36
+ additionalProperties: false,
37
+ required: ['vpc_id', 'subnet_ids'],
38
+ properties: {
39
+ vpc_id: { type: 'string' },
40
+ subnet_ids: { type: 'array', items: { type: 'string' }, minItems: 2 },
41
+ },
42
+ },
33
43
  triggers: {
34
44
  type: 'array',
35
45
  items: {
@@ -45,19 +45,15 @@ exports.functionSchema = {
45
45
  'php5.6',
46
46
  'go1',
47
47
  'dotnet_core3.1',
48
- 'nodejs/v20',
49
- 'nodejs/v18',
50
- 'nodejs/v16',
51
- 'nodejs/v14',
52
- 'python/v3.12',
53
- 'python/v3.11',
54
- 'python/v3.10',
55
- 'python/v3.9',
56
48
  'golang/v1',
57
- 'java/v21',
58
- 'java/v17',
59
- 'java/v11',
60
- 'java/v8',
49
+ 'native/v1',
50
+ 'nativejava8/v1',
51
+ 'node14/v1',
52
+ 'node20/v1',
53
+ 'nodeprime14/v1',
54
+ 'python3.12/v1',
55
+ 'python3.8/v1',
56
+ 'python3.9/v1',
61
57
  ]),
62
58
  handler: { type: 'string' },
63
59
  path: { type: 'string' },
@@ -159,6 +155,35 @@ exports.functionSchema = {
159
155
  },
160
156
  },
161
157
  },
158
+ triggers: {
159
+ type: 'object',
160
+ additionalProperties: false,
161
+ properties: {
162
+ http: {
163
+ type: 'object',
164
+ required: ['auth_type'],
165
+ additionalProperties: false,
166
+ properties: {
167
+ auth_type: (0, templateRefSchema_1.resolvableEnum)(['public', 'iam']),
168
+ access: {
169
+ type: 'array',
170
+ items: (0, templateRefSchema_1.resolvableEnum)(['public', 'internal']),
171
+ minItems: 1,
172
+ },
173
+ },
174
+ },
175
+ },
176
+ },
177
+ domain: {
178
+ type: 'object',
179
+ required: ['domain_name'],
180
+ additionalProperties: false,
181
+ properties: {
182
+ domain_name: { type: 'string' },
183
+ certificate_id: { type: 'string' },
184
+ protocol: (0, templateRefSchema_1.resolvableEnum)(['HTTP', 'HTTPS']),
185
+ },
186
+ },
162
187
  storage: {
163
188
  type: 'object',
164
189
  properties: {
@@ -14,6 +14,7 @@ const bucketSchema_1 = require("./bucketSchema");
14
14
  const tableschema_1 = require("./tableschema");
15
15
  const lang_1 = require("../lang");
16
16
  class IacSchemaErrors extends Error {
17
+ schemaErrors;
17
18
  constructor(errors) {
18
19
  const schemaErrors = errors.map((error) => ({
19
20
  instancePath: error.instancePath,