-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdk-stack.ts
More file actions
295 lines (273 loc) · 9.42 KB
/
Copy pathcdk-stack.ts
File metadata and controls
295 lines (273 loc) · 9.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs';
import * as awslogs from 'aws-cdk-lib/aws-logs';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as deployment from 'aws-cdk-lib/aws-s3-deployment';
import { buildCommon, buildFrontend } from './process/setup.js';
export interface Config extends cdk.StackProps {
bucketName: string;
appName: string;
cloudfront: {
comment: string;
};
}
interface CloudfrontCdnTemplateStackProps extends Config {
environment?: string;
endpoint?: string;
instanceName: string;
apiKey: string;
apiVersion: string;
langfuse?: {
sk: string;
pk: string;
endpoint: string;
};
anthoropicApiKey: string;
claudeModel: string;
langsmith?: {
apiKey: string;
project: string;
endpoint: string;
};
}
export class CloudfrontCdnTemplateStack extends cdk.Stack {
constructor(
scope: Construct,
id: string,
props: CloudfrontCdnTemplateStackProps,
) {
super(scope, id, props);
const {
bucketName,
appName,
environment,
cloudfront: { comment },
endpoint,
instanceName,
apiKey,
apiVersion,
langfuse,
anthoropicApiKey,
claudeModel,
langsmith,
} = props;
buildCommon();
buildFrontend();
const functionName = `${environment ? `${environment}-` : ''}llm-ts-example-api`;
new awslogs.LogGroup(this, 'ApolloLambdaFunctionLogGroup', {
logGroupName: `/aws/lambda/${functionName}`,
removalPolicy: cdk.RemovalPolicy.DESTROY,
retention: awslogs.RetentionDays.ONE_DAY,
});
const devOptions = {
// environment: {
// NODE_OPTIONS: '--enable-source-maps',
// },
// bundling: {
// sourceMap: true,
// sourceMapMode: nodejs.SourceMapMode.BOTH,
// sourcesContent: true,
// keepNames: true,
// },
applicationLogLevelV2: lambda.ApplicationLogLevel.TRACE,
};
const apiRootPath = '/api/';
const langfuseEnv = langfuse ? {
LANGFUSE_SECRET_KEY: langfuse.sk,
LANGFUSE_PUBLIC_KEY: langfuse.pk,
...(langfuse.endpoint ? {
LANGFUSE_BASEURL: langfuse.endpoint,
} : {}),
} : {};
const langsmithEnv: Record<string, string> = langsmith ? {
LANGCHAIN_TRACING_V2: 'true',
LANGCHAIN_ENDPOINT: langsmith.endpoint,
LANGCHAIN_API_KEY: langsmith.apiKey,
LANGCHAIN_PROJECT: langsmith.project,
} : {};
const fn = new nodejs.NodejsFunction(this, 'Lambda', {
runtime: lambda.Runtime.NODEJS_22_X,
architecture: lambda.Architecture.ARM_64,
entry: './lambda/index.ts',
functionName,
retryAttempts: 0,
environment: {
// ...devOptions.environment,
API_ROOT_PATH: apiRootPath,
...(endpoint ? {AZURE_OPENAI_API_ENDPOINT: endpoint} : {}),
AZURE_OPENAI_API_INSTANCE_NAME: instanceName,
AZURE_OPENAI_API_KEY: apiKey,
AZURE_OPENAI_API_VERSION: apiVersion,
ANTHROPIC_API_KEY: anthoropicApiKey,
CLAUDE_MODEL: claudeModel,
...langfuseEnv,
...langsmithEnv,
},
bundling: {
target: 'node22',
minify: true,
format: nodejs.OutputFormat.ESM,
banner: 'import { createRequire } from \'module\';const require = createRequire(import.meta.url);',
// ...devOptions.bundling,
},
memorySize: 256,
timeout: cdk.Duration.minutes(1),
role: new iam.Role(this, 'ApolloLambdaFunctionExecutionRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('AWSLambdaExecute'),
iam.ManagedPolicy.fromAwsManagedPolicyName('CloudFrontReadOnlyAccess'),
],
inlinePolicies: {
'bedrock-policy': new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel*',
'logs:PutLogEvents',
],
resources: ['*'],
}),
],
}),
},
}),
loggingFormat: lambda.LoggingFormat.JSON,
applicationLogLevelV2: devOptions.applicationLogLevelV2,
});
const s3bucket = new s3.Bucket(this, 'S3Bucket', {
bucketName,
versioned: false,
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
encryption: s3.BucketEncryption.S3_MANAGED,
});
const websiteIndexPageForwardFunction = new cloudfront.Function(this, 'WebsiteIndexPageForwardFunction', {
functionName: 'llm-ts-example-api-index-forword',
code: cloudfront.FunctionCode.fromFile({
filePath: 'function/index.js',
}),
runtime: cloudfront.FunctionRuntime.JS_2_0,
});
const functionAssociations = [
{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: websiteIndexPageForwardFunction,
},
];
const originAccessControl = new cloudfront.S3OriginAccessControl(this, 'S3OAC', {
originAccessControlName: 'OAC for S3 (llm-ts-example-api)',
signing: cloudfront.Signing.SIGV4_NO_OVERRIDE,
});
const cf = new cloudfront.Distribution(this, 'CloudFront', {
comment,
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(s3bucket, {
originAccessControl,
originAccessLevels: [cloudfront.AccessLevel.READ],
originId: 's3',
}),
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
functionAssociations,
},
additionalBehaviors: {
[`${apiRootPath}*`]: {
origin: new origins.FunctionUrlOrigin(fn.addFunctionUrl({
authType: cdk.aws_lambda.FunctionUrlAuthType.AWS_IAM,
invokeMode: cdk.aws_lambda.InvokeMode.RESPONSE_STREAM,
}),
{
originId: 'lambda',
readTimeout: cdk.Duration.minutes(1),
}),
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
responseHeadersPolicy: new cdk.aws_cloudfront.ResponseHeadersPolicy(
this,
'ResponseHeadersPolicy',
{
corsBehavior: {
accessControlAllowOrigins: [
'http://localhost:4173',
'http://localhost:5173',
],
accessControlAllowHeaders: ['*'],
accessControlAllowMethods: ['ALL'],
accessControlAllowCredentials: false,
originOverride: true,
},
},
),
},
},
httpVersion: cloudfront.HttpVersion.HTTP2_AND_3,
});
const deployRole = new iam.Role(this, 'DeployWebsiteRole', {
roleName: `${appName}-deploy-role`,
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
inlinePolicies: {
's3-policy': new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['s3:*'],
resources: [`${s3bucket.bucketArn}/`, `${s3bucket.bucketArn}/*`],
}),
],
}),
},
});
new deployment.BucketDeployment(this, 'DeployWebsite', {
sources: [deployment.Source.asset(`${process.cwd()}/../app/dist`)],
destinationBucket: s3bucket,
destinationKeyPrefix: '/',
exclude: ['.DS_Store', '*/.DS_Store'],
prune: true,
retainOnDelete: false,
role: deployRole,
});
// OAC for Lambda
const cfnOriginAccessControl =
new cdk.aws_cloudfront.CfnOriginAccessControl(
this,
'OriginAccessControl',
{
originAccessControlConfig: {
name: `OAC for Lambda Functions URL (${functionName})`,
originAccessControlOriginType: 'lambda',
signingBehavior: 'always',
signingProtocol: 'sigv4',
},
},
);
const cfnDistribution = cf.node.defaultChild as cdk.aws_cloudfront.CfnDistribution;
// Set OAC for Lambda
cfnDistribution.addPropertyOverride(
'DistributionConfig.Origins.1.OriginAccessControlId',
cfnOriginAccessControl.attrId,
);
// Add permission Lambda Function URLs
fn.addPermission('AllowCloudFrontServicePrincipalFunctionUrl', {
principal: new iam.ServicePrincipal('cloudfront.amazonaws.com'),
action: 'lambda:InvokeFunctionUrl',
sourceArn: `arn:aws:cloudfront::${cdk.Stack.of(this).account}:distribution/${cf.distributionId}`,
});
fn.addPermission('AllowCloudFrontServicePrincipal', {
principal: new iam.ServicePrincipal('cloudfront.amazonaws.com'),
action: 'lambda:InvokeFunction',
sourceArn: `arn:aws:cloudfront::${cdk.Stack.of(this).account}:distribution/${cf.distributionId}`,
});
new cdk.CfnOutput(this, 'AccessURLOutput', {
value: `https://${cf.distributionDomainName}`,
});
}
}