@geek-fun/serverlessinsight 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +15 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +33 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +359 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +15 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +154 -0
  6. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +1 -0
  7. package/README.md +26 -18
  8. package/README.zh-CN.md +19 -6
  9. package/dist/package.json +5 -2
  10. package/dist/src/commands/deploy.js +87 -4
  11. package/dist/src/commands/destroy.js +61 -10
  12. package/dist/src/commands/forceUnlock.js +8 -0
  13. package/dist/src/commands/index.js +34 -2
  14. package/dist/src/commands/login.js +195 -0
  15. package/dist/src/commands/logout.js +17 -0
  16. package/dist/src/commands/show.js +15 -7
  17. package/dist/src/commands/whoami.js +20 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +363 -30
  19. package/dist/src/common/aliyunClient/esOperations.js +43 -29
  20. package/dist/src/common/aliyunClient/fc3Operations.js +481 -207
  21. package/dist/src/common/aliyunClient/ossOperations.js +165 -13
  22. package/dist/src/common/aliyunClient/rdsOperations.js +143 -39
  23. package/dist/src/common/aliyunClient/slsOperations.js +90 -28
  24. package/dist/src/common/aliyunClient/tablestoreOperations.js +25 -22
  25. package/dist/src/common/apiClient.js +102 -0
  26. package/dist/src/common/constants.js +13 -4
  27. package/dist/src/common/credentialStore.js +94 -0
  28. package/dist/src/common/credentials.js +2 -0
  29. package/dist/src/common/eventQueue.js +208 -0
  30. package/dist/src/common/hashUtils.js +87 -11
  31. package/dist/src/common/imsClient.js +1 -0
  32. package/dist/src/common/index.js +3 -0
  33. package/dist/src/common/lockManager.js +61 -54
  34. package/dist/src/common/logger.js +2 -0
  35. package/dist/src/common/polling.js +54 -0
  36. package/dist/src/common/reportResourceEvent.js +8 -0
  37. package/dist/src/common/runtimeMapper.js +11 -12
  38. package/dist/src/common/stateBackend/index.js +10 -1
  39. package/dist/src/common/stateBackend/localStateBackend.js +4 -1
  40. package/dist/src/common/stateBackend/remoteStateBackend.js +10 -4
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +186 -14
  43. package/dist/src/common/tencentClient/clsOperations.js +137 -0
  44. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  45. package/dist/src/common/tencentClient/esOperations.js +110 -46
  46. package/dist/src/common/tencentClient/index.js +43 -2
  47. package/dist/src/common/tencentClient/scfOperations.js +266 -133
  48. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  49. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  50. package/dist/src/common/triggerMapper.js +36 -0
  51. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  52. package/dist/src/common/volcengineClient/iamOperations.js +91 -48
  53. package/dist/src/common/volcengineClient/index.js +46 -21
  54. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  55. package/dist/src/common/volcengineClient/tlsOperations.js +305 -171
  56. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  57. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  58. package/dist/src/lang/en.js +107 -1
  59. package/dist/src/lang/zh-CN.js +107 -1
  60. package/dist/src/parser/eventParser.js +2 -0
  61. package/dist/src/parser/functionParser.js +96 -65
  62. package/dist/src/parser/index.js +7 -4
  63. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  64. package/dist/src/stack/aliyunStack/apigwPlanner.js +16 -10
  65. package/dist/src/stack/aliyunStack/apigwResource.js +334 -125
  66. package/dist/src/stack/aliyunStack/apigwTypes.js +35 -4
  67. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  68. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  69. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  70. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  71. package/dist/src/stack/aliyunStack/destroyer.js +27 -2
  72. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  73. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  74. package/dist/src/stack/aliyunStack/fc3Resource.js +416 -94
  75. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  76. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  77. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  78. package/dist/src/stack/aliyunStack/sharedLogProject.js +137 -0
  79. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  80. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  81. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  82. package/dist/src/stack/alreadyExists.js +26 -0
  83. package/dist/src/stack/ownershipTag.js +58 -0
  84. package/dist/src/stack/rfsStack/index.js +3 -1
  85. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  86. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  87. package/dist/src/stack/scfStack/cosResource.js +167 -64
  88. package/dist/src/stack/scfStack/deployer.js +2 -2
  89. package/dist/src/stack/scfStack/destroyer.js +15 -2
  90. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  91. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  92. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  93. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  94. package/dist/src/stack/scfStack/scfPlanner.js +21 -3
  95. package/dist/src/stack/scfStack/scfResource.js +686 -24
  96. package/dist/src/stack/scfStack/scfTypes.js +6 -0
  97. package/dist/src/stack/scfStack/sharedLogset.js +126 -0
  98. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  99. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  100. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  101. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  102. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  103. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  104. package/dist/src/stack/volcengineStack/apigwResource.js +434 -222
  105. package/dist/src/stack/volcengineStack/apigwTypes.js +85 -66
  106. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  107. package/dist/src/stack/volcengineStack/destroyer.js +13 -1
  108. package/dist/src/stack/volcengineStack/index.js +1 -2
  109. package/dist/src/stack/volcengineStack/sharedLogProject.js +190 -0
  110. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  111. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  112. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  113. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  114. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  115. package/dist/src/stack/volcengineStack/vefaasPlanner.js +78 -2
  116. package/dist/src/stack/volcengineStack/vefaasResource.js +194 -144
  117. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  118. package/dist/src/types/domains/backend.js +1 -0
  119. package/dist/src/types/domains/state.js +32 -1
  120. package/dist/src/validator/eventSchema.js +10 -0
  121. package/dist/src/validator/functionSchema.js +37 -12
  122. package/dist/src/validator/iacSchema.js +1 -0
  123. package/dist/tsconfig.tsbuildinfo +1 -1
  124. package/package.json +5 -2
@@ -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,25 @@ 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");
12
+ const sharedLogProject_1 = require("./sharedLogProject");
43
13
  const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
14
+ // volcengine role TRN format: trn:iam::{accountId}:role/{roleName}. Prefer the
15
+ // stored TRN; else construct from the known accountId, else fetch it via STS.
16
+ const resolveRoleTrn = async (client, context, roleName, storedTrn) => {
17
+ if (storedTrn)
18
+ return storedTrn;
19
+ if (context.accountId)
20
+ return `trn:iam::${context.accountId}:role/${roleName}`;
21
+ const accountId = await client.sts.getAccountId();
22
+ return accountId ? `trn:iam::${accountId}:role/${roleName}` : undefined;
23
+ };
44
24
  const IAM_ROLE_PROPAGATION_DELAY_MS = 3000;
25
+ // Volcengine SDK surfaces "resource already exists" collisions with code
26
+ // `Conflict` (the shared isResourceAlreadyExistsError also matches the message
27
+ // "already exists" / "已存在" for the veFaaS flavor of the error).
28
+ const VEFAAS_ALREADY_EXISTS_CODES = ['Conflict'];
45
29
  const delay = async (ms) => {
46
30
  await new Promise((resolve) => {
47
31
  setTimeout(resolve, ms);
@@ -75,30 +59,55 @@ const buildVefaasInstanceFromProvider = (info, sid) => {
75
59
  memorySize: info.memoryMb ?? null,
76
60
  timeout: info.requestTimeout ?? null,
77
61
  environment: info.environmentVariables ?? {},
78
- description: info.description ?? null,
62
+ description: info.description ?? undefined,
79
63
  status: info.status ?? null,
80
64
  createdTime: info.createdTime ?? null,
81
65
  lastUpdateTime: info.lastModifiedTime ?? null,
82
- role: info.role ?? null,
66
+ role: info.role ?? undefined,
83
67
  vpcConfig: info.vpcConfig
84
68
  ? {
85
- vpcId: info.vpcConfig.vpcId ?? null,
69
+ vpcId: info.vpcConfig.vpcId ?? undefined,
86
70
  subnetIds: info.vpcConfig.subnetIds ?? [],
87
71
  securityGroupIds: info.vpcConfig.securityGroupIds ?? [],
72
+ enableVpc: info.vpcConfig.enableVpc ?? undefined,
73
+ enableSharedInternetAccess: info.vpcConfig.enableSharedInternetAccess ?? undefined,
88
74
  }
89
- : {},
75
+ : undefined,
90
76
  logConfig: info.logConfig
91
77
  ? {
92
- project: info.logConfig.project ?? null,
93
- topic: info.logConfig.topic ?? null,
78
+ project: info.logConfig.project ?? undefined,
79
+ topic: info.logConfig.topic ?? undefined,
80
+ enableLog: info.logConfig.enableLog ?? undefined,
94
81
  }
95
- : null,
82
+ : undefined,
83
+ Tags: info.Tags,
84
+ exclusiveMode: info.exclusiveMode,
85
+ maxConcurrency: info.maxConcurrency,
86
+ codeSize: info.codeSize,
87
+ codeSizeLimit: info.codeSizeLimit,
88
+ sourceLocation: info.sourceLocation,
89
+ sourceType: info.sourceType,
90
+ owner: info.owner,
91
+ triggersCount: info.triggersCount,
92
+ instanceType: info.instanceType,
93
+ initializerSec: info.initializerSec,
94
+ command: info.command,
95
+ port: info.port,
96
+ cpuStrategy: info.cpuStrategy,
97
+ projectName: info.projectName,
98
+ functionType: info.functionType,
99
+ cell: info.cell,
100
+ enableApmplus: info.enableApmplus,
101
+ nasStorage: info.nasStorage,
102
+ tosMountConfig: info.tosMountConfig,
103
+ asyncTaskConfig: info.asyncTaskConfig,
96
104
  };
97
105
  };
98
- const createDependentResources = async (context, fn, serviceName, existingInstances = []) => {
106
+ const createDependentResources = async (context, fn, serviceName, existingInstances = [], state) => {
99
107
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
100
108
  const instances = [];
101
109
  let logConfig;
110
+ let sharedInstance;
102
111
  const hasTlsProject = existingInstances.some((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
103
112
  const hasIamRole = existingInstances.some((i) => i.type === 'VOLCENGINE_IAM_ROLE');
104
113
  if (fn.log) {
@@ -112,49 +121,27 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
112
121
  }
113
122
  }
114
123
  else {
115
- const projectName = `${serviceName}-${context.stage}-tls`;
116
- const topicName = `${serviceName}-${context.stage}-logs`;
117
- logger_1.logger.info(lang_1.lang.__('CREATING_TLS_PROJECT', { projectName }));
118
- const project = await client.tls.createProject({
119
- projectName,
120
- description: `veFaaS logs for ${serviceName}`,
121
- region: context.region,
122
- });
123
- instances.push({
124
- type: 'VOLCENGINE_TLS_PROJECT',
125
- id: projectName,
126
- attributes: { ...project },
127
- });
128
- logger_1.logger.info(lang_1.lang.__('CREATING_TLS_TOPIC', { topicName }));
129
- const topic = await client.tls.createTopic({
130
- projectName,
124
+ // Shared app-scoped TLS project (#214): the project is tracked in the
125
+ // stage shared slot, the function's topic stays nested under the function.
126
+ const shared = await (0, sharedLogProject_1.ensureSharedLogProject)(context, client, state);
127
+ sharedInstance = (0, sharedLogProject_1.buildSharedProjectResourceState)(context, shared);
128
+ const topicName = `${context.service}-${context.stage}-fn-logs`;
129
+ const topic = await (0, sharedLogProject_1.ensureOwnedTopic)(context, client, {
130
+ projectName: shared.projectName,
131
131
  topicName,
132
- description: `Function logs for ${serviceName}`,
133
- ttl: 30,
132
+ logicalId: `functions.${fn.key}`,
134
133
  });
135
134
  instances.push({
136
135
  type: 'VOLCENGINE_TLS_TOPIC',
137
- id: `${projectName}/${topicName}`,
136
+ id: `${shared.projectName}/${topic.topicName}`,
138
137
  attributes: { ...topic },
139
138
  });
140
- logger_1.logger.info(lang_1.lang.__('CREATING_TLS_INDEX', { topicName }));
141
- await client.tls.createIndex({
142
- projectName,
143
- topicName,
144
- fullTextIndex: {
145
- delimiter: ' ,.?;!\n\t',
146
- caseSensitive: false,
147
- },
148
- });
149
139
  instances.push({
150
140
  type: 'VOLCENGINE_TLS_INDEX',
151
- id: `${projectName}/${topicName}/index`,
141
+ id: `${shared.projectName}/${topic.topicName}/index`,
152
142
  attributes: {},
153
143
  });
154
- logger_1.logger.info(lang_1.lang.__('WAITING_FOR_TLS_RESOURCES', { projectName, topicName }));
155
- await client.tls.waitForProject(projectName);
156
- await client.tls.waitForTopic(projectName, topicName);
157
- logConfig = { project: projectName, topic: topicName };
144
+ logConfig = { project: shared.projectName, topic: topic.topicName };
158
145
  }
159
146
  }
160
147
  const iamConfig = fn.iam?.role;
@@ -163,7 +150,9 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
163
150
  const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
164
151
  if (iamConfig && typeof iamConfig === 'string') {
165
152
  const role = { roleName: iamConfig, trn: iamConfig };
166
- return { logConfig, role, instances: [] };
153
+ // External role: never create/manage it, but keep TLS instances and the
154
+ // sharedInstance so log resources are tracked and torn down correctly.
155
+ return { logConfig, role, instances, sharedInstance };
167
156
  }
168
157
  const roleName = customRoleName ?? `${serviceName}-${context.stage}-role`;
169
158
  const trustedServices = (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context);
@@ -196,8 +185,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
196
185
  if (!iamRoleInstance) {
197
186
  throw new Error(lang_1.lang.__('IAM_ROLE_INSTANCE_NOT_FOUND', { roleName }));
198
187
  }
199
- const trn = iamRoleInstance.trn ??
200
- (context.accountId ? `trn:iam::${context.accountId}:role/${iamRoleInstance.id}` : undefined);
188
+ const trn = await resolveRoleTrn(client, context, iamRoleInstance.id, iamRoleInstance.trn);
201
189
  if (!trn) {
202
190
  throw new Error(lang_1.lang.__('IAM_ROLE_TRN_MISSING', { roleName }));
203
191
  }
@@ -209,49 +197,32 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
209
197
  logConfig,
210
198
  role,
211
199
  instances,
200
+ sharedInstance,
212
201
  };
213
202
  };
214
203
  const deleteDependentResources = async (context, instances) => {
215
204
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
216
- 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);
205
+ // TLS children (index → topic) then any legacy per-resource own-project are
206
+ // deleted in dependency order; the stage-shared project is never touched.
207
+ await (0, sharedLogProject_1.deleteTlsLogResources)(context, client, instances);
208
+ for (const instance of instances) {
209
+ switch (instance.type) {
210
+ case 'VOLCENGINE_TLS_INDEX':
211
+ case 'VOLCENGINE_TLS_TOPIC':
212
+ case 'VOLCENGINE_TLS_PROJECT':
213
+ break;
214
+ case 'VOLCENGINE_IAM_ROLE': {
215
+ const attrs = instance.attributes;
216
+ if (attrs?.external === true) {
217
+ logger_1.logger.info(`Skipping deletion of external IAM role: ${instance.id} (managed externally)`);
229
218
  break;
230
219
  }
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);
243
- break;
244
- }
245
- default:
246
- logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
220
+ logger_1.logger.info(lang_1.lang.__('DELETING_IAM_ROLE', { id: instance.id }));
221
+ await client.iam.deleteRole(instance.id);
222
+ break;
247
223
  }
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
- }));
224
+ default:
225
+ logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
255
226
  }
256
227
  }
257
228
  };
@@ -260,7 +231,7 @@ const createResource = async (context, fn, state) => {
260
231
  const serviceName = `${context.app}-${context.service}`;
261
232
  const existingResourceState = (0, common_1.getResource)(state, logicalId);
262
233
  const existingDependentInstances = (existingResourceState?.instances ?? []).filter((i) => i.type !== 'VOLCENGINE_VEFAAS_FUNCTION');
263
- const dependentResources = await createDependentResources(context, fn, serviceName, existingDependentInstances);
234
+ const dependentResources = await createDependentResources(context, fn, serviceName, existingDependentInstances, state);
264
235
  const config = (0, vefaasTypes_1.functionToVefaasConfig)(fn, {
265
236
  role: dependentResources.role?.trn,
266
237
  logConfig: dependentResources.logConfig,
@@ -278,8 +249,9 @@ const createResource = async (context, fn, state) => {
278
249
  }
279
250
  : undefined,
280
251
  });
252
+ config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
281
253
  const codePath = fn.code.path;
282
- const codeHash = (0, common_1.computeFileHash)(codePath);
254
+ const codeHash = await (0, common_1.computeZipContentHash)(codePath);
283
255
  const resourceAttributes = (0, vefaasTypes_1.extractVefaasDefinition)(config, codeHash);
284
256
  const definition = fn.iam ? { ...resourceAttributes, iam: fn.iam } : resourceAttributes;
285
257
  const sid = (0, common_1.buildSid)('volcengine', context.service, context.stage, fn.name);
@@ -308,18 +280,24 @@ const createResource = async (context, fn, state) => {
308
280
  status: 'tainted',
309
281
  lastUpdated: new Date().toISOString(),
310
282
  };
311
- const stateAfterDependents = (0, common_1.setResource)(state, logicalId, taintedResourceState);
283
+ const stateWithShared = dependentResources.sharedInstance
284
+ ? (0, common_1.setSharedResource)(state, context.stage, 'logs.project', dependentResources.sharedInstance)
285
+ : state;
286
+ const stateAfterDependents = (0, common_1.setResource)(stateWithShared, logicalId, taintedResourceState);
312
287
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
313
288
  const isTainted = existingResourceState?.status === 'tainted';
314
289
  const existingFunctionOnRetry = isTainted ? await client.vefaas.getFunction(fn.name) : null;
315
290
  if (existingFunctionOnRetry) {
316
291
  logger_1.logger.info(lang_1.lang.__('VEFAAS_FUNCTION_EXISTS_RECOVERY', { functionName: fn.name }));
317
292
  }
293
+ let createdFunctionId;
294
+ let releaseRecordId;
318
295
  try {
319
296
  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);
297
+ // createFunction validates + base64-encodes the zip at codePath itself.
298
+ const created = await client.vefaas.createFunction(config, codePath);
299
+ createdFunctionId = created.functionId;
300
+ releaseRecordId = created.releaseRecordId;
323
301
  }
324
302
  }
325
303
  catch (error) {
@@ -330,15 +308,35 @@ const createResource = async (context, fn, state) => {
330
308
  throw new types_1.PartialResourceError(stateAfterDependents, error);
331
309
  }
332
310
  }
311
+ else if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error, VEFAAS_ALREADY_EXISTS_CODES)) {
312
+ // Idempotent adoption: the function already exists in the provider.
313
+ // Adopt it ONLY if it carries our ownership tag (proves a previous run
314
+ // of THIS stack created it — e.g. state was reset). An untagged
315
+ // same-named function may belong to another project, so it must fail
316
+ // loudly rather than silently taking it over (destroy would then remove
317
+ // a resource that was never ours).
318
+ const probe = await client.vefaas.getFunction(fn.name);
319
+ if (probe && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.Tags)) {
320
+ logger_1.logger.info(`Function ${fn.name} exists and carries ownership tag (${ownershipTag_1.OWNERSHIP_TAG_KEY}), adopting idempotently`);
321
+ }
322
+ else {
323
+ 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.`));
324
+ }
325
+ }
333
326
  else {
334
327
  throw new types_1.PartialResourceError(stateAfterDependents, error);
335
328
  }
336
329
  }
337
- const functionInfo = await client.vefaas.getFunction(fn.name);
330
+ const functionInfo = createdFunctionId
331
+ ? await client.vefaas.getFunctionById(createdFunctionId)
332
+ : await client.vefaas.getFunction(fn.name);
338
333
  if (!functionInfo) {
339
334
  throw new Error(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: fn.name }));
340
335
  }
341
336
  const vefaasInstance = buildVefaasInstanceFromProvider(functionInfo, sid);
337
+ if (releaseRecordId) {
338
+ vefaasInstance.releaseRecordId = releaseRecordId;
339
+ }
342
340
  const resourceState = {
343
341
  mode: 'managed',
344
342
  region: context.region,
@@ -368,24 +366,59 @@ const updateResource = async (context, fn, state) => {
368
366
  }
369
367
  const existingInstances = (currentState.instances ?? []);
370
368
  const isTainted = currentState.status === 'tainted';
371
- const hasTlsResources = existingInstances.some((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
372
369
  const hasIamRole = existingInstances.some((i) => i.type === 'VOLCENGINE_IAM_ROLE');
373
370
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
374
371
  const newDependentInstances = [];
375
372
  let logConfig;
376
373
  let role;
377
- 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_')));
381
- }
382
- else if (hasTlsResources) {
383
- const tlsProjectInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
374
+ let logState;
375
+ if (fn.log) {
384
376
  const tlsTopicInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
385
- if (tlsProjectInstance && tlsTopicInstance) {
377
+ if (tlsTopicInstance) {
378
+ // Reuse the tracked topic — legacy own-project/topic instances behave
379
+ // exactly as before; shared-scheme topics live under the shared project.
386
380
  const [projectName, topicName] = tlsTopicInstance.id.split('/');
387
381
  logConfig = { project: projectName, topic: topicName };
388
382
  }
383
+ else if (!isTainted) {
384
+ // Persist a tainted state BEFORE creating dependent TLS resources so a
385
+ // partial failure (e.g. project created but topic creation fails) leaves a
386
+ // tainted marker for the executor instead of orphaning cloud resources
387
+ // untracked. A retry then resumes with the tainted state.
388
+ const tainted = (0, common_1.setResource)(state, logicalId, {
389
+ ...currentState,
390
+ status: 'tainted',
391
+ });
392
+ try {
393
+ const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { disk: undefined, nas: undefined } }, serviceName, [], tainted);
394
+ logState = deps.sharedInstance
395
+ ? (0, common_1.setSharedResource)(tainted, context.stage, 'logs.project', deps.sharedInstance)
396
+ : tainted;
397
+ logConfig = deps.logConfig;
398
+ newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_')));
399
+ }
400
+ catch (error) {
401
+ throw new types_1.PartialResourceError(logState ?? tainted, error instanceof Error ? error : new Error(String(error)));
402
+ }
403
+ }
404
+ }
405
+ else {
406
+ const tlsToRemove = existingInstances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_'));
407
+ if (tlsToRemove.length > 0) {
408
+ try {
409
+ await (0, sharedLogProject_1.deleteTlsLogResources)(context, client, tlsToRemove);
410
+ // Release the shared project when this was its last topic; keep the
411
+ // stage slot when other topics still reference it.
412
+ const shared = (0, common_1.getSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY);
413
+ const releaseResult = await (0, sharedLogProject_1.releaseSharedLogProjectIfUnused)(context, client, shared);
414
+ if (releaseResult === 'deleted') {
415
+ logState = (0, common_1.removeSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY);
416
+ }
417
+ }
418
+ catch (error) {
419
+ throw new types_1.PartialResourceError(state, error instanceof Error ? error : new Error(String(error)));
420
+ }
421
+ }
389
422
  }
390
423
  // Determine if the current role is external (string TRN)
391
424
  const currentIam = currentState.definition?.iam;
@@ -402,10 +435,7 @@ const updateResource = async (context, fn, state) => {
402
435
  else {
403
436
  const iamRoleInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
404
437
  if (iamRoleInstance) {
405
- const trn = iamRoleInstance.trn ??
406
- (context.accountId
407
- ? `trn:iam::${context.accountId}:role/${iamRoleInstance.id}`
408
- : undefined);
438
+ const trn = await resolveRoleTrn(client, context, iamRoleInstance.id, iamRoleInstance.trn);
409
439
  if (!trn) {
410
440
  throw new Error(lang_1.lang.__('IAM_ROLE_TRN_MISSING', { roleName: iamRoleInstance.id }));
411
441
  }
@@ -451,7 +481,7 @@ const updateResource = async (context, fn, state) => {
451
481
  : undefined,
452
482
  });
453
483
  const codePath = fn.code.path;
454
- const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
484
+ const desiredCodeHash = await (0, common_1.computeZipContentHash)(codePath);
455
485
  const baseDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
456
486
  const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
457
487
  const currentDefinition = currentState.definition || {};
@@ -482,22 +512,41 @@ const updateResource = async (context, fn, state) => {
482
512
  logConfig: desiredDefinition.logConfig,
483
513
  };
484
514
  const configChanged = !(0, common_1.attributesEqual)(existingConfigOnly, desiredConfigOnly);
515
+ // The instance in state carries the provider function Id — use it directly
516
+ // for all follow-up calls instead of re-resolving the name every time.
517
+ const currentFunctionId = currentInstance.functionId;
518
+ let lastReleaseRecordId;
485
519
  if (configChanged) {
486
- await client.vefaas.updateFunctionConfiguration(config);
520
+ const released = await client.vefaas.updateFunctionConfiguration(currentFunctionId ?? fn.name, config);
521
+ if (released)
522
+ lastReleaseRecordId = released;
487
523
  }
488
524
  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);
525
+ const updated = await client.vefaas.updateFunctionCode(currentFunctionId ?? fn.name, codePath);
526
+ lastReleaseRecordId = updated.releaseRecordId;
492
527
  }
493
- const functionInfo = await client.vefaas.getFunction(fn.name);
528
+ const functionInfo = currentFunctionId
529
+ ? await client.vefaas.getFunctionById(currentFunctionId)
530
+ : await client.vefaas.getFunction(fn.name);
494
531
  if (!functionInfo) {
495
532
  throw new Error(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: fn.name }));
496
533
  }
497
534
  const sid = currentInstance.sid ?? (0, common_1.buildSid)('volcengine', context.service, context.stage, fn.name);
498
535
  const vefaasInstance = buildVefaasInstanceFromProvider(functionInfo, sid);
536
+ if (lastReleaseRecordId) {
537
+ vefaasInstance.releaseRecordId = lastReleaseRecordId;
538
+ }
539
+ else if (!codeChanged && !configChanged) {
540
+ // Preserve the previously recorded release id when nothing changed.
541
+ const previousRelease = currentInstance
542
+ .releaseRecordId;
543
+ if (previousRelease) {
544
+ vefaasInstance.releaseRecordId = previousRelease;
545
+ }
546
+ }
499
547
  const existingDependentInstances = existingInstances
500
- .filter((i) => i.type !== 'VOLCENGINE_VEFAAS_FUNCTION')
548
+ .filter((i) => i.type !== 'VOLCENGINE_VEFAAS_FUNCTION' &&
549
+ (!!fn.log || !i.type.startsWith('VOLCENGINE_TLS_')))
501
550
  .map((i) => {
502
551
  const { sid: existingSid, id: existingId, ...rest } = i;
503
552
  return {
@@ -523,17 +572,18 @@ const updateResource = async (context, fn, state) => {
523
572
  status: 'ready',
524
573
  lastUpdated: new Date().toISOString(),
525
574
  };
526
- return (0, common_1.setResource)(state, logicalId, resourceState);
575
+ return (0, common_1.setResource)(logState ?? state, logicalId, resourceState);
527
576
  };
528
577
  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
@@ -13,6 +13,7 @@ var ResourceTypeEnum;
13
13
  ResourceTypeEnum["ALIYUN_APIGW_GROUP"] = "ALIYUN_APIGW_GROUP";
14
14
  ResourceTypeEnum["ALIYUN_APIGW_API"] = "ALIYUN_APIGW_API";
15
15
  ResourceTypeEnum["ALIYUN_APIGW_DEPLOYMENT"] = "ALIYUN_APIGW_DEPLOYMENT";
16
+ ResourceTypeEnum["ALIYUN_APIGW_LOG_CONFIG"] = "ALIYUN_APIGW_LOG_CONFIG";
16
17
  ResourceTypeEnum["ALIYUN_APIGW_DNS_VERIFICATION"] = "ALIYUN_APIGW_DNS_VERIFICATION";
17
18
  ResourceTypeEnum["ALIYUN_OSS_BUCKET"] = "ALIYUN_OSS_BUCKET";
18
19
  ResourceTypeEnum["ALIYUN_OSS_DNS_CNAME"] = "ALIYUN_OSS_DNS_CNAME";
@@ -29,6 +30,8 @@ var ResourceTypeEnum;
29
30
  ResourceTypeEnum["ALIYUN_RAM_ROLE"] = "ALIYUN_RAM_ROLE";
30
31
  ResourceTypeEnum["VOLCENGINE_IAM_ROLE"] = "VOLCENGINE_IAM_ROLE";
31
32
  ResourceTypeEnum["TENCENT_SCF_ROLE"] = "TENCENT_SCF_ROLE";
33
+ ResourceTypeEnum["TENCENT_CLS_LOGSET"] = "TENCENT_CLS_LOGSET";
34
+ ResourceTypeEnum["TENCENT_CLS_TOPIC"] = "TENCENT_CLS_TOPIC";
32
35
  ResourceTypeEnum["ALIYUN_ECS_SECURITY_GROUP"] = "ALIYUN_ECS_SECURITY_GROUP";
33
36
  ResourceTypeEnum["ALIYUN_NAS_ACCESS_GROUP"] = "ALIYUN_NAS_ACCESS_GROUP";
34
37
  ResourceTypeEnum["ALIYUN_NAS_FILE_SYSTEM"] = "ALIYUN_NAS_FILE_SYSTEM";
@@ -39,6 +42,8 @@ var ResourceTypeEnum;
39
42
  })(ResourceTypeEnum || (exports.ResourceTypeEnum = ResourceTypeEnum = {}));
40
43
  exports.CURRENT_STATE_VERSION = '3.0';
41
44
  class PartialResourceError extends Error {
45
+ updatedState;
46
+ cause;
42
47
  constructor(updatedState, cause) {
43
48
  super(`Partial resource creation failed: ${cause.message}`);
44
49
  this.name = 'PartialResourceError';
@@ -47,3 +52,29 @@ class PartialResourceError extends Error {
47
52
  }
48
53
  }
49
54
  exports.PartialResourceError = PartialResourceError;
55
+ class StateCorruptError extends Error {
56
+ path;
57
+ cause;
58
+ constructor(path, cause) {
59
+ super(`State file at "${path}" is corrupt and no valid "${path}.backup" is available to recover from. ` +
60
+ '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 });
61
+ this.name = 'StateCorruptError';
62
+ this.path = path;
63
+ this.cause = cause;
64
+ }
65
+ }
66
+ exports.StateCorruptError = StateCorruptError;
67
+ class StateVersionError extends Error {
68
+ version;
69
+ currentVersion;
70
+ cause;
71
+ constructor(version, currentVersion, cause) {
72
+ super(`State file version "${version}" is not supported by this CLI (current "${currentVersion}"). ` +
73
+ 'Upgrade the CLI to a version that understands this state format, or restore a compatible state file.', cause !== undefined ? { cause } : undefined);
74
+ this.name = 'StateVersionError';
75
+ this.version = version;
76
+ this.currentVersion = currentVersion;
77
+ this.cause = cause;
78
+ }
79
+ }
80
+ 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: {