-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapollo-lambda-websocket-stack.ts
More file actions
283 lines (250 loc) · 9.61 KB
/
Copy pathapollo-lambda-websocket-stack.ts
File metadata and controls
283 lines (250 loc) · 9.61 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
import { Runtime, Tracing } from '@aws-cdk/aws-lambda';
import { HttpMethod, WebSocketApi, WebSocketStage } from '@aws-cdk/aws-apigatewayv2';
import {
App, CfnOutput, Construct, RemovalPolicy, Stack, StackProps,
} from '@aws-cdk/core';
import {
AttributeType, BillingMode, ProjectionType, Table,
} from '@aws-cdk/aws-dynamodb';
import { NodejsFunction } from '@aws-cdk/aws-lambda-nodejs';
import { LambdaFunction } from '@aws-cdk/aws-events-targets';
import { EventBus, Rule } from '@aws-cdk/aws-events';
import { Duration } from '@aws-cdk/core/lib/duration';
import { Effect, PolicyStatement } from '@aws-cdk/aws-iam';
import { LambdaWebSocketIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
import path = require('path');
import { LambdaIntegration, RestApi } from '@aws-cdk/aws-apigateway';
export interface SimpleLambdaProps {
memorySize?: number;
reservedConcurrentExecutions?: number;
runtime?: Runtime;
name: string;
description: string;
entryFilename: string;
handler?: string;
timeout?: Duration;
envVariables?: any;
}
export class SimpleLambda extends Construct {
public fn: NodejsFunction;
constructor(scope: Construct, id: string, props: SimpleLambdaProps) {
super(scope, id);
this.fn = new NodejsFunction(this, id, {
entry: `../src/lambda/${props.entryFilename}`,
handler: props.handler ?? 'handler',
runtime: props.runtime ?? Runtime.NODEJS_14_X,
timeout: props.timeout ?? Duration.seconds(5),
memorySize: props.memorySize ?? 1024,
tracing: Tracing.ACTIVE,
functionName: props.name,
description: props.description,
depsLockFilePath: path.join(__dirname, '..', '..', 'src', 'package-lock.json'),
environment: props.envVariables ?? {},
});
}
}
export class ApolloLambdaWebsocketStack extends Stack {
private readonly webSocketApi: WebSocketApi;
constructor(scope: App, id: string, props?: StackProps) {
super(scope, id, props);
const REQUEST_EVENT_DETAIL_TYPE = 'ClientMessageReceived';
const RESPONSE_EVENT_DETAIL_TYPE = 'ClientMessageTranslated';
const connectionTable = new Table(this, 'WebsocketConnections', {
billingMode: BillingMode.PROVISIONED,
readCapacity: 1,
writeCapacity: 1,
removalPolicy: RemovalPolicy.DESTROY,
tableName: 'WebsocketConnections',
partitionKey: {
name: 'chatId',
type: AttributeType.STRING,
},
sortKey: {
name: 'connectionId',
type: AttributeType.STRING,
},
});
const GSI_NAME = 'ConnectionIdMap';
connectionTable.addGlobalSecondaryIndex({
partitionKey: {
name: 'connectionId',
type: AttributeType.STRING,
},
sortKey: {
name: 'chatId',
type: AttributeType.STRING,
},
indexName: GSI_NAME,
projectionType: ProjectionType.KEYS_ONLY,
});
const eventBus = new EventBus(this, 'ApolloMutationEvents', {
eventBusName: 'ApolloMutationEvents',
});
const connectionLambda = new SimpleLambda(this, 'ConnectionHandler', {
entryFilename: 'websocket-connection-handler.ts',
handler: 'connectionHandler',
name: 'ConnectionHandler',
description: 'Handles the onConnect & onDisconnect events emitted by the WebSocket API GW',
envVariables: {
TABLE_NAME: connectionTable.tableName,
GSI_NAME,
},
});
connectionTable.grantFullAccess(connectionLambda.fn);
this.webSocketApi = new WebSocketApi(this, 'ApolloWebsocketApi', {
apiName: 'WebSocketApi',
description: 'A Websocket API that handles GraphQL queries',
connectRouteOptions: {
integration: new LambdaWebSocketIntegration({
handler: connectionLambda.fn,
}),
},
disconnectRouteOptions: {
integration: new LambdaWebSocketIntegration({
handler: connectionLambda.fn,
}),
},
});
const websocketStage = new WebSocketStage(this, 'ApolloWebsocketStage', {
webSocketApi: this.webSocketApi,
stageName: 'dev',
autoDeploy: true,
});
const wsRequestHandlerLambda = new SimpleLambda(this, 'WSRequestHandler', {
entryFilename: 'graphql-query-ws-handler.ts',
handler: 'handleWSMessage',
name: 'WSRequestHandler',
description: 'Handles GraphQL queries sent via websocket. Stores (connectionId, topic) tuple in DynamoDB for subscriptions requests. Sends events to EventBridge for mutation requests',
envVariables: {
BUS_NAME: eventBus.eventBusName,
TABLE_NAME: connectionTable.tableName,
REQUEST_EVENT_DETAIL_TYPE,
API_GATEWAY_ENDPOINT: websocketStage.callbackUrl,
},
});
connectionTable.grantFullAccess(wsRequestHandlerLambda.fn);
eventBus.grantPutEventsTo(wsRequestHandlerLambda.fn);
wsRequestHandlerLambda.fn.addToRolePolicy(
new PolicyStatement({
effect: Effect.ALLOW,
resources: [
`arn:aws:execute-api:${this.region}:${this.account}:${this.webSocketApi.apiId}/${websocketStage.stageName}/*`,
],
actions: ['execute-api:ManageConnections'],
}),
);
this.webSocketApi.addRoute('$default', {
integration: new LambdaWebSocketIntegration({
handler: wsRequestHandlerLambda.fn,
}),
});
const eventBridgeToSubscriptionsLambda = new SimpleLambda(this, 'ResponseHandler', {
entryFilename: 'eventbus-response-handler.ts',
handler: 'handler',
name: 'ResponseHandler',
description: `Gets invoked when a new response event (${RESPONSE_EVENT_DETAIL_TYPE}) is published to EventBridge, finds the interested subscribers and pushes the event via WebSocket`,
envVariables: {
BUS_NAME: eventBus.eventBusName,
TABLE_NAME: connectionTable.tableName,
API_GATEWAY_ENDPOINT: websocketStage.callbackUrl,
},
});
const translateToFrenchLambda = new SimpleLambda(this, 'ProcessMutationEventLambda', {
entryFilename: 'event-processor.ts',
handler: 'translateMessage',
name: 'TranslateToFrench',
description: `Gets invoked when a new request event (${REQUEST_EVENT_DETAIL_TYPE}) is published to EventBridge. The function processes translates event.detail.message to French and publishes the result back to the event bus`,
envVariables: {
BUS_NAME: eventBus.eventBusName,
RESPONSE_EVENT_DETAIL_TYPE,
TARGET_LANGUAGE_CODE: 'fr',
},
});
const translateToGermanLambda = new SimpleLambda(this, 'ProcessMutationEventLambda2', {
entryFilename: 'event-processor.ts',
handler: 'translateMessage',
name: 'TranslateToGerman',
description: `Gets invoked when a new request event (${REQUEST_EVENT_DETAIL_TYPE}) is published to EventBridge. The function processes translates event.detail.message to German and publishes the result back to the event bus`,
envVariables: {
BUS_NAME: eventBus.eventBusName,
RESPONSE_EVENT_DETAIL_TYPE,
TARGET_LANGUAGE_CODE: 'de',
},
});
const allowUseOfAmazonTranslate = new PolicyStatement({
effect: Effect.ALLOW,
resources: [
'*',
],
actions: ['translate:TranslateText', 'comprehend:DetectDominantLanguage'],
});
translateToFrenchLambda.fn.addToRolePolicy(allowUseOfAmazonTranslate);
translateToGermanLambda.fn.addToRolePolicy(allowUseOfAmazonTranslate);
new Rule(this, 'ProcessRequest', {
eventBus,
enabled: true,
ruleName: 'TranslateMessage',
eventPattern: {
detailType: [REQUEST_EVENT_DETAIL_TYPE],
},
targets: [
new LambdaFunction(translateToFrenchLambda.fn),
new LambdaFunction(translateToGermanLambda.fn),
],
});
new Rule(this, 'NotifyApolloSubscribers', {
eventBus,
enabled: true,
ruleName: 'RespondToChat',
eventPattern: {
detailType: [RESPONSE_EVENT_DETAIL_TYPE],
},
targets: [
new LambdaFunction(eventBridgeToSubscriptionsLambda.fn),
],
});
connectionTable.grantFullAccess(eventBridgeToSubscriptionsLambda.fn);
eventBridgeToSubscriptionsLambda.fn.addToRolePolicy(
new PolicyStatement({
effect: Effect.ALLOW,
resources: [
`arn:aws:execute-api:${this.region}:${this.account}:${this.webSocketApi.apiId}/${websocketStage.stageName}/*`,
],
actions: ['execute-api:ManageConnections'],
}),
);
eventBus.grantPutEventsTo(translateToFrenchLambda.fn);
eventBus.grantPutEventsTo(translateToGermanLambda.fn);
const restApi = new RestApi(this, 'ApolloRestApi', {
description: 'A Rest API that handles GraphQl queries via POST to /graphql.',
deployOptions: {
stageName: 'dev',
tracingEnabled: true,
},
restApiName: 'RestApi',
});
const restRequestHandlerLambda = new SimpleLambda(this, 'RestRequestHandler', {
entryFilename: 'graphql-query-rest-handler.ts',
handler: 'handleRESTMessage',
name: 'RestRequestHandler',
description: 'Handles GraphQL queries sent via REST.',
envVariables: {
BUS_NAME: eventBus.eventBusName,
REQUEST_EVENT_DETAIL_TYPE,
},
});
// connectionTable(restRequestHandlerLambda.fn);
eventBus.grantPutEventsTo(restRequestHandlerLambda.fn);
restApi.root
.addResource('graphql')
.addMethod(HttpMethod.POST, new LambdaIntegration(restRequestHandlerLambda.fn));
new CfnOutput(this, 'WebsocketApiEndpoint', {
value: `${this.webSocketApi.apiEndpoint}/${websocketStage.stageName}`,
exportName: 'WebsocketApiEndpoint',
});
new CfnOutput(this, 'RestApiEndpoint', {
value: restApi.urlForPath('/graphql'),
exportName: 'RestApiEndpoint',
});
}
}