/
Stack.ts
293 lines (266 loc) · 8.74 KB
/
Stack.ts
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
import fs from "fs";
import url from "url";
import * as path from "path";
import { Construct, IConstruct } from "constructs";
import {
StackProps as CDKStackProps,
Stack as CDKStack,
CfnOutputProps,
CfnOutput,
Duration as CDKDuration,
DefaultStackSynthesizer,
DefaultStackSynthesizerProps,
} from "aws-cdk-lib/core";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { useProject } from "../project.js";
import { FunctionProps, Function as Fn } from "./Function.js";
import type { App } from "./App.js";
import { isConstruct } from "./Construct.js";
import { Permissions } from "./util/permission.js";
import { BindingResource } from "./util/binding.js";
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
export type StackProps = CDKStackProps;
/**
* The Stack construct extends cdk.Stack. It automatically prefixes the stack names with the stage and app name to ensure that they can be deployed to multiple regions in the same AWS account. It also ensure that the stack uses the same AWS profile and region as the app. They're defined using functions that return resources that can be imported by other stacks.
*
* @example
*
* ```js
* import { StackContext } from "sst/constructs";
*
* export function MyStack({ stack }: StackContext) {
* // Define your stack
* }
* ```
*/
export class Stack extends CDKStack {
/**
* The current stage of the stack.
*/
public readonly stage: string;
/**
* @internal
*/
public readonly defaultFunctionProps: FunctionProps[];
/**
* Create a custom resource handler per stack. This handler will
* be used by all the custom resources in the stack.
* @internal
*/
public readonly customResourceHandler: lambda.Function;
/**
* Skip building Function/Site code when stack is not active
* ie. `sst remove` and `sst deploy PATTERN` (pattern not matched)
* @internal
*/
public readonly isActive: boolean;
constructor(scope: Construct, id: string, props?: StackProps) {
const app = scope.node.root as App;
const stackId = app.logicalPrefixedName(id);
Stack.checkForPropsIsConstruct(id, props);
Stack.checkForEnvInProps(id, props);
super(scope, stackId, {
...props,
env: {
account: app.account,
region: app.region,
},
synthesizer: props?.synthesizer || Stack.buildSynthesizer(),
});
this.stage = app.stage;
this.defaultFunctionProps = app.defaultFunctionProps.map((dfp) =>
typeof dfp === "function" ? dfp(this) : dfp
);
this.customResourceHandler = this.createCustomResourceHandler();
this.isActive =
app.mode !== "remove" &&
(!app.isActiveStack || app.isActiveStack?.(this.stackName) === true);
}
/**
* The default function props to be applied to all the Lambda functions in the stack.
*
* @example
* ```js
* stack.setDefaultFunctionProps({
* srcPath: "backend",
* runtime: "nodejs18.x",
* });
* ```
*/
public setDefaultFunctionProps(props: FunctionProps): void {
const fns = this.getAllFunctions();
if (fns.length > 0)
throw new Error(
"Default function props for the stack must be set before any functions have been added. Use 'addDefaultFunctionEnv' or 'addDefaultFunctionPermissions' instead to add more default properties."
);
this.defaultFunctionProps.push(props);
}
/**
* Adds additional default Permissions to be applied to all Lambda functions in the stack.
*
* @example
* ```js
* stack.addDefaultFunctionPermissions(["sqs", "s3"]);
* ```
*/
public addDefaultFunctionPermissions(permissions: Permissions) {
this.defaultFunctionProps.push({
permissions,
});
}
/**
* Adds additional default environment variables to be applied to all Lambda functions in the stack.
*
* @example
* ```js
* stack.addDefaultFunctionEnv({
* DYNAMO_TABLE: table.name
* });
* ```
*/
public addDefaultFunctionEnv(environment: Record<string, string>) {
this.defaultFunctionProps.push({
environment,
});
}
/**
* Binds additional resources to be applied to all Lambda functions in the stack.
*
* @example
* ```js
* app.addDefaultFunctionBinding([STRIPE_KEY, bucket]);
* ```
*/
public addDefaultFunctionBinding(bind: BindingResource[]) {
this.defaultFunctionProps.push({ bind });
}
/**
* Adds additional default layers to be applied to all Lambda functions in the stack.
*
* @example
* ```js
* stack.addDefaultFunctionLayers(["arn:aws:lambda:us-east-1:123456789012:layer:nodejs:3"]);
* ```
*/
public addDefaultFunctionLayers(layers: lambda.ILayerVersion[]) {
this.defaultFunctionProps.push({
layers,
});
}
/**
* Returns all the Function instances in this stack.
*
* @example
* ```js
* stack.getAllFunctions();
* ```
*/
public getAllFunctions() {
return this.doGetAllFunctions(this);
}
private doGetAllFunctions(construct: IConstruct) {
const results: Fn[] = [];
for (const child of construct.node.children) {
if (child instanceof Fn) results.push(child);
results.push(...this.doGetAllFunctions(child));
}
return results;
}
/**
* Add outputs to this stack
*
* @example
* ```js
* stack.addOutputs({
* TableName: table.name,
* });
* ```
*
* ```js
* stack.addOutputs({
* TableName: {
* value: table.name,
* exportName: "MyTableName",
* }
* });
* ```
*/
public addOutputs(
outputs: Record<string, string | CfnOutputProps | undefined>
): void {
Object.entries(outputs)
.filter((e): e is [string, string | CfnOutputProps] => e[1] !== undefined)
.forEach(([key, value]) => {
// Note: add "SSTStackOutput" prefix to the CfnOutput id to ensure the id
// does not thrash w/ construct ids in the stack. So users can do this:
// ```
// const table = new Table(stack, "myTable");
// stack.addOutputs({ myTable: table.name });
// ```
// And then we override the logical id so the actual output name is
// still "myTable".
const output =
typeof value === "string"
? new CfnOutput(this, `SSTStackOutput${key}`, { value })
: new CfnOutput(this, `SSTStackOutput${key}`, value);
// CloudFormation only allows alphanumeric characters in the output name.
output.overrideLogicalId(key.replace(/[^A-Za-z0-9]/g, ""));
});
}
private createCustomResourceHandler() {
const dir = path.join(__dirname, "../support/custom-resources/");
return new lambda.Function(this, "CustomResourceHandler", {
code: lambda.Code.fromAsset(dir, {
//assetHash: this.stackName + "-custom-resources-20230130",
assetHash:
this.stackName + fs.readFileSync(dir + "/index.mjs").toString(),
}),
handler: "index.handler",
runtime: lambda.Runtime.NODEJS_18_X,
timeout: CDKDuration.seconds(900),
memorySize: 1024,
});
}
private static buildSynthesizer() {
const { config } = useProject();
const props: DefaultStackSynthesizerProps = {
qualifier: config.cdk?.qualifier,
bootstrapStackVersionSsmParameter:
config.cdk?.bootstrapStackVersionSsmParameter,
fileAssetsBucketName: config.cdk?.fileAssetsBucketName,
deployRoleArn: config.cdk?.deployRoleArn,
fileAssetPublishingRoleArn: config.cdk?.fileAssetPublishingRoleArn,
imageAssetPublishingRoleArn: config.cdk?.imageAssetPublishingRoleArn,
imageAssetsRepositoryName: config.cdk?.imageAssetsRepositoryName,
cloudFormationExecutionRole: config.cdk?.cloudFormationExecutionRole,
lookupRoleArn: config.cdk?.lookupRoleArn,
};
const isEmpty = Object.values(props).every((v) => v === undefined);
if (isEmpty) return;
return new DefaultStackSynthesizer(props);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static checkForPropsIsConstruct(id: string, props?: any) {
// If a construct is passed in as stack props, let's detect it and throw a
// friendlier error.
if (props && isConstruct(props)) {
throw new Error(
`Expected an associative array as the stack props while initializing "${id}" stack. Received a construct instead.`
);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static checkForEnvInProps(id: string, props?: any) {
if (props && props.env) {
let envS = "";
try {
envS = " (" + JSON.stringify(props.env) + ")";
} catch (e) {
// Ignore
}
throw new Error(
`Do not set the "env" prop while initializing "${id}" stack${envS}. Use the "AWS_PROFILE" environment variable and "--region" CLI option instead.`
);
}
}
}