-
Notifications
You must be signed in to change notification settings - Fork 42
/
api-service.ts
570 lines (547 loc) · 23.7 KB
/
api-service.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import { CfnOutput, Duration, StackProps } from "aws-cdk-lib";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import { Metric } from "aws-cdk-lib/aws-cloudwatch";
import { SnsAction } from "aws-cdk-lib/aws-cloudwatch-actions";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import { Repository } from "aws-cdk-lib/aws-ecr";
import * as ecs from "aws-cdk-lib/aws-ecs";
import { FargateService } from "aws-cdk-lib/aws-ecs";
import * as ecs_patterns from "aws-cdk-lib/aws-ecs-patterns";
import {
ApplicationProtocol,
NetworkLoadBalancer,
NetworkTargetGroup,
Protocol,
} from "aws-cdk-lib/aws-elasticloadbalancingv2";
import { AlbTarget } from "aws-cdk-lib/aws-elasticloadbalancingv2-targets";
import * as iam from "aws-cdk-lib/aws-iam";
import { IFunction as ILambda } from "aws-cdk-lib/aws-lambda";
import { LogGroup } from "aws-cdk-lib/aws-logs";
import * as rds from "aws-cdk-lib/aws-rds";
import * as r53 from "aws-cdk-lib/aws-route53";
import * as r53_targets from "aws-cdk-lib/aws-route53-targets";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as secret from "aws-cdk-lib/aws-secretsmanager";
import { ISecret } from "aws-cdk-lib/aws-secretsmanager";
import { IQueue } from "aws-cdk-lib/aws-sqs";
import { Construct } from "constructs";
import { EnvConfig } from "../../config/env-config";
import { DnsZones } from "../shared/dns";
import { Secrets, secretsToECS } from "../shared/secrets";
import { provideAccessToQueue } from "../shared/sqs";
import { isProd, isSandbox } from "../shared/util";
interface ApiServiceProps extends StackProps {
config: EnvConfig;
version: string | undefined;
}
export function createAPIService({
stack,
props,
secrets,
vpc,
dbCredsSecret,
dbReadReplicaEndpoint,
dynamoDBTokenTable,
alarmAction,
dnsZones,
fhirServerUrl,
fhirServerQueueUrl,
fhirConverterQueueUrl,
fhirConverterServiceUrl,
cdaToVisualizationLambda,
documentDownloaderLambda,
outboundPatientDiscoveryLambda,
outboundDocumentQueryLambda,
outboundDocumentRetrievalLambda,
medicalDocumentsUploadBucket,
fhirToMedicalRecordLambda,
fhirToCdaConverterLambda,
searchIngestionQueue,
searchEndpoint,
searchAuth,
searchIndexName,
appConfigEnvVars,
cookieStore,
}: {
stack: Construct;
props: ApiServiceProps;
secrets: Secrets;
vpc: ec2.IVpc;
dbCredsSecret: secret.ISecret;
dbReadReplicaEndpoint: rds.Endpoint;
dynamoDBTokenTable: dynamodb.Table;
alarmAction: SnsAction | undefined;
dnsZones: DnsZones;
fhirServerUrl: string;
fhirServerQueueUrl: string | undefined;
fhirConverterQueueUrl: string | undefined;
fhirConverterServiceUrl: string | undefined;
cdaToVisualizationLambda: ILambda;
documentDownloaderLambda: ILambda;
outboundPatientDiscoveryLambda: ILambda;
outboundDocumentQueryLambda: ILambda;
outboundDocumentRetrievalLambda: ILambda;
medicalDocumentsUploadBucket: s3.Bucket;
fhirToMedicalRecordLambda: ILambda | undefined;
fhirToCdaConverterLambda: ILambda | undefined;
searchIngestionQueue: IQueue;
searchEndpoint: string;
searchAuth: { userName: string; secret: ISecret };
searchIndexName: string;
appConfigEnvVars: {
appId: string;
configId: string;
};
cookieStore: secret.ISecret | undefined;
}): {
cluster: ecs.Cluster;
service: ecs_patterns.NetworkLoadBalancedFargateService;
serverAddress: string;
loadBalancerAddress: string;
apiServiceAdditional: FargateService;
} {
// Create a new Amazon Elastic Container Service (ECS) cluster
const cluster = new ecs.Cluster(stack, "APICluster", { vpc, containerInsights: true });
// Create an ECR repo where we'll deploy our Docker images to, and where ECS will pull from
const ecrRepo = new Repository(stack, "APIRepo", {
repositoryName: "metriport/api",
});
new CfnOutput(stack, "APIECRRepoURI", {
description: "API ECR repository URI",
value: ecrRepo.repositoryUri,
});
const connectWidgetUrlEnvVar = isSandbox(props.config)
? props.config.connectWidgetUrl
: `https://${props.config.connectWidget.subdomain}.${props.config.connectWidget.domain}/`;
const iheGateway = props.config.iheGateway;
const coverageEnhancementConfig = props.config.commonwell.coverageEnhancement;
const dbReadReplicaEndpointAsString = JSON.stringify({
host: dbReadReplicaEndpoint.hostname,
port: dbReadReplicaEndpoint.port,
});
// Run some servers on fargate containers
const listenerPort = 80;
const containerPort = 8080;
const logGroup = LogGroup.fromLogGroupArn(stack, "ApiLogGroup", props.config.logArn);
// TODO RENAME to remove "Alb"
const fargateServiceAlb = new ecs_patterns.ApplicationLoadBalancedFargateService(
stack,
"APIFargateServiceAlb",
{
cluster: cluster,
// Watch out for the combination of vCPUs and memory, more vCPU requires more memory
// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size
cpu: isProd(props.config) ? 2048 : 1024,
desiredCount: isProd(props.config) ? 2 : 1,
taskImageOptions: {
image: ecs.ContainerImage.fromEcrRepository(ecrRepo, "latest"),
containerPort,
containerName: "API-Server",
logDriver: ecs.LogDrivers.awsLogs({
logGroup,
streamPrefix: "APIFargateService",
}),
secrets: {
DB_CREDS: ecs.Secret.fromSecretsManager(dbCredsSecret),
SEARCH_PASSWORD: ecs.Secret.fromSecretsManager(searchAuth.secret),
...secretsToECS(secrets),
},
environment: {
NODE_ENV: "production", // Determines its being run in the cloud, the logical env is set on ENV_TYPE
ENV_TYPE: props.config.environmentType, // staging, production, sandbox
...(props.version ? { METRIPORT_VERSION: props.version } : undefined),
AWS_REGION: props.config.region,
DB_READ_REPLICA_ENDPOINT: dbReadReplicaEndpointAsString,
TOKEN_TABLE_NAME: dynamoDBTokenTable.tableName,
API_URL: `https://${props.config.subdomain}.${props.config.domain}`,
...(props.config.apiGatewayUsagePlanId
? { API_GW_USAGE_PLAN_ID: props.config.apiGatewayUsagePlanId }
: {}),
CONNECT_WIDGET_URL: connectWidgetUrlEnvVar,
SYSTEM_ROOT_OID: props.config.systemRootOID,
SYSTEM_ROOT_ORG_NAME: props.config.systemRootOrgName,
...props.config.commonwell.envVars,
...(props.config.slack ? props.config.slack : undefined),
...(props.config.sentryDSN ? { SENTRY_DSN: props.config.sentryDSN } : undefined),
...(props.config.usageReportUrl && {
USAGE_URL: props.config.usageReportUrl,
}),
...(props.config.medicalDocumentsBucketName && {
MEDICAL_DOCUMENTS_BUCKET_NAME: props.config.medicalDocumentsBucketName,
}),
...(props.config.medicalDocumentsUploadBucketName && {
MEDICAL_DOCUMENTS_UPLOADS_BUCKET_NAME: props.config.medicalDocumentsUploadBucketName,
}),
...(isSandbox(props.config) && {
SANDBOX_SEED_DATA_BUCKET_NAME: props.config.sandboxSeedDataBucketName,
}),
CONVERT_DOC_LAMBDA_NAME: cdaToVisualizationLambda.functionName,
DOCUMENT_DOWNLOADER_LAMBDA_NAME: documentDownloaderLambda.functionName,
...(iheGateway
? {
IHE_GW_URL: `http:https://${iheGateway.outboundSubdomain}.${props.config.domain}`,
IHE_GW_PORT_PD: iheGateway.outboundPorts.patientDiscovery.toString(),
IHE_GW_PORT_DQ: iheGateway.outboundPorts.documentQuery.toString(),
IHE_GW_PORT_DR: iheGateway.outboundPorts.documentRetrieval.toString(),
}
: undefined),
OUTBOUND_PATIENT_DISCOVERY_LAMBDA_NAME: outboundPatientDiscoveryLambda.functionName,
OUTBOUND_DOC_QUERY_LAMBDA_NAME: outboundDocumentQueryLambda.functionName,
OUTBOUND_DOC_RETRIEVAL_LAMBDA_NAME: outboundDocumentRetrievalLambda.functionName,
...(fhirToMedicalRecordLambda && {
FHIR_TO_MEDICAL_RECORD_LAMBDA_NAME: fhirToMedicalRecordLambda.functionName,
}),
...(fhirToCdaConverterLambda && {
FHIR_TO_CDA_CONVERTER_LAMBDA_NAME: fhirToCdaConverterLambda.functionName,
}),
FHIR_SERVER_URL: fhirServerUrl,
...(fhirServerQueueUrl && {
FHIR_SERVER_QUEUE_URL: fhirServerQueueUrl,
}),
...(fhirConverterQueueUrl && {
FHIR_CONVERTER_QUEUE_URL: fhirConverterQueueUrl,
}),
...(fhirConverterServiceUrl && {
FHIR_CONVERTER_SERVER_URL: fhirConverterServiceUrl,
}),
SEARCH_INGESTION_QUEUE_URL: searchIngestionQueue.queueUrl,
SEARCH_ENDPOINT: searchEndpoint,
SEARCH_USERNAME: searchAuth.userName,
SEARCH_INDEX: searchIndexName,
...(props.config.carequality?.envVars?.CQ_ORG_URLS && {
CQ_ORG_URLS: props.config.carequality.envVars.CQ_ORG_URLS,
}),
...(props.config.carequality?.envVars?.CQ_URLS_TO_EXCLUDE && {
CQ_URLS_TO_EXCLUDE: props.config.carequality.envVars.CQ_URLS_TO_EXCLUDE,
}),
...(props.config.locationService && {
PLACE_INDEX_NAME: props.config.locationService.placeIndexName,
PLACE_INDEX_REGION: props.config.locationService.placeIndexRegion,
}),
// app config
APPCONFIG_APPLICATION_ID: appConfigEnvVars.appId,
APPCONFIG_CONFIGURATION_ID: appConfigEnvVars.configId,
...(coverageEnhancementConfig && {
CW_MANAGEMENT_URL: coverageEnhancementConfig.managementUrl,
}),
...(cookieStore && {
CW_MANAGEMENT_COOKIE_SECRET_ARN: cookieStore.secretArn,
}),
...(props.config.iheGateway?.trustStoreBucketName && {
CQ_TRUST_BUNDLE_BUCKET_NAME: props.config.iheGateway.trustStoreBucketName,
}),
},
},
memoryLimitMiB: isProd(props.config) ? 4096 : 2048,
healthCheckGracePeriod: Duration.seconds(60),
protocol: ApplicationProtocol.HTTP,
listenerPort,
publicLoadBalancer: false,
}
);
// TODO DEPRECATED start
const fargateService = new ecs_patterns.NetworkLoadBalancedFargateService(
stack,
"APIFargateService",
{
cluster: cluster,
// Watch out for the combination of vCPUs and memory, more vCPU requires more memory
// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size
cpu: isProd(props.config) ? 2048 : 1024,
desiredCount: isProd(props.config) ? 2 : 1,
taskImageOptions: {
image: ecs.ContainerImage.fromEcrRepository(ecrRepo, "latest"),
containerPort: 8080,
containerName: "API-Server",
secrets: {
DB_CREDS: ecs.Secret.fromSecretsManager(dbCredsSecret),
SEARCH_PASSWORD: ecs.Secret.fromSecretsManager(searchAuth.secret),
...secretsToECS(secrets),
},
environment: {
NODE_ENV: "production", // Determines its being run in the cloud, the logical env is set on ENV_TYPE
ENV_TYPE: props.config.environmentType, // staging, production, sandbox
...(props.version ? { METRIPORT_VERSION: props.version } : undefined),
AWS_REGION: props.config.region,
DB_READ_REPLICA_ENDPOINT: dbReadReplicaEndpointAsString,
TOKEN_TABLE_NAME: dynamoDBTokenTable.tableName,
API_URL: `https://${props.config.subdomain}.${props.config.domain}`,
...(props.config.apiGatewayUsagePlanId
? { API_GW_USAGE_PLAN_ID: props.config.apiGatewayUsagePlanId }
: {}),
CONNECT_WIDGET_URL: connectWidgetUrlEnvVar,
SYSTEM_ROOT_OID: props.config.systemRootOID,
SYSTEM_ROOT_ORG_NAME: props.config.systemRootOrgName,
...props.config.commonwell.envVars,
...(props.config.slack ? props.config.slack : undefined),
...(props.config.sentryDSN ? { SENTRY_DSN: props.config.sentryDSN } : undefined),
...(props.config.usageReportUrl && {
USAGE_URL: props.config.usageReportUrl,
}),
...(props.config.medicalDocumentsBucketName && {
MEDICAL_DOCUMENTS_BUCKET_NAME: props.config.medicalDocumentsBucketName,
}),
...(props.config.medicalDocumentsUploadBucketName && {
MEDICAL_DOCUMENTS_UPLOADS_BUCKET_NAME: props.config.medicalDocumentsUploadBucketName,
}),
...(isSandbox(props.config) && {
SANDBOX_SEED_DATA_BUCKET_NAME: props.config.sandboxSeedDataBucketName,
}),
CONVERT_DOC_LAMBDA_NAME: cdaToVisualizationLambda.functionName,
DOCUMENT_DOWNLOADER_LAMBDA_NAME: documentDownloaderLambda.functionName,
...(iheGateway
? {
IHE_GW_URL: `http:https://${iheGateway.outboundSubdomain}.${props.config.domain}`,
IHE_GW_PORT_PD: iheGateway.outboundPorts.patientDiscovery.toString(),
IHE_GW_PORT_DQ: iheGateway.outboundPorts.documentQuery.toString(),
IHE_GW_PORT_DR: iheGateway.outboundPorts.documentRetrieval.toString(),
}
: undefined),
OUTBOUND_PATIENT_DISCOVERY_LAMBDA_NAME: outboundPatientDiscoveryLambda.functionName,
OUTBOUND_DOC_QUERY_LAMBDA_NAME: outboundDocumentQueryLambda.functionName,
OUTBOUND_DOC_RETRIEVAL_LAMBDA_NAME: outboundDocumentRetrievalLambda.functionName,
...(fhirToMedicalRecordLambda && {
FHIR_TO_MEDICAL_RECORD_LAMBDA_NAME: fhirToMedicalRecordLambda.functionName,
}),
...(fhirToCdaConverterLambda && {
FHIR_TO_CDA_CONVERTER_LAMBDA_NAME: fhirToCdaConverterLambda.functionName,
}),
FHIR_SERVER_URL: fhirServerUrl,
...(fhirServerQueueUrl && {
FHIR_SERVER_QUEUE_URL: fhirServerQueueUrl,
}),
...(fhirConverterQueueUrl && {
FHIR_CONVERTER_QUEUE_URL: fhirConverterQueueUrl,
}),
...(fhirConverterServiceUrl && {
FHIR_CONVERTER_SERVER_URL: fhirConverterServiceUrl,
}),
SEARCH_INGESTION_QUEUE_URL: searchIngestionQueue.queueUrl,
SEARCH_ENDPOINT: searchEndpoint,
SEARCH_USERNAME: searchAuth.userName,
SEARCH_INDEX: searchIndexName,
...(props.config.carequality?.envVars?.CQ_ORG_URLS && {
CQ_ORG_URLS: props.config.carequality.envVars.CQ_ORG_URLS,
}),
...(props.config.carequality?.envVars?.CQ_URLS_TO_EXCLUDE && {
CQ_URLS_TO_EXCLUDE: props.config.carequality.envVars.CQ_URLS_TO_EXCLUDE,
}),
...(props.config.locationService && {
PLACE_INDEX_NAME: props.config.locationService.placeIndexName,
PLACE_INDEX_REGION: props.config.locationService.placeIndexRegion,
}),
// app config
APPCONFIG_APPLICATION_ID: appConfigEnvVars.appId,
APPCONFIG_CONFIGURATION_ID: appConfigEnvVars.configId,
...(coverageEnhancementConfig && {
CW_MANAGEMENT_URL: coverageEnhancementConfig.managementUrl,
}),
...(cookieStore && {
CW_MANAGEMENT_COOKIE_SECRET_ARN: cookieStore.secretArn,
}),
...(props.config.iheGateway?.trustStoreBucketName && {
CQ_TRUST_BUNDLE_BUCKET_NAME: props.config.iheGateway.trustStoreBucketName,
}),
},
},
memoryLimitMiB: isProd(props.config) ? 4096 : 2048,
healthCheckGracePeriod: Duration.seconds(60),
publicLoadBalancer: false,
}
);
// TODO DEPRECATED end
const serverAddress = fargateService.loadBalancer.loadBalancerDnsName;
const apiUrl = `${props.config.subdomain}.${props.config.domain}`;
new r53.ARecord(stack, "APIDomainPrivateRecord", {
recordName: apiUrl,
zone: dnsZones.privateZone,
target: r53.RecordTarget.fromAlias(
new r53_targets.LoadBalancerTarget(fargateService.loadBalancer)
),
});
const alb = fargateServiceAlb.loadBalancer;
const nlb = new NetworkLoadBalancer(stack, `ApiNetworkLoadBalancer`, {
vpc,
internetFacing: false,
});
const nlbListener = nlb.addListener(`ApiNetworkLoadBalancerListener`, {
port: listenerPort,
protocol: Protocol.TCP,
});
const nlbTargetGroup = new NetworkTargetGroup(stack, `ApiNetworkTargetGroup`, {
port: listenerPort,
protocol: Protocol.TCP,
vpc,
targets: [new AlbTarget(alb, listenerPort)],
});
nlbListener.addTargetGroups("ApiNetworkLoadBalancerTargetGroup", nlbTargetGroup);
// Health checks
const healthcheck = {
healthyThresholdCount: 2,
unhealthyThresholdCount: 2,
interval: Duration.seconds(10),
};
fargateServiceAlb.targetGroup.configureHealthCheck(healthcheck);
nlbTargetGroup.configureHealthCheck({
...healthcheck,
interval: healthcheck.interval.plus(Duration.seconds(3)),
});
// Access grant for Aurora DB's secret
dbCredsSecret.grantRead(fargateService.taskDefinition.taskRole);
dbCredsSecret.grantRead(fargateServiceAlb.taskDefinition.taskRole);
// RW grant for Dynamo DB
dynamoDBTokenTable.grantReadWriteData(fargateService.taskDefinition.taskRole);
cdaToVisualizationLambda.grantInvoke(fargateService.taskDefinition.taskRole);
documentDownloaderLambda.grantInvoke(fargateService.taskDefinition.taskRole);
outboundPatientDiscoveryLambda.grantInvoke(fargateService.taskDefinition.taskRole);
outboundDocumentQueryLambda.grantInvoke(fargateService.taskDefinition.taskRole);
outboundDocumentRetrievalLambda.grantInvoke(fargateService.taskDefinition.taskRole);
fhirToCdaConverterLambda?.grantInvoke(fargateService.taskDefinition.taskRole);
dynamoDBTokenTable.grantReadWriteData(fargateServiceAlb.taskDefinition.taskRole);
cdaToVisualizationLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
documentDownloaderLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
outboundPatientDiscoveryLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
outboundDocumentQueryLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
outboundDocumentRetrievalLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
fhirToCdaConverterLambda?.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
// Access grant for medical document buckets
medicalDocumentsUploadBucket.grantReadWrite(fargateService.taskDefinition.taskRole);
medicalDocumentsUploadBucket.grantReadWrite(fargateServiceAlb.taskDefinition.taskRole);
if (fhirToMedicalRecordLambda) {
fhirToMedicalRecordLambda.grantInvoke(fargateService.taskDefinition.taskRole);
fhirToMedicalRecordLambda.grantInvoke(fargateServiceAlb.taskDefinition.taskRole);
cdaToVisualizationLambda.grantInvoke(fhirToMedicalRecordLambda);
}
if (cookieStore) {
cookieStore.grantRead(fargateService.service.taskDefinition.taskRole);
cookieStore.grantWrite(fargateService.service.taskDefinition.taskRole);
cookieStore.grantRead(fargateServiceAlb.service.taskDefinition.taskRole);
cookieStore.grantWrite(fargateServiceAlb.service.taskDefinition.taskRole);
}
// Allow access to search services/infra
provideAccessToQueue({
accessType: "send",
queue: searchIngestionQueue,
resource: fargateService.taskDefinition.taskRole,
});
searchAuth.secret.grantRead(fargateService.taskDefinition.taskRole);
provideAccessToQueue({
accessType: "send",
queue: searchIngestionQueue,
resource: fargateServiceAlb.taskDefinition.taskRole,
});
searchAuth.secret.grantRead(fargateServiceAlb.taskDefinition.taskRole);
// Setting permissions for AppConfig
fargateService.taskDefinition.taskRole.attachInlinePolicy(
new iam.Policy(stack, "OSSAPIPermissionsForAppConfig", {
statements: [
new iam.PolicyStatement({
actions: [
"appconfig:StartConfigurationSession",
"appconfig:GetLatestConfiguration",
"appconfig:GetConfiguration",
"apigateway:GET",
],
resources: ["*"],
}),
new iam.PolicyStatement({
actions: ["geo:SearchPlaceIndexForText"],
resources: [`arn:aws:geo:*`],
effect: iam.Effect.ALLOW,
}),
],
})
);
fargateServiceAlb.taskDefinition.taskRole.attachInlinePolicy(
new iam.Policy(stack, "ApiPermissionsForAppConfig", {
statements: [
new iam.PolicyStatement({
actions: [
"appconfig:StartConfigurationSession",
"appconfig:GetLatestConfiguration",
"appconfig:GetConfiguration",
"apigateway:GET",
],
resources: ["*"],
}),
new iam.PolicyStatement({
actions: ["geo:SearchPlaceIndexForText"],
resources: [`arn:aws:geo:*`],
effect: iam.Effect.ALLOW,
}),
],
})
);
// CloudWatch Alarms and Notifications
// Allow the service to publish metrics to cloudwatch
Metric.grantPutMetricData(fargateService.service.taskDefinition.taskRole);
const fargateCPUAlarm = fargateService.service
.metricCpuUtilization()
.createAlarm(stack, "CPUAlarm", {
threshold: 80,
evaluationPeriods: 3,
datapointsToAlarm: 2,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
alarmAction && fargateCPUAlarm.addAlarmAction(alarmAction);
alarmAction && fargateCPUAlarm.addOkAction(alarmAction);
const fargateMemoryAlarm = fargateService.service
.metricMemoryUtilization()
.createAlarm(stack, "MemoryAlarm", {
threshold: 70,
evaluationPeriods: 3,
datapointsToAlarm: 2,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
alarmAction && fargateMemoryAlarm.addAlarmAction(alarmAction);
alarmAction && fargateMemoryAlarm.addOkAction(alarmAction);
// allow the NLB to talk to fargate
fargateService.service.connections.allowFrom(
ec2.Peer.ipv4(vpc.vpcCidrBlock),
ec2.Port.allTraffic(),
"Allow traffic from within the VPC to the service secure port"
);
fargateServiceAlb.service.connections.allowFrom(
ec2.Peer.ipv4(vpc.vpcCidrBlock),
ec2.Port.allTraffic(),
"Allow traffic from within the VPC to the service secure port"
);
// TODO: #489 ain't the most secure, but the above code doesn't work as CDK complains we can't use the connections
// from the cluster created above, should be fine for now as it will only accept connections in the VPC
fargateService.service.connections.allowFromAnyIpv4(ec2.Port.allTcp());
fargateServiceAlb.service.connections.allowFromAnyIpv4(ec2.Port.allTcp());
// TODO DEPRECATED start
// This speeds up deployments so the tasks are swapped quicker.
// See for details: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#deregistration-delay
fargateService.targetGroup.setAttribute("deregistration_delay.timeout_seconds", "17");
// This also speeds up deployments so the health checks have a faster turnaround.
// See for details: https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html
fargateService.targetGroup.configureHealthCheck({
healthyThresholdCount: 2,
interval: Duration.seconds(10),
});
// TODO DEPRECATED end
// hookup autoscaling based on 90% thresholds
const scaling = fargateService.service.autoScaleTaskCount({
minCapacity: isProd(props.config) ? 2 : 1,
maxCapacity: isProd(props.config) ? 10 : 2,
});
scaling.scaleOnCpuUtilization("autoscale_cpu", {
targetUtilizationPercent: 90,
scaleInCooldown: Duration.minutes(2),
scaleOutCooldown: Duration.seconds(30),
});
scaling.scaleOnMemoryUtilization("autoscale_mem", {
targetUtilizationPercent: 90,
scaleInCooldown: Duration.minutes(2),
scaleOutCooldown: Duration.seconds(30),
});
return {
cluster,
service: fargateService,
serverAddress: apiUrl,
loadBalancerAddress: serverAddress,
apiServiceAdditional: fargateServiceAlb.service,
};
}