@geek-fun/serverlessinsight 0.5.3 → 0.5.5

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 (34) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/commands/deploy.js +1 -0
  3. package/dist/src/common/aliyunClient/apigwOperations.js +153 -82
  4. package/dist/src/common/aliyunClient/ecsOperations.js +64 -13
  5. package/dist/src/common/aliyunClient/fc3Operations.js +15 -12
  6. package/dist/src/common/aliyunClient/index.js +3 -0
  7. package/dist/src/common/aliyunClient/ossOperations.js +4 -0
  8. package/dist/src/common/aliyunClient/ramOperations.js +45 -17
  9. package/dist/src/common/constants.js +14 -1
  10. package/dist/src/common/index.js +1 -0
  11. package/dist/src/common/lockManager.js +29 -1
  12. package/dist/src/common/sidUtils.js +24 -0
  13. package/dist/src/common/stateBackend/cosStateBackend.js +31 -0
  14. package/dist/src/common/stateBackend/ossStateBackend.js +32 -0
  15. package/dist/src/common/stateManager.js +2 -2
  16. package/dist/src/lang/en.js +13 -5
  17. package/dist/src/lang/zh-CN.js +38 -5
  18. package/dist/src/stack/aliyunStack/apigwPlanner.js +1 -1
  19. package/dist/src/stack/aliyunStack/apigwResource.js +18 -17
  20. package/dist/src/stack/aliyunStack/apigwTypes.js +4 -4
  21. package/dist/src/stack/aliyunStack/databaseResource.js +37 -21
  22. package/dist/src/stack/aliyunStack/fc3Executor.js +15 -5
  23. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  24. package/dist/src/stack/aliyunStack/fc3Resource.js +257 -132
  25. package/dist/src/stack/aliyunStack/ossResource.js +19 -8
  26. package/dist/src/stack/aliyunStack/tablestoreResource.js +19 -7
  27. package/dist/src/stack/scfStack/cosResource.js +21 -7
  28. package/dist/src/stack/scfStack/esServerlessResource.js +20 -7
  29. package/dist/src/stack/scfStack/scfResource.js +20 -7
  30. package/dist/src/stack/scfStack/tdsqlcResource.js +24 -7
  31. package/dist/src/types/domains/state.js +11 -2
  32. package/dist/src/validator/functionSchema.js +9 -2
  33. package/dist/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeFunctionPlan = void 0;
4
+ const types_1 = require("../../types");
4
5
  const fc3Resource_1 = require("./fc3Resource");
5
6
  const common_1 = require("../../common");
6
7
  const stateManager_1 = require("../../common/stateManager");
7
- const lang_1 = require("../../lang");
8
8
  const executeCreateAction = async (context, fn, currentState) => {
9
9
  common_1.logger.info(`Creating function: ${fn.name}`);
10
10
  const newState = await (0, fc3Resource_1.createResource)(context, fn, currentState);
@@ -68,14 +68,24 @@ const executeFunctionPlan = async (context, plan, functions, initialState, onSta
68
68
  successfulItems.push(item);
69
69
  if (onStateChange) {
70
70
  onStateChange(currentState);
71
- common_1.logger.debug(lang_1.lang.__('STATE_PERSISTED_AFTER_OPERATION', {
72
- action: item.action,
73
- resourceId: item.logicalId,
74
- }));
75
71
  }
76
72
  }
77
73
  }
78
74
  catch (error) {
75
+ if (error instanceof types_1.PartialResourceError) {
76
+ const updatedState = error.updatedState;
77
+ if (onStateChange) {
78
+ onStateChange(updatedState);
79
+ }
80
+ return {
81
+ state: updatedState,
82
+ partialFailure: {
83
+ failedItem: item,
84
+ error: error.cause,
85
+ successfulItems,
86
+ },
87
+ };
88
+ }
79
89
  return {
80
90
  state: currentState,
81
91
  partialFailure: {
@@ -26,7 +26,7 @@ const generateFunctionPlan = async (context, state, functions) => {
26
26
  const codePath = fn.code.path;
27
27
  const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
28
28
  const desiredDefinition = (0, fc3Types_1.extractFc3Definition)(config, desiredCodeHash);
29
- if (!currentState) {
29
+ if (!currentState || currentState.status === 'tainted') {
30
30
  return {
31
31
  logicalId,
32
32
  action: 'create',
@@ -1,15 +1,61 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
4
7
  const aliyunClient_1 = require("../../common/aliyunClient");
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
5
10
  const common_1 = require("../../common");
11
+ const constants_1 = require("../../common/constants");
12
+ const types_1 = require("../../types");
6
13
  const fc3Types_1 = require("./fc3Types");
7
14
  const logger_1 = require("../../common/logger");
8
- const lang_1 = require("../../lang");
9
- const buildFc3InstanceFromProvider = (info, arn) => {
15
+ const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
16
+ const delay = async (ms) => {
17
+ await new Promise((resolve) => {
18
+ setTimeout(resolve, ms);
19
+ });
20
+ };
21
+ const isRecoverableCreateError = (error) => {
22
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
23
+ ? error.code.toLowerCase()
24
+ : '';
25
+ const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
26
+ return (code === 'readtimeout' ||
27
+ code === 'timeout' ||
28
+ code === 'requesttimeout' ||
29
+ code === 'econnreset' ||
30
+ code === 'etimedout' ||
31
+ message.includes('readtimeout') ||
32
+ message.includes('timeout') ||
33
+ message.includes('socket hang up') ||
34
+ message.includes('econnreset') ||
35
+ message.includes('etimedout'));
36
+ };
37
+ const ensureOssCodeUpload = async (client, codePath, region, functionName) => {
38
+ const fileSize = node_fs_1.default.statSync(codePath).size;
39
+ if (fileSize <= constants_1.FC3_CODE_INLINE_SIZE_LIMIT) {
40
+ return undefined;
41
+ }
42
+ const bucketName = `${constants_1.SI_BOOTSTRAP_BUCKET_PREFIX}-${region}`;
43
+ logger_1.logger.info(`Code package ${node_path_1.default.basename(codePath)} is ${(fileSize / (1024 * 1024)).toFixed(1)}MB, uploading to OSS bucket ${bucketName}`);
44
+ const existingBucket = await client.oss.getBucket(bucketName);
45
+ if (!existingBucket) {
46
+ logger_1.logger.info(`Creating bootstrap OSS bucket: ${bucketName}`);
47
+ await client.oss.createBucket({ bucketName });
48
+ }
49
+ const codeHash = (0, common_1.computeFileHash)(codePath);
50
+ const ossObjectName = `fc3-code/${functionName}/${codeHash}.zip`;
51
+ await client.oss.putFile(bucketName, ossObjectName, codePath);
52
+ logger_1.logger.info(`Uploaded code to oss://${bucketName}/${ossObjectName}`);
53
+ return { ossBucketName: bucketName, ossObjectName };
54
+ };
55
+ const buildFc3InstanceFromProvider = (info, sid) => {
10
56
  return {
11
57
  type: 'ALIYUN_FC3_FUNCTION',
12
- arn,
58
+ sid,
13
59
  id: info.functionName ?? '',
14
60
  functionName: info.functionName ?? null,
15
61
  functionId: info.functionId ?? null,
@@ -77,104 +123,158 @@ const buildFc3InstanceFromProvider = (info, arn) => {
77
123
  lastUpdateStatusReasonCode: info.lastUpdateStatusReasonCode ?? null,
78
124
  };
79
125
  };
80
- // Helper function to create dependent resources directly using the client
81
- const createDependentResources = async (context, fn, serviceName) => {
126
+ const createDependentResources = async (context, fn, serviceName, existingInstances = []) => {
82
127
  const client = (0, aliyunClient_1.createAliyunClient)(context);
83
128
  const instances = [];
84
129
  let logConfig;
85
130
  let securityGroup;
86
131
  let nasConfig;
87
- // Create SLS resources if logging is enabled
132
+ const hasSlsProject = existingInstances.some((i) => i.type === 'ALIYUN_SLS_PROJECT');
133
+ const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
134
+ const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
135
+ const hasNasResources = existingInstances.some((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
88
136
  if (fn.log) {
89
- const projectName = `${serviceName}-sls`;
90
- const logstoreName = `${serviceName}-sls-logstore`;
91
- logger_1.logger.info(`Creating SLS project: ${projectName}`);
92
- const project = await client.sls.createProject(projectName);
93
- instances.push({
94
- type: 'ALIYUN_SLS_PROJECT',
95
- id: projectName,
96
- attributes: { ...project },
97
- });
98
- logger_1.logger.info(`Creating SLS logstore: ${logstoreName}`);
99
- const logstore = await client.sls.createLogstore(projectName, logstoreName);
100
- instances.push({
101
- type: 'ALIYUN_SLS_LOGSTORE',
102
- id: `${projectName}/${logstoreName}`,
103
- attributes: { ...logstore },
104
- });
105
- logger_1.logger.info(`Creating SLS index for: ${logstoreName}`);
106
- const index = await client.sls.createIndex(projectName, logstoreName);
107
- instances.push({
108
- type: 'ALIYUN_SLS_INDEX',
109
- id: `${projectName}/${logstoreName}/index`,
110
- attributes: { ...index },
111
- });
112
- logger_1.logger.info(`Waiting for SLS project and logstore to be ready: ${projectName}/${logstoreName}`);
113
- await client.sls.waitForProject(projectName);
114
- await client.sls.waitForLogstore(projectName, logstoreName);
115
- logConfig = { project: projectName, logstore: logstoreName };
116
- }
117
- // Create RAM role
118
- const roleName = `${serviceName}-fc-role`;
119
- logger_1.logger.info(`Creating RAM role: ${roleName}`);
120
- const ramRole = await client.ram.createRole(roleName);
121
- instances.push({
122
- type: 'ALIYUN_RAM_ROLE',
123
- id: roleName,
124
- arn: ramRole.arn,
125
- attributes: { ...ramRole },
126
- });
127
- const role = { roleName, arn: ramRole.arn ?? `acs:ram::${context.accountId}:role/${roleName}` };
128
- // Create security group if network is configured
129
- if (fn.network) {
130
- const sgName = fn.network.security_group.name;
131
- logger_1.logger.info(`Creating security group: ${sgName}`);
132
- const sg = await client.ecs.createSecurityGroup(sgName, fn.network.vpc_id, fn.network.security_group.ingress, fn.network.security_group.egress);
133
- instances.push({
134
- type: 'ALIYUN_ECS_SECURITY_GROUP',
135
- id: sg.securityGroupId,
136
- attributes: { ...sg },
137
- });
138
- securityGroup = { securityGroupId: sg.securityGroupId };
139
- }
140
- // Create NAS resources if configured
141
- if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network) {
142
- const mountPoints = [];
143
- for (const nasItem of fn.storage.nas) {
144
- const mountPath = nasItem.mount_path.replace(/\//g, '-').replace(/^-/, '');
145
- const accessGroupName = `${fn.name}-nas-access-${mountPath}`;
146
- logger_1.logger.info(`Creating NAS access group: ${accessGroupName}`);
147
- const accessGroup = await client.nas.createAccessGroup(accessGroupName);
137
+ if (hasSlsProject) {
138
+ const slsProjectInstance = existingInstances.find((i) => i.type === 'ALIYUN_SLS_PROJECT');
139
+ const slsLogstoreInstance = existingInstances.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
140
+ if (slsProjectInstance && slsLogstoreInstance) {
141
+ const [projectName, logstoreName] = slsLogstoreInstance.id.split('/');
142
+ logConfig = { project: projectName, logstore: logstoreName };
143
+ instances.push(...existingInstances.filter((i) => i.type.startsWith('ALIYUN_SLS_')));
144
+ }
145
+ }
146
+ else {
147
+ const projectName = `${serviceName}-${context.stage}-sls`;
148
+ const logstoreName = `${serviceName}-${context.stage}-sls-logstore`;
149
+ logger_1.logger.info(`Creating SLS project: ${projectName}`);
150
+ const project = await client.sls.createProject(projectName);
151
+ instances.push({ type: 'ALIYUN_SLS_PROJECT', id: projectName, attributes: { ...project } });
152
+ logger_1.logger.info(`Creating SLS logstore: ${logstoreName}`);
153
+ const logstore = await client.sls.createLogstore(projectName, logstoreName);
148
154
  instances.push({
149
- type: 'ALIYUN_NAS_ACCESS_GROUP',
150
- id: accessGroupName,
151
- attributes: { ...accessGroup },
155
+ type: 'ALIYUN_SLS_LOGSTORE',
156
+ id: `${projectName}/${logstoreName}`,
157
+ attributes: { ...logstore },
152
158
  });
153
- logger_1.logger.info(`Creating NAS access rule for: ${accessGroupName}`);
154
- await client.nas.createAccessRule(accessGroupName, '10.0.0.0/8');
155
- logger_1.logger.info(`Creating NAS file system for: ${fn.name}`);
156
- const fileSystem = await client.nas.createFileSystem(nasItem.storage_class, fn.name);
159
+ logger_1.logger.info(`Creating SLS index for: ${logstoreName}`);
160
+ const index = await client.sls.createIndex(projectName, logstoreName);
157
161
  instances.push({
158
- type: 'ALIYUN_NAS_FILE_SYSTEM',
159
- id: fileSystem.fileSystemId,
160
- attributes: { ...fileSystem },
162
+ type: 'ALIYUN_SLS_INDEX',
163
+ id: `${projectName}/${logstoreName}/index`,
164
+ attributes: { ...index },
161
165
  });
162
- logger_1.logger.info(`Creating NAS mount target for: ${fileSystem.fileSystemId}`);
163
- const mountTarget = await client.nas.createMountTarget(fileSystem.fileSystemId, accessGroupName, fn.network.vpc_id, fn.network.subnet_ids[0]);
166
+ logger_1.logger.info(`Waiting for SLS project and logstore to be ready: ${projectName}/${logstoreName}`);
167
+ await client.sls.waitForProject(projectName);
168
+ await client.sls.waitForLogstore(projectName, logstoreName);
169
+ logConfig = { project: projectName, logstore: logstoreName };
170
+ }
171
+ }
172
+ const roleName = `${serviceName}-${context.stage}-fc-role`;
173
+ if (hasRamRole) {
174
+ const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
175
+ if (ramRoleInstance) {
176
+ instances.push(ramRoleInstance);
177
+ }
178
+ }
179
+ else {
180
+ const fnHasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => String(trigger.backend) === fn.name));
181
+ const trustedServices = fnHasApiGateway
182
+ ? ['fc.aliyuncs.com', 'apigateway.aliyuncs.com']
183
+ : ['fc.aliyuncs.com'];
184
+ logger_1.logger.info(`Creating RAM role: ${roleName}`);
185
+ const ramRole = await client.ram.createRole(roleName, trustedServices);
186
+ instances.push({
187
+ type: 'ALIYUN_RAM_ROLE',
188
+ id: roleName,
189
+ roleArn: ramRole.arn,
190
+ attributes: { ...ramRole },
191
+ });
192
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
193
+ }
194
+ const ramRoleInstance = instances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
195
+ const role = {
196
+ roleName,
197
+ arn: ramRoleInstance?.roleArn ?? `acs:ram::${context.accountId}:role/${roleName}`,
198
+ };
199
+ if (fn.network) {
200
+ if (hasSecurityGroup) {
201
+ const sgInstance = existingInstances.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
202
+ if (sgInstance) {
203
+ instances.push(sgInstance);
204
+ securityGroup = { securityGroupId: sgInstance.id };
205
+ }
206
+ }
207
+ else {
208
+ const sgName = fn.network.security_group.name;
209
+ logger_1.logger.info(`Creating security group: ${sgName}`);
210
+ const sg = await client.ecs.createSecurityGroup(sgName, fn.network.vpc_id, fn.network.security_group.ingress, fn.network.security_group.egress);
164
211
  instances.push({
165
- type: 'ALIYUN_NAS_MOUNT_TARGET',
166
- id: `${fileSystem.fileSystemId}/${mountTarget.mountTargetDomain}`,
167
- attributes: { ...mountTarget },
168
- });
169
- mountPoints.push({
170
- serverAddr: `${mountTarget.mountTargetDomain}:/`,
171
- mountDir: nasItem.mount_path,
172
- fileSystemId: fileSystem.fileSystemId,
173
- mountTargetDomain: mountTarget.mountTargetDomain,
174
- accessGroupName,
212
+ type: 'ALIYUN_ECS_SECURITY_GROUP',
213
+ id: sg.securityGroupId,
214
+ attributes: { ...sg },
175
215
  });
216
+ securityGroup = { securityGroupId: sg.securityGroupId };
217
+ }
218
+ }
219
+ if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network) {
220
+ if (hasNasResources) {
221
+ const nasInstances = existingInstances.filter((i) => i.type.startsWith('ALIYUN_NAS_'));
222
+ instances.push(...nasInstances);
223
+ const mountTargetInstances = nasInstances.filter((i) => i.type === 'ALIYUN_NAS_MOUNT_TARGET');
224
+ const nasStorageItems = fn.storage.nas;
225
+ if (mountTargetInstances.length > 0) {
226
+ nasConfig = {
227
+ mountPoints: mountTargetInstances.map((mt, idx) => {
228
+ const [fileSystemId, mountTargetDomain] = mt.id.split('/');
229
+ return {
230
+ serverAddr: `${mountTargetDomain}:/`,
231
+ mountDir: nasStorageItems[idx]?.mount_path ?? '/mnt/nas',
232
+ fileSystemId,
233
+ mountTargetDomain,
234
+ accessGroupName: mt.attributes?.accessGroupName ?? '',
235
+ };
236
+ }),
237
+ };
238
+ }
239
+ }
240
+ else {
241
+ const mountPoints = [];
242
+ for (const nasItem of fn.storage.nas) {
243
+ const mountPath = nasItem.mount_path.replace(/\//g, '-').replace(/^-/, '');
244
+ const accessGroupName = `${fn.name}-${context.stage}-nas-access-${mountPath}`;
245
+ logger_1.logger.info(`Creating NAS access group: ${accessGroupName}`);
246
+ const accessGroup = await client.nas.createAccessGroup(accessGroupName);
247
+ instances.push({
248
+ type: 'ALIYUN_NAS_ACCESS_GROUP',
249
+ id: accessGroupName,
250
+ attributes: { ...accessGroup },
251
+ });
252
+ logger_1.logger.info(`Creating NAS access rule for: ${accessGroupName}`);
253
+ await client.nas.createAccessRule(accessGroupName, '10.0.0.0/8');
254
+ logger_1.logger.info(`Creating NAS file system for: ${fn.name}`);
255
+ const fileSystem = await client.nas.createFileSystem(nasItem.storage_class, fn.name);
256
+ instances.push({
257
+ type: 'ALIYUN_NAS_FILE_SYSTEM',
258
+ id: fileSystem.fileSystemId,
259
+ attributes: { ...fileSystem },
260
+ });
261
+ logger_1.logger.info(`Creating NAS mount target for: ${fileSystem.fileSystemId}`);
262
+ const mountTarget = await client.nas.createMountTarget(fileSystem.fileSystemId, accessGroupName, fn.network.vpc_id, fn.network.subnet_ids[0]);
263
+ instances.push({
264
+ type: 'ALIYUN_NAS_MOUNT_TARGET',
265
+ id: `${fileSystem.fileSystemId}/${mountTarget.mountTargetDomain}`,
266
+ attributes: { ...mountTarget, accessGroupName },
267
+ });
268
+ mountPoints.push({
269
+ serverAddr: `${mountTarget.mountTargetDomain}:/`,
270
+ mountDir: nasItem.mount_path,
271
+ fileSystemId: fileSystem.fileSystemId,
272
+ mountTargetDomain: mountTarget.mountTargetDomain,
273
+ accessGroupName,
274
+ });
275
+ }
276
+ nasConfig = { mountPoints };
176
277
  }
177
- nasConfig = { mountPoints };
178
278
  }
179
279
  return {
180
280
  logConfig,
@@ -184,10 +284,8 @@ const createDependentResources = async (context, fn, serviceName) => {
184
284
  instances,
185
285
  };
186
286
  };
187
- // Helper function to delete dependent resources directly using the client
188
287
  const deleteDependentResources = async (context, instances) => {
189
288
  const client = (0, aliyunClient_1.createAliyunClient)(context);
190
- // Delete in reverse order of creation
191
289
  for (const instance of [...instances].reverse()) {
192
290
  try {
193
291
  switch (instance.type) {
@@ -241,11 +339,11 @@ const deleteDependentResources = async (context, instances) => {
241
339
  const createResource = async (context, fn, state) => {
242
340
  const ctx = (0, common_1.getContext)();
243
341
  const serviceName = `${ctx.app}-${ctx.service}`;
244
- // Create dependent resources (SLS, RAM, ECS SecurityGroup, NAS)
245
- const dependentResources = await createDependentResources(context, fn, serviceName);
246
- // Build FC3 config with dependent resources
342
+ const logicalId = `functions.${fn.key}`;
343
+ const existingResourceState = (0, common_1.getResource)(state, logicalId);
344
+ const existingDependentInstances = (existingResourceState?.instances ?? []).filter((i) => i.type !== 'ALIYUN_FC3_FUNCTION');
345
+ const dependentResources = await createDependentResources(context, fn, serviceName, existingDependentInstances);
247
346
  let config = (0, fc3Types_1.functionToFc3Config)(fn);
248
- // Update config with dependent resources
249
347
  if (dependentResources.logConfig) {
250
348
  config = {
251
349
  ...config,
@@ -288,52 +386,72 @@ const createResource = async (context, fn, state) => {
288
386
  const codePath = fn.code.path;
289
387
  const codeHash = (0, common_1.computeFileHash)(codePath);
290
388
  const definition = (0, fc3Types_1.extractFc3Definition)(config, codeHash);
291
- const logicalId = `functions.${fn.key}`;
292
- // Save state with dependent resources BEFORE attempting function creation
293
389
  const dependentInstances = dependentResources.instances.map((dep) => ({
294
- arn: dep.arn ??
295
- `arn:acs:${dep.type.toLowerCase()}:${context.region}:${context.accountId}:${dep.id}`,
390
+ sid: dep.sid ??
391
+ (0, common_1.buildSid)('aliyun', dep.type.replace('ALIYUN_', '').toLowerCase(), context.stage, dep.id),
296
392
  id: dep.id,
297
393
  type: dep.type,
394
+ ...(dep.roleArn ? { roleArn: dep.roleArn } : {}),
298
395
  ...dep.attributes,
299
396
  }));
300
- // Create partial state with just dependent resources
301
- const partialResourceState = {
397
+ const taintedResourceState = {
302
398
  mode: 'managed',
303
399
  region: context.region,
304
400
  definition,
305
401
  instances: dependentInstances,
306
402
  lastUpdated: new Date().toISOString(),
403
+ status: 'tainted',
307
404
  };
308
- state = (0, common_1.setResource)(state, logicalId, partialResourceState);
309
- // Now attempt to create the function
405
+ const stateAfterDependents = (0, common_1.setResource)(state, logicalId, taintedResourceState);
310
406
  const client = (0, aliyunClient_1.createAliyunClient)(context);
407
+ const isTainted = existingResourceState?.status === 'tainted';
408
+ const existingFunctionOnRetry = isTainted ? await client.fc3.getFunction(fn.name) : null;
409
+ if (existingFunctionOnRetry) {
410
+ logger_1.logger.info(`Function ${fn.name} already exists in provider (tainted recovery), skipping create and refreshing state`);
411
+ }
311
412
  try {
312
- await client.fc3.createFunction(config, codePath);
413
+ if (!existingFunctionOnRetry) {
414
+ const ossCode = await ensureOssCodeUpload(client, codePath, context.region, fn.name);
415
+ await client.fc3.createFunction(config, codePath, ossCode);
416
+ }
313
417
  }
314
418
  catch (error) {
315
- logger_1.logger.error(`Failed to create function, but dependent resources were created and saved to state: ${error}`);
316
- logger_1.logger.info(lang_1.lang.__('FC3_DEPENDENT_RESOURCES_TRACKED'));
317
- logger_1.logger.info(lang_1.lang.__('FC3_CAN_RETRY_DEPLOYMENT'));
318
- return state;
419
+ if (isRecoverableCreateError(error)) {
420
+ logger_1.logger.warn(`Create function returned recoverable error for ${fn.name}, reconciling with provider state: ${String(error)}`);
421
+ const functionAfterError = await client.fc3.getFunction(fn.name);
422
+ if (functionAfterError) {
423
+ logger_1.logger.info(`Function ${fn.name} found after create error reconciliation, continuing deployment flow`);
424
+ }
425
+ else {
426
+ await delay(RECOVERY_GET_FUNCTION_DELAY_MS);
427
+ const functionAfterDelay = await client.fc3.getFunction(fn.name);
428
+ if (functionAfterDelay) {
429
+ logger_1.logger.info(`Function ${fn.name} found after delayed reconciliation, continuing deployment flow`);
430
+ }
431
+ else {
432
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
433
+ }
434
+ }
435
+ }
436
+ else {
437
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
438
+ }
319
439
  }
320
- // Refresh state from provider to get all attributes
321
440
  const functionInfo = await client.fc3.getFunction(fn.name);
322
441
  if (!functionInfo) {
323
442
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
324
443
  }
325
- const arn = functionInfo.functionArn ??
326
- `arn:acs:fc:${context.region}:${context.accountId}:function/${fn.name}`;
327
- // Build instances array with FC function as first item, followed by dependent resources
328
- const fcInstance = buildFc3InstanceFromProvider(functionInfo, arn);
444
+ const sid = (0, common_1.buildSid)('aliyun', 'fc3', context.stage, fn.name);
445
+ const fcInstance = buildFc3InstanceFromProvider(functionInfo, sid);
329
446
  const resourceState = {
330
447
  mode: 'managed',
331
448
  region: context.region,
332
449
  definition,
333
450
  instances: [fcInstance, ...dependentInstances],
334
451
  lastUpdated: new Date().toISOString(),
452
+ status: 'ready',
335
453
  };
336
- return (0, common_1.setResource)(state, logicalId, resourceState);
454
+ return (0, common_1.setResource)(stateAfterDependents, logicalId, resourceState);
337
455
  };
338
456
  exports.createResource = createResource;
339
457
  const readResource = async (context, functionName) => {
@@ -345,10 +463,8 @@ const updateResource = async (context, fn, state) => {
345
463
  const ctx = (0, common_1.getContext)();
346
464
  const serviceName = `${ctx.app}-${ctx.service}`;
347
465
  const logicalId = `functions.${fn.key}`;
348
- // Get existing resource state to check if dependent resources exist
349
466
  const existingState = (0, common_1.getResource)(state, logicalId);
350
467
  const existingInstances = (existingState?.instances ?? []);
351
- // Check if we need to create new dependent resources
352
468
  const hasSlsResources = existingInstances.some((i) => i.type === 'ALIYUN_SLS_PROJECT');
353
469
  const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
354
470
  const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
@@ -358,7 +474,6 @@ const updateResource = async (context, fn, state) => {
358
474
  let role;
359
475
  let securityGroup;
360
476
  let nasConfig;
361
- // Create new dependent resources if they don't exist
362
477
  if (fn.log && !hasSlsResources) {
363
478
  const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName);
364
479
  logConfig = deps.logConfig;
@@ -382,7 +497,7 @@ const updateResource = async (context, fn, state) => {
382
497
  if (ramRoleInstance) {
383
498
  role = {
384
499
  roleName: ramRoleInstance.id,
385
- arn: ramRoleInstance.arn ?? `acs:ram::${context.accountId}:role/${ramRoleInstance.id}`,
500
+ arn: ramRoleInstance.roleArn ?? `acs:ram::${context.accountId}:role/${ramRoleInstance.id}`,
386
501
  };
387
502
  }
388
503
  }
@@ -414,7 +529,6 @@ const updateResource = async (context, fn, state) => {
414
529
  };
415
530
  }
416
531
  }
417
- // Build FC3 config with dependent resources
418
532
  let config = (0, fc3Types_1.functionToFc3Config)(fn);
419
533
  if (logConfig) {
420
534
  config = {
@@ -455,33 +569,33 @@ const updateResource = async (context, fn, state) => {
455
569
  const codePath = fn.code.path;
456
570
  const client = (0, aliyunClient_1.createAliyunClient)(context);
457
571
  await client.fc3.updateFunctionConfiguration(config);
458
- await client.fc3.updateFunctionCode(fn.name, codePath);
572
+ const ossCode = await ensureOssCodeUpload(client, codePath, context.region, fn.name);
573
+ await client.fc3.updateFunctionCode(fn.name, codePath, ossCode);
459
574
  const functionInfo = await client.fc3.getFunction(fn.name);
460
575
  if (!functionInfo) {
461
576
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
462
577
  }
463
578
  const codeHash = (0, common_1.computeFileHash)(codePath);
464
579
  const definition = (0, fc3Types_1.extractFc3Definition)(config, codeHash);
465
- const arn = functionInfo.functionArn ??
466
- `arn:acs:fc:${context.region}:${context.accountId}:function/${fn.name}`;
467
- // Build instances array: FC function + existing dependent resources + new dependent resources
468
- const fcInstance = buildFc3InstanceFromProvider(functionInfo, arn);
580
+ const sid = (0, common_1.buildSid)('aliyun', 'fc3', context.stage, fn.name);
581
+ const fcInstance = buildFc3InstanceFromProvider(functionInfo, sid);
469
582
  const existingDependentInstances = existingInstances
470
583
  .filter((i) => i.type !== 'ALIYUN_FC3_FUNCTION')
471
584
  .map((i) => {
472
- const { arn: existingArn, id: existingId, ...rest } = i;
585
+ const { sid: existingSid, id: existingId, ...rest } = i;
473
586
  return {
474
- arn: existingArn ??
475
- `arn:acs:${i.type?.toString().toLowerCase()}:${context.region}:${context.accountId}:${existingId}`,
587
+ sid: existingSid ??
588
+ (0, common_1.buildSid)('aliyun', i.type?.toString().replace('ALIYUN_', '').toLowerCase() ?? '', context.stage, existingId?.toString() ?? ''),
476
589
  id: existingId?.toString() ?? '',
477
590
  ...rest,
478
591
  };
479
592
  });
480
593
  const newDependentInstancesMapped = newDependentInstances.map((dep) => ({
481
- arn: dep.arn ??
482
- `arn:acs:${dep.type.toLowerCase()}:${context.region}:${context.accountId}:${dep.id}`,
594
+ sid: dep.sid ??
595
+ (0, common_1.buildSid)('aliyun', dep.type.replace('ALIYUN_', '').toLowerCase(), context.stage, dep.id),
483
596
  id: dep.id,
484
597
  type: dep.type,
598
+ ...(dep.roleArn ? { roleArn: dep.roleArn } : {}),
485
599
  ...dep.attributes,
486
600
  }));
487
601
  const resourceState = {
@@ -495,13 +609,24 @@ const updateResource = async (context, fn, state) => {
495
609
  };
496
610
  exports.updateResource = updateResource;
497
611
  const deleteResource = async (context, functionName, logicalId, state) => {
498
- // Get existing resource state to find dependent resources
499
612
  const existingState = (0, common_1.getResource)(state, logicalId);
500
613
  const existingInstances = (existingState?.instances ?? []);
501
- // Delete FC function first
614
+ const hasFcFunction = existingInstances.some((i) => i.type === 'ALIYUN_FC3_FUNCTION');
502
615
  const client = (0, aliyunClient_1.createAliyunClient)(context);
503
- await client.fc3.deleteFunction(functionName);
504
- // Delete dependent resources
616
+ if (hasFcFunction) {
617
+ try {
618
+ await client.fc3.deleteFunction(functionName);
619
+ }
620
+ catch (err) {
621
+ const errorCode = err?.code;
622
+ if (errorCode === 'FunctionNotFound') {
623
+ logger_1.logger.warn(`Function ${functionName} not found in provider, skipping deletion`);
624
+ }
625
+ else {
626
+ throw err;
627
+ }
628
+ }
629
+ }
505
630
  const dependentInstances = existingInstances.filter((i) => i.type !== 'ALIYUN_FC3_FUNCTION' && !i.type.includes('undefined'));
506
631
  if (dependentInstances.length > 0) {
507
632
  await deleteDependentResources(context, dependentInstances);
@@ -10,10 +10,10 @@ const ossTypes_1 = require("./ossTypes");
10
10
  const logger_1 = require("../../common/logger");
11
11
  const lang_1 = require("../../lang");
12
12
  const node_path_1 = __importDefault(require("node:path"));
13
- const buildOssInstanceFromProvider = (info, arn) => {
13
+ const buildOssInstanceFromProvider = (info, sid) => {
14
14
  return {
15
15
  type: 'ALIYUN_OSS_BUCKET',
16
- arn,
16
+ sid,
17
17
  id: info.name,
18
18
  bucketName: info.name,
19
19
  location: info.location ?? null,
@@ -111,14 +111,14 @@ const createBucketResource = async (context, bucket, state) => {
111
111
  throw new Error(`Failed to refresh state for bucket: ${config.bucketName}`);
112
112
  }
113
113
  const definition = (0, ossTypes_1.extractOssBucketDefinition)(config);
114
- const arn = `arn:acs:oss:${context.region}:${context.accountId}:${config.bucketName}`;
114
+ const sid = (0, common_1.buildSid)('aliyun', 'oss', context.stage, config.bucketName);
115
115
  const logicalId = `buckets.${bucket.key}`;
116
116
  // Save state immediately after bucket creation, before file upload
117
117
  const partialResourceState = {
118
118
  mode: 'managed',
119
119
  region: context.region,
120
120
  definition,
121
- instances: [buildOssInstanceFromProvider(bucketInfo, arn)],
121
+ instances: [buildOssInstanceFromProvider(bucketInfo, sid)],
122
122
  lastUpdated: new Date().toISOString(),
123
123
  };
124
124
  state = (0, common_1.setResource)(state, logicalId, partialResourceState);
@@ -134,7 +134,7 @@ const createBucketResource = async (context, bucket, state) => {
134
134
  mode: 'managed',
135
135
  region: context.region,
136
136
  definition,
137
- instances: [buildOssInstanceFromProvider(bucketInfo, arn)],
137
+ instances: [buildOssInstanceFromProvider(bucketInfo, sid)],
138
138
  lastUpdated: new Date().toISOString(),
139
139
  };
140
140
  return (0, common_1.setResource)(state, logicalId, updatedResourceState);
@@ -176,12 +176,12 @@ const updateBucketResource = async (context, bucket, state) => {
176
176
  throw new Error(`Failed to refresh state for bucket: ${config.bucketName}`);
177
177
  }
178
178
  const definition = (0, ossTypes_1.extractOssBucketDefinition)(config);
179
- const arn = `arn:acs:oss:${context.region}:${context.accountId}:${config.bucketName}`;
179
+ const sid = (0, common_1.buildSid)('aliyun', 'oss', context.stage, config.bucketName);
180
180
  const resourceState = {
181
181
  mode: 'managed',
182
182
  region: context.region,
183
183
  definition,
184
- instances: [buildOssInstanceFromProvider(bucketInfo, arn)],
184
+ instances: [buildOssInstanceFromProvider(bucketInfo, sid)],
185
185
  lastUpdated: new Date().toISOString(),
186
186
  };
187
187
  const logicalId = `buckets.${bucket.key}`;
@@ -190,7 +190,18 @@ const updateBucketResource = async (context, bucket, state) => {
190
190
  exports.updateBucketResource = updateBucketResource;
191
191
  const deleteBucketResource = async (context, bucketName, logicalId, state) => {
192
192
  const client = (0, aliyunClient_1.createAliyunClient)(context);
193
- await client.oss.deleteBucket(bucketName);
193
+ try {
194
+ await client.oss.deleteBucket(bucketName);
195
+ }
196
+ catch (err) {
197
+ const errorCode = err?.code;
198
+ if (errorCode === 'NoSuchBucket') {
199
+ logger_1.logger.warn(`Bucket ${bucketName} not found in provider, skipping deletion`);
200
+ }
201
+ else {
202
+ throw err;
203
+ }
204
+ }
194
205
  return (0, common_1.removeResource)(state, logicalId);
195
206
  };
196
207
  exports.deleteBucketResource = deleteBucketResource;