@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
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geek-fun/serverlessinsight",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "Full life cycle cross providers serverless application management for your fast-growing business.",
5
5
  "homepage": "https://serverlessinsight.geekfun.club",
6
6
  "main": "dist/src/index.js",
@@ -24,6 +24,7 @@ const deploy = async (options) => {
24
24
  (0, common_1.setIac)(iac);
25
25
  common_1.logger.info(lang_1.lang.__('DEPLOYING_STACK'));
26
26
  const backend = (0, stateBackend_1.createStateBackend)(iac.backend, context);
27
+ common_1.logger.info(lang_1.lang.__('ACQUIRING_LOCK'));
27
28
  await backend.withLock('deploy', async () => {
28
29
  await (0, stack_1.deployStack)(iac, backend);
29
30
  });
@@ -35,10 +35,13 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createApigwOperations = void 0;
37
37
  const cloudapi = __importStar(require("@alicloud/cloudapi20160714"));
38
+ const node_dns_1 = require("node:dns");
38
39
  const dnsOperations_1 = require("./dnsOperations");
39
40
  const logger_1 = require("../logger");
40
41
  const lang_1 = require("../../lang");
41
42
  const stateManager_1 = require("../stateManager");
43
+ const sidUtils_1 = require("../sidUtils");
44
+ const constants_1 = require("../constants");
42
45
  const removeUndefined = (obj) => {
43
46
  return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined));
44
47
  };
@@ -62,24 +65,11 @@ const extractHostRecord = (fullDomain, mainDomain) => {
62
65
  };
63
66
  const createApigwOperations = (apigwClient, dnsClient, _context) => {
64
67
  const dnsOps = (0, dnsOperations_1.createDnsOperations)(dnsClient);
65
- const extractVerificationToken = (error, groupInfo) => {
66
- try {
67
- if (groupInfo?.subDomain) {
68
- const match = groupInfo.subDomain.match(/^([a-f0-9]+)-[^.]+\.alicloudapi\.com$/);
69
- if (match) {
70
- return match[1];
71
- }
72
- }
73
- const errorStr = String(error);
74
- const cnameMatch = errorStr.match(/([a-f0-9]{32})-[^.]+\.alicloudapi\.com/);
75
- if (cnameMatch) {
76
- return cnameMatch[1];
77
- }
78
- }
79
- catch {
80
- // Ignore extraction errors
81
- }
82
- return null;
68
+ const buildTxtVerificationRecord = (groupId, domainName, groupSubdomain, mainDomain) => {
69
+ const hostRecord = extractHostRecord(domainName, mainDomain);
70
+ const rr = hostRecord === '@' ? groupId : `${groupId}.${hostRecord}`;
71
+ // NOTE: "verfication" is Aliyun's actual typo in their API — must match exactly
72
+ return { rr, value: `apigateway-domain-verfication=${groupSubdomain}` };
83
73
  };
84
74
  const pollDnsPropagation = async (mainDomain, verificationHost, verificationValue, shouldLoop = true) => {
85
75
  const checkPropagation = async () => {
@@ -117,6 +107,34 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
117
107
  logger_1.logger.warn(lang_1.lang.__('APIGW_DNS_PROPAGATION_TIMEOUT'));
118
108
  return false;
119
109
  };
110
+ const verifyCnameResolution = async (hostname) => {
111
+ try {
112
+ await node_dns_1.promises.resolveCname(hostname);
113
+ return true;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ };
119
+ const pollPublicDnsResolution = async (domainName) => {
120
+ logger_1.logger.info(lang_1.lang.__('APIGW_PUBLIC_DNS_CHECKING', { domain: domainName }));
121
+ for (let attempt = 1; attempt <= constants_1.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS; attempt++) {
122
+ logger_1.logger.info(lang_1.lang.__('APIGW_PUBLIC_DNS_CHECK_ATTEMPT', {
123
+ attempt: String(attempt),
124
+ max: String(constants_1.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS),
125
+ }));
126
+ const resolved = await verifyCnameResolution(domainName);
127
+ if (resolved) {
128
+ logger_1.logger.info(lang_1.lang.__('APIGW_PUBLIC_DNS_RESOLVED', { domain: domainName }));
129
+ return true;
130
+ }
131
+ if (attempt < constants_1.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS) {
132
+ await sleep(constants_1.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS);
133
+ }
134
+ }
135
+ logger_1.logger.warn(lang_1.lang.__('APIGW_PUBLIC_DNS_TIMEOUT', { domain: domainName }));
136
+ return false;
137
+ };
120
138
  const addDomainVerificationRecord = async (domainName, verificationToken, groupSubdomain, region, state, eventLogicalId) => {
121
139
  logger_1.logger.info(lang_1.lang.__('APIGW_DNS_ADDING_RECORD', { domain: domainName }));
122
140
  const mainDomain = extractMainDomain(domainName);
@@ -187,7 +205,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
187
205
  },
188
206
  instances: [
189
207
  {
190
- arn: `arn:acs:alidns:${region}:dns-record/${recordId}`,
208
+ sid: (0, sidUtils_1.buildSid)('aliyun', 'alidns', _context.stage, recordId),
191
209
  id: recordId,
192
210
  type: 'CNAME',
193
211
  status: 'PENDING',
@@ -213,7 +231,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
213
231
  },
214
232
  instances: [
215
233
  {
216
- arn: `arn:acs:alidns:${region}:dns-record/existing`,
234
+ sid: (0, sidUtils_1.buildSid)('aliyun', 'alidns', _context.stage, 'existing'),
217
235
  id: 'existing',
218
236
  type: 'CNAME',
219
237
  status: 'EXISTING',
@@ -232,9 +250,65 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
232
250
  throw error;
233
251
  }
234
252
  };
235
- const logVerificationInstructions = (domainName, verificationToken, groupSubdomain) => {
253
+ const addTxtVerificationRecord = async (groupId, domainName, groupSubdomain, region, state, eventLogicalId) => {
254
+ const mainDomain = extractMainDomain(domainName);
255
+ const txtRecord = buildTxtVerificationRecord(groupId, domainName, groupSubdomain, mainDomain);
256
+ const txtResourceId = `${eventLogicalId}.dns_txt_verification`;
257
+ logger_1.logger.info(lang_1.lang.__('APIGW_TXT_ADDING_RECORD', { rr: txtRecord.rr, value: txtRecord.value }));
258
+ try {
259
+ const existingRecords = await dnsOps.describeDomainRecords(mainDomain, txtRecord.rr);
260
+ const recordExists = existingRecords.some((record) => record.rr === txtRecord.rr && record.type === 'TXT' && record.value === txtRecord.value);
261
+ if (recordExists) {
262
+ logger_1.logger.info(lang_1.lang.__('APIGW_TXT_RECORD_ALREADY_EXISTS', { rr: txtRecord.rr }));
263
+ return state;
264
+ }
265
+ const recordId = await dnsOps.addDomainRecord({
266
+ domainName: mainDomain,
267
+ rr: txtRecord.rr,
268
+ type: 'TXT',
269
+ value: txtRecord.value,
270
+ ttl: 600,
271
+ });
272
+ const dnsResourceState = {
273
+ mode: 'managed',
274
+ region,
275
+ definition: {
276
+ domainName,
277
+ mainDomain,
278
+ rr: txtRecord.rr,
279
+ value: txtRecord.value,
280
+ type: 'TXT',
281
+ groupId,
282
+ groupSubdomain,
283
+ },
284
+ instances: [
285
+ {
286
+ sid: (0, sidUtils_1.buildSid)('aliyun', 'alidns', _context.stage, recordId),
287
+ id: recordId,
288
+ type: 'TXT',
289
+ status: 'CREATED',
290
+ },
291
+ ],
292
+ lastUpdated: new Date().toISOString(),
293
+ };
294
+ state = (0, stateManager_1.setResource)(state, txtResourceId, dnsResourceState);
295
+ logger_1.logger.info(lang_1.lang.__('APIGW_DNS_RECORD_ADDED', {
296
+ record: txtRecord.rr,
297
+ type: 'TXT',
298
+ value: txtRecord.value,
299
+ }));
300
+ return state;
301
+ }
302
+ catch (error) {
303
+ logger_1.logger.error(lang_1.lang.__('APIGW_TXT_ADD_FAILED', { error: String(error) }));
304
+ throw error;
305
+ }
306
+ };
307
+ const logVerificationInstructions = (domainName, groupId, groupSubdomain) => {
308
+ const mainDomain = extractMainDomain(domainName);
309
+ const txtRecord = buildTxtVerificationRecord(groupId, domainName, groupSubdomain, mainDomain);
236
310
  const separator = '='.repeat(80);
237
- logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_HEADER')}\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_DOMAIN', { domain: domainName })}\n\n${lang_1.lang.__('APIGW_VERIFICATION_INSTRUCTIONS')}\n\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_NAME', { name: domainName })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_TYPE', { type: 'CNAME' })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_VALUE', { value: groupSubdomain })}`);
311
+ logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_HEADER')}\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_DOMAIN', { domain: domainName })}\n\n${lang_1.lang.__('APIGW_VERIFICATION_INSTRUCTIONS')}\n\n${lang_1.lang.__('APIGW_VERIFICATION_OPTION1')}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_NAME', { name: domainName })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_TYPE', { type: 'CNAME' })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_VALUE', { value: groupSubdomain })}\n\n${lang_1.lang.__('APIGW_VERIFICATION_OPTION2')}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_NAME', { name: txtRecord.rr })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_TYPE', { type: 'TXT' })}\n${lang_1.lang.__('APIGW_VERIFICATION_RECORD_VALUE', { value: txtRecord.value })}`);
238
312
  logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_NEXT_STEPS')}\n${lang_1.lang.__('APIGW_VERIFICATION_STEP1')}\n${lang_1.lang.__('APIGW_VERIFICATION_STEP2')}\n${separator}\n`);
239
313
  };
240
314
  return {
@@ -551,24 +625,29 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
551
625
  await apigwClient.abolishApi(request);
552
626
  },
553
627
  /**
554
- * Bind custom domain to API group with automatic verification
628
+ * Per Aliyun docs: CNAME must exist BEFORE calling SetDomain.
629
+ * On SingleDomainOwnershipCheckFail, falls back to TXT verification with retry.
555
630
  */
556
631
  bindCustomDomain: async (config, state, eventLogicalId) => {
557
632
  logger_1.logger.info(lang_1.lang.__('APIGW_BINDING_DOMAIN', { domain: config.domainName }));
558
- // Get the API group info to extract verification token from subDomain
559
633
  const groupInfo = await apigwClient.describeApiGroup(new cloudapi.DescribeApiGroupRequest({ groupId: config.groupId }));
560
634
  const region = groupInfo.body?.regionId || _context.region;
561
- // Try to bind the domain first
562
- try {
563
- const request = new cloudapi.SetDomainRequest({
564
- groupId: config.groupId,
565
- domainName: config.domainName,
566
- bindStageName: config.bindStageName || 'RELEASE',
567
- customDomainType: config.customDomainType,
568
- isHttpRedirectToHttps: config.isHttpRedirectToHttps,
569
- });
570
- await apigwClient.setDomain(request);
571
- // Set certificate if provided
635
+ const groupSubdomain = groupInfo.body?.subDomain;
636
+ const groupId = groupInfo.body?.groupId || config.groupId;
637
+ if (!groupSubdomain) {
638
+ throw new Error(`API group ${config.groupId} has no subDomain — cannot configure domain binding`);
639
+ }
640
+ logger_1.logger.info(lang_1.lang.__('APIGW_ENSURING_CNAME', { domain: config.domainName }));
641
+ state = await addDomainVerificationRecord(config.domainName, groupId, groupSubdomain, region, state, eventLogicalId);
642
+ await pollPublicDnsResolution(config.domainName);
643
+ const setDomainRequest = new cloudapi.SetDomainRequest({
644
+ groupId: config.groupId,
645
+ domainName: config.domainName,
646
+ bindStageName: config.bindStageName || 'RELEASE',
647
+ customDomainType: config.customDomainType,
648
+ isHttpRedirectToHttps: config.isHttpRedirectToHttps,
649
+ });
650
+ const setCertificate = async () => {
572
651
  if (config.certificateName && config.certificateBody && config.certificatePrivateKey) {
573
652
  const certRequest = new cloudapi.SetDomainCertificateRequest({
574
653
  groupId: config.groupId,
@@ -579,61 +658,53 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
579
658
  });
580
659
  await apigwClient.setDomainCertificate(certRequest);
581
660
  }
661
+ };
662
+ try {
663
+ await apigwClient.setDomain(setDomainRequest);
664
+ await setCertificate();
582
665
  logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BOUND_SUCCESS', { domain: config.domainName }));
583
666
  return state;
584
667
  }
585
668
  catch (error) {
586
669
  const err = error;
587
- // Check if it's a domain ownership verification error
588
- if (err.code === 'SingleDomainOwnershipCheckFail' || err.message?.includes('ownership')) {
589
- logger_1.logger.error(lang_1.lang.__('APIGW_DOMAIN_OWNERSHIP_FAILED', { domain: config.domainName }));
590
- const verificationToken = extractVerificationToken(error, groupInfo.body);
591
- if (verificationToken && groupInfo.body?.subDomain) {
592
- logger_1.logger.info(lang_1.lang.__('APIGW_ATTEMPTING_AUTO_VERIFICATION', { token: verificationToken }));
593
- try {
594
- // Try to add DNS verification record automatically and update state
595
- state = await addDomainVerificationRecord(config.domainName, verificationToken, groupInfo.body.subDomain, region, state, eventLogicalId);
596
- // Retry domain binding after DNS verification
597
- logger_1.logger.info(lang_1.lang.__('APIGW_RETRYING_DOMAIN_BINDING'));
598
- const retryRequest = new cloudapi.SetDomainRequest({
599
- groupId: config.groupId,
600
- domainName: config.domainName,
601
- bindStageName: config.bindStageName || 'RELEASE',
602
- customDomainType: config.customDomainType,
603
- isHttpRedirectToHttps: config.isHttpRedirectToHttps,
604
- });
605
- await apigwClient.setDomain(retryRequest);
606
- // Set certificate if provided
607
- if (config.certificateName &&
608
- config.certificateBody &&
609
- config.certificatePrivateKey) {
610
- const certRequest = new cloudapi.SetDomainCertificateRequest({
611
- groupId: config.groupId,
612
- domainName: config.domainName,
613
- certificateName: config.certificateName,
614
- certificateBody: config.certificateBody,
615
- certificatePrivateKey: config.certificatePrivateKey,
616
- });
617
- await apigwClient.setDomainCertificate(certRequest);
618
- }
619
- logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BOUND_AFTER_VERIFICATION', { domain: config.domainName }));
620
- return state;
621
- }
622
- catch (retryError) {
623
- logger_1.logger.error(lang_1.lang.__('APIGW_AUTO_VERIFICATION_FAILED', { error: String(retryError) }));
624
- // Fall through to show manual instructions
625
- }
626
- }
627
- // Show manual verification instructions
628
- if (verificationToken && groupInfo.body?.subDomain) {
629
- logVerificationInstructions(config.domainName, verificationToken, groupInfo.body.subDomain);
670
+ if (err.code !== 'SingleDomainOwnershipCheckFail' && !err.message?.includes('ownership')) {
671
+ throw error;
672
+ }
673
+ logger_1.logger.warn(lang_1.lang.__('APIGW_DOMAIN_OWNERSHIP_FAILED', { domain: config.domainName }));
674
+ logger_1.logger.info(lang_1.lang.__('APIGW_TXT_FALLBACK', { domain: config.domainName }));
675
+ try {
676
+ state = await addTxtVerificationRecord(groupId, config.domainName, groupSubdomain, region, state, eventLogicalId);
677
+ }
678
+ catch (txtError) {
679
+ logger_1.logger.error(lang_1.lang.__('APIGW_TXT_ADD_FAILED', { error: String(txtError) }));
680
+ logVerificationInstructions(config.domainName, groupId, groupSubdomain);
681
+ throw error;
682
+ }
683
+ for (let attempt = 1; attempt <= constants_1.APIGW_DOMAIN_BIND_MAX_RETRIES; attempt++) {
684
+ logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BIND_RETRY', {
685
+ attempt: String(attempt),
686
+ max: String(constants_1.APIGW_DOMAIN_BIND_MAX_RETRIES),
687
+ }));
688
+ await sleep(constants_1.APIGW_DOMAIN_BIND_RETRY_DELAY_MS);
689
+ try {
690
+ await apigwClient.setDomain(setDomainRequest);
691
+ await setCertificate();
692
+ logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BOUND_AFTER_VERIFICATION', { domain: config.domainName }));
693
+ return state;
630
694
  }
631
- else {
632
- logger_1.logger.error(lang_1.lang.__('APIGW_NO_VERIFICATION_TOKEN'));
633
- logger_1.logger.error(lang_1.lang.__('APIGW_MANUAL_VERIFICATION_REQUIRED'));
695
+ catch (retryError) {
696
+ const retryErr = retryError;
697
+ if (retryErr.code !== 'SingleDomainOwnershipCheckFail' &&
698
+ attempt === constants_1.APIGW_DOMAIN_BIND_MAX_RETRIES) {
699
+ throw retryError;
700
+ }
701
+ logger_1.logger.warn(lang_1.lang.__('APIGW_DOMAIN_BIND_RETRY_FAILED', {
702
+ attempt: String(attempt),
703
+ error: String(retryError),
704
+ }));
634
705
  }
635
706
  }
636
- // Re-throw the error to be handled by caller
707
+ logVerificationInstructions(config.domainName, groupId, groupSubdomain);
637
708
  throw error;
638
709
  }
639
710
  },
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.createEcsOperations = exports.securityGroupRangeMap = void 0;
36
+ exports.createEcsOperations = exports.parseSecurityGroupRule = exports.securityGroupRangeMap = void 0;
37
37
  const ecs = __importStar(require("@alicloud/ecs20140526"));
38
38
  const logger_1 = require("../logger");
39
39
  exports.securityGroupRangeMap = {
@@ -49,6 +49,35 @@ const transformPortRange = (protocol, portRange) => {
49
49
  }
50
50
  return portRange.includes('/') ? portRange : `${portRange}/${portRange}`;
51
51
  };
52
+ const normalizeProtocol = (protocol) => protocol.trim().toUpperCase();
53
+ const parseSecurityGroupRule = (rule) => {
54
+ const [rawProtocol, second, third, ...rest] = rule.split(':');
55
+ if (rest.length > 0 || !rawProtocol || !second || !third) {
56
+ throw new Error(`Invalid security group rule format: ${rule}`);
57
+ }
58
+ const protocol = normalizeProtocol(rawProtocol);
59
+ const secondTrimmed = second.trim();
60
+ const thirdTrimmed = third.trim();
61
+ if (!secondTrimmed || !thirdTrimmed) {
62
+ throw new Error(`Invalid security group rule format: ${rule}`);
63
+ }
64
+ return { protocol, cidr: secondTrimmed, portRange: thirdTrimmed };
65
+ };
66
+ exports.parseSecurityGroupRule = parseSecurityGroupRule;
67
+ const isDuplicateSecurityGroupRuleError = (error) => {
68
+ if (!error || typeof error !== 'object') {
69
+ return false;
70
+ }
71
+ if (!('code' in error) || typeof error.code !== 'string') {
72
+ return false;
73
+ }
74
+ const duplicateCodes = new Set([
75
+ 'InvalidPermission.Duplicate',
76
+ 'InvalidSecurityGroupRule.Duplicate',
77
+ 'SecurityRuleDuplicate',
78
+ ]);
79
+ return duplicateCodes.has(error.code);
80
+ };
52
81
  const createEcsOperations = (ecsClient, context) => ({
53
82
  createSecurityGroup: async (securityGroupName, vpcId, ingressRules, egressRules, description) => {
54
83
  const createRequest = new ecs.CreateSecurityGroupRequest({
@@ -64,36 +93,58 @@ const createEcsOperations = (ecsClient, context) => ({
64
93
  }
65
94
  // Add ingress rules
66
95
  for (const rule of ingressRules) {
67
- const [protocol, cidrIp, portRange] = rule.split(':');
96
+ let parsedRule;
97
+ try {
98
+ parsedRule = (0, exports.parseSecurityGroupRule)(rule);
99
+ }
100
+ catch (error) {
101
+ logger_1.logger.warn(`Skipping invalid ingress rule: ${rule}. ${String(error)}`);
102
+ continue;
103
+ }
68
104
  const ingressRequest = new ecs.AuthorizeSecurityGroupRequest({
69
105
  regionId: context.region,
70
106
  securityGroupId,
71
- ipProtocol: protocol.toLowerCase(),
72
- sourceCidrIp: cidrIp,
73
- portRange: transformPortRange(protocol, portRange),
107
+ ipProtocol: parsedRule.protocol.toLowerCase(),
108
+ sourceCidrIp: parsedRule.cidr,
109
+ portRange: transformPortRange(parsedRule.protocol, parsedRule.portRange),
74
110
  });
75
111
  try {
76
112
  await ecsClient.authorizeSecurityGroup(ingressRequest);
77
113
  }
78
- catch {
79
- logger_1.logger.warn(`Failed to add ingress rule: ${rule}`);
114
+ catch (error) {
115
+ if (isDuplicateSecurityGroupRuleError(error)) {
116
+ logger_1.logger.debug(`Ingress rule already exists, skipping: ${rule}`);
117
+ continue;
118
+ }
119
+ logger_1.logger.warn(`Failed to add ingress rule: ${rule}. ${String(error)}`);
80
120
  }
81
121
  }
82
122
  // Add egress rules
83
123
  for (const rule of egressRules) {
84
- const [protocol, cidrIp, portRange] = rule.split(':');
124
+ let parsedRule;
125
+ try {
126
+ parsedRule = (0, exports.parseSecurityGroupRule)(rule);
127
+ }
128
+ catch (error) {
129
+ logger_1.logger.warn(`Skipping invalid egress rule: ${rule}. ${String(error)}`);
130
+ continue;
131
+ }
85
132
  const egressRequest = new ecs.AuthorizeSecurityGroupEgressRequest({
86
133
  regionId: context.region,
87
134
  securityGroupId,
88
- ipProtocol: protocol.toLowerCase(),
89
- destCidrIp: cidrIp,
90
- portRange: transformPortRange(protocol, portRange),
135
+ ipProtocol: parsedRule.protocol.toLowerCase(),
136
+ destCidrIp: parsedRule.cidr,
137
+ portRange: transformPortRange(parsedRule.protocol, parsedRule.portRange),
91
138
  });
92
139
  try {
93
140
  await ecsClient.authorizeSecurityGroupEgress(egressRequest);
94
141
  }
95
- catch {
96
- logger_1.logger.warn(`Failed to add egress rule: ${rule}`);
142
+ catch (error) {
143
+ if (isDuplicateSecurityGroupRuleError(error)) {
144
+ logger_1.logger.debug(`Egress rule already exists, skipping: ${rule}`);
145
+ continue;
146
+ }
147
+ logger_1.logger.warn(`Failed to add egress rule: ${rule}. ${String(error)}`);
97
148
  }
98
149
  }
99
150
  return {
@@ -39,19 +39,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.createFc3Operations = void 0;
40
40
  const fc = __importStar(require("@alicloud/fc20230330"));
41
41
  const node_fs_1 = __importDefault(require("node:fs"));
42
+ const buildCodeLocation = (codePath, ossCode) => {
43
+ if (ossCode) {
44
+ return new fc.InputCodeLocation({
45
+ ossBucketName: ossCode.ossBucketName,
46
+ ossObjectName: ossCode.ossObjectName,
47
+ });
48
+ }
49
+ const codeBuffer = node_fs_1.default.readFileSync(codePath);
50
+ const codeBase64 = codeBuffer.toString('base64');
51
+ return new fc.InputCodeLocation({ zipFile: codeBase64 });
52
+ };
42
53
  const createFc3Operations = (fc3Client) => ({
43
- createFunction: async (config, codePath) => {
44
- const codeBuffer = node_fs_1.default.readFileSync(codePath);
45
- const codeBase64 = codeBuffer.toString('base64');
54
+ createFunction: async (config, codePath, ossCode) => {
46
55
  const createFunctionInput = new fc.CreateFunctionInput({
47
56
  functionName: config.functionName,
48
57
  runtime: config.runtime,
49
58
  handler: config.handler,
50
59
  memorySize: config.memorySize,
51
60
  timeout: config.timeout,
52
- code: new fc.InputCodeLocation({
53
- zipFile: codeBase64,
54
- }),
61
+ code: buildCodeLocation(codePath, ossCode),
55
62
  ...(config.diskSize && { diskSize: config.diskSize }),
56
63
  ...(config.environmentVariables && { environmentVariables: config.environmentVariables }),
57
64
  ...(config.gpuConfig && {
@@ -250,13 +257,9 @@ const createFc3Operations = (fc3Client) => ({
250
257
  });
251
258
  await fc3Client.updateFunction(config.functionName, request);
252
259
  },
253
- updateFunctionCode: async (functionName, codePath) => {
254
- const codeBuffer = node_fs_1.default.readFileSync(codePath);
255
- const codeBase64 = codeBuffer.toString('base64');
260
+ updateFunctionCode: async (functionName, codePath, ossCode) => {
256
261
  const updateFunctionInput = new fc.UpdateFunctionInput({
257
- code: new fc.InputCodeLocation({
258
- zipFile: codeBase64,
259
- }),
262
+ code: buildCodeLocation(codePath, ossCode),
260
263
  });
261
264
  const request = new fc.UpdateFunctionRequest({
262
265
  body: updateFunctionInput,
@@ -51,6 +51,7 @@ const es_serverless20230627_1 = __importDefault(require("@alicloud/es-serverless
51
51
  const alidns20150109_1 = __importDefault(require("@alicloud/alidns20150109"));
52
52
  const $OpenApi = __importStar(require("@alicloud/openapi-client"));
53
53
  const ali_oss_1 = __importDefault(require("ali-oss"));
54
+ const constants_1 = require("../constants");
54
55
  const fc3Operations_1 = require("./fc3Operations");
55
56
  const slsOperations_1 = require("./slsOperations");
56
57
  const ramOperations_1 = require("./ramOperations");
@@ -78,6 +79,8 @@ const initializeSdkClients = (context) => {
78
79
  };
79
80
  const fc3Config = new $OpenApi.Config(baseConfig);
80
81
  fc3Config.endpoint = `${context.accountId}.${context.region}.fc.aliyuncs.com`;
82
+ fc3Config.connectTimeout = constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS;
83
+ fc3Config.readTimeout = constants_1.ALIYUN_FC3_READ_TIMEOUT_MS;
81
84
  const fc3Client = new fc20230330_1.default(fc3Config);
82
85
  const slsConfig = new $OpenApi.Config(baseConfig);
83
86
  slsConfig.endpoint = `${context.region}.log.aliyuncs.com`;
@@ -232,6 +232,10 @@ const createOssOperations = (ossClient, region) => {
232
232
  await ossClient.put(fileName, sourcePath);
233
233
  }
234
234
  },
235
+ putFile: async (bucketName, objectKey, filePath) => {
236
+ useBucket(bucketName);
237
+ await ossClient.put(objectKey, filePath);
238
+ },
235
239
  };
236
240
  };
237
241
  exports.createOssOperations = createOssOperations;
@@ -35,14 +35,14 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createRamOperations = void 0;
37
37
  const ram = __importStar(require("@alicloud/ram20150501"));
38
- const FC_ASSUME_ROLE_POLICY = JSON.stringify({
38
+ const buildAssumeRolePolicy = (trustedServices) => JSON.stringify({
39
39
  Version: '1',
40
40
  Statement: [
41
41
  {
42
42
  Action: 'sts:AssumeRole',
43
43
  Effect: 'Allow',
44
44
  Principal: {
45
- Service: ['fc.aliyuncs.com'],
45
+ Service: trustedServices,
46
46
  },
47
47
  },
48
48
  ],
@@ -126,22 +126,50 @@ const createRamOperations = (ramClient) => {
126
126
  }
127
127
  };
128
128
  return {
129
- createRole: async (roleName, description) => {
130
- const request = new ram.CreateRoleRequest({
131
- roleName,
132
- assumeRolePolicyDocument: FC_ASSUME_ROLE_POLICY,
133
- description: description ?? `ServerlessInsight FC execution role for ${roleName}`,
134
- });
135
- const response = await ramClient.createRole(request);
136
- // Attach policy to role
129
+ createRole: async (roleName, trustedServices, description) => {
130
+ let roleInfo;
131
+ const assumeRolePolicy = buildAssumeRolePolicy(trustedServices);
132
+ try {
133
+ const request = new ram.CreateRoleRequest({
134
+ roleName,
135
+ assumeRolePolicyDocument: assumeRolePolicy,
136
+ description: description ?? `ServerlessInsight FC execution role for ${roleName}`,
137
+ });
138
+ const response = await ramClient.createRole(request);
139
+ roleInfo = {
140
+ roleName,
141
+ roleId: response.body?.role?.roleId,
142
+ arn: response.body?.role?.arn,
143
+ description: response.body?.role?.description,
144
+ createDate: response.body?.role?.createDate,
145
+ };
146
+ }
147
+ catch (error) {
148
+ if (error &&
149
+ typeof error === 'object' &&
150
+ 'code' in error &&
151
+ error.code === 'EntityAlreadyExists.Role') {
152
+ const getRequest = new ram.GetRoleRequest({ roleName });
153
+ const getResponse = await ramClient.getRole(getRequest);
154
+ roleInfo = {
155
+ roleName,
156
+ roleId: getResponse.body?.role?.roleId,
157
+ arn: getResponse.body?.role?.arn,
158
+ description: getResponse.body?.role?.description,
159
+ createDate: getResponse.body?.role?.createDate,
160
+ };
161
+ const updateRequest = new ram.UpdateRoleRequest({
162
+ roleName,
163
+ newAssumeRolePolicyDocument: assumeRolePolicy,
164
+ });
165
+ await ramClient.updateRole(updateRequest);
166
+ }
167
+ else {
168
+ throw error;
169
+ }
170
+ }
137
171
  await attachRolePolicyForFc(roleName);
138
- return {
139
- roleName,
140
- roleId: response.body?.role?.roleId,
141
- arn: response.body?.role?.arn,
142
- description: response.body?.role?.description,
143
- createDate: response.body?.role?.createDate,
144
- };
172
+ return roleInfo;
145
173
  },
146
174
  getRole: async (roleName) => {
147
175
  try {
@@ -1,14 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.ROS_STACK_OPERATION_TIMEOUT = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
3
+ exports.RAM_ROLE_PROPAGATION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.OSS_STATE_REQUEST_TIMEOUT_MS = exports.OSS_STATE_CONNECT_TIMEOUT_MS = exports.FC3_CODE_INLINE_SIZE_LIMIT = exports.ALIYUN_FC3_READ_TIMEOUT_MS = exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.ROS_STACK_OPERATION_TIMEOUT = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
4
4
  exports.CODE_ZIP_SIZE_LIMIT = 300 * 1000; // 300 KB ROS TemplateBody size limit 512 KB
5
5
  exports.OSS_DEPLOYMENT_TIMEOUT = 3000; // in seconds
6
6
  exports.ROS_STACK_OPERATION_TIMEOUT = 3600; // in seconds
7
7
  exports.SI_BOOTSTRAP_FC_PREFIX = 'si-bootstrap-api';
8
8
  exports.SI_BOOTSTRAP_BUCKET_PREFIX = 'si-bootstrap-artifacts';
9
9
  exports.SI_LOCALSTACK_SERVER_PORT = 4567;
10
+ exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = 120000;
11
+ exports.ALIYUN_FC3_READ_TIMEOUT_MS = 600000;
12
+ exports.FC3_CODE_INLINE_SIZE_LIMIT = 70 * 1024 * 1024; // 70MB threshold for OSS upload
13
+ // OSS state backend timeouts
14
+ exports.OSS_STATE_CONNECT_TIMEOUT_MS = 10000; // 10 seconds
15
+ exports.OSS_STATE_REQUEST_TIMEOUT_MS = 30000; // 30 seconds
10
16
  // Lock manager constants
11
17
  exports.LOCK_FILE_SUFFIX = '.si-lock';
12
18
  exports.DEFAULT_LOCK_TIMEOUT = 10 * 60 * 1000; // 10 minutes
13
19
  exports.DEFAULT_LOCK_RETRY_DELAY = 2000; // 2 seconds
14
20
  exports.STALE_LOCK_THRESHOLD = 60 * 60 * 1000; // 1 hour
21
+ // API Gateway domain binding
22
+ exports.APIGW_DOMAIN_BIND_MAX_RETRIES = 5;
23
+ exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = 30000; // 30 seconds
24
+ exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = 10;
25
+ exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = 30000; // 30 seconds
26
+ // RAM role propagation
27
+ exports.RAM_ROLE_PROPAGATION_DELAY_MS = 5000; // 5 seconds
@@ -30,3 +30,4 @@ __exportStar(require("./scfClient"), exports);
30
30
  __exportStar(require("./runtimeMapper"), exports);
31
31
  __exportStar(require("./hashUtils"), exports);
32
32
  __exportStar(require("./dependencyGraph"), exports);
33
+ __exportStar(require("./sidUtils"), exports);