@bitblit/ratchet-epsilon-deployment 4.0.85-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/License.txt +13 -0
  3. package/README.md +242 -0
  4. package/dist/cjs/build/ratchet-epsilon-deployment-info.js +18 -0
  5. package/dist/cjs/deployment/cdk/epsilon-api-stack-props.js +2 -0
  6. package/dist/cjs/deployment/cdk/epsilon-api-stack.js +182 -0
  7. package/dist/cjs/deployment/cdk/epsilon-stack-util.js +71 -0
  8. package/dist/cjs/deployment/cdk/epsilon-website-stack-props.js +8 -0
  9. package/dist/cjs/deployment/cdk/epsilon-website-stack.js +157 -0
  10. package/dist/cjs/deployment/cdk/simple-additional-s3-website-mapping.js +2 -0
  11. package/dist/cjs/index.js +10 -0
  12. package/dist/es/build/ratchet-epsilon-deployment-info.js +14 -0
  13. package/dist/es/deployment/cdk/epsilon-api-stack-props.js +1 -0
  14. package/dist/es/deployment/cdk/epsilon-api-stack.js +178 -0
  15. package/dist/es/deployment/cdk/epsilon-stack-util.js +67 -0
  16. package/dist/es/deployment/cdk/epsilon-website-stack-props.js +5 -0
  17. package/dist/es/deployment/cdk/epsilon-website-stack.js +151 -0
  18. package/dist/es/deployment/cdk/simple-additional-s3-website-mapping.js +1 -0
  19. package/dist/es/index.js +7 -0
  20. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  21. package/dist/tsconfig.es.tsbuildinfo +1 -0
  22. package/dist/tsconfig.types.tsbuildinfo +1 -0
  23. package/dist/types/build/ratchet-epsilon-deployment-info.d.ts +5 -0
  24. package/dist/types/deployment/cdk/epsilon-api-stack-props.d.ts +17 -0
  25. package/dist/types/deployment/cdk/epsilon-api-stack.d.ts +9 -0
  26. package/dist/types/deployment/cdk/epsilon-stack-util.d.ts +13 -0
  27. package/dist/types/deployment/cdk/epsilon-website-stack-props.d.ts +15 -0
  28. package/dist/types/deployment/cdk/epsilon-website-stack.d.ts +13 -0
  29. package/dist/types/deployment/cdk/simple-additional-s3-website-mapping.d.ts +4 -0
  30. package/dist/types/index.d.ts +10 -0
  31. package/package.json +71 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,177 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Notes]
9
+
10
+ The comments above about changelogs and semantic versioning start about 2022-09-05. I'm trying to be better about
11
+ documenting things now, but earlier versions of Ratchet don't necessarily fully follow semantic versioning.
12
+
13
+ Alpha releases are exactly what they sound like - places where I am trying out new things that aren't ready for prime
14
+ time, but I need published to see how they interact with the rest of my software ecosystem. If you use an alpha
15
+ package without knowing why it is alpha you'll get exactly what you deserve.
16
+
17
+ ## [Unreleased]
18
+
19
+ - Currently, expanding Epsilon to take advantage of CDK for my most common deployments
20
+
21
+ ## [4.0.x] - In Process
22
+
23
+ - Added ability to serve HTTPS from the sample local server
24
+ - Switched to AWS SDK version 3
25
+
26
+ ## [3.3.x] - 2023-01-02
27
+
28
+ ### Added
29
+
30
+ - DaemonHandler and associated classes to make it easy to expose Ratchet Daemons through your REST API
31
+
32
+ ### Changed
33
+
34
+ - Changed the index files to move all deployment to its own barrel, so that if you don't use CDK you don't have to have it in your build
35
+
36
+ ## [3.2.x] - 2022-12-12
37
+
38
+ ### Changed
39
+
40
+ - Updated to newer library versions
41
+
42
+ ## [3.1.x] - 2022-11-21
43
+
44
+ ### Changed
45
+
46
+ - Updated to newer library versions
47
+ - (Backwards incompatible) Changed Local web token manipulator to be async to allow keys to be pulled from async source
48
+ - Refactored local web token manipulator to delegate all actual work to JwtRatchet
49
+ - New JwtRatchet correctly uses the exp field as seconds instead of MS (may log out old tokens, or push exp so far in the
50
+ future that changing keys is advisable)
51
+ - Updated Commander to much newer version, breaking old wiring
52
+
53
+ ## [2.1.x] - 2022-10-27
54
+
55
+ ### Changed
56
+
57
+ - Updated to newer library versions
58
+ - Official release of CDK support for "Standard" Epsilon design
59
+
60
+ ## [1.0.x] - 2022-08-24
61
+
62
+ ### Added
63
+
64
+ - Support for trace id and level in structured logs
65
+
66
+ ### Changed
67
+
68
+ - Switched to default to structured logging
69
+
70
+ ## [0.13.x] - 2022-01-26
71
+
72
+ ### Changed
73
+
74
+ - Updated AWS, switched to Github actions
75
+ - Above 0.13.10 added most basic support for ApiGatewayV2 (and Lambda Function Url) handling backwards compatibility
76
+
77
+ ## [0.12.x] - 2022-01-16
78
+
79
+ ### Changed
80
+
81
+ - Updated Apollo (GraphQL) to v3 which may be backwards incompatible
82
+
83
+ ## [0.11.x] - 2021-11-01
84
+
85
+ ### Changed
86
+
87
+ - Adding concept of inter-api events (Only useful when combining multiple related apis and decoupling)
88
+
89
+ ## [0.10.x] - 2021-09-10
90
+
91
+ ### Changed
92
+
93
+ - Deprecated Salt Mine library and moved all handling into Epsilon under "Background" handling
94
+ - Switched HTTP handling to a filter based model
95
+
96
+ ## [0.9.x] - 2021-02-28
97
+
98
+ ### Changed
99
+
100
+ - TBD
101
+
102
+ ## [0.8.x] - 2021-02-26
103
+
104
+ ### Changed
105
+
106
+ - Updated core libs
107
+ - Switched to Luxon from Moment to match Ratchet
108
+
109
+ ## [0.7.x] - 2021-01-08
110
+
111
+ ### Changed
112
+
113
+ - Updated core libs
114
+ - Added ContextUtil to get static access to the AWS context object
115
+ - Renamed apiGateway to http in config
116
+ - Add ability to log JWT parse errors at defined levels
117
+ - Added new endpoints to the sample server
118
+ - Added outbound model validation
119
+ - Added blocking on "null" literal string on query and path params
120
+ - Added request id as outbound header
121
+ - Added better (no longer crashes) handling when a null object returns from a handler
122
+
123
+ ## [0.6.x] - 2020-11-04
124
+
125
+ ### Changed
126
+
127
+ - Updated core libs
128
+ - Added richer error object and builder pattern for errors
129
+
130
+ ## [0.5.x] - 2020-09-19
131
+
132
+ ### Changed
133
+
134
+ - Updated core libs
135
+ - Moved to eslint and cleaned up
136
+
137
+ ## [0.4.x] - 2020-07-08
138
+
139
+ ### Changed
140
+
141
+ - Switched logging for GraphQL introspection calls on local-server down to silly level
142
+ - Updated to new version of libraries
143
+ - Switched to js-yaml instead of node-yaml
144
+ - Moved api-gateway package to http package to reflect that this also handles ALB endpoints
145
+
146
+ ## [0.3.x] - 2020-04-30
147
+
148
+ ### Changed
149
+
150
+ - Remapped CRON handler to be able to filter on more than just the incoming Event name. Given the new mapping,
151
+ I'd recommend just setting up an "every minute" Cloudwatch event and using filters. Filters now allow
152
+ running multiple Batch processors, eg Dev/QA/Prod
153
+ - Adding logging of request ID to output errors
154
+ - Added default error (to allow masking of 500 errors in prod and prevent information leakage)
155
+ - Allow optional access to the request context for handlers (esp for the request id, remaining time)
156
+
157
+ ## [0.2.x] - 2020-02-13
158
+
159
+ ### Changed
160
+
161
+ - TBD when I do some repo diving
162
+
163
+ ## [0.1.x] - 2019-08-02
164
+
165
+ ### Changed
166
+
167
+ - TBD when I do some repo diving
168
+
169
+ ## [0.0.x] - 2018-07-13
170
+
171
+ ### Changed
172
+
173
+ - TBD when I do some repo diving
174
+
175
+ ### Added
176
+
177
+ - Initial releases
package/License.txt ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2018 Christopher Weiss
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,242 @@
1
+ # Epsilon
2
+
3
+ A tiny library to simplify serving consistent apis from Lambda with OpenAPI
4
+
5
+ You may wish to read [the changelog](CHANGELOG.md)
6
+
7
+ # TODO:
8
+
9
+ - Discuss pros/cons of single lambda for http/batch in this document
10
+ - path/query var checking against open api doc
11
+ - check compression handling
12
+
13
+ ## How better than just using straight Node?
14
+
15
+ - Uses typescript instead of the Godforsaken straight javascript
16
+ - Handles route mapping (multiple ends, single lambda)
17
+ - Uses Promises and has a top level .catch to convert to 500
18
+ - Adds compression
19
+ - Adds CORS
20
+ - Adds JWT handling
21
+ - Consistent error handling
22
+ - Can serve static content as well
23
+ - Kinda-persistent objects allow for optimistic caching
24
+ - Built in support for Non-HTTP (Batch) processing via SaltMint, SNS, SQS, Email, etc
25
+
26
+ # How better than using Express?
27
+
28
+ - Doesn't have req/res architecture to fake so much easier to test
29
+ - OpenAPI first design
30
+ - Much lighter
31
+ - Support for backgrounding, CRON, Inter-API messaging, AWS Batch out of the box
32
+
33
+ # Other services
34
+
35
+ - Environmental service
36
+ - Simple redirects
37
+
38
+ # CDK Automatic Construction
39
+
40
+ ## Introduction
41
+
42
+ ## Prerequisites
43
+
44
+ - Any time you are doing something automated like this, I **HIGHLY RECOMMEND** setting up a billing alert first. Don't
45
+ blame me if you skip this step and then accidentally spend $1,000 next month. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html)
46
+ - CDK V2 must be bootstrapped in your account (https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)
47
+ -- e.g. (**npx cdk bootstrap aws://1234567890/us-east-1**)
48
+ - The user running the CDK deploy needs -LOTS- of AWS privs (I'll list them all later. For now, assume a bunch)
49
+ - Policy **arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole** must exist (this should be there by default)
50
+ - Policy **arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole** must exist (You may have to create it - see https://docs.aws.amazon.com/batch/latest/userguide/service_IAM_role.html)
51
+ - You should have a VPC that your Lambda's will deploy into, and you should know its id (e.g., **vpc-123456789**)
52
+ - That VPC should have one or more subnets, and you should know their ids (e.g., **05966bfadca940a88**)
53
+ - That VPC should have a security group, which probably should allow outbound traffic if you want your lambda to talk to the internet. You should know its id (e.g., **02a89a55b0f2cb4ae** - leave off the **sg-** prefix)
54
+
55
+ ## Api Setup
56
+
57
+ - Your api layer, in addition to depending on Epsilon, will need:
58
+ ** "aws-cdk-lib": (Peer version)
59
+ ** "constructs": (Peer version)
60
+ \*\* "walk": (Peer version)
61
+
62
+ ## Docker setup
63
+
64
+ ### .dockerignore
65
+
66
+ In general the docker file needs to be in a folder above both your api and cdk folders, but it must ignore
67
+ the cdk folder in that case or it will infinitely recurse
68
+
69
+ ```
70
+ # Need this here to prevent infinite recusion of cdk folder at least
71
+ .github
72
+ .idea
73
+ .yarn
74
+ .git
75
+ modules/cdk
76
+ node_modules
77
+ ```
78
+
79
+ ### DockerFile
80
+
81
+ ```
82
+ FROM public.ecr.aws/lambda/nodejs:14
83
+ COPY modules/api/package.json modules/api/gql-codegen.yml modules/api/tsconfig.json ${LAMBDA_TASK_ROOT}/
84
+ COPY modules/api/src ${LAMBDA_TASK_ROOT}/src
85
+ COPY lambda-bootstrap-shell.sh ${LAMBDA_TASK_ROOT}
86
+ RUN npm install -g yarn
87
+ RUN yarn install
88
+ RUN yarn clean-compile
89
+ ENTRYPOINT ["sh","/var/task/lambda-bootstrap-shell.sh"]
90
+ CMD [ "dist/lambda.handler" ]
91
+ ```
92
+
93
+ ### lambda-bootstrap-shell.sh
94
+
95
+ ```
96
+ #!/bin/sh
97
+ # Based on the default script in public.ecr.aws/lambda/nodejs:14, which is copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
98
+ # Modifications copyright Christopher Weiss, 2022
99
+
100
+ if [ -z "${EPSILON_RUNNING_IN_AWS_BATCH}" ]; then
101
+ if [ $# -lt 1 ]; then
102
+ echo "entrypoint requires the handler name to be the first argument" 1>&2
103
+ exit 142
104
+ fi
105
+ export _HANDLER="$1"
106
+
107
+ RUNTIME_ENTRYPOINT=/var/runtime/bootstrap
108
+ if [ -z "${AWS_LAMBDA_RUNTIME_API}" ]; then
109
+ exec /usr/local/bin/aws-lambda-rie $RUNTIME_ENTRYPOINT
110
+ else
111
+ exec $RUNTIME_ENTRYPOINT
112
+ fi
113
+ else
114
+ echo "Running Epsilon inside AWS batch - triggering direct $1 $2"
115
+ exec node dist/aws-batch-cli.js --process $1 --data $2
116
+ fi
117
+ ```
118
+
119
+ # GraphQL Support (v0.1.x and above)
120
+
121
+ If you are just doing straight GraphQL then you don't really need to use Epsilon at all (I'd recommend just
122
+ going with straight https://www.npmjs.com/package/apollo-server-lambda). However, if you want to start messing
123
+ with GraphQL while maintaining your existing OpenAPI 3.0 endpoints, Epsilon allows you to designate a regular
124
+ expression for which all matching requests are delegated to a supplied ApolloServer, bypassing Epsilon.
125
+
126
+ To do this, you must include the following libraries (They aren't marked as dependencies of Epsilon since they
127
+ aren't required if you don't support GraphQL)
128
+
129
+ ```
130
+ "apollo-server-lambda": "2.8.1",
131
+ "graphql": "14.4.2",
132
+ ```
133
+
134
+ Then, in your router-config, you must set an ApolloServer and an Apollo Regex:
135
+
136
+ ```typescript
137
+ const typeDefs = gql`
138
+ type Query {
139
+ hello: String
140
+ }
141
+ `;
142
+
143
+ // Provide resolver functions for your schema fields
144
+ const resolvers = {
145
+ Query: {
146
+ hello: () => 'Hello world!',
147
+ },
148
+ };
149
+
150
+ const server: ApolloServer = new ApolloServer({ typeDefs, resolvers });
151
+
152
+ // ...
153
+
154
+ const cfg: RouterConfig = RouterUtil.openApiYamlToRouterConfig(yamlString, handlers, authorizers, options);
155
+
156
+ // ...
157
+ cfg.apolloServer = server;
158
+ cfg.apolloCreateHandlerOptions = {
159
+ origin: '*',
160
+ credentials: true,
161
+ } as CreateHandlerOptions;
162
+ cfg.apolloRegex = new RegExp('.*graphql.*');
163
+ ```
164
+
165
+ # Usage
166
+
167
+ ## Using WebHandler to simplify the Lambda
168
+
169
+ You will configure a RouterConfig, and then create a WebHandler from that. Your lambda
170
+ function should look like:
171
+
172
+ ```
173
+ const handler: Handler = (event: APIGatewayEvent, context: Context, callback: Callback) => {
174
+ const routerConfig: RouterConfig = getMyRouterConfig(); // Implement this function
175
+ const commonHandler: WebHandler = new WebHandler(routerConfig);
176
+ commonHandler.lambdaHandler(event, context, callback);
177
+ };
178
+
179
+ export {handler};
180
+
181
+ ```
182
+
183
+ ## Using auth/AuthHandler to simplify a JWT token based auth
184
+
185
+ Your auth lambda should look like this (I here assume you are storing your encryption key in AWS
186
+ System Manager so you can keep it encrypted at rest, which you definitely should be doing):
187
+
188
+ ```
189
+
190
+ import {AuthHandler} from '@bitblit/epsilon/dist/auth/auth-handler';
191
+ import {Callback, Context, CustomAuthorizerEvent, Handler} from 'aws-lambda';
192
+ import {EnvironmentService} from '@bitblit/ratchet/dist/aws/environment-service';
193
+ import 'reflect-metadata';
194
+
195
+ const handler: Handler = (event: CustomAuthorizerEvent, context: Context, callback: Callback) => {
196
+
197
+ EnvironmentService.getConfig('MyConfigurationName').then(cfg => {
198
+ const commonAuth: AuthHandler = new AuthHandler('api.mycompany.com', cfg['encryptionKey']);
199
+ commonAuth.lambdaHandler(event, context, callback);
200
+ });
201
+ };
202
+
203
+ export {handler};
204
+
205
+ ```
206
+
207
+ This will pass through anyone with a valid JWT token. Note that Epsilon doesn't yet support role based
208
+ filtering in this version.
209
+
210
+ To create valid JWT tokens, your authentication endpoint can use the **auth/WebTokenManipulator** class like so
211
+ (after you have verified the users principal/credentials pair) :
212
+
213
+ ```
214
+ // Other authentication stuff happens up here.
215
+ const email: string = 'user-email@test.com';
216
+ const roles: string[] = ['USER','NOT-AN-ADMIN'];
217
+ const userData: any = {'other': 'stuff'};
218
+ const myConfig: any = await EnvironmentService.getConfig('MyConfigurationName'); // same as above
219
+ const encryptionKey: string = cfg['encryptionKey'];
220
+ const adminUser: any = null; // Set this if the user is an admin doing run-as (this is the admin user)
221
+ const expSec: number = 3600; // How long until this token expires in seconds
222
+
223
+ const tokenHandler: WebTokenManipulator = new WebTokenManipulator(encryptionKey, 'api.mycompany.com');
224
+ const token: string = tokenHandler.createJWTString(email, userData, roles, expSec, admin);
225
+
226
+ ```
227
+
228
+ # Notes on adding a new gateway/stage
229
+
230
+ You'll need to auth the gateway to hit the lambda (yes, as of 2018-10-13 this is still ugly) :
231
+
232
+ ```
233
+ aws lambda add-permission --function-name "arn:aws:lambda:us-east-1:{accountId}:function:{lambda-function-name}"
234
+ --source-arn "arn:aws:execute-api:us-east-1:{account number}:{api id}/*/*/*"
235
+ --principal apigateway.amazonaws.com
236
+ --statement-id b57d8a0f-08e5-407c-9093-47d7e8e840bc
237
+ --action lambda:InvokeFunction
238
+
239
+ ```
240
+
241
+ And you'll need to remember to go to IAM / Keys and authorize the new stack user to use your KMS key (if you are
242
+ using KMS to encrypt your config via SystemManager, which you should be doing)
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RatchetEpsilonDeploymentInfo = void 0;
4
+ class RatchetEpsilonDeploymentInfo {
5
+ constructor() { }
6
+ static buildInformation() {
7
+ const val = {
8
+ version: '85',
9
+ hash: '7b2bd151314408f02450300b0d5fb0e008d38deb',
10
+ branch: 'alpha-2023-03-14-1',
11
+ tag: 'alpha-2023-03-14-1',
12
+ timeBuiltISO: '2023-03-14T20:58:46-0700',
13
+ notes: '',
14
+ };
15
+ return val;
16
+ }
17
+ }
18
+ exports.RatchetEpsilonDeploymentInfo = RatchetEpsilonDeploymentInfo;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EpsilonApiStack = void 0;
4
+ const aws_cdk_lib_1 = require("aws-cdk-lib");
5
+ const aws_batch_1 = require("aws-cdk-lib/aws-batch");
6
+ const aws_lambda_1 = require("aws-cdk-lib/aws-lambda");
7
+ const aws_iam_1 = require("aws-cdk-lib/aws-iam");
8
+ const aws_sns_1 = require("aws-cdk-lib/aws-sns");
9
+ const aws_sqs_1 = require("aws-cdk-lib/aws-sqs");
10
+ const aws_sns_subscriptions_1 = require("aws-cdk-lib/aws-sns-subscriptions");
11
+ const aws_events_1 = require("aws-cdk-lib/aws-events");
12
+ const aws_events_targets_1 = require("aws-cdk-lib/aws-events-targets");
13
+ const aws_ecr_assets_1 = require("aws-cdk-lib/aws-ecr-assets");
14
+ const ratchet_common_1 = require("@bitblit/ratchet-common");
15
+ const epsilon_stack_util_1 = require("./epsilon-stack-util");
16
+ const ratchet_epsilon_deployment_info_1 = require("../../build/ratchet-epsilon-deployment-info");
17
+ class EpsilonApiStack extends aws_cdk_lib_1.Stack {
18
+ constructor(scope, id, props) {
19
+ super(scope, id, props);
20
+ const dockerImageAsset = new aws_ecr_assets_1.DockerImageAsset(this, id + 'DockerImage', {
21
+ directory: props.dockerFileFolder,
22
+ file: props.dockerFileName,
23
+ });
24
+ const dockerImageCode = aws_lambda_1.DockerImageCode.fromImageAsset(props.dockerFileFolder, { file: props.dockerFileName });
25
+ const notificationTopic = new aws_sns_1.Topic(this, id + 'WorkNotificationTopic');
26
+ const workQueue = new aws_sqs_1.Queue(this, id + 'WorkQueue', {
27
+ fifo: true,
28
+ retentionPeriod: aws_cdk_lib_1.Duration.hours(8),
29
+ visibilityTimeout: aws_cdk_lib_1.Duration.minutes(5),
30
+ contentBasedDeduplication: true,
31
+ ...props,
32
+ });
33
+ const interApiGenericEventTopic = new aws_sns_1.Topic(this, id + 'InterApiTopic');
34
+ const epsilonEnv = {
35
+ EPSILON_AWS_REGION: ratchet_common_1.StringRatchet.safeString(aws_cdk_lib_1.Stack.of(this).region),
36
+ EPSILON_AWS_AVAILABILITY_ZONES: ratchet_common_1.StringRatchet.safeString(JSON.stringify(aws_cdk_lib_1.Stack.of(this).availabilityZones)),
37
+ EPSILON_BACKGROUND_SQS_QUEUE_URL: ratchet_common_1.StringRatchet.safeString(workQueue.queueUrl),
38
+ EPSILON_BACKGROUND_SNS_TOPIC_ARN: ratchet_common_1.StringRatchet.safeString(notificationTopic.topicArn),
39
+ EPSILON_INTER_API_EVENT_TOPIC_ARN: ratchet_common_1.StringRatchet.safeString(interApiGenericEventTopic.topicArn),
40
+ EPSILON_LIB_BUILD_HASH: ratchet_common_1.StringRatchet.safeString(ratchet_epsilon_deployment_info_1.RatchetEpsilonDeploymentInfo.buildInformation().hash),
41
+ EPSILON_LIB_BUILD_TIME: ratchet_common_1.StringRatchet.safeString(ratchet_epsilon_deployment_info_1.RatchetEpsilonDeploymentInfo.buildInformation().timeBuiltISO),
42
+ EPSILON_LIB_BUILD_BRANCH_OR_TAG: ratchet_common_1.StringRatchet.safeString(ratchet_epsilon_deployment_info_1.RatchetEpsilonDeploymentInfo.buildInformation().branch || ratchet_epsilon_deployment_info_1.RatchetEpsilonDeploymentInfo.buildInformation().tag),
43
+ EPSILON_LIB_BUILD_VERSION: ratchet_common_1.StringRatchet.safeString(ratchet_epsilon_deployment_info_1.RatchetEpsilonDeploymentInfo.buildInformation().version),
44
+ };
45
+ const env = Object.assign({}, props.extraEnvironmentalVars || {}, epsilonEnv);
46
+ const ecsRole = new aws_iam_1.Role(this, id + 'AwsEcsRole', {
47
+ assumedBy: new aws_iam_1.ServicePrincipal('ec2.amazonaws.com'),
48
+ inlinePolicies: {
49
+ root: new aws_iam_1.PolicyDocument({
50
+ statements: epsilon_stack_util_1.EpsilonStackUtil.ECS_POLICY_STATEMENTS,
51
+ }),
52
+ },
53
+ });
54
+ const ecsInstanceProfile = new aws_iam_1.CfnInstanceProfile(this, id + 'EcsInstanceProfile', {
55
+ path: '/',
56
+ roles: [ecsRole.roleName],
57
+ });
58
+ const jobRole = new aws_iam_1.Role(this, id + 'AwsBatchRole', {
59
+ assumedBy: new aws_iam_1.ServicePrincipal('ecs-tasks.amazonaws.com'),
60
+ managedPolicies: [aws_iam_1.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaVPCAccessExecutionRole')],
61
+ inlinePolicies: {
62
+ root: new aws_iam_1.PolicyDocument({
63
+ statements: epsilon_stack_util_1.EpsilonStackUtil.createDefaultPolicyStatementList(props, workQueue, notificationTopic, interApiGenericEventTopic),
64
+ }),
65
+ },
66
+ });
67
+ const compEnvProps = {
68
+ replaceComputeEnvironment: false,
69
+ computeResources: {
70
+ minvCpus: 0,
71
+ maxvCpus: 16,
72
+ instanceTypes: ['optimal'],
73
+ instanceRole: ecsInstanceProfile.attrArn,
74
+ ec2KeyPair: props.batchInstancesEc2KeyPairName,
75
+ type: 'EC2',
76
+ subnets: props.vpcSubnetIds.map((s) => 'subnet-' + s),
77
+ securityGroupIds: props.lambdaSecurityGroupIds.map((s) => 'sg-' + s),
78
+ allocationStrategy: 'BEST_FIT',
79
+ },
80
+ serviceRole: 'arn:aws:iam::' + props.env.account + ':role/AWSBatchServiceRole',
81
+ type: 'MANAGED',
82
+ state: 'ENABLED',
83
+ };
84
+ const compEnv = new aws_batch_1.CfnComputeEnvironment(this, id + 'ComputeEnv', compEnvProps);
85
+ const batchJobQueueProps = {
86
+ state: 'ENABLED',
87
+ priority: 1,
88
+ computeEnvironmentOrder: [
89
+ {
90
+ computeEnvironment: compEnv.attrComputeEnvironmentArn,
91
+ order: 1,
92
+ },
93
+ ],
94
+ tags: {
95
+ tagsKey: id,
96
+ },
97
+ };
98
+ const batchJobQueue = new aws_batch_1.CfnJobQueue(this, id + 'BatchJobQueue', batchJobQueueProps);
99
+ const batchEnvVars = epsilon_stack_util_1.EpsilonStackUtil.toEnvironmentVariables([
100
+ env,
101
+ props.extraEnvironmentalVars || {},
102
+ {
103
+ EPSILON_RUNNING_IN_AWS_BATCH: true,
104
+ },
105
+ ]);
106
+ const jobProps = {
107
+ type: 'container',
108
+ platformCapabilities: ['EC2'],
109
+ containerProperties: {
110
+ mountPoints: [],
111
+ volumes: [],
112
+ memory: 4294,
113
+ privileged: false,
114
+ jobRoleArn: jobRole.roleArn,
115
+ readonlyRootFilesystem: false,
116
+ vcpus: 1,
117
+ image: dockerImageAsset.imageUri,
118
+ command: ['Ref::taskName', 'Ref::taskData', 'Ref::traceId', 'Ref::traceDepth'],
119
+ environment: batchEnvVars,
120
+ },
121
+ };
122
+ const jobDef = new aws_batch_1.CfnJobDefinition(this, id + 'JobDefinition', jobProps);
123
+ const lambdaRole = new aws_iam_1.Role(this, 'customRole', {
124
+ roleName: id + 'LambdaCustomRole',
125
+ assumedBy: new aws_iam_1.ServicePrincipal('lambda.amazonaws.com'),
126
+ managedPolicies: [aws_iam_1.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaVPCAccessExecutionRole')],
127
+ inlinePolicies: {
128
+ root: new aws_iam_1.PolicyDocument({
129
+ statements: epsilon_stack_util_1.EpsilonStackUtil.createDefaultPolicyStatementList(props, workQueue, notificationTopic, interApiGenericEventTopic),
130
+ }),
131
+ },
132
+ });
133
+ env['EPSILON_AWS_BATCH_JOB_DEFINITION_ARN'] = jobDef.ref;
134
+ env['EPSILON_AWS_BATCH_JOB_QUEUE_ARN'] = batchJobQueue.ref;
135
+ this.webHandler = new aws_lambda_1.DockerImageFunction(this, id + 'Web', {
136
+ retryAttempts: 2,
137
+ memorySize: props.webMemorySizeMb || 128,
138
+ ephemeralStorageSize: aws_cdk_lib_1.Size.mebibytes(512),
139
+ timeout: aws_cdk_lib_1.Duration.seconds(props.webTimeoutSeconds || 20),
140
+ code: dockerImageCode,
141
+ role: lambdaRole,
142
+ environment: env,
143
+ });
144
+ if ((props === null || props === void 0 ? void 0 : props.webLambdaPingMinutes) && props.webLambdaPingMinutes > 0) {
145
+ const rule = new aws_events_1.Rule(this, id + 'WebKeepaliveRule', {
146
+ schedule: aws_events_1.Schedule.rate(aws_cdk_lib_1.Duration.minutes(Math.ceil(props.webLambdaPingMinutes))),
147
+ });
148
+ rule.addTarget(new aws_events_targets_1.LambdaFunction(this.webHandler));
149
+ }
150
+ const fnUrl = this.webHandler.addFunctionUrl({
151
+ authType: aws_lambda_1.FunctionUrlAuthType.NONE,
152
+ cors: {
153
+ allowedOrigins: ['*'],
154
+ allowedHeaders: ['Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key'],
155
+ allowedMethods: [aws_lambda_1.HttpMethod.ALL],
156
+ allowCredentials: true,
157
+ },
158
+ });
159
+ this.backgroundHandler = new aws_lambda_1.DockerImageFunction(this, id + 'Background', {
160
+ retryAttempts: 2,
161
+ memorySize: props.backgroundMemorySizeMb || 3000,
162
+ ephemeralStorageSize: aws_cdk_lib_1.Size.mebibytes(512),
163
+ timeout: aws_cdk_lib_1.Duration.seconds(props.backgroundTimeoutSeconds || 900),
164
+ code: dockerImageCode,
165
+ role: lambdaRole,
166
+ environment: env,
167
+ });
168
+ notificationTopic.addSubscription(new aws_sns_subscriptions_1.LambdaSubscription(this.backgroundHandler));
169
+ interApiGenericEventTopic.addSubscription(new aws_sns_subscriptions_1.LambdaSubscription(this.backgroundHandler));
170
+ const rule = new aws_events_1.Rule(this, id + 'CronRule', {
171
+ schedule: aws_events_1.Schedule.rate(aws_cdk_lib_1.Duration.minutes(1)),
172
+ });
173
+ rule.addTarget(new aws_events_targets_1.LambdaFunction(this.backgroundHandler));
174
+ this.apiDomain = aws_cdk_lib_1.Lazy.uncachedString({
175
+ produce: (context) => {
176
+ const resolved = context.resolve(fnUrl.url);
177
+ return { 'Fn::Select': [2, { 'Fn::Split': ['/', resolved] }] };
178
+ },
179
+ });
180
+ }
181
+ }
182
+ exports.EpsilonApiStack = EpsilonApiStack;