Skip to content

Commit 7428739

Browse files
committed
feat: implement calcValue to get real values of references
Signed-off-by: seven <[email protected]>
1 parent 0c87a82 commit 7428739

File tree

11 files changed

+159
-76
lines changed

11 files changed

+159
-76
lines changed

src/common/iacHelper.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as ros from '@alicloud/ros-cdk-core';
44
import { Context } from '../types';
55
import * as ossDeployment from '@alicloud/ros-cdk-ossdeployment';
66
import crypto from 'node:crypto';
7+
import { get } from 'lodash';
78

89
export const resolveCode = (location: string): string => {
910
const filePath = path.resolve(process.cwd(), location);
@@ -40,7 +41,7 @@ const evalCtx = (value: string, ctx: Context): string => {
4041
return containsStage ? value.replace(/\$\{ctx.stage}/g, ctx.stage) : value;
4142
};
4243

43-
export const replaceReference = <T>(value: T, ctx: Context): T => {
44+
export const calcRefers = <T>(value: T, ctx: Context): T => {
4445
if (typeof value === 'string') {
4546
const matchVar = value.match(/^\$\{vars\.(\w+)}$/);
4647
const containsVar = value.match(/\$\{vars\.(\w+)}/);
@@ -76,14 +77,42 @@ export const replaceReference = <T>(value: T, ctx: Context): T => {
7677
}
7778

7879
if (Array.isArray(value)) {
79-
return value.map((item) => replaceReference(item, ctx)) as T;
80+
return value.map((item) => calcRefers(item, ctx)) as T;
8081
}
8182

8283
if (typeof value === 'object' && value !== null) {
8384
return Object.fromEntries(
84-
Object.entries(value).map(([key, val]) => [key, replaceReference(val, ctx)]),
85+
Object.entries(value).map(([key, val]) => [key, calcRefers(val, ctx)]),
8586
) as T;
8687
}
8788

8889
return value;
8990
};
91+
92+
const getParam = (key: string, records?: Array<{ key: string; value: string }>) => {
93+
return records?.find((param) => param.key === key)?.value as string;
94+
};
95+
96+
export const realValue = <T>(rawValue: string, ctx: Context): T => {
97+
const containsStage = rawValue.match(/\$\{ctx.stage}/);
98+
const containsVar = rawValue.match(/\$\{vars.\w+}/);
99+
const containsMap = rawValue.match(/\$\{stages\.(\w+)}/);
100+
101+
let value = rawValue;
102+
103+
if (containsStage?.length) {
104+
value = rawValue.replace(/\$\{ctx.stage}/g, ctx.stage);
105+
}
106+
107+
if (containsVar?.length) {
108+
value = value.replace(/\$\{vars\.(\w+)}/g, (_, key) => getParam(key, ctx.parameters));
109+
}
110+
111+
if (containsMap?.length) {
112+
value = value.replace(/\$\{stages\.(\w+)}/g, (_, key) =>
113+
getParam(key, get(ctx.stages, `${ctx.stage}`)),
114+
);
115+
}
116+
117+
return value as T;
118+
};

src/stack/rosStack/bucket.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
encodeBase64ForRosId,
66
getAssets,
77
OSS_DEPLOYMENT_TIMEOUT,
8-
replaceReference,
8+
calcRefers,
99
splitDomain,
1010
} from '../../common';
1111
import * as ossDeployment from '@alicloud/ros-cdk-ossdeployment';
@@ -58,27 +58,27 @@ export const resolveBuckets = (
5858
}
5959

6060
buckets.forEach((bucket) => {
61-
const ossBucket = new oss.Bucket(scope, replaceReference(bucket.key, context), {
62-
bucketName: replaceReference(bucket.name, context),
61+
const ossBucket = new oss.Bucket(scope, calcRefers(bucket.key, context), {
62+
bucketName: calcRefers(bucket.name, context),
6363
accessControl: aclMap.get(
64-
replaceReference(bucket.security?.acl, context) ?? ('' as BucketAccessEnum),
64+
calcRefers(bucket.security?.acl, context) ?? ('' as BucketAccessEnum),
6565
),
6666
websiteConfigurationV2: bucket.website
6767
? {
6868
indexDocument: {
6969
type: '0',
70-
suffix: replaceReference(bucket.website.index, context),
70+
suffix: calcRefers(bucket.website.index, context),
7171
supportSubDir: 'true',
7272
},
7373
errorDocument: {
74-
httpStatus: `${replaceReference(bucket.website.error_code, context)}`,
75-
key: replaceReference(bucket.website.error_page, context),
74+
httpStatus: `${calcRefers(bucket.website.error_code, context)}`,
75+
key: calcRefers(bucket.website.error_page, context),
7676
},
7777
}
7878
: undefined,
7979
});
8080
if (bucket.website?.code) {
81-
const filePath = path.resolve(process.cwd(), replaceReference(bucket.website.code, context));
81+
const filePath = path.resolve(process.cwd(), calcRefers(bucket.website.code, context));
8282
new ossDeployment.BucketDeployment(
8383
scope,
8484
`si_auto_${bucket.key}_bucket_code_deployment`,
@@ -100,7 +100,7 @@ export const resolveBuckets = (
100100
`${bucket.key}_custom_domain_${encodeBase64ForRosId(bucket.website.domain)}`,
101101
{
102102
bucketName: ossBucket.attrName,
103-
domainName: replaceReference(bucket.website.domain, context),
103+
domainName: calcRefers(bucket.website.domain, context),
104104
},
105105
);
106106

src/stack/rosStack/database.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as ros from '@alicloud/ros-cdk-core';
22
import * as rds from '@alicloud/ros-cdk-rds';
3-
import { replaceReference } from '../../common';
3+
import { calcRefers } from '../../common';
44
import { Context, DatabaseDomain, DatabaseEnum, DatabaseVersionEnum } from '../../types';
55
import { isEmpty } from 'lodash';
66
import * as esServerless from '@alicloud/ros-cdk-elasticsearchserverless';
@@ -208,14 +208,14 @@ export const resolveDatabases = (
208208
if ([DatabaseEnum.ELASTICSEARCH_SERVERLESS].includes(db.type)) {
209209
new esServerless.App(
210210
scope,
211-
replaceReference(db.key, context),
211+
calcRefers(db.key, context),
212212
{
213-
appName: replaceReference(db.name, context),
213+
appName: calcRefers(db.name, context),
214214
appVersion: version,
215215
authentication: {
216216
basicAuth: [
217217
{
218-
password: replaceReference(db.security.basicAuth.password, context),
218+
password: calcRefers(db.security.basicAuth.password, context),
219219
},
220220
],
221221
},
@@ -249,7 +249,7 @@ export const resolveDatabases = (
249249
) {
250250
new rds.DBInstance(
251251
scope,
252-
replaceReference(db.key, context),
252+
calcRefers(db.key, context),
253253
{
254254
engine: engine as string,
255255
/**
@@ -259,7 +259,7 @@ export const resolveDatabases = (
259259
* PostgreSQL:14.0、15.0、16.0 - PGSQL_HA_14, PGSQL_14 PGSQL_HA_15, PGSQL_15, PGSQL_HA_16,PGSQL_16
260260
*/
261261
engineVersion: version as string,
262-
dbInstanceStorage: replaceReference(db.storage.min, context),
262+
dbInstanceStorage: calcRefers(db.storage.min, context),
263263
/** Serverless 实例
264264
* serverless_basic:Serverless 基础系列。(仅适用 MySQL 和 PostgreSQL)
265265
* serverless_standard:Serverless 高可用系列。(仅适用 MySQL 和 PostgreSQL)
@@ -297,11 +297,11 @@ export const resolveDatabases = (
297297
*/
298298
serverlessConfig: {
299299
// @TODO db.cu.min should get parameter value when it refer to a parameter
300-
minCapacity: replaceReference(
300+
minCapacity: calcRefers(
301301
db.cu.min === 0 ? quota!.minCapacity : db.cu.min + quota!.minCapacity,
302302
context,
303303
),
304-
maxCapacity: replaceReference(
304+
maxCapacity: calcRefers(
305305
db.cu.max + quota!.minCapacity <= quota!.maxCapacity
306306
? db.cu.max + quota!.minCapacity
307307
: quota!.maxCapacity,
@@ -310,11 +310,11 @@ export const resolveDatabases = (
310310
autoPause: db.cu.min === 0,
311311
switchForce: false,
312312
},
313-
masterUsername: replaceReference(db.security.basicAuth.username, context),
314-
masterUserPassword: replaceReference(db.security.basicAuth.password, context),
313+
masterUsername: calcRefers(db.security.basicAuth.username, context),
314+
masterUserPassword: calcRefers(db.security.basicAuth.password, context),
315315
masterUserType: 'Super',
316316
multiAz: quota!.ha,
317-
securityIpList: replaceReference(db.network.ingressRules.join(','), context),
317+
securityIpList: calcRefers(db.network.ingressRules.join(','), context),
318318
connectionStringType: db.network.type === 'PRIVATE' ? 'Inner' : 'Public',
319319
dbInstanceNetType: db.network.type === 'PRIVATE' ? 'Intranet' : 'Internet',
320320
},

src/stack/rosStack/event.ts

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as ros from '@alicloud/ros-cdk-core';
22
import { Context, EventDomain, EventTypes, ServerlessIac } from '../../types';
33
import * as ram from '@alicloud/ros-cdk-ram';
4-
import { encodeBase64ForRosId, replaceReference, splitDomain } from '../../common';
4+
import { encodeBase64ForRosId, calcRefers, splitDomain } from '../../common';
55
import * as agw from '@alicloud/ros-cdk-apigateway';
66
import { isEmpty } from 'lodash';
77
import * as dns from '@alicloud/ros-cdk-dns';
@@ -22,10 +22,10 @@ export const resolveEvents = (
2222
apiGateway.forEach((event) => {
2323
const gatewayAccessRole = new ram.RosRole(
2424
scope,
25-
replaceReference(`${event.key}_role`, context),
25+
calcRefers(`${event.key}_role`, context),
2626
{
27-
roleName: replaceReference(`${service}-${event.name}-agw-access-role`, context),
28-
description: replaceReference(`${service} role`, context),
27+
roleName: calcRefers(`${service}-${event.name}-agw-access-role`, context),
28+
description: calcRefers(`${service} role`, context),
2929
assumeRolePolicyDocument: {
3030
version: '1',
3131
statement: [
@@ -40,7 +40,7 @@ export const resolveEvents = (
4040
},
4141
policies: [
4242
{
43-
policyName: replaceReference(`${service}-${event.name}-policy`, context),
43+
policyName: calcRefers(`${service}-${event.name}-policy`, context),
4444
policyDocument: {
4545
version: '1',
4646
statement: [
@@ -60,10 +60,10 @@ export const resolveEvents = (
6060

6161
const apiGatewayGroup = new agw.RosGroup(
6262
scope,
63-
replaceReference(`${service}_apigroup`, context),
63+
calcRefers(`${service}_apigroup`, context),
6464
{
65-
groupName: replaceReference(`${service}_apigroup`, context),
66-
tags: replaceReference(tags, context),
65+
groupName: calcRefers(`${service}_apigroup`, context),
66+
tags: calcRefers(tags, context),
6767
passthroughHeaders: 'host',
6868
},
6969
true,
@@ -96,37 +96,35 @@ export const resolveEvents = (
9696
}
9797

9898
event.triggers.forEach((trigger) => {
99-
const key = encodeBase64ForRosId(
100-
replaceReference(`${trigger.method}_${trigger.path}`, context),
101-
);
99+
const key = encodeBase64ForRosId(calcRefers(`${trigger.method}_${trigger.path}`, context));
102100

103101
const api = new agw.RosApi(
104102
scope,
105103
`${event.key}_api_${key}`,
106104
{
107-
apiName: replaceReference(`${event.name}_api_${key}`, context),
105+
apiName: calcRefers(`${event.name}_api_${key}`, context),
108106
groupId: apiGatewayGroup.attrGroupId,
109107
visibility: 'PRIVATE',
110108
authType: 'ANONYMOUS',
111109
requestConfig: {
112110
requestProtocol: 'HTTP',
113-
requestHttpMethod: replaceReference(trigger.method, context),
114-
requestPath: replaceReference(trigger.path, context),
111+
requestHttpMethod: calcRefers(trigger.method, context),
112+
requestPath: calcRefers(trigger.path, context),
115113
requestMode: 'PASSTHROUGH',
116114
},
117115
serviceConfig: {
118116
serviceProtocol: 'FunctionCompute',
119117
functionComputeConfig: {
120118
fcRegionId: context.region,
121-
functionName: replaceReference(trigger.backend, context),
119+
functionName: calcRefers(trigger.backend, context),
122120
roleArn: gatewayAccessRole.attrArn,
123121
fcVersion: '3.0',
124-
method: replaceReference(trigger.method, context),
122+
method: calcRefers(trigger.method, context),
125123
},
126124
},
127125
resultSample: 'ServerlessInsight resultSample',
128126
resultType: 'PASSTHROUGH',
129-
tags: replaceReference(tags, context),
127+
tags: calcRefers(tags, context),
130128
},
131129
true,
132130
);

src/stack/rosStack/function.ts

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
getFileSource,
1212
OSS_DEPLOYMENT_TIMEOUT,
1313
readCodeSize,
14-
replaceReference,
14+
calcRefers,
1515
resolveCode,
1616
} from '../../common';
1717
import * as fc from '@alicloud/ros-cdk-fc3';
@@ -92,7 +92,7 @@ export const resolveFunctions = (
9292
const slsService = new sls.Project(
9393
scope,
9494
`${service}_sls`,
95-
{ name: `${service}-sls`, tags: replaceReference(tags, context) },
95+
{ name: `${service}-sls`, tags: calcRefers(tags, context) },
9696
true,
9797
);
9898

@@ -128,7 +128,7 @@ export const resolveFunctions = (
128128
const fileSources = functions
129129
?.filter(({ code }) => code?.path && readCodeSize(code.path) > CODE_ZIP_SIZE_LIMIT)
130130
.map(({ code, name }) => {
131-
const fcName = replaceReference(name, context);
131+
const fcName = calcRefers(name, context);
132132

133133
return { fcName, ...getFileSource(fcName, code!.path) };
134134
});
@@ -185,15 +185,14 @@ export const resolveFunctions = (
185185
if (storeInBucket) {
186186
code = {
187187
ossBucketName: destinationBucketName,
188-
ossObjectName: fileSources?.find(
189-
({ fcName }) => fcName === replaceReference(fnc.name, context),
190-
)?.objectKey,
188+
ossObjectName: fileSources?.find(({ fcName }) => fcName === calcRefers(fnc.name, context))
189+
?.objectKey,
191190
};
192191
}
193192
runtimeConfig = {
194193
code,
195-
handler: replaceReference(fnc.code!.handler, context),
196-
runtime: replaceReference(fnc.code!.runtime, context),
194+
handler: calcRefers(fnc.code!.handler, context),
195+
runtime: calcRefers(fnc.code!.runtime, context),
197196
};
198197
}
199198

@@ -204,8 +203,8 @@ export const resolveFunctions = (
204203
`${fnc.key}_security_group`,
205204
{
206205
securityGroupName: fnc.network.security_group.name,
207-
vpcId: replaceReference(fnc.network.vpc_id, context),
208-
tags: replaceReference(tags, context),
206+
vpcId: calcRefers(fnc.network.vpc_id, context),
207+
tags: calcRefers(tags, context),
209208
securityGroupIngress: transformSecurityRules(
210209
fnc.network.security_group.ingress,
211210
'INGRESS',
@@ -216,8 +215,8 @@ export const resolveFunctions = (
216215
);
217216

218217
vpcConfig = {
219-
vpcId: replaceReference(fnc.network.vpc_id, context),
220-
vSwitchIds: replaceReference(fnc.network.subnet_ids, context),
218+
vpcId: calcRefers(fnc.network.vpc_id, context),
219+
vSwitchIds: calcRefers(fnc.network.subnet_ids, context),
221220
securityGroupId: securityGroup.attrSecurityGroupId,
222221
};
223222
}
@@ -269,10 +268,7 @@ export const resolveFunctions = (
269268
fileSystemType,
270269
storageType,
271270
protocolType: 'NFS',
272-
tags: [
273-
...(replaceReference(tags, context) ?? []),
274-
{ key: 'function-name', value: fnc.name },
275-
],
271+
tags: [...(calcRefers(tags, context) ?? []), { key: 'function-name', value: fnc.name }],
276272
},
277273
true,
278274
);
@@ -297,12 +293,12 @@ export const resolveFunctions = (
297293
scope,
298294
fnc.key,
299295
{
300-
functionName: replaceReference(fnc.name, context),
301-
memorySize: replaceReference(fnc.memory, context),
296+
functionName: calcRefers(fnc.name, context),
297+
memorySize: calcRefers(fnc.memory, context),
302298
diskSize: fnc.storage?.disk,
303299
gpuConfig: transformGpuConfig(fnc.gpu),
304-
timeout: replaceReference(fnc.timeout, context),
305-
environmentVariables: replaceReference(fnc.environment, context),
300+
timeout: calcRefers(fnc.timeout, context),
301+
environmentVariables: calcRefers(fnc.environment, context),
306302
logConfig,
307303
vpcConfig,
308304
...runtimeConfig,

src/stack/rosStack/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as ros from '@alicloud/ros-cdk-core';
22
import { Context, ServerlessIac } from '../../types';
3-
import { replaceReference } from '../../common';
3+
import { calcRefers } from '../../common';
44
import { resolveTags } from './tag';
55
import { resolveFunctions } from './function';
66
import { resolveStages } from './stage';
@@ -15,12 +15,12 @@ export class RosStack extends ros.Stack {
1515
private readonly service: string;
1616

1717
constructor(scope: ros.Construct, iac: ServerlessIac, context: Context) {
18-
super(scope, replaceReference(iac.service, context), {
18+
super(scope, calcRefers(iac.service, context), {
1919
stackName: context.stackName,
2020
tags: resolveTags(iac.tags, context),
2121
});
2222

23-
this.service = replaceReference(iac.service, context);
23+
this.service = calcRefers(iac.service, context);
2424
new ros.RosInfo(this, ros.RosInfo.description, `${this.service} stack`);
2525

2626
// Define Parameters

0 commit comments

Comments
 (0)