forked from anomalyco/sst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript.ts
More file actions
317 lines (296 loc) · 8.87 KB
/
Copy pathScript.ts
File metadata and controls
317 lines (296 loc) · 8.87 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import path from "path";
import url from "url";
import { Construct } from "constructs";
import { CustomResource, Duration } from "aws-cdk-lib/core";
import { PolicyStatement } from "aws-cdk-lib/aws-iam";
import { Code, Runtime, Function as CdkFunction } from "aws-cdk-lib/aws-lambda";
import { App } from "./App.js";
import { Stack } from "./Stack.js";
import {
Function as Fn,
FunctionProps,
FunctionDefinition,
} from "./Function.js";
import {
SSTConstruct,
SSTConstructMetadata,
getFunctionRef,
} from "./Construct.js";
import { Permissions } from "./util/permission.js";
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
export interface ScriptProps {
/**
* An object of input parameters to be passed to the script. Made available in the `event` object of the function.
*
* @example
* ```js
* import { Script } from "sst/constructs";
*
* new Script(stack, "Script", {
* onCreate: "src/script.create",
* params: {
* hello: "world",
* },
* });
* ```
*/
params?: Record<string, any>;
/**
* By default, the script runs during each deployment. If a version is provided, the script will only run when the version changes.
*
* @example
* ```js
* import { Script } from "sst/constructs";
*
* new Script(stack, "Script", {
* onCreate: "src/script.create",
* version: "v17",
* });
* ```
*/
version?: string;
defaults?: {
/**
* The default function props to be applied to all the Lambda functions in the API. The `environment`, `permissions` and `layers` properties will be merged with per route definitions if they are defined.
*
* @example
* ```js
* new Script(stack, "Api", {
* defaults: {
* function: {
* timeout: 20,
* }
* }
* });
* ```
*/
function?: FunctionProps;
};
/**
* Creates the function that runs when the Script is created.
*
* @example
* ```js
* new Script(stack, "Api", {
* onCreate: "src/function.handler",
* })
* ```
*/
onCreate?: FunctionDefinition;
/**
* Creates the function that runs on every deploy after the Script is created
*
* @example
* ```js
* new Script(stack, "Api", {
* onUpdate: "src/function.handler",
* })
* ```
*/
onUpdate?: FunctionDefinition;
/**
* Create the function that runs when the Script is deleted from the stack.
*
* @example
* ```js
* new Script(stack, "Api", {
* onDelete: "src/function.handler",
* })
* ```
*/
onDelete?: FunctionDefinition;
}
/////////////////////
// Construct
/////////////////////
/**
* The `Script` construct is a higher level CDK construct that makes it easy to run a script in a Lambda function during the deployment process.
*
* @example
*
* ```js
* import { Script } from "sst/constructs";
*
* new Script(stack, "Script", {
* onCreate: "src/function.create",
* onUpdate: "src/function.update",
* onDelete: "src/function.delete",
* });
* ```
*/
export class Script extends Construct implements SSTConstruct {
/**
* The internally created onCreate `Function` instance.
*/
public readonly createFunction?: Fn;
/**
* The internally created onUpdate `Function` instance.
*/
public readonly updateFunction?: Fn;
/**
* The internally created onDelete `Function` instance.
*/
public readonly deleteFunction?: Fn;
protected readonly props: ScriptProps;
public readonly id: string;
constructor(scope: Construct, id: string, props: ScriptProps) {
super(scope, id);
this.id = id;
if ((props as any).function) this.checkDeprecatedFunction();
// Validate deprecated "function" prop
// Validate at least 1 function is provided
if (!props.onCreate && !props.onUpdate && !props.onDelete) {
throw new Error(
`Need to provide at least one of "onCreate", "onUpdate", or "onDelete" functions for the "${this.node.id}" Script`
);
}
const root = scope.node.root as App;
this.props = props;
this.createFunction = this.createUserFunction("onCreate", props.onCreate);
this.updateFunction = this.createUserFunction("onUpdate", props.onUpdate);
this.deleteFunction = this.createUserFunction("onDelete", props.onDelete);
const crFunction = this.createCustomResourceFunction();
this.createCustomResource(root, crFunction);
}
/**
* Binds additional resources to the script
*
* @example
* ```js
* script.bind([STRIPE_KEY, bucket]);
* ```
*/
public bind(constructs: SSTConstruct[]): void {
this.createFunction?.bind(constructs);
this.updateFunction?.bind(constructs);
this.deleteFunction?.bind(constructs);
}
/**
* Grants additional permissions to the script
*
* @example
* ```js
* script.attachPermissions(["s3"]);
* ```
*/
public attachPermissions(permissions: Permissions): void {
this.createFunction?.attachPermissions(permissions);
this.updateFunction?.attachPermissions(permissions);
this.deleteFunction?.attachPermissions(permissions);
}
protected createUserFunction(
type: string,
fnDef?: FunctionDefinition
): Fn | undefined {
if (!fnDef) {
return;
}
// function is construct => return function directly
if (fnDef instanceof Fn) {
// validate live dev is not enabled
if (fnDef._isLiveDevEnabled) {
throw new Error(
`Live Lambda Dev cannot be enabled for functions in the Script construct. Set the "enableLiveDev" prop for the function to "false".`
);
}
return Fn.fromDefinition(
this,
`${type}Function`,
fnDef,
this.props.defaults?.function,
`The "defaults.function" cannot be applied if an instance of a Function construct is passed in. Make sure to define the "${type}" function using FunctionProps, so the Script construct can apply the "defaults.function" to them.`
);
}
// function is string => create function
else if (typeof fnDef === "string") {
return Fn.fromDefinition(
this,
`${type}Function`,
{
handler: fnDef,
enableLiveDev: false,
},
{
timeout: 900,
...this.props.defaults?.function,
}
);
}
// function is props => create function
return Fn.fromDefinition(
this,
`${type}Function`,
{
...fnDef,
enableLiveDev: false,
},
{
timeout: 900,
...this.props.defaults?.function,
}
);
}
private createCustomResourceFunction(): CdkFunction {
const handler = new CdkFunction(this, "ScriptHandler", {
code: Code.fromAsset(path.join(__dirname, "../support/script-function")),
runtime: Runtime.NODEJS_16_X,
handler: "index.handler",
timeout: Duration.minutes(15),
memorySize: 1024,
initialPolicy: [
new PolicyStatement({
actions: ["cloudformation:DescribeStacks"],
resources: [Stack.of(this).stackId],
}),
],
});
this.createFunction?.grantInvoke(handler);
this.updateFunction?.grantInvoke(handler);
this.deleteFunction?.grantInvoke(handler);
return handler;
}
private createCustomResource(app: App, crFunction: CdkFunction): void {
// Note: "Version" is set to current timestamp to ensure the Custom
// Resource function is run on every update.
//
// Do not use the current timestamp in Live mode, b/c we want the
// this custom resource to remain the same in CloudFormation template
// when rebuilding infrastructure. Otherwise, there will always be
// a change when rebuilding infrastructure b/c the "version" property
// changes on each build.
const defaultVersion =
app.mode === "dev" ? app.debugScriptVersion : Date.now().toString();
const version = this.props.version ?? defaultVersion;
new CustomResource(this, "ScriptResource", {
serviceToken: crFunction.functionArn,
resourceType: "Custom::SSTScript",
properties: {
UserCreateFunction: this.createFunction?.functionName,
UserUpdateFunction: this.updateFunction?.functionName,
UserDeleteFunction: this.deleteFunction?.functionName,
UserParams: JSON.stringify(this.props.params || {}),
Version: version,
},
});
}
private checkDeprecatedFunction(): void {
throw new Error(
`The "function" property has been replaced by "onCreate" and "onUpdate". More details on upgrading - https://docs.sst.dev/constructs/Script#upgrading-to-v0460`
);
}
/** @internal */
public getConstructMetadata() {
return {
type: "Script" as const,
data: {
createfn: getFunctionRef(this.createFunction),
deletefn: getFunctionRef(this.deleteFunction),
updatefn: getFunctionRef(this.updateFunction),
},
};
}
/** @internal */
public getFunctionBinding() {
return undefined;
}
}