@geek-fun/serverlessinsight 0.5.4 → 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.
- package/dist/package.json +1 -1
- package/dist/src/commands/deploy.js +1 -0
- package/dist/src/common/aliyunClient/apigwOperations.js +150 -80
- package/dist/src/common/aliyunClient/ecsOperations.js +64 -13
- package/dist/src/common/aliyunClient/fc3Operations.js +15 -12
- package/dist/src/common/aliyunClient/index.js +3 -0
- package/dist/src/common/aliyunClient/ossOperations.js +4 -0
- package/dist/src/common/aliyunClient/ramOperations.js +45 -17
- package/dist/src/common/constants.js +14 -1
- package/dist/src/common/lockManager.js +29 -1
- package/dist/src/common/stateBackend/cosStateBackend.js +31 -0
- package/dist/src/common/stateBackend/ossStateBackend.js +32 -0
- package/dist/src/lang/en.js +13 -5
- package/dist/src/lang/zh-CN.js +38 -5
- package/dist/src/stack/aliyunStack/apigwPlanner.js +1 -1
- package/dist/src/stack/aliyunStack/apigwResource.js +5 -5
- package/dist/src/stack/aliyunStack/apigwTypes.js +4 -4
- package/dist/src/stack/aliyunStack/fc3Resource.js +87 -8
- package/dist/src/validator/functionSchema.js +9 -2
- 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
|
+
"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,11 +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");
|
|
42
43
|
const sidUtils_1 = require("../sidUtils");
|
|
44
|
+
const constants_1 = require("../constants");
|
|
43
45
|
const removeUndefined = (obj) => {
|
|
44
46
|
return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined));
|
|
45
47
|
};
|
|
@@ -63,24 +65,11 @@ const extractHostRecord = (fullDomain, mainDomain) => {
|
|
|
63
65
|
};
|
|
64
66
|
const createApigwOperations = (apigwClient, dnsClient, _context) => {
|
|
65
67
|
const dnsOps = (0, dnsOperations_1.createDnsOperations)(dnsClient);
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
return match[1];
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
const errorStr = String(error);
|
|
75
|
-
const cnameMatch = errorStr.match(/([a-f0-9]{32})-[^.]+\.alicloudapi\.com/);
|
|
76
|
-
if (cnameMatch) {
|
|
77
|
-
return cnameMatch[1];
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
catch {
|
|
81
|
-
// Ignore extraction errors
|
|
82
|
-
}
|
|
83
|
-
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}` };
|
|
84
73
|
};
|
|
85
74
|
const pollDnsPropagation = async (mainDomain, verificationHost, verificationValue, shouldLoop = true) => {
|
|
86
75
|
const checkPropagation = async () => {
|
|
@@ -118,6 +107,34 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
|
|
|
118
107
|
logger_1.logger.warn(lang_1.lang.__('APIGW_DNS_PROPAGATION_TIMEOUT'));
|
|
119
108
|
return false;
|
|
120
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
|
+
};
|
|
121
138
|
const addDomainVerificationRecord = async (domainName, verificationToken, groupSubdomain, region, state, eventLogicalId) => {
|
|
122
139
|
logger_1.logger.info(lang_1.lang.__('APIGW_DNS_ADDING_RECORD', { domain: domainName }));
|
|
123
140
|
const mainDomain = extractMainDomain(domainName);
|
|
@@ -233,9 +250,65 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
|
|
|
233
250
|
throw error;
|
|
234
251
|
}
|
|
235
252
|
};
|
|
236
|
-
const
|
|
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);
|
|
237
310
|
const separator = '='.repeat(80);
|
|
238
|
-
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 })}`);
|
|
239
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`);
|
|
240
313
|
};
|
|
241
314
|
return {
|
|
@@ -552,24 +625,29 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
|
|
|
552
625
|
await apigwClient.abolishApi(request);
|
|
553
626
|
},
|
|
554
627
|
/**
|
|
555
|
-
*
|
|
628
|
+
* Per Aliyun docs: CNAME must exist BEFORE calling SetDomain.
|
|
629
|
+
* On SingleDomainOwnershipCheckFail, falls back to TXT verification with retry.
|
|
556
630
|
*/
|
|
557
631
|
bindCustomDomain: async (config, state, eventLogicalId) => {
|
|
558
632
|
logger_1.logger.info(lang_1.lang.__('APIGW_BINDING_DOMAIN', { domain: config.domainName }));
|
|
559
|
-
// Get the API group info to extract verification token from subDomain
|
|
560
633
|
const groupInfo = await apigwClient.describeApiGroup(new cloudapi.DescribeApiGroupRequest({ groupId: config.groupId }));
|
|
561
634
|
const region = groupInfo.body?.regionId || _context.region;
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
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 () => {
|
|
573
651
|
if (config.certificateName && config.certificateBody && config.certificatePrivateKey) {
|
|
574
652
|
const certRequest = new cloudapi.SetDomainCertificateRequest({
|
|
575
653
|
groupId: config.groupId,
|
|
@@ -580,61 +658,53 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
|
|
|
580
658
|
});
|
|
581
659
|
await apigwClient.setDomainCertificate(certRequest);
|
|
582
660
|
}
|
|
661
|
+
};
|
|
662
|
+
try {
|
|
663
|
+
await apigwClient.setDomain(setDomainRequest);
|
|
664
|
+
await setCertificate();
|
|
583
665
|
logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BOUND_SUCCESS', { domain: config.domainName }));
|
|
584
666
|
return state;
|
|
585
667
|
}
|
|
586
668
|
catch (error) {
|
|
587
669
|
const err = error;
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
groupId: config.groupId,
|
|
613
|
-
domainName: config.domainName,
|
|
614
|
-
certificateName: config.certificateName,
|
|
615
|
-
certificateBody: config.certificateBody,
|
|
616
|
-
certificatePrivateKey: config.certificatePrivateKey,
|
|
617
|
-
});
|
|
618
|
-
await apigwClient.setDomainCertificate(certRequest);
|
|
619
|
-
}
|
|
620
|
-
logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_BOUND_AFTER_VERIFICATION', { domain: config.domainName }));
|
|
621
|
-
return state;
|
|
622
|
-
}
|
|
623
|
-
catch (retryError) {
|
|
624
|
-
logger_1.logger.error(lang_1.lang.__('APIGW_AUTO_VERIFICATION_FAILED', { error: String(retryError) }));
|
|
625
|
-
// Fall through to show manual instructions
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
// Show manual verification instructions
|
|
629
|
-
if (verificationToken && groupInfo.body?.subDomain) {
|
|
630
|
-
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;
|
|
631
694
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
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
|
+
}));
|
|
635
705
|
}
|
|
636
706
|
}
|
|
637
|
-
|
|
707
|
+
logVerificationInstructions(config.domainName, groupId, groupSubdomain);
|
|
638
708
|
throw error;
|
|
639
709
|
}
|
|
640
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
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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:
|
|
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:
|
|
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
|
|
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:
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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
|
|
@@ -11,6 +11,7 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
|
11
11
|
const node_child_process_1 = require("node:child_process");
|
|
12
12
|
const constants_1 = require("./constants");
|
|
13
13
|
const lang_1 = require("../lang");
|
|
14
|
+
const logger_1 = require("./logger");
|
|
14
15
|
class LockError extends Error {
|
|
15
16
|
constructor(message, lockInfo) {
|
|
16
17
|
super(message);
|
|
@@ -85,6 +86,15 @@ const isLockStale = (lock) => {
|
|
|
85
86
|
const now = Date.now();
|
|
86
87
|
return now - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
|
|
87
88
|
};
|
|
89
|
+
const isProcessAlive = (pid) => {
|
|
90
|
+
try {
|
|
91
|
+
process.kill(pid, 0);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
88
98
|
const getTimeAgo = (acquiredAt) => {
|
|
89
99
|
const now = new Date();
|
|
90
100
|
const minutesAgo = Math.floor((now.getTime() - acquiredAt.getTime()) / 60000);
|
|
@@ -150,7 +160,17 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
|
|
|
150
160
|
}
|
|
151
161
|
}
|
|
152
162
|
else {
|
|
153
|
-
|
|
163
|
+
if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
|
|
164
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
|
|
165
|
+
processId: String(existingLock.processId),
|
|
166
|
+
hostname: existingLock.hostname,
|
|
167
|
+
user: existingLock.user,
|
|
168
|
+
acquiredAt: existingLock.acquiredAt,
|
|
169
|
+
}));
|
|
170
|
+
removeLockFile(lockPath);
|
|
171
|
+
attempt++;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
154
174
|
if (isLockStale(existingLock)) {
|
|
155
175
|
// Lock is stale, but we don't auto-remove it
|
|
156
176
|
// User must use force-unlock
|
|
@@ -160,6 +180,14 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
|
|
|
160
180
|
if (Date.now() - startTime >= timeout) {
|
|
161
181
|
throw new LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, exports.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
|
|
162
182
|
}
|
|
183
|
+
const acquiredAt = new Date(existingLock.acquiredAt);
|
|
184
|
+
const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
|
|
185
|
+
const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
|
|
186
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
|
|
187
|
+
user: existingLock.user,
|
|
188
|
+
timeAgo,
|
|
189
|
+
attempt: String(attempt + 1),
|
|
190
|
+
}));
|
|
163
191
|
}
|
|
164
192
|
// Wait before retrying with exponential backoff
|
|
165
193
|
const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000); // Cap at 30 seconds
|
|
@@ -11,6 +11,8 @@ const node_child_process_1 = require("node:child_process");
|
|
|
11
11
|
const types_1 = require("../../types");
|
|
12
12
|
const constants_1 = require("../constants");
|
|
13
13
|
const lockManager_1 = require("../lockManager");
|
|
14
|
+
const logger_1 = require("../logger");
|
|
15
|
+
const lang_1 = require("../../lang");
|
|
14
16
|
const LOCK_KEY_SUFFIX = '.si-lock';
|
|
15
17
|
const getUserEmail = () => {
|
|
16
18
|
try {
|
|
@@ -33,6 +35,15 @@ const isLockStale = (lock) => {
|
|
|
33
35
|
const acquiredAt = new Date(lock.acquiredAt).getTime();
|
|
34
36
|
return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
|
|
35
37
|
};
|
|
38
|
+
const isProcessAlive = (pid) => {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(pid, 0);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
36
47
|
const promisifyGet = (cosClient, bucket, region, key) => {
|
|
37
48
|
return new Promise((resolve, reject) => {
|
|
38
49
|
cosClient.getObject({ Bucket: bucket, Region: region, Key: key }, (err, data) => {
|
|
@@ -75,6 +86,7 @@ const createCosStateBackend = (config) => {
|
|
|
75
86
|
SecretId: config.accessKeyId,
|
|
76
87
|
SecretKey: config.accessKeySecret,
|
|
77
88
|
SecurityToken: config.securityToken,
|
|
89
|
+
Timeout: constants_1.OSS_STATE_REQUEST_TIMEOUT_MS,
|
|
78
90
|
});
|
|
79
91
|
const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
|
|
80
92
|
const readObject = async (key) => {
|
|
@@ -117,12 +129,31 @@ const createCosStateBackend = (config) => {
|
|
|
117
129
|
}
|
|
118
130
|
}
|
|
119
131
|
else {
|
|
132
|
+
if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
|
|
133
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
|
|
134
|
+
processId: String(existingLock.processId),
|
|
135
|
+
hostname: existingLock.hostname,
|
|
136
|
+
user: existingLock.user,
|
|
137
|
+
acquiredAt: existingLock.acquiredAt,
|
|
138
|
+
}));
|
|
139
|
+
await deleteObject(lockKey);
|
|
140
|
+
attempt++;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
120
143
|
if (isLockStale(existingLock)) {
|
|
121
144
|
throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
|
|
122
145
|
}
|
|
123
146
|
if (Date.now() - startTime >= timeout) {
|
|
124
147
|
throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
|
|
125
148
|
}
|
|
149
|
+
const acquiredAt = new Date(existingLock.acquiredAt);
|
|
150
|
+
const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
|
|
151
|
+
const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
|
|
152
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
|
|
153
|
+
user: existingLock.user,
|
|
154
|
+
timeAgo,
|
|
155
|
+
attempt: String(attempt + 1),
|
|
156
|
+
}));
|
|
126
157
|
}
|
|
127
158
|
const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
|
|
128
159
|
await sleep(delay);
|
|
@@ -11,6 +11,8 @@ const node_child_process_1 = require("node:child_process");
|
|
|
11
11
|
const types_1 = require("../../types");
|
|
12
12
|
const constants_1 = require("../constants");
|
|
13
13
|
const lockManager_1 = require("../lockManager");
|
|
14
|
+
const logger_1 = require("../logger");
|
|
15
|
+
const lang_1 = require("../../lang");
|
|
14
16
|
const LOCK_KEY_SUFFIX = '.si-lock';
|
|
15
17
|
const getUserEmail = () => {
|
|
16
18
|
try {
|
|
@@ -33,6 +35,15 @@ const isLockStale = (lock) => {
|
|
|
33
35
|
const acquiredAt = new Date(lock.acquiredAt).getTime();
|
|
34
36
|
return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
|
|
35
37
|
};
|
|
38
|
+
const isProcessAlive = (pid) => {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(pid, 0);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
36
47
|
const createOssStateBackend = (config) => {
|
|
37
48
|
const ossClient = new ali_oss_1.default({
|
|
38
49
|
accessKeyId: config.accessKeyId,
|
|
@@ -40,6 +51,8 @@ const createOssStateBackend = (config) => {
|
|
|
40
51
|
region: `oss-${config.region}`,
|
|
41
52
|
bucket: config.bucket,
|
|
42
53
|
stsToken: config.securityToken,
|
|
54
|
+
timeout: constants_1.OSS_STATE_REQUEST_TIMEOUT_MS,
|
|
55
|
+
connectTimeout: constants_1.OSS_STATE_CONNECT_TIMEOUT_MS,
|
|
43
56
|
});
|
|
44
57
|
const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
|
|
45
58
|
const readObject = async (key) => {
|
|
@@ -98,12 +111,31 @@ const createOssStateBackend = (config) => {
|
|
|
98
111
|
}
|
|
99
112
|
}
|
|
100
113
|
else {
|
|
114
|
+
if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
|
|
115
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
|
|
116
|
+
processId: String(existingLock.processId),
|
|
117
|
+
hostname: existingLock.hostname,
|
|
118
|
+
user: existingLock.user,
|
|
119
|
+
acquiredAt: existingLock.acquiredAt,
|
|
120
|
+
}));
|
|
121
|
+
await deleteObject(lockKey);
|
|
122
|
+
attempt++;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
101
125
|
if (isLockStale(existingLock)) {
|
|
102
126
|
throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
|
|
103
127
|
}
|
|
104
128
|
if (Date.now() - startTime >= timeout) {
|
|
105
129
|
throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
|
|
106
130
|
}
|
|
131
|
+
const acquiredAt = new Date(existingLock.acquiredAt);
|
|
132
|
+
const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
|
|
133
|
+
const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
|
|
134
|
+
logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
|
|
135
|
+
user: existingLock.user,
|
|
136
|
+
timeAgo,
|
|
137
|
+
attempt: String(attempt + 1),
|
|
138
|
+
}));
|
|
107
139
|
}
|
|
108
140
|
const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
|
|
109
141
|
await sleep(delay);
|
package/dist/src/lang/en.js
CHANGED
|
@@ -180,6 +180,8 @@ exports.en = {
|
|
|
180
180
|
ACQUIRING_LOCK: 'Acquiring state lock...',
|
|
181
181
|
LOCK_ACQUIRED: 'Lock acquired',
|
|
182
182
|
LOCK_RELEASED: '✓ Lock released',
|
|
183
|
+
LOCK_WAITING: 'State is locked by {{user}} ({{timeAgo}}). Waiting to acquire lock... (attempt {{attempt}})',
|
|
184
|
+
LOCK_AUTO_RELEASED_DEAD_PROCESS: 'Auto-releasing stale lock held by dead process (PID {{processId}} on {{hostname}}). Lock was held by {{user}} since {{acquiredAt}}.',
|
|
183
185
|
FAILED_TO_RELEASE_LOCK: 'Failed to release lock',
|
|
184
186
|
NO_LOCK_FOUND: 'No lock found',
|
|
185
187
|
LOCK_ID_MISMATCH: 'Lock ID mismatch. Current lock ID is {{actualId}}, but you provided {{providedId}}',
|
|
@@ -224,12 +226,18 @@ exports.en = {
|
|
|
224
226
|
APIGW_BINDING_DOMAIN: 'Binding custom domain: {{domain}}',
|
|
225
227
|
APIGW_DOMAIN_BOUND_SUCCESS: 'Successfully bound domain: {{domain}}',
|
|
226
228
|
APIGW_DOMAIN_OWNERSHIP_FAILED: 'Domain ownership verification failed for: {{domain}}',
|
|
227
|
-
|
|
228
|
-
|
|
229
|
+
APIGW_ENSURING_CNAME: 'Ensuring CNAME record exists for domain: {{domain}}',
|
|
230
|
+
APIGW_PUBLIC_DNS_CHECKING: 'Checking public DNS resolution for: {{domain}}',
|
|
231
|
+
APIGW_PUBLIC_DNS_CHECK_ATTEMPT: 'Public DNS resolution check (attempt {{attempt}}/{{max}})...',
|
|
232
|
+
APIGW_PUBLIC_DNS_RESOLVED: 'Public DNS resolution confirmed for: {{domain}}',
|
|
233
|
+
APIGW_PUBLIC_DNS_TIMEOUT: 'Public DNS resolution could not be verified for {{domain}}. Proceeding anyway...',
|
|
234
|
+
APIGW_TXT_FALLBACK: 'CNAME verification insufficient for {{domain}}, adding TXT verification record as fallback...',
|
|
235
|
+
APIGW_TXT_ADDING_RECORD: 'Adding TXT verification record: RR={{rr}}, Value={{value}}',
|
|
236
|
+
APIGW_TXT_RECORD_ALREADY_EXISTS: 'TXT verification record already exists: {{rr}}',
|
|
237
|
+
APIGW_TXT_ADD_FAILED: 'Failed to add TXT verification record: {{error}}',
|
|
238
|
+
APIGW_DOMAIN_BIND_RETRY: 'Retrying domain binding (attempt {{attempt}}/{{max}}, waiting for DNS propagation)...',
|
|
239
|
+
APIGW_DOMAIN_BIND_RETRY_FAILED: 'Domain binding retry {{attempt}} failed: {{error}}',
|
|
229
240
|
APIGW_DOMAIN_BOUND_AFTER_VERIFICATION: 'Successfully bound domain after verification: {{domain}}',
|
|
230
|
-
APIGW_AUTO_VERIFICATION_FAILED: 'Automatic verification failed: {{error}}',
|
|
231
|
-
APIGW_NO_VERIFICATION_TOKEN: 'Could not extract verification token from error response',
|
|
232
|
-
APIGW_MANUAL_VERIFICATION_REQUIRED: 'Please manually verify domain ownership in Aliyun console',
|
|
233
241
|
APIGW_VERIFICATION_HEADER: 'Domain Ownership Verification Required',
|
|
234
242
|
APIGW_VERIFICATION_DOMAIN: 'Domain: {{domain}}',
|
|
235
243
|
APIGW_VERIFICATION_INSTRUCTIONS: 'To verify domain ownership, add ONE of the following DNS records:',
|
package/dist/src/lang/zh-CN.js
CHANGED
|
@@ -176,6 +176,33 @@ exports.zhCN = {
|
|
|
176
176
|
PARTIAL_FAILURE_NEXT_STEPS: '后续步骤: 1) 查看上面的错误, 2) 修复配置问题, 3) 再次运行 deploy 继续。',
|
|
177
177
|
FAILED_TO_EXECUTE_ACTION: '执行 {{action}} 失败: {{logicalId}}: {{error}}',
|
|
178
178
|
STATE_PERSISTED_AFTER_OPERATION: '{{action}} {{resourceId}} 后状态已持久化',
|
|
179
|
+
// Lock messages
|
|
180
|
+
ACQUIRING_LOCK: '正在获取状态锁...',
|
|
181
|
+
LOCK_ACQUIRED: '锁已获取',
|
|
182
|
+
LOCK_RELEASED: '✓ 锁已释放',
|
|
183
|
+
LOCK_WAITING: '状态被 {{user}} 锁定({{timeAgo}})。等待获取锁...(第 {{attempt}} 次尝试)',
|
|
184
|
+
LOCK_AUTO_RELEASED_DEAD_PROCESS: '自动释放已终止进程持有的过期锁(PID {{processId}},主机 {{hostname}})。锁由 {{user}} 于 {{acquiredAt}} 获取。',
|
|
185
|
+
FAILED_TO_RELEASE_LOCK: '释放锁失败',
|
|
186
|
+
NO_LOCK_FOUND: '未找到锁',
|
|
187
|
+
LOCK_ID_MISMATCH: '锁 ID 不匹配。当前锁 ID 为 {{actualId}},但您提供了 {{providedId}}',
|
|
188
|
+
CURRENT_LOCK_INFO: '当前锁信息:',
|
|
189
|
+
FORCE_UNLOCK_WARNING: '\n⚠️ 警告: 强制解锁可能会导致状态损坏,如果另一个操作仍在运行!',
|
|
190
|
+
FORCE_UNLOCK_CONFIRM: '您确定吗?(yes/no): ',
|
|
191
|
+
FORCE_UNLOCK_CANCELLED: '强制解锁已取消',
|
|
192
|
+
PLAN_COMMAND_NOT_SUPPORTED: '此提供商不支持 Plan 命令',
|
|
193
|
+
// Lock info formatting
|
|
194
|
+
LOCK_INFO_HEADER: '锁信息:',
|
|
195
|
+
LOCK_INFO_ID: ' ID: {{id}}',
|
|
196
|
+
LOCK_INFO_HELD_BY: ' 持有者: {{user}}',
|
|
197
|
+
LOCK_INFO_PROCESS: ' 进程: si {{operation}} (PID {{processId}})',
|
|
198
|
+
LOCK_INFO_HOST: ' 主机: {{hostname}}',
|
|
199
|
+
LOCK_INFO_ACQUIRED: ' 获取时间: {{acquiredAt}} ({{timeAgo}})',
|
|
200
|
+
LOCK_INFO_OPERATION: ' 操作: {{operation}}',
|
|
201
|
+
LOCK_TIME_AGO_LESS_THAN_MINUTE: '不到一分钟前',
|
|
202
|
+
LOCK_TIME_AGO_ONE_MINUTE: '1 分钟前',
|
|
203
|
+
LOCK_TIME_AGO_MINUTES: '{{minutes}} 分钟前',
|
|
204
|
+
LOCK_TIME_AGO_ONE_HOUR: '1 小时前',
|
|
205
|
+
LOCK_TIME_AGO_HOURS: '{{hours}} 小时前',
|
|
179
206
|
// API Gateway messages
|
|
180
207
|
APIGW_GROUP_FOUND_REUSING: '找到现有 API 分组: {{groupName}},将复用它',
|
|
181
208
|
APIGW_DOMAIN_BINDING_FAILED: '绑定自定义域名失败: {{error}}',
|
|
@@ -199,12 +226,18 @@ exports.zhCN = {
|
|
|
199
226
|
APIGW_BINDING_DOMAIN: '绑定自定义域名: {{domain}}',
|
|
200
227
|
APIGW_DOMAIN_BOUND_SUCCESS: '成功绑定域名: {{domain}}',
|
|
201
228
|
APIGW_DOMAIN_OWNERSHIP_FAILED: '域名所有权验证失败: {{domain}}',
|
|
202
|
-
|
|
203
|
-
|
|
229
|
+
APIGW_ENSURING_CNAME: '确保域名 CNAME 记录存在: {{domain}}',
|
|
230
|
+
APIGW_PUBLIC_DNS_CHECKING: '检查公共 DNS 解析: {{domain}}',
|
|
231
|
+
APIGW_PUBLIC_DNS_CHECK_ATTEMPT: '公共 DNS 解析检查(第 {{attempt}}/{{max}} 次尝试)...',
|
|
232
|
+
APIGW_PUBLIC_DNS_RESOLVED: '已确认公共 DNS 解析: {{domain}}',
|
|
233
|
+
APIGW_PUBLIC_DNS_TIMEOUT: '无法验证 {{domain}} 的公共 DNS 解析。继续执行...',
|
|
234
|
+
APIGW_TXT_FALLBACK: 'CNAME 验证不足以绑定 {{domain}},添加 TXT 验证记录作为备选...',
|
|
235
|
+
APIGW_TXT_ADDING_RECORD: '添加 TXT 验证记录: RR={{rr}}, 值={{value}}',
|
|
236
|
+
APIGW_TXT_RECORD_ALREADY_EXISTS: 'TXT 验证记录已存在: {{rr}}',
|
|
237
|
+
APIGW_TXT_ADD_FAILED: '添加 TXT 验证记录失败: {{error}}',
|
|
238
|
+
APIGW_DOMAIN_BIND_RETRY: '重试域名绑定(第 {{attempt}}/{{max}} 次尝试,等待 DNS 传播)...',
|
|
239
|
+
APIGW_DOMAIN_BIND_RETRY_FAILED: '域名绑定第 {{attempt}} 次重试失败: {{error}}',
|
|
204
240
|
APIGW_DOMAIN_BOUND_AFTER_VERIFICATION: '验证后成功绑定域名: {{domain}}',
|
|
205
|
-
APIGW_AUTO_VERIFICATION_FAILED: '自动验证失败: {{error}}',
|
|
206
|
-
APIGW_NO_VERIFICATION_TOKEN: '无法从错误响应中提取验证令牌',
|
|
207
|
-
APIGW_MANUAL_VERIFICATION_REQUIRED: '请在阿里云控制台手动验证域名所有权',
|
|
208
241
|
APIGW_VERIFICATION_HEADER: '需要域名所有权验证',
|
|
209
242
|
APIGW_VERIFICATION_DOMAIN: '域名: {{domain}}',
|
|
210
243
|
APIGW_VERIFICATION_INSTRUCTIONS: '要验证域名所有权,请添加以下 DNS 记录之一:',
|
|
@@ -27,7 +27,7 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
|
|
|
27
27
|
const eventItems = await Promise.all(events.map(async (event) => {
|
|
28
28
|
const logicalId = `events.${event.key}`;
|
|
29
29
|
const currentState = (0, stateManager_1.getResource)(state, logicalId);
|
|
30
|
-
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
|
|
30
|
+
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
|
|
31
31
|
const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
|
|
32
32
|
const client = (0, aliyunClient_1.createAliyunClient)(context);
|
|
33
33
|
// Build desired definition including triggers
|
|
@@ -59,7 +59,7 @@ const buildApigwDeploymentInstance = (groupId, apiId, stageName, stage) => {
|
|
|
59
59
|
const createApigwResource = async (context, event, serviceName, roleArn, state) => {
|
|
60
60
|
const logicalId = `events.${event.key}`;
|
|
61
61
|
const client = (0, aliyunClient_1.createAliyunClient)(context);
|
|
62
|
-
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
|
|
62
|
+
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
|
|
63
63
|
let groupId;
|
|
64
64
|
try {
|
|
65
65
|
const existingGroup = await client.apigw.findApiGroupByName(groupConfig.groupName);
|
|
@@ -107,7 +107,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
|
|
|
107
107
|
state = (0, stateManager_1.setResource)(state, logicalId, partialResourceState);
|
|
108
108
|
// Create APIs and deployments for each trigger
|
|
109
109
|
for (const trigger of event.triggers) {
|
|
110
|
-
const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, roleArn);
|
|
110
|
+
const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
|
|
111
111
|
const apiId = await client.apigw.createApi(apiConfig);
|
|
112
112
|
// Get API info for state
|
|
113
113
|
const apiInfo = await client.apigw.getApi(groupId, apiId);
|
|
@@ -209,7 +209,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
|
|
|
209
209
|
return (0, exports.createApigwResource)(context, event, serviceName, roleArn, state);
|
|
210
210
|
}
|
|
211
211
|
const groupId = groupInstance.id;
|
|
212
|
-
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
|
|
212
|
+
const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
|
|
213
213
|
await client.apigw.updateApiGroup(groupId, groupConfig);
|
|
214
214
|
const groupInfo = await client.apigw.getApiGroup(groupId);
|
|
215
215
|
if (!groupInfo) {
|
|
@@ -221,7 +221,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
|
|
|
221
221
|
const existingApis = existingInstances.filter((i) => i.type === 'ALIYUN_APIGW_API');
|
|
222
222
|
const neededApiKeys = new Set();
|
|
223
223
|
for (const trigger of event.triggers) {
|
|
224
|
-
const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, roleArn);
|
|
224
|
+
const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
|
|
225
225
|
const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
|
|
226
226
|
neededApiKeys.add(apiKey);
|
|
227
227
|
const existingApi = existingApis.find((a) => {
|
|
@@ -252,7 +252,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
|
|
|
252
252
|
const apiInfo = await client.apigw.getApi(groupId, existingApi.id);
|
|
253
253
|
if (apiInfo) {
|
|
254
254
|
const isNeeded = event.triggers.some((t) => {
|
|
255
|
-
const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, roleArn).apiName;
|
|
255
|
+
const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArn).apiName;
|
|
256
256
|
return apiInfo.apiName === expectedName;
|
|
257
257
|
});
|
|
258
258
|
if (!isNeeded) {
|
|
@@ -5,9 +5,9 @@ const common_1 = require("../../common");
|
|
|
5
5
|
/**
|
|
6
6
|
* Convert EventDomain to API Gateway group config
|
|
7
7
|
*/
|
|
8
|
-
const eventToApigwGroupConfig = (event, serviceName) => {
|
|
8
|
+
const eventToApigwGroupConfig = (event, serviceName, stage) => {
|
|
9
9
|
return {
|
|
10
|
-
groupName: `${serviceName}-agw-group`.replace(/_/g, '-'),
|
|
10
|
+
groupName: `${serviceName}-${stage}-agw-group`.replace(/_/g, '-'),
|
|
11
11
|
description: `API Gateway group for ${serviceName}`,
|
|
12
12
|
};
|
|
13
13
|
};
|
|
@@ -51,7 +51,7 @@ const resolveFunctionReference = (backendRef) => {
|
|
|
51
51
|
/**
|
|
52
52
|
* Convert EventDomain trigger to API Gateway API config
|
|
53
53
|
*/
|
|
54
|
-
const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, roleArn) => {
|
|
54
|
+
const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, stage, roleArn) => {
|
|
55
55
|
const method = trigger.method;
|
|
56
56
|
const path = trigger.path;
|
|
57
57
|
const backend = trigger.backend;
|
|
@@ -59,7 +59,7 @@ const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, r
|
|
|
59
59
|
const apiKey = (0, exports.generateApiKey)(method, path);
|
|
60
60
|
return {
|
|
61
61
|
groupId,
|
|
62
|
-
apiName: `${event.name}-agw-api-${apiKey}`.replace(/_/g, '-'),
|
|
62
|
+
apiName: `${event.name}-${stage}-agw-api-${apiKey}`.replace(/_/g, '-'),
|
|
63
63
|
visibility: 'PRIVATE',
|
|
64
64
|
authType: 'ANONYMOUS',
|
|
65
65
|
requestConfig: {
|
|
@@ -1,11 +1,57 @@
|
|
|
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");
|
|
6
12
|
const types_1 = require("../../types");
|
|
7
13
|
const fc3Types_1 = require("./fc3Types");
|
|
8
14
|
const logger_1 = require("../../common/logger");
|
|
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
|
+
};
|
|
9
55
|
const buildFc3InstanceFromProvider = (info, sid) => {
|
|
10
56
|
return {
|
|
11
57
|
type: 'ALIYUN_FC3_FUNCTION',
|
|
@@ -98,8 +144,8 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
|
|
|
98
144
|
}
|
|
99
145
|
}
|
|
100
146
|
else {
|
|
101
|
-
const projectName = `${serviceName}-sls`;
|
|
102
|
-
const logstoreName = `${serviceName}-sls-logstore`;
|
|
147
|
+
const projectName = `${serviceName}-${context.stage}-sls`;
|
|
148
|
+
const logstoreName = `${serviceName}-${context.stage}-sls-logstore`;
|
|
103
149
|
logger_1.logger.info(`Creating SLS project: ${projectName}`);
|
|
104
150
|
const project = await client.sls.createProject(projectName);
|
|
105
151
|
instances.push({ type: 'ALIYUN_SLS_PROJECT', id: projectName, attributes: { ...project } });
|
|
@@ -123,7 +169,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
|
|
|
123
169
|
logConfig = { project: projectName, logstore: logstoreName };
|
|
124
170
|
}
|
|
125
171
|
}
|
|
126
|
-
const roleName = `${serviceName}-fc-role`;
|
|
172
|
+
const roleName = `${serviceName}-${context.stage}-fc-role`;
|
|
127
173
|
if (hasRamRole) {
|
|
128
174
|
const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
|
|
129
175
|
if (ramRoleInstance) {
|
|
@@ -131,14 +177,19 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
|
|
|
131
177
|
}
|
|
132
178
|
}
|
|
133
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'];
|
|
134
184
|
logger_1.logger.info(`Creating RAM role: ${roleName}`);
|
|
135
|
-
const ramRole = await client.ram.createRole(roleName);
|
|
185
|
+
const ramRole = await client.ram.createRole(roleName, trustedServices);
|
|
136
186
|
instances.push({
|
|
137
187
|
type: 'ALIYUN_RAM_ROLE',
|
|
138
188
|
id: roleName,
|
|
139
189
|
roleArn: ramRole.arn,
|
|
140
190
|
attributes: { ...ramRole },
|
|
141
191
|
});
|
|
192
|
+
await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
|
|
142
193
|
}
|
|
143
194
|
const ramRoleInstance = instances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
|
|
144
195
|
const role = {
|
|
@@ -190,7 +241,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
|
|
|
190
241
|
const mountPoints = [];
|
|
191
242
|
for (const nasItem of fn.storage.nas) {
|
|
192
243
|
const mountPath = nasItem.mount_path.replace(/\//g, '-').replace(/^-/, '');
|
|
193
|
-
const accessGroupName = `${fn.name}-nas-access-${mountPath}`;
|
|
244
|
+
const accessGroupName = `${fn.name}-${context.stage}-nas-access-${mountPath}`;
|
|
194
245
|
logger_1.logger.info(`Creating NAS access group: ${accessGroupName}`);
|
|
195
246
|
const accessGroup = await client.nas.createAccessGroup(accessGroupName);
|
|
196
247
|
instances.push({
|
|
@@ -353,11 +404,38 @@ const createResource = async (context, fn, state) => {
|
|
|
353
404
|
};
|
|
354
405
|
const stateAfterDependents = (0, common_1.setResource)(state, logicalId, taintedResourceState);
|
|
355
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
|
+
}
|
|
356
412
|
try {
|
|
357
|
-
|
|
413
|
+
if (!existingFunctionOnRetry) {
|
|
414
|
+
const ossCode = await ensureOssCodeUpload(client, codePath, context.region, fn.name);
|
|
415
|
+
await client.fc3.createFunction(config, codePath, ossCode);
|
|
416
|
+
}
|
|
358
417
|
}
|
|
359
418
|
catch (error) {
|
|
360
|
-
|
|
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
|
+
}
|
|
361
439
|
}
|
|
362
440
|
const functionInfo = await client.fc3.getFunction(fn.name);
|
|
363
441
|
if (!functionInfo) {
|
|
@@ -491,7 +569,8 @@ const updateResource = async (context, fn, state) => {
|
|
|
491
569
|
const codePath = fn.code.path;
|
|
492
570
|
const client = (0, aliyunClient_1.createAliyunClient)(context);
|
|
493
571
|
await client.fc3.updateFunctionConfiguration(config);
|
|
494
|
-
await client.
|
|
572
|
+
const ossCode = await ensureOssCodeUpload(client, codePath, context.region, fn.name);
|
|
573
|
+
await client.fc3.updateFunctionCode(fn.name, codePath, ossCode);
|
|
495
574
|
const functionInfo = await client.fc3.getFunction(fn.name);
|
|
496
575
|
if (!functionInfo) {
|
|
497
576
|
throw new Error(`Failed to refresh state for function: ${fn.name}`);
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.functionSchema = void 0;
|
|
4
4
|
const templateRefSchema_1 = require("./templateRefSchema");
|
|
5
|
+
const securityGroupRulePattern = '^[A-Za-z]+:\\d{1,3}(?:\\.\\d{1,3}){3}\\/\\d{1,2}:(?:ALL|\\d{1,5}(?:\\/\\d{1,5})?)$';
|
|
5
6
|
exports.functionSchema = {
|
|
6
7
|
$id: 'https://serverlessinsight.geekfun.club/schemas/functionschema.json',
|
|
7
8
|
type: 'object',
|
|
@@ -87,8 +88,14 @@ exports.functionSchema = {
|
|
|
87
88
|
type: 'object',
|
|
88
89
|
properties: {
|
|
89
90
|
name: { type: 'string' },
|
|
90
|
-
ingress: {
|
|
91
|
-
|
|
91
|
+
ingress: {
|
|
92
|
+
type: 'array',
|
|
93
|
+
items: { type: 'string', pattern: securityGroupRulePattern },
|
|
94
|
+
},
|
|
95
|
+
egress: {
|
|
96
|
+
type: 'array',
|
|
97
|
+
items: { type: 'string', pattern: securityGroupRulePattern },
|
|
98
|
+
},
|
|
92
99
|
},
|
|
93
100
|
required: ['name', 'ingress'],
|
|
94
101
|
additionalProperties: false,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geek-fun/serverlessinsight",
|
|
3
|
-
"version": "0.5.
|
|
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",
|