-
Notifications
You must be signed in to change notification settings - Fork 4k
/
stepfunctions.ts
353 lines (318 loc) · 11.4 KB
/
stepfunctions.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import * as fs from 'fs';
import * as path from 'path';
import { RequestContext } from '.';
import { AwsIntegration } from './aws';
import * as iam from '../../../aws-iam';
import * as sfn from '../../../aws-stepfunctions';
import { Token } from '../../../core';
import { IntegrationConfig, IntegrationOptions, PassthroughBehavior } from '../integration';
import { Method } from '../method';
import { Model } from '../model';
/**
* Options when configuring Step Functions synchronous integration with Rest API
*/
export interface StepFunctionsExecutionIntegrationOptions extends IntegrationOptions {
/**
* Which details of the incoming request must be passed onto the underlying state machine,
* such as, account id, user identity, request id, etc. The execution input will include a new key `requestContext`:
*
* {
* "body": {},
* "requestContext": {
* "key": "value"
* }
* }
*
* @default - all parameters within request context will be set as false
*/
readonly requestContext?: RequestContext;
/**
* Check if querystring is to be included inside the execution input. The execution input will include a new key `queryString`:
*
* {
* "body": {},
* "querystring": {
* "key": "value"
* }
* }
*
* @default true
*/
readonly querystring?: boolean;
/**
* Check if path is to be included inside the execution input. The execution input will include a new key `path`:
*
* {
* "body": {},
* "path": {
* "resourceName": "resourceValue"
* }
* }
*
* @default true
*/
readonly path?: boolean;
/**
* Check if header is to be included inside the execution input. The execution input will include a new key `headers`:
*
* {
* "body": {},
* "headers": {
* "header1": "value",
* "header2": "value"
* }
* }
* @default false
*/
readonly headers?: boolean;
/**
* If the whole authorizer object, including custom context values should be in the execution input. The execution input will include a new key `authorizer`:
*
* {
* "body": {},
* "authorizer": {
* "key": "value"
* }
* }
*
* @default false
*/
readonly authorizer?: boolean;
/**
* Whether to add default response models with 200, 400, and 500 status codes to the method.
*
* @default true
*/
readonly useDefaultMethodResponses?: boolean;
}
/**
* Options to integrate with various StepFunction API
*/
export class StepFunctionsIntegration {
/**
* Integrates a Synchronous Express State Machine from AWS Step Functions to an API Gateway method.
*
* @example
*
* const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', {
* stateMachineType: stepfunctions.StateMachineType.EXPRESS,
* definition: stepfunctions.Chain.start(new stepfunctions.Pass(this, 'Pass')),
* });
*
* const api = new apigateway.RestApi(this, 'Api', {
* restApiName: 'MyApi',
* });
* api.root.addMethod('GET', apigateway.StepFunctionsIntegration.startExecution(stateMachine));
*/
public static startExecution(stateMachine: sfn.IStateMachine, options?: StepFunctionsExecutionIntegrationOptions): AwsIntegration {
return new StepFunctionsExecutionIntegration(stateMachine, options);
}
}
class StepFunctionsExecutionIntegration extends AwsIntegration {
private readonly stateMachine: sfn.IStateMachine;
private readonly useDefaultMethodResponses: boolean;
constructor(stateMachine: sfn.IStateMachine, options: StepFunctionsExecutionIntegrationOptions = {}) {
super({
service: 'states',
action: 'StartSyncExecution',
options: {
credentialsRole: options.credentialsRole,
integrationResponses: options.integrationResponses ?? integrationResponse(),
passthroughBehavior: PassthroughBehavior.NEVER,
requestTemplates: requestTemplates(stateMachine, options),
...options,
},
});
this.stateMachine = stateMachine;
this.useDefaultMethodResponses = options.useDefaultMethodResponses ?? true;
}
public bind(method: Method): IntegrationConfig {
const bindResult = super.bind(method);
const credentialsRole = bindResult.options?.credentialsRole ?? new iam.Role(method, 'StartSyncExecutionRole', {
assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'),
});
this.stateMachine.grantStartSyncExecution(credentialsRole);
let stateMachineName;
if (this.stateMachine instanceof sfn.StateMachine) {
const stateMachineType = (this.stateMachine as sfn.StateMachine).stateMachineType;
if (stateMachineType !== sfn.StateMachineType.EXPRESS) {
throw new Error('State Machine must be of type "EXPRESS". Please use StateMachineType.EXPRESS as the stateMachineType');
}
//if not imported, extract the name from the CFN layer to reach the
//literal value if it is given (rather than a token)
stateMachineName = (this.stateMachine.node.defaultChild as sfn.CfnStateMachine).stateMachineName;
} else {
//imported state machine
stateMachineName = `StateMachine-${this.stateMachine.stack.node.addr}`;
}
let deploymentToken;
if (stateMachineName !== undefined && !Token.isUnresolved(stateMachineName)) {
deploymentToken = JSON.stringify({ stateMachineName });
}
if (this.useDefaultMethodResponses) {
for (const methodResponse of METHOD_RESPONSES) {
method.addMethodResponse(methodResponse);
}
}
return {
...bindResult,
options: {
...bindResult.options,
credentialsRole,
},
deploymentToken,
};
}
}
/**
* Defines the integration response that passes the result on success,
* or the error on failure, from the synchronous execution to the caller.
*
* @returns integrationResponse mapping
*/
function integrationResponse() {
const errorResponse = [
{
/**
* Specifies the regular expression (regex) pattern used to choose
* an integration response based on the response from the back end.
* In this case it will match all '4XX' HTTP Errors
*/
selectionPattern: '4\\d{2}',
statusCode: '400',
responseTemplates: {
'application/json': `{
"error": "Bad request!"
}`,
},
},
{
/**
* Match all '5XX' HTTP Errors
*/
selectionPattern: '5\\d{2}',
statusCode: '500',
responseTemplates: {
'application/json': '"error": $input.path(\'$.error\')',
},
},
];
const integResponse = [
{
statusCode: '200',
responseTemplates: {
/* eslint-disable */
'application/json': [
'#set($inputRoot = $input.path(\'$\'))',
'#if($input.path(\'$.status\').toString().equals("FAILED"))',
'#set($context.responseOverride.status = 500)',
'{',
'"error": "$input.path(\'$.error\')",',
'"cause": "$input.path(\'$.cause\')"',
'}',
'#else',
'$input.path(\'$.output\')',
'#end',
/* eslint-enable */
].join('\n'),
},
},
...errorResponse,
];
return integResponse;
}
/**
* Defines the request template that will be used for the integration
* @param stateMachine
* @param options
* @returns requestTemplate
*/
function requestTemplates(stateMachine: sfn.IStateMachine, options: StepFunctionsExecutionIntegrationOptions) {
const templateStr = templateString(stateMachine, options);
const requestTemplate: { [contentType:string] : string } =
{
'application/json': templateStr,
};
return requestTemplate;
}
/**
* Reads the VTL template and returns the template string to be used
* for the request template.
*
* @param stateMachine
* @param includeRequestContext
* @param options
* @reutrns templateString
*/
function templateString(
stateMachine: sfn.IStateMachine,
options: StepFunctionsExecutionIntegrationOptions): string {
let templateStr: string;
let requestContextStr = '';
const includeHeader = options.headers?? false;
const includeQueryString = options.querystring?? true;
const includePath = options.path?? true;
const includeAuthorizer = options.authorizer ?? false;
if (options.requestContext && Object.keys(options.requestContext).length > 0) {
requestContextStr = requestContext(options.requestContext);
}
templateStr = fs.readFileSync(path.join(__dirname, 'stepfunctions.vtl'), { encoding: 'utf-8' });
templateStr = templateStr.replace('%STATEMACHINE%', stateMachine.stateMachineArn);
templateStr = templateStr.replace('%INCLUDE_HEADERS%', String(includeHeader));
templateStr = templateStr.replace('%INCLUDE_QUERYSTRING%', String(includeQueryString));
templateStr = templateStr.replace('%INCLUDE_PATH%', String(includePath));
templateStr = templateStr.replace('%INCLUDE_AUTHORIZER%', String(includeAuthorizer));
templateStr = templateStr.replace('%REQUESTCONTEXT%', requestContextStr);
return templateStr;
}
function requestContext(requestContextObj: RequestContext | undefined): string {
const context = {
accountId: requestContextObj?.accountId? '$context.identity.accountId': undefined,
apiId: requestContextObj?.apiId? '$context.apiId': undefined,
apiKey: requestContextObj?.apiKey? '$context.identity.apiKey': undefined,
authorizerPrincipalId: requestContextObj?.authorizerPrincipalId? '$context.authorizer.principalId': undefined,
caller: requestContextObj?.caller? '$context.identity.caller': undefined,
cognitoAuthenticationProvider: requestContextObj?.cognitoAuthenticationProvider? '$context.identity.cognitoAuthenticationProvider': undefined,
cognitoAuthenticationType: requestContextObj?.cognitoAuthenticationType? '$context.identity.cognitoAuthenticationType': undefined,
cognitoIdentityId: requestContextObj?.cognitoIdentityId? '$context.identity.cognitoIdentityId': undefined,
cognitoIdentityPoolId: requestContextObj?.cognitoIdentityPoolId? '$context.identity.cognitoIdentityPoolId': undefined,
httpMethod: requestContextObj?.httpMethod? '$context.httpMethod': undefined,
stage: requestContextObj?.stage? '$context.stage': undefined,
sourceIp: requestContextObj?.sourceIp? '$context.identity.sourceIp': undefined,
user: requestContextObj?.user? '$context.identity.user': undefined,
userAgent: requestContextObj?.userAgent? '$context.identity.userAgent': undefined,
userArn: requestContextObj?.userArn? '$context.identity.userArn': undefined,
requestId: requestContextObj?.requestId? '$context.requestId': undefined,
resourceId: requestContextObj?.resourceId? '$context.resourceId': undefined,
resourcePath: requestContextObj?.resourcePath? '$context.resourcePath': undefined,
};
const contextAsString = JSON.stringify(context);
// The VTL Template conflicts with double-quotes (") for strings.
// Before sending to the template, we replace double-quotes (") with @@ and replace it back inside the .vtl file
const doublequotes = '"';
const replaceWith = '@@';
return contextAsString.split(doublequotes).join(replaceWith);
}
/**
* Method response model for each HTTP code response
*/
const METHOD_RESPONSES = [
{
statusCode: '200',
responseModels: {
'application/json': Model.EMPTY_MODEL,
},
},
{
statusCode: '400',
responseModels: {
'application/json': Model.ERROR_MODEL,
},
},
{
statusCode: '500',
responseModels: {
'application/json': Model.ERROR_MODEL,
},
},
];