@guardian/cdk 50.10.5 → 50.10.7
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.
- package/lib/aspects/cfn-include-reporter.js.map +1 -1
- package/lib/aspects/cfn-parameter-reporter.js.map +1 -1
- package/lib/bin/aws-credential-provider.js.map +1 -1
- package/lib/bin/commands/account-readiness/index.js.map +1 -1
- package/lib/bin/commands/account-readiness/ssm.js.map +1 -1
- package/lib/bin/commands/new-project/index.js.map +1 -1
- package/lib/bin/commands/new-project/utils/app.js.map +1 -1
- package/lib/bin/commands/new-project/utils/init.js +1 -1
- package/lib/bin/commands/new-project/utils/init.js.map +1 -1
- package/lib/bin/commands/new-project/utils/snapshot.js.map +1 -1
- package/lib/bin/commands/new-project/utils/utils.js.map +1 -1
- package/lib/bin/index.js.map +1 -1
- package/lib/constants/ssm-parameter-paths.js.map +1 -1
- package/lib/constructs/autoscaling/asg.js.map +1 -1
- package/lib/constructs/core/stack.js.map +1 -1
- package/lib/constructs/dns/dns-records.js.map +1 -1
- package/lib/constructs/ec2/vpc.js.map +1 -1
- package/lib/constructs/ecs/ecs-task.js.map +1 -1
- package/lib/constructs/iam/policies/base-policy.js.map +1 -1
- package/lib/constructs/iam/roles/github-actions.js.map +1 -1
- package/lib/constructs/vpc/vpc.js.map +1 -1
- package/lib/experimental/constructs/error-budget-alarm.js.map +1 -1
- package/lib/experimental/constructs/iam/roles/fastly-kinesis-log.js.map +1 -1
- package/lib/experimental/patterns/kinesis-lambda.js.map +1 -1
- package/lib/experimental/patterns/sns-lambda.js.map +1 -1
- package/lib/experimental/riff-raff-yaml-file/deployments/autoscaling.js.map +1 -1
- package/lib/experimental/riff-raff-yaml-file/deployments/cloudformation.js.map +1 -1
- package/lib/experimental/riff-raff-yaml-file/deployments/lambda.js.map +1 -1
- package/lib/experimental/riff-raff-yaml-file/group-by.js.map +1 -1
- package/lib/experimental/riff-raff-yaml-file/index.js.map +1 -1
- package/lib/patterns/api-multiple-lambdas.js.map +1 -1
- package/lib/patterns/ec2-app/base.js.map +1 -1
- package/lib/types/access.js.map +1 -1
- package/lib/utils/cli/vpc.js.map +1 -1
- package/lib/utils/security-groups/helpers.js.map +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github-actions.js","sourceRoot":"","sources":["../../../../src/constructs/iam/roles/github-actions.ts"],"names":[],"mappings":";;;AAAA,6CAAqD;AACrD,iDAAyD;AAGzD,mCAAiC;AAEjC,MAAM,sCAAsC,GAAG,qCAAqC,CAAC;AAErF;;;;;;EAME;AACF,MAAM,kDAAkD,GAAG;IACzD,0CAA0C;IAC1C,0CAA0C;CAC3C,CAAC;AAcF,MAAM,kCAAkC,GAAG;IACzC,QAAQ,EAAE,CAAC,EAAE,kBAAkB,EAAE,YAAY,EAAsC,EAAU,EAAE,CAC7F,QAAQ,kBAAkB,IAAI,YAAY,IAAI,GAAG,EAAE;CACtD,CAAC;AAEF,MAAM,yBAAyB,GAAuC;IACpE,kBAAkB,EAAE,UAAU;IAC9B,YAAY,EAAE,GAAG;CAClB,CAAC;AAeF;;;;;;;;;GASG;AACH,MAAM,kBAAmB,SAAQ,yBAAW;IAC1C,YAAY,KAAc;QACxB,KAAK,CAAC,KAAK,EAAE,mBAAmB,EAAE;YAChC,IAAI,EAAE,wBAAwB;YAC9B,UAAU,EAAE;gBACV,GAAG,EAAE,WAAW,sCAAsC,EAAE;gBACxD,YAAY,EAAE,CAAC,mBAAmB,CAAC;gBACnC,cAAc,EAAE,kDAAkD;aACnE;SACF,CAAC,CAAC;IACL,CAAC;CACF;AAED;;;;;;;;GAQG;AACH,MAAa,mBAAoB,SAAQ,cAAM;IAC7C,YAAY,KAAc,EAAE,KAA+B;QACzD,KAAK,CAAC,KAAK,EAAE,mBAAmB,EAAE;YAChC,SAAS,EAAE,IAAI,4BAAkB,CAC/B,IAAI,kBAAkB,CAAC,KAAK,CAAC,CAAC,GAAG,EACjC;gBACE,UAAU,EAAE;oBACV,CAAC,GAAG,sCAAsC,MAAM,CAAC,EAAE,kCAAkC,CAAC,QAAQ,CAC5F,KAAK,CAAC,SAAS,IAAI,yBAAyB,CAC7C;iBACF;aACF,EACD,+BAA+B,CAChC;SACF,CAAC,CAAC;QAEH,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAEpD,IAAI,uBAAS,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;CACF;AApBD,kDAoBC","sourcesContent":["import { CfnOutput, CfnResource } from \"aws-cdk-lib\";\nimport { FederatedPrincipal } from \"aws-cdk-lib/aws-iam\";\nimport type { GuStack } from \"../../core\";\nimport type { GuPolicy } from \"../policies\";\nimport { GuRole } from \"./roles\";\n\nconst GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN = \"token.actions.githubusercontent.com\";\n\n/*\nThumbprint of `GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN`.\n\nSee:\n - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html\n - https://github.blog/changelog/2023-06-27-github-actions-update-on-oidc-integration-with-aws/\n*/\nconst GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN_THUMBPRINTS = [\n \"6938fd4d98bab03faadb97b34396831e3780aea1\",\n \"1c58a3a8518e8759bf075b76b750d4f2df264fcd\",\n];\n\nexport interface GuGithubActionsRepositoryCondition {\n /**\n * The GitHub organisation/user to constrain the IAM Role to.\n */\n githubOrganisation: string;\n\n /**\n * Repositories to constrain the IAM Role to.\n */\n repositories?: string;\n}\n\nconst GuGithubActionsRepositoryCondition = {\n toString: ({ githubOrganisation, repositories }: GuGithubActionsRepositoryCondition): string =>\n `repo:${githubOrganisation}/${repositories ?? \"*\"}`,\n};\n\nconst ALL_GUARDIAN_REPOSITORIES: GuGithubActionsRepositoryCondition = {\n githubOrganisation: \"guardian\",\n repositories: \"*\",\n};\n\nexport interface GuGithubActionsRoleProps {\n /**\n * A list of IAM Policies for the GitHub Action.\n */\n policies: GuPolicy[];\n\n /**\n * Repositories where GitHub Actions can assumes this role.\n * Defaults to [[`ALL_GUARDIAN_REPOSITORIES`]].\n */\n condition?: GuGithubActionsRepositoryCondition;\n}\n\n/*\nAWS CDK implements an OIDCProvider as a custom resource.\nThis requires a lambda to be deployed into the account.\nAs far as I can tell, the lambda is automating the setting of `ThumbprintList`, which is quite generic.\nIt's simpler for us to be specific here.\n\nSee:\n - https://github.com/aws/aws-cdk/blob/851c8ca9989856fa61496ff113f9cb8c66d02f3b/packages/%40aws-cdk/aws-iam/lib/oidc-provider.ts\n - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html\n */\nclass GitHubOidcProvider extends CfnResource {\n constructor(scope: GuStack) {\n super(scope, \"GithubActionsOidc\", {\n type: \"AWS::IAM::OIDCProvider\",\n properties: {\n Url: `https://${GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN}`,\n ClientIdList: [\"sts.amazonaws.com\"],\n ThumbprintList: GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN_THUMBPRINTS,\n },\n });\n }\n}\n\n/**\n * A construct to create an IAM role for GitHub Actions to assume via `AssumeRoleWithWebIdentity`.\n *\n * An Output will be added to the stack with the Role's ARN for use with https://github.com/aws-actions/configure-aws-credentials.\n *\n * See:\n * - https://github.com/aws-actions/configure-aws-credentials\n * - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html\n */\nexport class GuGithubActionsRole extends GuRole {\n constructor(scope: GuStack, props: GuGithubActionsRoleProps) {\n super(scope, \"GithubActionsRole\", {\n assumedBy: new FederatedPrincipal(\n new GitHubOidcProvider(scope).ref,\n {\n StringLike: {\n [`${GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN}:sub`]: GuGithubActionsRepositoryCondition.toString(\n props.condition ?? ALL_GUARDIAN_REPOSITORIES
|
|
1
|
+
{"version":3,"file":"github-actions.js","sourceRoot":"","sources":["../../../../src/constructs/iam/roles/github-actions.ts"],"names":[],"mappings":";;;AAAA,6CAAqD;AACrD,iDAAyD;AAGzD,mCAAiC;AAEjC,MAAM,sCAAsC,GAAG,qCAAqC,CAAC;AAErF;;;;;;EAME;AACF,MAAM,kDAAkD,GAAG;IACzD,0CAA0C;IAC1C,0CAA0C;CAC3C,CAAC;AAcF,MAAM,kCAAkC,GAAG;IACzC,QAAQ,EAAE,CAAC,EAAE,kBAAkB,EAAE,YAAY,EAAsC,EAAU,EAAE,CAC7F,QAAQ,kBAAkB,IAAI,YAAY,IAAI,GAAG,EAAE;CACtD,CAAC;AAEF,MAAM,yBAAyB,GAAuC;IACpE,kBAAkB,EAAE,UAAU;IAC9B,YAAY,EAAE,GAAG;CAClB,CAAC;AAeF;;;;;;;;;GASG;AACH,MAAM,kBAAmB,SAAQ,yBAAW;IAC1C,YAAY,KAAc;QACxB,KAAK,CAAC,KAAK,EAAE,mBAAmB,EAAE;YAChC,IAAI,EAAE,wBAAwB;YAC9B,UAAU,EAAE;gBACV,GAAG,EAAE,WAAW,sCAAsC,EAAE;gBACxD,YAAY,EAAE,CAAC,mBAAmB,CAAC;gBACnC,cAAc,EAAE,kDAAkD;aACnE;SACF,CAAC,CAAC;IACL,CAAC;CACF;AAED;;;;;;;;GAQG;AACH,MAAa,mBAAoB,SAAQ,cAAM;IAC7C,YAAY,KAAc,EAAE,KAA+B;QACzD,KAAK,CAAC,KAAK,EAAE,mBAAmB,EAAE;YAChC,SAAS,EAAE,IAAI,4BAAkB,CAC/B,IAAI,kBAAkB,CAAC,KAAK,CAAC,CAAC,GAAG,EACjC;gBACE,UAAU,EAAE;oBACV,CAAC,GAAG,sCAAsC,MAAM,CAAC,EAAE,kCAAkC,CAAC,QAAQ,CAC5F,KAAK,CAAC,SAAS,IAAI,yBAAyB,CAC7C;iBACF;aACF,EACD,+BAA+B,CAChC;SACF,CAAC,CAAC;QAEH,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAEpD,IAAI,uBAAS,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;CACF;AApBD,kDAoBC","sourcesContent":["import { CfnOutput, CfnResource } from \"aws-cdk-lib\";\nimport { FederatedPrincipal } from \"aws-cdk-lib/aws-iam\";\nimport type { GuStack } from \"../../core\";\nimport type { GuPolicy } from \"../policies\";\nimport { GuRole } from \"./roles\";\n\nconst GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN = \"token.actions.githubusercontent.com\";\n\n/*\nThumbprint of `GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN`.\n\nSee:\n - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html\n - https://github.blog/changelog/2023-06-27-github-actions-update-on-oidc-integration-with-aws/\n*/\nconst GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN_THUMBPRINTS = [\n \"6938fd4d98bab03faadb97b34396831e3780aea1\",\n \"1c58a3a8518e8759bf075b76b750d4f2df264fcd\",\n];\n\nexport interface GuGithubActionsRepositoryCondition {\n /**\n * The GitHub organisation/user to constrain the IAM Role to.\n */\n githubOrganisation: string;\n\n /**\n * Repositories to constrain the IAM Role to.\n */\n repositories?: string;\n}\n\nconst GuGithubActionsRepositoryCondition = {\n toString: ({ githubOrganisation, repositories }: GuGithubActionsRepositoryCondition): string =>\n `repo:${githubOrganisation}/${repositories ?? \"*\"}`,\n};\n\nconst ALL_GUARDIAN_REPOSITORIES: GuGithubActionsRepositoryCondition = {\n githubOrganisation: \"guardian\",\n repositories: \"*\",\n};\n\nexport interface GuGithubActionsRoleProps {\n /**\n * A list of IAM Policies for the GitHub Action.\n */\n policies: GuPolicy[];\n\n /**\n * Repositories where GitHub Actions can assumes this role.\n * Defaults to [[`ALL_GUARDIAN_REPOSITORIES`]].\n */\n condition?: GuGithubActionsRepositoryCondition;\n}\n\n/*\nAWS CDK implements an OIDCProvider as a custom resource.\nThis requires a lambda to be deployed into the account.\nAs far as I can tell, the lambda is automating the setting of `ThumbprintList`, which is quite generic.\nIt's simpler for us to be specific here.\n\nSee:\n - https://github.com/aws/aws-cdk/blob/851c8ca9989856fa61496ff113f9cb8c66d02f3b/packages/%40aws-cdk/aws-iam/lib/oidc-provider.ts\n - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html\n */\nclass GitHubOidcProvider extends CfnResource {\n constructor(scope: GuStack) {\n super(scope, \"GithubActionsOidc\", {\n type: \"AWS::IAM::OIDCProvider\",\n properties: {\n Url: `https://${GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN}`,\n ClientIdList: [\"sts.amazonaws.com\"],\n ThumbprintList: GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN_THUMBPRINTS,\n },\n });\n }\n}\n\n/**\n * A construct to create an IAM role for GitHub Actions to assume via `AssumeRoleWithWebIdentity`.\n *\n * An Output will be added to the stack with the Role's ARN for use with https://github.com/aws-actions/configure-aws-credentials.\n *\n * See:\n * - https://github.com/aws-actions/configure-aws-credentials\n * - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html\n */\nexport class GuGithubActionsRole extends GuRole {\n constructor(scope: GuStack, props: GuGithubActionsRoleProps) {\n super(scope, \"GithubActionsRole\", {\n assumedBy: new FederatedPrincipal(\n new GitHubOidcProvider(scope).ref,\n {\n StringLike: {\n [`${GITHUB_ACTIONS_ID_TOKEN_REQUEST_DOMAIN}:sub`]: GuGithubActionsRepositoryCondition.toString(\n props.condition ?? ALL_GUARDIAN_REPOSITORIES,\n ),\n },\n },\n \"sts:AssumeRoleWithWebIdentity\",\n ),\n });\n\n props.policies.forEach((p) => p.attachToRole(this));\n\n new CfnOutput(this, `${this.node.id}-Arn`, { value: this.roleArn });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vpc.js","sourceRoot":"","sources":["../../../src/constructs/vpc/vpc.ts"],"names":[],"mappings":";;;AAAA,6CAAoC;AAEpC,iDAAoF;AAKpF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAa,KAAM,SAAQ,aAAG;IAC5B;;;;;;;OAOG;IACK,MAAM,CAAC,0BAA0B,CAAC,EAAE,OAAO,EAAE,IAAI,EAAW;QAClE,IAAI,mBAAK,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,8JAA8J,CAC/J,CAAC;SACH;QAED,IAAI,CAAC,UAAU,CAAC,8BAA8B,OAAO,mBAAmB,EAAE;YACxE,YAAY;YACZ,YAAY;YACZ,YAAY;SACb,CAAC,CAAC;IACL,CAAC;IAED,YAAY,KAAc,EAAE,EAAU,EAAE,KAAkB;QACxD,MAAM,eAAe,GAAa;YAChC,gBAAgB,EAAE;gBAChB,EAAE,EAAE;oBACF,OAAO,EAAE,sCAA4B,CAAC,EAAE;iBACzC;gBACD,QAAQ,EAAE;oBACR,OAAO,EAAE,sCAA4B,CAAC,QAAQ;iBAC/C;aACF;YAED,mBAAmB,EAAE;gBACnB;oBACE,IAAI,EAAE,SAAS;oBACf,UAAU,EAAE,oBAAU,CAAC,MAAM;iBAC9B;gBACD;oBACE,IAAI,EAAE,aAAa;oBACnB,UAAU,EAAE,oBAAU,CAAC,mBAAmB;iBAC3C;aACF;SACF,CAAC;QAEF,8GAA8G;QAC9G,KAAK,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC;QAExC,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,eAAe,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;IACrD,CAAC;CACF;AAnDD,sBAmDC","sourcesContent":["import { Token } from \"aws-cdk-lib\";\nimport type { VpcProps } from \"aws-cdk-lib/aws-ec2\";\nimport { GatewayVpcEndpointAwsService, SubnetType, Vpc } from \"aws-cdk-lib/aws-ec2\";\nimport type { GuStack } from \"../core\";\n\nexport type GuVpcProps = VpcProps;\n\n/**\n * Construct which creates a Virtual Private Cloud.\n *\n * NOTE: This construct requires an\n * [environment](https://docs.aws.amazon.com/cdk/latest/guide/environments.html)\n * to be set to function correctly. Without this, an environment-agnostic\n * template will be produced, which will only use two AZs even if the region\n * contains more than that. To set this, set the `env` prop when instantiating\n * your stack.\n *\n * NOTE: If using this construct outside eu-west-1, you'll need to commit the\n * `cdk.context.json` file that's created after synthesising locally.\n *\n * Be aware that account IDs are considered sensitive information and should NOT\n * be committed to public repos.\n *\n * The VPC is provisioned with a public and private subnet for each availability\n * zone, with IPs spread evenly across these. Instances in private subnets\n * cannot be accessed directly over the internet. You should locate services in\n * instances in the private subnets, and provide HTTP(S) as required via load\n * balancers living in the public subnets.\n *\n * A CIDR block is a combined IP and network mask that specifies the IP\n * addresses in your VPC. For testing purposes any (AWS supported) CIDR block\n * will do, but for production you should:\n *\n * - use a /21 network mask (providing up to 2048 IPs, which is plenty for most\n * accounts)\n * - ask Enterprise Tech for an IP address to go with this range (so that\n * peering with other company VPCs is possible without IP clashes)\n *\n * A managed NAT is created for each private subnet to allow access to the\n * internet.\n *\n * For recommendations on how best to configure your VPC see:\n * https://github.com/guardian/recommendations/blob/main/AWS.md#vpc\n *\n * For more information on VPCs and AWS see:\n * https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html.\n */\nexport class GuVpc extends Vpc {\n /**\n * Programmatically sets the CDK context with a list of AZs for eu-west-1.\n * This means consuming stacks do NOT have to commit a `cdk.context.json`\n * file when using this construct in eu-west-1.\n *\n * @throws {Error} if the account ID has not been explicitly set on the parent GuStack\n * @private\n */\n private static setAvailabilityZoneContext({ account, node }: GuStack) {\n if (Token.isUnresolved(account)) {\n throw new Error(\n `Account ID not set - the resulting VPC might not be shaped how you'd expect. See https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.StackProps.html#env
|
|
1
|
+
{"version":3,"file":"vpc.js","sourceRoot":"","sources":["../../../src/constructs/vpc/vpc.ts"],"names":[],"mappings":";;;AAAA,6CAAoC;AAEpC,iDAAoF;AAKpF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAa,KAAM,SAAQ,aAAG;IAC5B;;;;;;;OAOG;IACK,MAAM,CAAC,0BAA0B,CAAC,EAAE,OAAO,EAAE,IAAI,EAAW;QAClE,IAAI,mBAAK,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,8JAA8J,CAC/J,CAAC;SACH;QAED,IAAI,CAAC,UAAU,CAAC,8BAA8B,OAAO,mBAAmB,EAAE;YACxE,YAAY;YACZ,YAAY;YACZ,YAAY;SACb,CAAC,CAAC;IACL,CAAC;IAED,YAAY,KAAc,EAAE,EAAU,EAAE,KAAkB;QACxD,MAAM,eAAe,GAAa;YAChC,gBAAgB,EAAE;gBAChB,EAAE,EAAE;oBACF,OAAO,EAAE,sCAA4B,CAAC,EAAE;iBACzC;gBACD,QAAQ,EAAE;oBACR,OAAO,EAAE,sCAA4B,CAAC,QAAQ;iBAC/C;aACF;YAED,mBAAmB,EAAE;gBACnB;oBACE,IAAI,EAAE,SAAS;oBACf,UAAU,EAAE,oBAAU,CAAC,MAAM;iBAC9B;gBACD;oBACE,IAAI,EAAE,aAAa;oBACnB,UAAU,EAAE,oBAAU,CAAC,mBAAmB;iBAC3C;aACF;SACF,CAAC;QAEF,8GAA8G;QAC9G,KAAK,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC;QAExC,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,eAAe,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;IACrD,CAAC;CACF;AAnDD,sBAmDC","sourcesContent":["import { Token } from \"aws-cdk-lib\";\nimport type { VpcProps } from \"aws-cdk-lib/aws-ec2\";\nimport { GatewayVpcEndpointAwsService, SubnetType, Vpc } from \"aws-cdk-lib/aws-ec2\";\nimport type { GuStack } from \"../core\";\n\nexport type GuVpcProps = VpcProps;\n\n/**\n * Construct which creates a Virtual Private Cloud.\n *\n * NOTE: This construct requires an\n * [environment](https://docs.aws.amazon.com/cdk/latest/guide/environments.html)\n * to be set to function correctly. Without this, an environment-agnostic\n * template will be produced, which will only use two AZs even if the region\n * contains more than that. To set this, set the `env` prop when instantiating\n * your stack.\n *\n * NOTE: If using this construct outside eu-west-1, you'll need to commit the\n * `cdk.context.json` file that's created after synthesising locally.\n *\n * Be aware that account IDs are considered sensitive information and should NOT\n * be committed to public repos.\n *\n * The VPC is provisioned with a public and private subnet for each availability\n * zone, with IPs spread evenly across these. Instances in private subnets\n * cannot be accessed directly over the internet. You should locate services in\n * instances in the private subnets, and provide HTTP(S) as required via load\n * balancers living in the public subnets.\n *\n * A CIDR block is a combined IP and network mask that specifies the IP\n * addresses in your VPC. For testing purposes any (AWS supported) CIDR block\n * will do, but for production you should:\n *\n * - use a /21 network mask (providing up to 2048 IPs, which is plenty for most\n * accounts)\n * - ask Enterprise Tech for an IP address to go with this range (so that\n * peering with other company VPCs is possible without IP clashes)\n *\n * A managed NAT is created for each private subnet to allow access to the\n * internet.\n *\n * For recommendations on how best to configure your VPC see:\n * https://github.com/guardian/recommendations/blob/main/AWS.md#vpc\n *\n * For more information on VPCs and AWS see:\n * https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html.\n */\nexport class GuVpc extends Vpc {\n /**\n * Programmatically sets the CDK context with a list of AZs for eu-west-1.\n * This means consuming stacks do NOT have to commit a `cdk.context.json`\n * file when using this construct in eu-west-1.\n *\n * @throws {Error} if the account ID has not been explicitly set on the parent GuStack\n * @private\n */\n private static setAvailabilityZoneContext({ account, node }: GuStack) {\n if (Token.isUnresolved(account)) {\n throw new Error(\n `Account ID not set - the resulting VPC might not be shaped how you'd expect. See https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.StackProps.html#env`,\n );\n }\n\n node.setContext(`availability-zones:account=${account}:region=eu-west-1`, [\n \"eu-west-1a\",\n \"eu-west-1b\",\n \"eu-west-1c\",\n ]);\n }\n\n constructor(scope: GuStack, id: string, props?: GuVpcProps) {\n const defaultVpcProps: VpcProps = {\n gatewayEndpoints: {\n s3: {\n service: GatewayVpcEndpointAwsService.S3,\n },\n dynamodb: {\n service: GatewayVpcEndpointAwsService.DYNAMODB,\n },\n },\n\n subnetConfiguration: [\n {\n name: \"ingress\",\n subnetType: SubnetType.PUBLIC,\n },\n {\n name: \"application\",\n subnetType: SubnetType.PRIVATE_WITH_EGRESS,\n },\n ],\n };\n\n // Set the context BEFORE the `super` call to avoid `Error: Cannot set context after children have been added`\n GuVpc.setAvailabilityZoneContext(scope);\n\n super(scope, id, { ...defaultVpcProps, ...props });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-budget-alarm.js","sourceRoot":"","sources":["../../../src/experimental/constructs/error-budget-alarm.ts"],"names":[],"mappings":";;;AAAA,6CAAuC;AAEvC,+DAQoC;AACpC,+EAA+D;AAE/D,iDAA4C;AAC5C,2CAAuC;AAuDvC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,8BAA+B,SAAQ,sBAAS;IAC3D,YAAY,KAAc,EAAE,KAA4B;QACtD,MAAM,mBAAmB,GAAG,IAAI,CAAC;QACjC,MAAM,oBAAoB,GAAG,MAAM,CAAC;QACpC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,IAAI,mBAAmB,IAAI,KAAK,CAAC,SAAS,IAAI,oBAAoB,CAAC,EAAE;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CAAC,QAAQ,CAAC;YAC5D,QAAQ,CAAC,2BAA2B,GAAG,GAAG,CAAC;YAC3C,QAAQ,CAAC,gCAAgC,GAAG,KAAK,CAAC,kBAAkB,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC;SAC9F;IACH,CAAC;CACF","sourcesContent":["import { Duration } from \"aws-cdk-lib\";\nimport type { CfnCompositeAlarm, IMetric } from \"aws-cdk-lib/aws-cloudwatch\";\nimport {\n Alarm,\n AlarmRule,\n AlarmState,\n ComparisonOperator,\n CompositeAlarm,\n MathExpression,\n TreatMissingData,\n} from \"aws-cdk-lib/aws-cloudwatch\";\nimport { SnsAction } from \"aws-cdk-lib/aws-cloudwatch-actions\";\nimport type { ITopic } from \"aws-cdk-lib/aws-sns\";\nimport { Topic } from \"aws-cdk-lib/aws-sns\";\nimport { Construct } from \"constructs\";\nimport type { GuStack } from \"../../constructs/core\";\n\nexport interface ErrorBudgetAlarmProps {\n /**\n * The name of the SLO. Assumed to be unique per stack.\n */\n sloName: string;\n /**\n * The percentange target for the SLO, expressed as a decimal floating point number. Must be between 0.95 and 0.995.\n */\n sloTarget: number;\n /**\n * The metric representing the bad events. Can be any IMetric type, like Metric or MathExpression.\n */\n badEvents: IMetric;\n /**\n * The metric representing the events to be considered. Can be any IMetric type, like Metric or MathExpression.\n */\n validEvents: IMetric;\n /**\n * The sns topic name (not the full arn) used by the alarm to send email alerts.\n */\n snsTopicNameForAlerts: string;\n}\n\ninterface BurnRate {\n speed: \"Fast\" | \"Medium\" | \"Slow\";\n burnRate: number;\n}\n\ninterface BurnRateMonitoring extends BurnRate {\n longPeriod: Duration;\n shortPeriod: Duration;\n}\n\ninterface MonitorBurnRateForPeriodProps {\n alarmName: string;\n burnRateSpeed: BurnRate;\n period: Duration;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n}\n\ninterface CompositeBurnRateAlarmProps {\n sloName: string;\n burnRateMonitoring: BurnRateMonitoring;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n snsTopic: ITopic;\n suppressorAlarm?: CompositeBurnRateAlarm;\n}\n\n/**\n * Use this construct to create alarms that will notify you when you are at risk of missing your SLO targets.\n *\n * These alarms follow the recommendations in the [SRE Workbook](https://sre.google/workbook/alerting-on-slos/) to\n * implement Multiwindow, Multi-Burn-Rate Alerts.\n *\n * The CloudWatch implementation of this strategy creates nine separate CloudWatch alarms. The main alarms that users\n * need to care about are the three composite alarms. These track different burn rates of error budget consumption:\n * fast (e.g. complete outages), medium (e.g. moderate error percentage over hours, rather than minutes) and slow (e.g.\n * a small percentage of errors sustained over a much longer period). Multiple burn rates are used to ensure that\n * we are able to pick up all scenarios which could threaten the SLO, without interrupting developers with an\n * unnecessary level of urgency.\n *\n * Each composite alarm creates two child alarms; these are used to support multiple windows (or periods in CloudWatch\n * terminology). A composite alarm is configured to send notifications if both of its child alarms are in an alarm state.\n * The child alarms themselves have no actions/notifications configured and users should not need to interact with them\n * directly. Multiple windows are helpful for accuracy and reset time. The long window helps us to avoid sending an\n * alert in scenarios where no intervention is required, for example a very brief spike in errors that is resolved\n * automatically (e.g. when AWS replaces a 'bad' EC2 instance). The short window helps to ensure that the alert is reset\n * (or moved back into OK state, in CloudWatch terminology) promptly once a problem has been resolved.\n *\n * The composite alarms have an awareness of priority, meaning that low priority alarm notifications are suppressed if\n * a higher priority alarm is already firing. That is, if you receive an alert about fast error budget consumption, you\n * should not receive an alert from the medium or slow versions of the alarm.\n *\n * For how to instantiate an ErrorBudgetAlarm check the unit-test in error-budget-alarm.test.ts,\n * and for a description of the props that need to be passed see [[ErrorBudgetAlarmProps]]\n */\nexport class GuErrorBudgetAlarmExperimental extends Construct {\n constructor(scope: GuStack, props: ErrorBudgetAlarmProps) {\n const lowestTargetAllowed = 0.95;\n const highestTargetAllowed = 0.9995;\n if (!(props.sloTarget >= lowestTargetAllowed && props.sloTarget <= highestTargetAllowed)) {\n throw new Error(\n `ErrorBudgetAlarm only works with SLO targets between ${lowestTargetAllowed} and ${highestTargetAllowed}`\n );\n }\n\n super(scope, props.sloName); // The assumption here is that `sloName` will be unique (per stack)\n\n const errorBudget = 1 - props.sloTarget;\n\n const snsTopic: ITopic = Topic.fromTopicArn(\n scope,\n `SnsSloAlarmsFor${props.sloName}`,\n `arn:aws:sns:${scope.region}:${scope.account}:${props.snsTopicNameForAlerts}`\n );\n\n const fastBurnRate: BurnRateMonitoring = {\n speed: \"Fast\",\n burnRate: 14.4,\n longPeriod: Duration.hours(1),\n shortPeriod: Duration.minutes(5),\n };\n\n const fastBurnAlarm = new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: fastBurnRate,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n });\n\n const mediumBurnRateMonitoring: BurnRateMonitoring = {\n speed: \"Medium\",\n burnRate: 6,\n longPeriod: Duration.hours(6),\n shortPeriod: Duration.minutes(30),\n };\n\n const mediumBurnRateAlarm = new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: mediumBurnRateMonitoring,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n suppressorAlarm: fastBurnAlarm,\n });\n\n const slowBurnRate: BurnRateMonitoring = {\n speed: \"Slow\",\n burnRate: 3,\n longPeriod: Duration.days(1),\n shortPeriod: Duration.hours(2),\n };\n\n new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: slowBurnRate,\n errorBudget,\n // TODO - use a different topic for tickets or figure out how to route notifications vs tickets using a single topic\n snsTopic,\n validEvents: props.validEvents,\n suppressorAlarm: mediumBurnRateAlarm,\n });\n }\n}\n\nclass MonitorBurnRateForPeriod extends Alarm {\n constructor(scope: GuStack, props: MonitorBurnRateForPeriodProps) {\n const undesirableErrorBudgetConsumption = props.errorBudget * props.burnRateSpeed.burnRate;\n super(scope, props.alarmName, {\n alarmName: props.alarmName,\n metric: new MathExpression({\n expression: \"badEvents/validEvents\",\n label: \"Observed failure rate\",\n usingMetrics: {\n badEvents: props.badEvents,\n validEvents: props.validEvents,\n },\n period: props.period,\n }),\n evaluationPeriods: 1,\n threshold: undesirableErrorBudgetConsumption,\n comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,\n treatMissingData: TreatMissingData.NOT_BREACHING,\n });\n }\n}\n\nclass CompositeBurnRateAlarm extends CompositeAlarm {\n constructor(scope: GuStack, props: CompositeBurnRateAlarmProps) {\n const alarmName = `${props.sloName}${props.burnRateMonitoring.speed}BurnCompositeAlarm`;\n const sharedIndividualAlarmProps = {\n badEvents: props.badEvents,\n burnRateSpeed: {\n speed: props.burnRateMonitoring.speed,\n burnRate: props.burnRateMonitoring.burnRate,\n },\n errorBudget: props.errorBudget,\n validEvents: props.validEvents,\n };\n super(scope, alarmName, {\n alarmRule: AlarmRule.allOf(\n AlarmRule.fromAlarm(\n new MonitorBurnRateForPeriod(scope, {\n ...sharedIndividualAlarmProps,\n alarmName: `ChildAlarmLongPeriod${alarmName}`,\n period: props.burnRateMonitoring.longPeriod,\n }),\n AlarmState.ALARM\n ),\n AlarmRule.fromAlarm(\n new MonitorBurnRateForPeriod(scope, {\n ...sharedIndividualAlarmProps,\n alarmName: `ChildAlarmShortPeriod${alarmName}`,\n period: props.burnRateMonitoring.shortPeriod,\n }),\n AlarmState.ALARM\n )\n ),\n });\n this.addAlarmAction(new SnsAction(props.snsTopic));\n if (props.suppressorAlarm) {\n const cfnAlarm = this.node.defaultChild as CfnCompositeAlarm;\n cfnAlarm.actionsSuppressor = props.suppressorAlarm.alarmArn;\n cfnAlarm.actionsSuppressorWaitPeriod = 120;\n cfnAlarm.actionsSuppressorExtensionPeriod = props.burnRateMonitoring.shortPeriod.toSeconds();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-budget-alarm.js","sourceRoot":"","sources":["../../../src/experimental/constructs/error-budget-alarm.ts"],"names":[],"mappings":";;;AAAA,6CAAuC;AAEvC,+DAQoC;AAC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EAAE,KAAK,CAAC,kBAAkB,CAAC,WAAW;aAC7C,CAAC,EACF,2BAAU,CAAC,KAAK,CACjB,CACF;SACF,CAAC,CAAC;QACH,IAAI,CAAC,cAAc,CAAC,IAAI,kCAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;QACnD,IAAI,KAAK,CAAC,eAAe,EAAE;YACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,YAAiC,CAAC;YAC7D,QAAQ,CAAC,iBAAiB,GAAG,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC;YAC5D,QAAQ,CAAC,2BAA2B,GAAG,GAAG,CAAC;YAC3C,QAAQ,CAAC,gCAAgC,GAAG,KAAK,CAAC,kBAAkB,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC;SAC9F;IACH,CAAC;CACF","sourcesContent":["import { Duration } from \"aws-cdk-lib\";\nimport type { CfnCompositeAlarm, IMetric } from \"aws-cdk-lib/aws-cloudwatch\";\nimport {\n Alarm,\n AlarmRule,\n AlarmState,\n ComparisonOperator,\n CompositeAlarm,\n MathExpression,\n TreatMissingData,\n} from \"aws-cdk-lib/aws-cloudwatch\";\nimport { SnsAction } from \"aws-cdk-lib/aws-cloudwatch-actions\";\nimport type { ITopic } from \"aws-cdk-lib/aws-sns\";\nimport { Topic } from \"aws-cdk-lib/aws-sns\";\nimport { Construct } from \"constructs\";\nimport type { GuStack } from \"../../constructs/core\";\n\nexport interface ErrorBudgetAlarmProps {\n /**\n * The name of the SLO. Assumed to be unique per stack.\n */\n sloName: string;\n /**\n * The percentange target for the SLO, expressed as a decimal floating point number. Must be between 0.95 and 0.995.\n */\n sloTarget: number;\n /**\n * The metric representing the bad events. Can be any IMetric type, like Metric or MathExpression.\n */\n badEvents: IMetric;\n /**\n * The metric representing the events to be considered. Can be any IMetric type, like Metric or MathExpression.\n */\n validEvents: IMetric;\n /**\n * The sns topic name (not the full arn) used by the alarm to send email alerts.\n */\n snsTopicNameForAlerts: string;\n}\n\ninterface BurnRate {\n speed: \"Fast\" | \"Medium\" | \"Slow\";\n burnRate: number;\n}\n\ninterface BurnRateMonitoring extends BurnRate {\n longPeriod: Duration;\n shortPeriod: Duration;\n}\n\ninterface MonitorBurnRateForPeriodProps {\n alarmName: string;\n burnRateSpeed: BurnRate;\n period: Duration;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n}\n\ninterface CompositeBurnRateAlarmProps {\n sloName: string;\n burnRateMonitoring: BurnRateMonitoring;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n snsTopic: ITopic;\n suppressorAlarm?: CompositeBurnRateAlarm;\n}\n\n/**\n * Use this construct to create alarms that will notify you when you are at risk of missing your SLO targets.\n *\n * These alarms follow the recommendations in the [SRE Workbook](https://sre.google/workbook/alerting-on-slos/) to\n * implement Multiwindow, Multi-Burn-Rate Alerts.\n *\n * The CloudWatch implementation of this strategy creates nine separate CloudWatch alarms. The main alarms that users\n * need to care about are the three composite alarms. These track different burn rates of error budget consumption:\n * fast (e.g. complete outages), medium (e.g. moderate error percentage over hours, rather than minutes) and slow (e.g.\n * a small percentage of errors sustained over a much longer period). Multiple burn rates are used to ensure that\n * we are able to pick up all scenarios which could threaten the SLO, without interrupting developers with an\n * unnecessary level of urgency.\n *\n * Each composite alarm creates two child alarms; these are used to support multiple windows (or periods in CloudWatch\n * terminology). A composite alarm is configured to send notifications if both of its child alarms are in an alarm state.\n * The child alarms themselves have no actions/notifications configured and users should not need to interact with them\n * directly. Multiple windows are helpful for accuracy and reset time. The long window helps us to avoid sending an\n * alert in scenarios where no intervention is required, for example a very brief spike in errors that is resolved\n * automatically (e.g. when AWS replaces a 'bad' EC2 instance). The short window helps to ensure that the alert is reset\n * (or moved back into OK state, in CloudWatch terminology) promptly once a problem has been resolved.\n *\n * The composite alarms have an awareness of priority, meaning that low priority alarm notifications are suppressed if\n * a higher priority alarm is already firing. That is, if you receive an alert about fast error budget consumption, you\n * should not receive an alert from the medium or slow versions of the alarm.\n *\n * For how to instantiate an ErrorBudgetAlarm check the unit-test in error-budget-alarm.test.ts,\n * and for a description of the props that need to be passed see [[ErrorBudgetAlarmProps]]\n */\nexport class GuErrorBudgetAlarmExperimental extends Construct {\n constructor(scope: GuStack, props: ErrorBudgetAlarmProps) {\n const lowestTargetAllowed = 0.95;\n const highestTargetAllowed = 0.9995;\n if (!(props.sloTarget >= lowestTargetAllowed && props.sloTarget <= highestTargetAllowed)) {\n throw new Error(\n `ErrorBudgetAlarm only works with SLO targets between ${lowestTargetAllowed} and ${highestTargetAllowed}`,\n );\n }\n\n super(scope, props.sloName); // The assumption here is that `sloName` will be unique (per stack)\n\n const errorBudget = 1 - props.sloTarget;\n\n const snsTopic: ITopic = Topic.fromTopicArn(\n scope,\n `SnsSloAlarmsFor${props.sloName}`,\n `arn:aws:sns:${scope.region}:${scope.account}:${props.snsTopicNameForAlerts}`,\n );\n\n const fastBurnRate: BurnRateMonitoring = {\n speed: \"Fast\",\n burnRate: 14.4,\n longPeriod: Duration.hours(1),\n shortPeriod: Duration.minutes(5),\n };\n\n const fastBurnAlarm = new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: fastBurnRate,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n });\n\n const mediumBurnRateMonitoring: BurnRateMonitoring = {\n speed: \"Medium\",\n burnRate: 6,\n longPeriod: Duration.hours(6),\n shortPeriod: Duration.minutes(30),\n };\n\n const mediumBurnRateAlarm = new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: mediumBurnRateMonitoring,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n suppressorAlarm: fastBurnAlarm,\n });\n\n const slowBurnRate: BurnRateMonitoring = {\n speed: \"Slow\",\n burnRate: 3,\n longPeriod: Duration.days(1),\n shortPeriod: Duration.hours(2),\n };\n\n new CompositeBurnRateAlarm(scope, {\n sloName: props.sloName,\n badEvents: props.badEvents,\n burnRateMonitoring: slowBurnRate,\n errorBudget,\n // TODO - use a different topic for tickets or figure out how to route notifications vs tickets using a single topic\n snsTopic,\n validEvents: props.validEvents,\n suppressorAlarm: mediumBurnRateAlarm,\n });\n }\n}\n\nclass MonitorBurnRateForPeriod extends Alarm {\n constructor(scope: GuStack, props: MonitorBurnRateForPeriodProps) {\n const undesirableErrorBudgetConsumption = props.errorBudget * props.burnRateSpeed.burnRate;\n super(scope, props.alarmName, {\n alarmName: props.alarmName,\n metric: new MathExpression({\n expression: \"badEvents/validEvents\",\n label: \"Observed failure rate\",\n usingMetrics: {\n badEvents: props.badEvents,\n validEvents: props.validEvents,\n },\n period: props.period,\n }),\n evaluationPeriods: 1,\n threshold: undesirableErrorBudgetConsumption,\n comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,\n treatMissingData: TreatMissingData.NOT_BREACHING,\n });\n }\n}\n\nclass CompositeBurnRateAlarm extends CompositeAlarm {\n constructor(scope: GuStack, props: CompositeBurnRateAlarmProps) {\n const alarmName = `${props.sloName}${props.burnRateMonitoring.speed}BurnCompositeAlarm`;\n const sharedIndividualAlarmProps = {\n badEvents: props.badEvents,\n burnRateSpeed: {\n speed: props.burnRateMonitoring.speed,\n burnRate: props.burnRateMonitoring.burnRate,\n },\n errorBudget: props.errorBudget,\n validEvents: props.validEvents,\n };\n super(scope, alarmName, {\n alarmRule: AlarmRule.allOf(\n AlarmRule.fromAlarm(\n new MonitorBurnRateForPeriod(scope, {\n ...sharedIndividualAlarmProps,\n alarmName: `ChildAlarmLongPeriod${alarmName}`,\n period: props.burnRateMonitoring.longPeriod,\n }),\n AlarmState.ALARM,\n ),\n AlarmRule.fromAlarm(\n new MonitorBurnRateForPeriod(scope, {\n ...sharedIndividualAlarmProps,\n alarmName: `ChildAlarmShortPeriod${alarmName}`,\n period: props.burnRateMonitoring.shortPeriod,\n }),\n AlarmState.ALARM,\n ),\n ),\n });\n this.addAlarmAction(new SnsAction(props.snsTopic));\n if (props.suppressorAlarm) {\n const cfnAlarm = this.node.defaultChild as CfnCompositeAlarm;\n cfnAlarm.actionsSuppressor = props.suppressorAlarm.alarmArn;\n cfnAlarm.actionsSuppressorWaitPeriod = 120;\n cfnAlarm.actionsSuppressorExtensionPeriod = props.burnRateMonitoring.shortPeriod.toSeconds();\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastly-kinesis-log.js","sourceRoot":"","sources":["../../../../../src/experimental/constructs/iam/roles/fastly-kinesis-log.ts"],"names":[],"mappings":";;;AAAA,iDAAuD;AACvD,uFAAoF;AAEpF,sDAA0E;AAC1E,oDAAoD;AAEpD,4EAA2F;AAiB3F;;;;;;;;GAQG;AACH,MAAa,kCAAmC,SAAQ,YAAM;IAC5D,YAAY,KAAc,EAAE,EAAU,EAAE,KAAkC;QACxE,MAAM,gBAAgB,GAAG,kCAA2B,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,aAAa,CAAC;QACtF,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAE/C,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,QAAQ;YACR,SAAS,EAAE,IAAI,0BAAgB,CAAC,6CAAqB,CAAC;YACtD,WAAW,EAAE,CAAC,gBAAgB,CAAC;SAChC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,2DAAqC,CACtD,KAAK,EACL,UAAU,IAAI,uCAAuC,EACrD;YACE,MAAM;SACP,CACF,CAAC;QAEF,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AArBD,gFAqBC","sourcesContent":["import { AccountPrincipal } from \"aws-cdk-lib/aws-iam\";\nimport { FASTLY_AWS_ACCOUNT_ID } from \"../../../../constants/fastly-aws-account-id\";\nimport type { GuStack } from \"../../../../constructs/core\";\nimport { GuFastlyCustomerIdParameter } from \"../../../../constructs/core\";\nimport { GuRole } from \"../../../../constructs/iam\";\nimport type { GuKinesisStream } from \"../../../../constructs/kinesis\";\nimport { GuKinesisPutRecordsPolicyExperimental } from \"../../policies/kinesis-put-records\";\n\nexport interface GuFastlyKinesisLogRoleProps {\n /**\n * The Kinesis stream into which Fastly will put records\n */\n stream: GuKinesisStream;\n /**\n * The name of the IAM role\n */\n roleName?: string;\n /**\n * The name of the policy attached to this role which allows writing to the Kinesis stream\n */\n policyName?: string;\n}\n\n/**\n * A construct to create an IAM Role for Fastly to assume in order to write to a\n * specific Kinesis stream.\n *\n * In order to use this construct, an SSM parameter named `/account/external/fastly/customer.id`\n * needs to exist in the AWS account's parameter store, and the value should be\n * the Guardian's Fastly customer id.\n *\n */\nexport class GuFastlyKinesisLogRoleExperimental extends GuRole {\n constructor(scope: GuStack, id: string, props: GuFastlyKinesisLogRoleProps) {\n const fastlyCustomerId = GuFastlyCustomerIdParameter.getInstance(scope).valueAsString;\n const { policyName, roleName, stream } = props;\n\n super(scope, id, {\n roleName,\n assumedBy: new AccountPrincipal(FASTLY_AWS_ACCOUNT_ID),\n externalIds: [fastlyCustomerId],\n });\n\n const policy = new GuKinesisPutRecordsPolicyExperimental(\n scope,\n policyName ?? \"GuKinesisPutRecordsPolicyExperimental\",\n {\n stream,\n }
|
|
1
|
+
{"version":3,"file":"fastly-kinesis-log.js","sourceRoot":"","sources":["../../../../../src/experimental/constructs/iam/roles/fastly-kinesis-log.ts"],"names":[],"mappings":";;;AAAA,iDAAuD;AACvD,uFAAoF;AAEpF,sDAA0E;AAC1E,oDAAoD;AAEpD,4EAA2F;AAiB3F;;;;;;;;GAQG;AACH,MAAa,kCAAmC,SAAQ,YAAM;IAC5D,YAAY,KAAc,EAAE,EAAU,EAAE,KAAkC;QACxE,MAAM,gBAAgB,GAAG,kCAA2B,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,aAAa,CAAC;QACtF,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAE/C,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,QAAQ;YACR,SAAS,EAAE,IAAI,0BAAgB,CAAC,6CAAqB,CAAC;YACtD,WAAW,EAAE,CAAC,gBAAgB,CAAC;SAChC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,2DAAqC,CACtD,KAAK,EACL,UAAU,IAAI,uCAAuC,EACrD;YACE,MAAM;SACP,CACF,CAAC;QAEF,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AArBD,gFAqBC","sourcesContent":["import { AccountPrincipal } from \"aws-cdk-lib/aws-iam\";\nimport { FASTLY_AWS_ACCOUNT_ID } from \"../../../../constants/fastly-aws-account-id\";\nimport type { GuStack } from \"../../../../constructs/core\";\nimport { GuFastlyCustomerIdParameter } from \"../../../../constructs/core\";\nimport { GuRole } from \"../../../../constructs/iam\";\nimport type { GuKinesisStream } from \"../../../../constructs/kinesis\";\nimport { GuKinesisPutRecordsPolicyExperimental } from \"../../policies/kinesis-put-records\";\n\nexport interface GuFastlyKinesisLogRoleProps {\n /**\n * The Kinesis stream into which Fastly will put records\n */\n stream: GuKinesisStream;\n /**\n * The name of the IAM role\n */\n roleName?: string;\n /**\n * The name of the policy attached to this role which allows writing to the Kinesis stream\n */\n policyName?: string;\n}\n\n/**\n * A construct to create an IAM Role for Fastly to assume in order to write to a\n * specific Kinesis stream.\n *\n * In order to use this construct, an SSM parameter named `/account/external/fastly/customer.id`\n * needs to exist in the AWS account's parameter store, and the value should be\n * the Guardian's Fastly customer id.\n *\n */\nexport class GuFastlyKinesisLogRoleExperimental extends GuRole {\n constructor(scope: GuStack, id: string, props: GuFastlyKinesisLogRoleProps) {\n const fastlyCustomerId = GuFastlyCustomerIdParameter.getInstance(scope).valueAsString;\n const { policyName, roleName, stream } = props;\n\n super(scope, id, {\n roleName,\n assumedBy: new AccountPrincipal(FASTLY_AWS_ACCOUNT_ID),\n externalIds: [fastlyCustomerId],\n });\n\n const policy = new GuKinesisPutRecordsPolicyExperimental(\n scope,\n policyName ?? \"GuKinesisPutRecordsPolicyExperimental\",\n {\n stream,\n },\n );\n\n policy.attachToRole(this);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kinesis-lambda.js","sourceRoot":"","sources":["../../../src/experimental/patterns/kinesis-lambda.ts"],"names":[],"mappings":";;;AAAA,yDAAmE;AAEnE,uDAA0D;AAC1D,mFAA0E;AAG1E,gDAAoD;AAEpD,sDAA2D;AAC3D,oDAA2D;AAE3D,+CAA6D;AAwD7D;;;;;;;;;;;;GAYG;AACH,MAAa,2BAA4B,SAAQ,yBAAgB;IAG/D,YAAY,KAAc,EAAE,EAAU,EAAE,KAA2B;QACjE,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,GAAG,KAAK;YACR,yBAAyB,EAAE,KAAK,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,uBAAuB;SAClH,CAAC,CAAC;QAEH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAClC,MAAM,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,GAAG,KAAK,CAAC;QAE5D,IAAI,CAAC,aAAa,GAAG,qBAAqB;YACxC,CAAC,CAAC,oBAAM,CAAC,aAAa,CAClB,KAAK,EACL,qBAAqB,CAAC,yBAAyB,EAC/C,mBAAmB,MAAM,IAAI,OAAO,WAAW,qBAAqB,CAAC,yBAAyB,EAAE,CACjG;YACH,CAAC,CAAC,kBAAW,CAAC,eAAe,CACzB,KAAK,EACL,IAAI,yBAAe,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE,UAAU,EAAE,8BAAgB,CAAC,OAAO,EAAE,GAAG,kBAAkB,EAAE,CAAC,CAC7G,CAAC;QAEN,MAAM,4BAA4B,GAAG,IAAA,gCAAuB,EAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAE/F,MAAM,gBAAgB,GAA4B;YAChD,gBAAgB,EAAE,6BAAgB,CAAC,MAAM;YACzC,GAAG,KAAK,CAAC,eAAe;YACxB,GAAG,4BAA4B;SAChC,CAAC;QAEF,kGAAkG;QAClG,yEAAyE;QACzE,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAC7C,iBAAiB,CAAC,cAAc,CAAC,IAAI,6CAAkB,CAAC,IAAI,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC;IACjG,CAAC;CACF;AApCD,kEAoCC","sourcesContent":["import { Stream, StreamEncryption } from \"aws-cdk-lib/aws-kinesis\";\nimport type { IStream, StreamProps } from \"aws-cdk-lib/aws-kinesis\";\nimport { StartingPosition } from \"aws-cdk-lib/aws-lambda\";\nimport { KinesisEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { KinesisEventSourceProps } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { GuLambdaErrorPercentageMonitoringProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { AppIdentity } from \"../../constructs/core\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { GuKinesisStream } from \"../../constructs/kinesis\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport type { GuFunctionProps } from \"../../constructs/lambda\";\nimport { toAwsErrorHandlingProps } from \"../../utils/lambda\";\nimport type { StreamErrorHandlingProps, StreamProcessingProps } from \"../../utils/lambda\";\n\n/**\n * Used to provide information about an existing Kinesis stream to the [[`GuKinesisLambda`]] pattern.\n *\n * Specify an `externalKinesisStreamName` to link the lambda to a Kinesis stream owned by a different stack\n * (or created outside of version control).\n */\nexport interface ExistingKinesisStream {\n externalKinesisStreamName: string;\n}\n\n/**\n * Configuration options for the [[`GuKinesisLambda`]] pattern.\n *\n * For all lambda function configuration options, see [[`GuFunctionProps`]].\n *\n * The `existingKinesisStream` property can be used to reference a Kinesis stream which\n * has been created outside of this pattern (i.e. via CloudFormation, or via a different `cdk` pattern, or stack).\n * For more details see [[`ExistingKinesisStream`]].\n *\n * If you have specific stream configuration requirements (e.g. data retention period), these can be set via\n * `kinesisStreamProps`.\n *\n * If you need to override the default stream processing options (e.g. batch size and parallelization), pass\n * [[`StreamProcessingProps`]] via `processingProps`.\n *\n * You must provide `errorHandlingConfiguration` to this pattern. Retry conditions can be configured\n * via [[`StreamErrorHandlingProps`]].\n *\n * It is advisable to configure an alarm based on the lambda's error percentage.\n * To do this, add the `monitoringConfiguration` property. The required properties for this are:\n *\n * ```typescript\n * monitoringConfiguration: {\n * toleratedErrorPercentage: <sensible_error_percentage_threshold>,\n * snsTopicName: \"my-topic-for-cloudwatch-alerts\",\n * }\n * ```\n * Other alarm properties (e.g. alarm name and description) will be pre-populated with sensible defaults.\n * For a full list of optional properties, see [[`GuLambdaErrorPercentageMonitoringProps`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true } as NoMonitoring\n * ```\n */\nexport interface GuKinesisLambdaProps extends Omit<GuFunctionProps, \"errorPercentageMonitoring\"> {\n monitoringConfiguration: NoMonitoring | GuLambdaErrorPercentageMonitoringProps;\n existingKinesisStream?: ExistingKinesisStream;\n errorHandlingConfiguration: StreamErrorHandlingProps;\n kinesisStreamProps?: StreamProps;\n processingProps?: StreamProcessingProps;\n}\n\n/**\n * Pattern which creates all of the resources needed to invoke a lambda function whenever a record is\n * put onto a Kinesis stream.\n *\n * This pattern will create a new Kinesis stream by default. If you are migrating a stack from CloudFormation,\n * you will need to opt-out of this behaviour. For information on overriding the default behaviour,\n * see [[`GuKinesisLambdaProps`]].\n *\n * The Kinesis stream is stateful, and is accessible via `kinesisStream`.\n * @see https://github.com/guardian/cdk/blob/main/docs/stateful-resources.md\n *\n * @experimental This pattern is in early development. The API is likely to change in future releases.\n */\nexport class GuKinesisLambdaExperimental extends GuLambdaFunction {\n public readonly kinesisStream: IStream;\n\n constructor(scope: GuStack, id: string, props: GuKinesisLambdaProps) {\n super(scope, id, {\n ...props,\n errorPercentageMonitoring: props.monitoringConfiguration.noMonitoring ? undefined : props.monitoringConfiguration,\n });\n\n const { account, region } = scope;\n const { existingKinesisStream, kinesisStreamProps } = props;\n\n this.kinesisStream = existingKinesisStream\n ? Stream.fromStreamArn(\n scope,\n existingKinesisStream.externalKinesisStreamName,\n `arn:aws:kinesis:${region}:${account}:stream/${existingKinesisStream.externalKinesisStreamName}
|
|
1
|
+
{"version":3,"file":"kinesis-lambda.js","sourceRoot":"","sources":["../../../src/experimental/patterns/kinesis-lambda.ts"],"names":[],"mappings":";;;AAAA,yDAAmE;AAEnE,uDAA0D;AAC1D,mFAA0E;AAG1E,gDAAoD;AAEpD,sDAA2D;AAC3D,oDAA2D;AAE3D,+CAA6D;AAwD7D;;;;;;;;;;;;GAYG;AACH,MAAa,2BAA4B,SAAQ,yBAAgB;IAG/D,YAAY,KAAc,EAAE,EAAU,EAAE,KAA2B;QACjE,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,GAAG,KAAK;YACR,yBAAyB,EAAE,KAAK,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,uBAAuB;SAClH,CAAC,CAAC;QAEH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAClC,MAAM,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,GAAG,KAAK,CAAC;QAE5D,IAAI,CAAC,aAAa,GAAG,qBAAqB;YACxC,CAAC,CAAC,oBAAM,CAAC,aAAa,CAClB,KAAK,EACL,qBAAqB,CAAC,yBAAyB,EAC/C,mBAAmB,MAAM,IAAI,OAAO,WAAW,qBAAqB,CAAC,yBAAyB,EAAE,CACjG;YACH,CAAC,CAAC,kBAAW,CAAC,eAAe,CACzB,KAAK,EACL,IAAI,yBAAe,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE,UAAU,EAAE,8BAAgB,CAAC,OAAO,EAAE,GAAG,kBAAkB,EAAE,CAAC,CAC7G,CAAC;QAEN,MAAM,4BAA4B,GAAG,IAAA,gCAAuB,EAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAE/F,MAAM,gBAAgB,GAA4B;YAChD,gBAAgB,EAAE,6BAAgB,CAAC,MAAM;YACzC,GAAG,KAAK,CAAC,eAAe;YACxB,GAAG,4BAA4B;SAChC,CAAC;QAEF,kGAAkG;QAClG,yEAAyE;QACzE,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAC7C,iBAAiB,CAAC,cAAc,CAAC,IAAI,6CAAkB,CAAC,IAAI,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC;IACjG,CAAC;CACF;AApCD,kEAoCC","sourcesContent":["import { Stream, StreamEncryption } from \"aws-cdk-lib/aws-kinesis\";\nimport type { IStream, StreamProps } from \"aws-cdk-lib/aws-kinesis\";\nimport { StartingPosition } from \"aws-cdk-lib/aws-lambda\";\nimport { KinesisEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { KinesisEventSourceProps } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { GuLambdaErrorPercentageMonitoringProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { AppIdentity } from \"../../constructs/core\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { GuKinesisStream } from \"../../constructs/kinesis\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport type { GuFunctionProps } from \"../../constructs/lambda\";\nimport { toAwsErrorHandlingProps } from \"../../utils/lambda\";\nimport type { StreamErrorHandlingProps, StreamProcessingProps } from \"../../utils/lambda\";\n\n/**\n * Used to provide information about an existing Kinesis stream to the [[`GuKinesisLambda`]] pattern.\n *\n * Specify an `externalKinesisStreamName` to link the lambda to a Kinesis stream owned by a different stack\n * (or created outside of version control).\n */\nexport interface ExistingKinesisStream {\n externalKinesisStreamName: string;\n}\n\n/**\n * Configuration options for the [[`GuKinesisLambda`]] pattern.\n *\n * For all lambda function configuration options, see [[`GuFunctionProps`]].\n *\n * The `existingKinesisStream` property can be used to reference a Kinesis stream which\n * has been created outside of this pattern (i.e. via CloudFormation, or via a different `cdk` pattern, or stack).\n * For more details see [[`ExistingKinesisStream`]].\n *\n * If you have specific stream configuration requirements (e.g. data retention period), these can be set via\n * `kinesisStreamProps`.\n *\n * If you need to override the default stream processing options (e.g. batch size and parallelization), pass\n * [[`StreamProcessingProps`]] via `processingProps`.\n *\n * You must provide `errorHandlingConfiguration` to this pattern. Retry conditions can be configured\n * via [[`StreamErrorHandlingProps`]].\n *\n * It is advisable to configure an alarm based on the lambda's error percentage.\n * To do this, add the `monitoringConfiguration` property. The required properties for this are:\n *\n * ```typescript\n * monitoringConfiguration: {\n * toleratedErrorPercentage: <sensible_error_percentage_threshold>,\n * snsTopicName: \"my-topic-for-cloudwatch-alerts\",\n * }\n * ```\n * Other alarm properties (e.g. alarm name and description) will be pre-populated with sensible defaults.\n * For a full list of optional properties, see [[`GuLambdaErrorPercentageMonitoringProps`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true } as NoMonitoring\n * ```\n */\nexport interface GuKinesisLambdaProps extends Omit<GuFunctionProps, \"errorPercentageMonitoring\"> {\n monitoringConfiguration: NoMonitoring | GuLambdaErrorPercentageMonitoringProps;\n existingKinesisStream?: ExistingKinesisStream;\n errorHandlingConfiguration: StreamErrorHandlingProps;\n kinesisStreamProps?: StreamProps;\n processingProps?: StreamProcessingProps;\n}\n\n/**\n * Pattern which creates all of the resources needed to invoke a lambda function whenever a record is\n * put onto a Kinesis stream.\n *\n * This pattern will create a new Kinesis stream by default. If you are migrating a stack from CloudFormation,\n * you will need to opt-out of this behaviour. For information on overriding the default behaviour,\n * see [[`GuKinesisLambdaProps`]].\n *\n * The Kinesis stream is stateful, and is accessible via `kinesisStream`.\n * @see https://github.com/guardian/cdk/blob/main/docs/stateful-resources.md\n *\n * @experimental This pattern is in early development. The API is likely to change in future releases.\n */\nexport class GuKinesisLambdaExperimental extends GuLambdaFunction {\n public readonly kinesisStream: IStream;\n\n constructor(scope: GuStack, id: string, props: GuKinesisLambdaProps) {\n super(scope, id, {\n ...props,\n errorPercentageMonitoring: props.monitoringConfiguration.noMonitoring ? undefined : props.monitoringConfiguration,\n });\n\n const { account, region } = scope;\n const { existingKinesisStream, kinesisStreamProps } = props;\n\n this.kinesisStream = existingKinesisStream\n ? Stream.fromStreamArn(\n scope,\n existingKinesisStream.externalKinesisStreamName,\n `arn:aws:kinesis:${region}:${account}:stream/${existingKinesisStream.externalKinesisStreamName}`,\n )\n : AppIdentity.taggedConstruct(\n props,\n new GuKinesisStream(scope, \"KinesisStream\", { encryption: StreamEncryption.MANAGED, ...kinesisStreamProps }),\n );\n\n const errorHandlingPropsToAwsProps = toAwsErrorHandlingProps(props.errorHandlingConfiguration);\n\n const eventSourceProps: KinesisEventSourceProps = {\n startingPosition: StartingPosition.LATEST,\n ...props.processingProps,\n ...errorHandlingPropsToAwsProps,\n };\n\n // If we have an alias, use this to ensure that all events are sent to a published Lambda version.\n // Otherwise, send all events to the latest unpublished version ($LATEST)\n const eventSourceTarget = this.alias ?? this;\n eventSourceTarget.addEventSource(new KinesisEventSource(this.kinesisStream, eventSourceProps));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sns-lambda.js","sourceRoot":"","sources":["../../../src/experimental/patterns/sns-lambda.ts"],"names":[],"mappings":";;;AAAA,6CAAwC;AACxC,mFAAsE;AAEtE,iDAA4C;AAE5C,gDAAoD;AAEpD,oDAA2D;AA4C3D;;;;;;;;;;;;GAYG;AACH,MAAa,uBAAwB,SAAQ,yBAAgB;IAG3D,YAAY,KAAc,EAAE,EAAU,EAAE,KAAuB;QAC7D,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,GAAG,KAAK;YACR,yBAAyB,EAAE,KAAK,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,uBAAuB;SAClH,CAAC,CAAC;QAEH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAClC,MAAM,EAAE,gBAAgB,EAAE,GAAG,KAAK,CAAC;QAEnC,IAAI,CAAC,QAAQ,GAAG,gBAAgB;YAC9B,CAAC,CAAC,eAAK,CAAC,YAAY,CAChB,KAAK,EACL,GAAG,EAAE,iCAAiC,EACtC,eAAe,MAAM,IAAI,OAAO,IAAI,gBAAgB,CAAC,iBAAiB,EAAE,CACzE;YACH,CAAC,CAAC,kBAAW,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,eAAK,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAEnF,kGAAkG;QAClG,yEAAyE;QACzE,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAC7C,iBAAiB,CAAC,cAAc,CAAC,IAAI,yCAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACpE,IAAI,uBAAS,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC;IACvE,CAAC;CACF;AA1BD,0DA0BC","sourcesContent":["import { CfnOutput } from \"aws-cdk-lib\";\nimport { SnsEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { ITopic } from \"aws-cdk-lib/aws-sns\";\nimport { Topic } from \"aws-cdk-lib/aws-sns\";\nimport type { GuLambdaErrorPercentageMonitoringProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { AppIdentity } from \"../../constructs/core\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport type { GuFunctionProps } from \"../../constructs/lambda\";\n\n/**\n * Used to provide information about an existing SNS topic to the [[`GuSnsLambda`]] pattern.\n *\n * Specify an `externalTopicName` to link the lambda to an SNS topic owned by a different stack\n * (or created outside of version control).\n */\nexport interface ExistingSnsTopic {\n externalTopicName: string;\n}\n\n/**\n * Configuration options for the [[`GuSnsLambda`]] pattern.\n *\n * For all lambda function configuration options, see [[`GuFunctionProps`]].\n *\n * The `existingSnsTopic` property can be used to inherit or reference an SNS topic which\n * has been created outside of `cdk`. If this property is omitted, the [[`GuSnsLambda`]] pattern\n * will create a new topic. For more details and example usage, see [[`ExistingSnsTopic`]].\n *\n * It is advisable to configure an alarm based on the lambda's error percentage.\n * To do this, add the `monitoringConfiguration` property. The required properties for this are:\n *\n * ```typescript\n * monitoringConfiguration: {\n * toleratedErrorPercentage: <sensible_error_percentage_threshold>,\n * snsTopicName: \"my-topic-for-cloudwatch-alerts\",\n * }\n * ```\n * Other alarm properties (e.g. alarm name and description) will be pre-populated with sensible defaults.\n * For a full list of optional properties, see [[`GuLambdaErrorPercentageMonitoringProps`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true } as NoMonitoring\n * ```\n */\nexport interface GuSnsLambdaProps extends Omit<GuFunctionProps, \"errorPercentageMonitoring\"> {\n monitoringConfiguration: NoMonitoring | GuLambdaErrorPercentageMonitoringProps;\n existingSnsTopic?: ExistingSnsTopic;\n}\n\n/**\n * Pattern which creates all of the resources needed to invoke a lambda function whenever a message\n * is published onto an SNS topic.\n *\n * This pattern will create a new SNS topic by default. If you are migrating a stack from CloudFormation,\n * you will need to opt-out of this behaviour. For information on overriding the default behaviour,\n * see [[`GuSnsLambdaProps`]].\n *\n * The SNS topic is stateful, and is accessible via `snsTopic`.\n * @see https://github.com/guardian/cdk/blob/main/docs/stateful-resources.md\n *\n * @experimental This pattern is in early development. The API is likely to change in future releases.\n */\nexport class GuSnsLambdaExperimental extends GuLambdaFunction {\n public readonly snsTopic: ITopic;\n\n constructor(scope: GuStack, id: string, props: GuSnsLambdaProps) {\n super(scope, id, {\n ...props,\n errorPercentageMonitoring: props.monitoringConfiguration.noMonitoring ? undefined : props.monitoringConfiguration,\n });\n\n const { account, region } = scope;\n const { existingSnsTopic } = props;\n\n this.snsTopic = existingSnsTopic\n ? Topic.fromTopicArn(\n scope,\n `${id}-SnsExistingIncomingEventsTopic`,\n `arn:aws:sns:${region}:${account}:${existingSnsTopic.externalTopicName}
|
|
1
|
+
{"version":3,"file":"sns-lambda.js","sourceRoot":"","sources":["../../../src/experimental/patterns/sns-lambda.ts"],"names":[],"mappings":";;;AAAA,6CAAwC;AACxC,mFAAsE;AAEtE,iDAA4C;AAE5C,gDAAoD;AAEpD,oDAA2D;AA4C3D;;;;;;;;;;;;GAYG;AACH,MAAa,uBAAwB,SAAQ,yBAAgB;IAG3D,YAAY,KAAc,EAAE,EAAU,EAAE,KAAuB;QAC7D,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE;YACf,GAAG,KAAK;YACR,yBAAyB,EAAE,KAAK,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,uBAAuB;SAClH,CAAC,CAAC;QAEH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAClC,MAAM,EAAE,gBAAgB,EAAE,GAAG,KAAK,CAAC;QAEnC,IAAI,CAAC,QAAQ,GAAG,gBAAgB;YAC9B,CAAC,CAAC,eAAK,CAAC,YAAY,CAChB,KAAK,EACL,GAAG,EAAE,iCAAiC,EACtC,eAAe,MAAM,IAAI,OAAO,IAAI,gBAAgB,CAAC,iBAAiB,EAAE,CACzE;YACH,CAAC,CAAC,kBAAW,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,eAAK,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAEnF,kGAAkG;QAClG,yEAAyE;QACzE,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAC7C,iBAAiB,CAAC,cAAc,CAAC,IAAI,yCAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACpE,IAAI,uBAAS,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC;IACvE,CAAC;CACF;AA1BD,0DA0BC","sourcesContent":["import { CfnOutput } from \"aws-cdk-lib\";\nimport { SnsEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport type { ITopic } from \"aws-cdk-lib/aws-sns\";\nimport { Topic } from \"aws-cdk-lib/aws-sns\";\nimport type { GuLambdaErrorPercentageMonitoringProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { AppIdentity } from \"../../constructs/core\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport type { GuFunctionProps } from \"../../constructs/lambda\";\n\n/**\n * Used to provide information about an existing SNS topic to the [[`GuSnsLambda`]] pattern.\n *\n * Specify an `externalTopicName` to link the lambda to an SNS topic owned by a different stack\n * (or created outside of version control).\n */\nexport interface ExistingSnsTopic {\n externalTopicName: string;\n}\n\n/**\n * Configuration options for the [[`GuSnsLambda`]] pattern.\n *\n * For all lambda function configuration options, see [[`GuFunctionProps`]].\n *\n * The `existingSnsTopic` property can be used to inherit or reference an SNS topic which\n * has been created outside of `cdk`. If this property is omitted, the [[`GuSnsLambda`]] pattern\n * will create a new topic. For more details and example usage, see [[`ExistingSnsTopic`]].\n *\n * It is advisable to configure an alarm based on the lambda's error percentage.\n * To do this, add the `monitoringConfiguration` property. The required properties for this are:\n *\n * ```typescript\n * monitoringConfiguration: {\n * toleratedErrorPercentage: <sensible_error_percentage_threshold>,\n * snsTopicName: \"my-topic-for-cloudwatch-alerts\",\n * }\n * ```\n * Other alarm properties (e.g. alarm name and description) will be pre-populated with sensible defaults.\n * For a full list of optional properties, see [[`GuLambdaErrorPercentageMonitoringProps`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true } as NoMonitoring\n * ```\n */\nexport interface GuSnsLambdaProps extends Omit<GuFunctionProps, \"errorPercentageMonitoring\"> {\n monitoringConfiguration: NoMonitoring | GuLambdaErrorPercentageMonitoringProps;\n existingSnsTopic?: ExistingSnsTopic;\n}\n\n/**\n * Pattern which creates all of the resources needed to invoke a lambda function whenever a message\n * is published onto an SNS topic.\n *\n * This pattern will create a new SNS topic by default. If you are migrating a stack from CloudFormation,\n * you will need to opt-out of this behaviour. For information on overriding the default behaviour,\n * see [[`GuSnsLambdaProps`]].\n *\n * The SNS topic is stateful, and is accessible via `snsTopic`.\n * @see https://github.com/guardian/cdk/blob/main/docs/stateful-resources.md\n *\n * @experimental This pattern is in early development. The API is likely to change in future releases.\n */\nexport class GuSnsLambdaExperimental extends GuLambdaFunction {\n public readonly snsTopic: ITopic;\n\n constructor(scope: GuStack, id: string, props: GuSnsLambdaProps) {\n super(scope, id, {\n ...props,\n errorPercentageMonitoring: props.monitoringConfiguration.noMonitoring ? undefined : props.monitoringConfiguration,\n });\n\n const { account, region } = scope;\n const { existingSnsTopic } = props;\n\n this.snsTopic = existingSnsTopic\n ? Topic.fromTopicArn(\n scope,\n `${id}-SnsExistingIncomingEventsTopic`,\n `arn:aws:sns:${region}:${account}:${existingSnsTopic.externalTopicName}`,\n )\n : AppIdentity.taggedConstruct(props, new Topic(scope, \"SnsIncomingEventsTopic\"));\n\n // If we have an alias, use this to ensure that all events are sent to a published Lambda version.\n // Otherwise, send all events to the latest unpublished version ($LATEST)\n const eventSourceTarget = this.alias ?? this;\n eventSourceTarget.addEventSource(new SnsEventSource(this.snsTopic));\n new CfnOutput(this, \"TopicName\", { value: this.snsTopic.topicName });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoscaling.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/autoscaling.ts"],"names":[],"mappings":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Y,EAAE,CAAC,aAAa,CAAC;YAC7B,gBAAgB,EAAE,GAAG;SACtB;KACF,CAAC;AACJ,CAAC;AAvBD,sDAuBC","sourcesContent":["import type { GuAutoScalingGroup } from \"../../../constructs/autoscaling\";\nimport type { GuStack } from \"../../../constructs/core\";\nimport type { RiffRaffDeployment } from \"../types\";\n\nexport function uploadAutoscalingArtifact(asg: GuAutoScalingGroup): RiffRaffDeployment {\n const { app } = asg;\n const { stack, region } = asg.stack as GuStack;\n\n return {\n name: [\"asg-upload\", region, stack, app].join(\"-\"),\n props: {\n type: \"autoscaling\",\n actions: [\"uploadArtifacts\"],\n regions: new Set([region]),\n stacks: new Set([stack]),\n app,\n parameters: {\n bucketSsmLookup: true,\n prefixApp: true,\n },\n contentDirectory: app,\n },\n };\n}\n\nexport function autoscalingDeployment(\n asg: GuAutoScalingGroup,\n { name: cfnDeployName }: RiffRaffDeployment
|
|
1
|
+
{"version":3,"file":"autoscaling.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/autoscaling.ts"],"names":[],"mappings":";;;AAIA,SAAgB,yBAAyB,CAAC,GAAuB;IAC/D,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC;IACpB,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,KAAgB,CAAC;IAE/C,OAAO;QACL,IAAI,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAClD,KAAK,EAAE;YACL,IAAI,EAAE,aAAa;YACnB,OAAO,EAAE,CAAC,iBAAiB,CAAC;YAC5B,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1B,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;YACxB,GAAG;YACH,UAAU,EAAE;gBACV,eAAe,EAAE,IAAI;gBACrB,SAAS,EAAE,IAAI;aAChB;YACD,gBAAgB,EAAE,GAAG;SACtB;KACF,CAAC;AACJ,CAAC;AAnBD,8DAmBC;AAED,SAAgB,qBAAqB,CACnC,GAAuB,EACvB,EAAE,IAAI,EAAE,aAAa,EAAsB;IAE3C,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC;IACpB,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,KAAgB,CAAC;IAE/C,OAAO;QACL,IAAI,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAClD,KAAK,EAAE;YACL,IAAI,EAAE,aAAa;YACnB,OAAO,EAAE,CAAC,QAAQ,CAAC;YACnB,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1B,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;YACxB,GAAG;YACH,UAAU,EAAE;gBACV,eAAe,EAAE,IAAI;gBACrB,SAAS,EAAE,IAAI;aAChB;YACD,YAAY,EAAE,CAAC,aAAa,CAAC;YAC7B,gBAAgB,EAAE,GAAG;SACtB;KACF,CAAC;AACJ,CAAC;AAvBD,sDAuBC","sourcesContent":["import type { GuAutoScalingGroup } from \"../../../constructs/autoscaling\";\nimport type { GuStack } from \"../../../constructs/core\";\nimport type { RiffRaffDeployment } from \"../types\";\n\nexport function uploadAutoscalingArtifact(asg: GuAutoScalingGroup): RiffRaffDeployment {\n const { app } = asg;\n const { stack, region } = asg.stack as GuStack;\n\n return {\n name: [\"asg-upload\", region, stack, app].join(\"-\"),\n props: {\n type: \"autoscaling\",\n actions: [\"uploadArtifacts\"],\n regions: new Set([region]),\n stacks: new Set([stack]),\n app,\n parameters: {\n bucketSsmLookup: true,\n prefixApp: true,\n },\n contentDirectory: app,\n },\n };\n}\n\nexport function autoscalingDeployment(\n asg: GuAutoScalingGroup,\n { name: cfnDeployName }: RiffRaffDeployment,\n): RiffRaffDeployment {\n const { app } = asg;\n const { stack, region } = asg.stack as GuStack;\n\n return {\n name: [\"asg-update\", region, stack, app].join(\"-\"),\n props: {\n type: \"autoscaling\",\n actions: [\"deploy\"],\n regions: new Set([region]),\n stacks: new Set([stack]),\n app,\n parameters: {\n bucketSsmLookup: true,\n prefixApp: true,\n },\n dependencies: [cfnDeployName],\n contentDirectory: app,\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudformation.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/cloudformation.ts"],"names":[],"mappings":";;;AAGA,SAAgB,wBAAwB,CACtC,SAAwC,EACxC,YAAkC,EAClC,gBAAwB;IAExB,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAC1B,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;KAC1F;IAED,qHAAqH;IACrH,8GAA8G;IAC9G,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAE,CAAC;IAC/B,MAAM,EACJ,MAAM,EACN,KAAK,EACL,WAAW,EAAE,EAAE,IAAI,EAAE,GACtB,GAAG,QAAQ,CAAC;IAEb,yFAAyF;IACzF,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;IAE9E,MAAM,kBAAkB,GAAG,SAAS,CAAC,MAAM,CACzC,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC,CAAC;QACjC,GAAG,GAAG;QACN,CAAC,KAAK,CAAC,EAAE,YAAY;KACtB,CAAC,EACF,EAAE,CACH,CAAC;IAEF,OAAO;QACL,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACtD,KAAK,EAAE;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,IAAI,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AChB,UAAU;gBACV,MAAM;gBACN,SAAS;aACV;SACF,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,GAAG,aAAa,CAAC,KAAK;QACtB,UAAU,EAAE;YACV,GAAG,aAAa,CAAC,KAAK,CAAC,UAAU;YAEjC,gEAAgE;YAChE,GAAG,CAAC,iBAAiB,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,mBAAmB,EAAE,CAAC;SAC7D;KACF,CAAC;AACJ,CAAC;AArCD,gGAqCC","sourcesContent":["import type { GuAutoScalingGroup } from \"../../../constructs/autoscaling\";\nimport type { CdkStacksDifferingOnlyByStage, RiffRaffDeployment, RiffRaffDeploymentProps } from \"../types\";\n\nexport function cloudFormationDeployment(\n cdkStacks: CdkStacksDifferingOnlyByStage,\n dependencies: RiffRaffDeployment[],\n contentDirectory: string
|
|
1
|
+
{"version":3,"file":"cloudformation.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/cloudformation.ts"],"names":[],"mappings":";;;AAGA,SAAgB,wBAAwB,CACtC,SAAwC,EACxC,YAAkC,EAClC,gBAAwB;IAExB,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAC1B,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;KAC1F;IAED,qHAAqH;IACrH,8GAA8G;IAC9G,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAE,CAAC;IAC/B,MAAM,EACJ,MAAM,EACN,KAAK,EACL,WAAW,EAAE,EAAE,IAAI,EAAE,GACtB,GAAG,QAAQ,CAAC;IAEb,yFAAyF;IACzF,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;IAE9E,MAAM,kBAAkB,GAAG,SAAS,CAAC,MAAM,CACzC,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC,CAAC;Q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G,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;QAEtG,OAAO;YACL,GAAG,GAAG;YACN,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;gBACtB,OAAO,EAAE,OAAO;gBAChB,UAAU;gBACV,MAAM;gBACN,SAAS;aACV;SACF,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,GAAG,aAAa,CAAC,KAAK;QACtB,UAAU,EAAE;YACV,GAAG,aAAa,CAAC,KAAK,CAAC,UAAU;YAEjC,gEAAgE;YAChE,GAAG,CAAC,iBAAiB,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,mBAAmB,EAAE,CAAC;SAC7D;KACF,CAAC;AACJ,CAAC;AArCD,gGAqCC","sourcesContent":["import type { GuAutoScalingGroup } from \"../../../constructs/autoscaling\";\nimport type { CdkStacksDifferingOnlyByStage, RiffRaffDeployment, RiffRaffDeploymentProps } from \"../types\";\n\nexport function cloudFormationDeployment(\n cdkStacks: CdkStacksDifferingOnlyByStage,\n dependencies: RiffRaffDeployment[],\n contentDirectory: string,\n): RiffRaffDeployment {\n if (cdkStacks.length === 0) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n // The stacks in `cdkStacks` only differ by stage, so we can just use the first item in the list for key information.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length of `cdkStacks` is checked above\n const cdkStack = cdkStacks[0]!;\n const {\n region,\n stack,\n constructor: { name },\n } = cdkStack;\n\n // TODO remove `lodash.kebabcase` dep as it's not that much code to kebab-ise a string...\n const kebabClassName = name.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase();\n\n const templateStagePaths = cdkStacks.reduce(\n (acc, { stage, templateFile }) => ({\n ...acc,\n [stage]: templateFile,\n }),\n {},\n );\n\n return {\n name: [\"cfn\", region, stack, kebabClassName].join(\"-\"),\n props: {\n type: \"cloud-formation\",\n regions: new Set([region]),\n stacks: new Set([stack]),\n app: kebabClassName,\n contentDirectory,\n parameters: {\n templateStagePaths,\n },\n // only add the `dependencies` property if there are some\n ...(dependencies.length > 0 && { dependencies: dependencies.map(({ name }) => name) }),\n },\n };\n}\n\nexport function addAmiParametersToCloudFormationDeployment(\n cfnDeployment: RiffRaffDeployment,\n autoScalingGroups: GuAutoScalingGroup[],\n): RiffRaffDeploymentProps {\n const amiParametersToTags = autoScalingGroups.reduce((acc, asg) => {\n const { imageRecipe, app, amiParameter } = asg;\n\n if (!imageRecipe) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; imageRecipe missing from ASG ${app}`);\n }\n\n const Recipe = typeof imageRecipe === \"string\" ? imageRecipe : imageRecipe.Recipe;\n const AmigoStage = typeof imageRecipe === \"string\" ? \"PROD\" : imageRecipe.AmigoStage ?? \"PROD\";\n\n // In YAML `true` is a Boolean. Riff-Raff expects a String here, so call `toString` to make it `'true'`.\n const Encrypted = (typeof imageRecipe === \"string\" ? true : imageRecipe.Encrypted ?? true).toString();\n\n return {\n ...acc,\n [amiParameter.node.id]: {\n BuiltBy: \"amigo\",\n AmigoStage,\n Recipe,\n Encrypted,\n },\n };\n }, {});\n\n return {\n ...cfnDeployment.props,\n parameters: {\n ...cfnDeployment.props.parameters,\n\n // only add the `amiParametersToTags` property if there are some\n ...(autoScalingGroups.length > 0 && { amiParametersToTags }),\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lambda.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/lambda.ts"],"names":[],"mappings":";;;AAYA,MAAM,aAAa,GAAG,CAAC,MAAwB,EAAmB,EAAE;IAClE,MAAM,UAAU,GACd,MAAM,CAAC,cAAc,KAAK,SAAS;QACjC,CAAC,CAAC;YACE,eAAe,EAAE,IAA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CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACrD,KAAK,EAAE;YACL,IAAI,EAAE,YAAY;YAClB,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;YACxB,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1B,GAAG;YACH,gBAAgB,EAAE,GAAG;YACrB,UAAU,EAAE;gBACV,GAAG,aAAa,CAAC,MAAM,CAAC;gBACxB,YAAY,EAAE,IAAI;gBAClB,QAAQ;aACT;YACD,OAAO,EAAE,CAAC,cAAc,CAAC;YACzB,YAAY,EAAE,CAAC,aAAa,CAAC;SAC9B;KACF,CAAC;AACJ,CAAC;AAxBD,wDAwBC","sourcesContent":["import type { GuStack } from \"../../../constructs/core\";\nimport type { GuLambdaFunction } from \"../../../constructs/lambda\";\nimport type { RiffRaffDeployment } from \"../types\";\n\ninterface S3LocationProps {\n bucketSsmLookup?: boolean;\n bucketSsmKey?: string;\n prefixStackToKey?: boolean;\n prefixAppToKey?: boolean;\n prefixStageToKey?: boolean;\n}\n\nconst locationProps = (lambda: GuLambdaFunction): S3LocationProps => {\n const bucketProp =\n lambda.bucketNamePath === undefined\n ? {\n bucketSsmLookup: true,\n }\n : {\n bucketSsmKey: lambda.bucketNamePath,\n };\n\n /**\n * If the lambda has a file prefix, we don't want to prefix the key with the stack, app or stage.\n * The default value for these properties is `true`, so we don't need to set them explicitly if\n * we *do* want to add the prefixes (and RiffRaff will complain if we add them).\n */\n const prefixProps = lambda.withoutFilePrefix\n ? {\n prefixStackToKey: false,\n prefixAppToKey: false,\n prefixStageToKey: false,\n }\n : {};\n\n return {\n ...bucketProp,\n ...prefixProps,\n };\n};\n\nexport function uploadLambdaArtifact(lambda: GuLambdaFunction): RiffRaffDeployment {\n const { app, fileName } = lambda;\n const { stack, region } = lambda.stack as GuStack;\n\n return {\n name: [\"lambda-upload\", region, stack, app].join(\"-\"),\n props: {\n type: \"aws-lambda\",\n stacks: new Set([stack]),\n regions: new Set([region]),\n app,\n contentDirectory: app,\n parameters: {\n ...locationProps(lambda),\n lookupByTags: true,\n fileName,\n },\n actions: [\"uploadLambda\"],\n },\n };\n}\n\nexport function updateLambdaDeployment(\n lambda: GuLambdaFunction,\n { name: cfnDeployName }: RiffRaffDeployment
|
|
1
|
+
{"version":3,"file":"lambda.js","sourceRoot":"","sources":["../../../../src/experimental/riff-raff-yaml-file/deployments/lambda.ts"],"names":[],"mappings":";;;AAYA,MAAM,aAAa,GAAG,CAAC,MAAwB,EAAmB,EAAE;IAClE,MAAM,UAAU,GACd,MAAM,CAAC,cAAc,KAAK,SAAS;QACjC,CAAC,CAAC;YACE,eAAe,EAAE,IAAI;SACtB;QACH,CAAC,CAAC;YACE,YAAY,EAAE,MAAM,CAAC,cAAc;SACpC,CAAC;IAER;;;;OAIG;IACH,MAAM,WAAW,GAAG,MAAM,CAAC,iBAAiB;QAC1C,CAAC,CAAC;YACE,gBAAgB,EAAE,KAAK;YACvB,cAAc,EAAE,KAAK;YACrB,gBAAgB,EAAE,KAAK;SACxB;QACH,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;QACL,GAAG,UAAU;QACb,GAAG,WAAW;KACf,CAAC;AACJ,CAAC,CAAC;AAEF,SAAgB,oBAAoB,CAAC,MAAwB;IAC3D,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;IACjC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,KAAgB,CAAC;IAElD,OAAO;QACL,IAAI,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACrD,KAAK,EAAE;YACL,IAAI,EAAE,YAAY;YAClB,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;YACxB,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1B,GAAG;YACH,gBAAgB,EAAE,GAAG;YACrB,UAAU,EAAE;gBACV,GAAG,aAAa,CAAC,MAAM,CAAC;gBACxB,YAAY,EAAE,IAAI;gBAClB,QAAQ;aACT;YACD,OAAO,EAAE,CAAC,cAAc,CAAC;SAC1B;KACF,CAAC;AACJ,CAAC;AApBD,oDAoBC;AAED,SAAgB,sBAAsB,CACpC,MAAwB,EACxB,EAAE,IAAI,EAAE,aAAa,EAAsB;IAE3C,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;IACjC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,KAAgB,CAAC;IAElD,OAAO;QACL,IAAI,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACrD,KAAK,EAAE;YACL,IAAI,EAAE,YAAY;YAClB,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;YACxB,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1B,GAAG;YACH,gBAAgB,EAAE,GAAG;YACrB,UAAU,EAAE;gBACV,GAAG,aAAa,CAAC,MAAM,CAAC;gBACxB,YAAY,EAAE,IAAI;gBAClB,QAAQ;aACT;YACD,OAAO,EAAE,CAAC,cAAc,CAAC;YACzB,YAAY,EAAE,CAAC,aAAa,CAAC;SAC9B;KACF,CAAC;AACJ,CAAC;AAxBD,wDAwBC","sourcesContent":["import type { GuStack } from \"../../../constructs/core\";\nimport type { GuLambdaFunction } from \"../../../constructs/lambda\";\nimport type { RiffRaffDeployment } from \"../types\";\n\ninterface S3LocationProps {\n bucketSsmLookup?: boolean;\n bucketSsmKey?: string;\n prefixStackToKey?: boolean;\n prefixAppToKey?: boolean;\n prefixStageToKey?: boolean;\n}\n\nconst locationProps = (lambda: GuLambdaFunction): S3LocationProps => {\n const bucketProp =\n lambda.bucketNamePath === undefined\n ? {\n bucketSsmLookup: true,\n }\n : {\n bucketSsmKey: lambda.bucketNamePath,\n };\n\n /**\n * If the lambda has a file prefix, we don't want to prefix the key with the stack, app or stage.\n * The default value for these properties is `true`, so we don't need to set them explicitly if\n * we *do* want to add the prefixes (and RiffRaff will complain if we add them).\n */\n const prefixProps = lambda.withoutFilePrefix\n ? {\n prefixStackToKey: false,\n prefixAppToKey: false,\n prefixStageToKey: false,\n }\n : {};\n\n return {\n ...bucketProp,\n ...prefixProps,\n };\n};\n\nexport function uploadLambdaArtifact(lambda: GuLambdaFunction): RiffRaffDeployment {\n const { app, fileName } = lambda;\n const { stack, region } = lambda.stack as GuStack;\n\n return {\n name: [\"lambda-upload\", region, stack, app].join(\"-\"),\n props: {\n type: \"aws-lambda\",\n stacks: new Set([stack]),\n regions: new Set([region]),\n app,\n contentDirectory: app,\n parameters: {\n ...locationProps(lambda),\n lookupByTags: true,\n fileName,\n },\n actions: [\"uploadLambda\"],\n },\n };\n}\n\nexport function updateLambdaDeployment(\n lambda: GuLambdaFunction,\n { name: cfnDeployName }: RiffRaffDeployment,\n): RiffRaffDeployment {\n const { app, fileName } = lambda;\n const { stack, region } = lambda.stack as GuStack;\n\n return {\n name: [\"lambda-update\", region, stack, app].join(\"-\"),\n props: {\n type: \"aws-lambda\",\n stacks: new Set([stack]),\n regions: new Set([region]),\n app,\n contentDirectory: app,\n parameters: {\n ...locationProps(lambda),\n lookupByTags: true,\n fileName,\n },\n actions: [\"updateLambda\"],\n dependencies: [cfnDeployName],\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"group-by.js","sourceRoot":"","sources":["../../../src/experimental/riff-raff-yaml-file/group-by.ts"],"names":[],"mappings":";;;AACA,6CAA4C;AAG5C,SAAS,gBAAgB,CAAC,SAAoB;IAC5C,OAAO,IAAA,eAAO,EAAC,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,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ACF,EAAE,CACH,CAAC;AACJ,CAAC;AApBD,4EAoBC","sourcesContent":["import type { GuStack } from \"../../constructs/core\";\nimport { groupBy } from \"../../utils/array\";\nimport type { ClassName, GroupedCdkStacks, Region, StackTag, StageTag } from \"./types\";\n\nfunction groupByClassName(cdkStacks: GuStack[]): Record<ClassName, GuStack[]> {\n return groupBy(cdkStacks, (stack) => stack.constructor.name);\n}\n\nfunction groupByStackTag(cdkStacks: GuStack[]): Record<StackTag, GuStack[]> {\n return groupBy(cdkStacks, ({ stack }) => stack);\n}\n\nfunction groupByStageTag(cdkStacks: GuStack[]): Record<StageTag, GuStack[]> {\n return groupBy(cdkStacks, ({ stage }) => stage);\n}\n\nfunction groupByRegion(cdkStacks: GuStack[]): Record<Region, GuStack[]> {\n return groupBy(cdkStacks, ({ region }) => region);\n}\n\nexport function groupByClassNameStackRegionStage(cdkStacks: GuStack[]): GroupedCdkStacks {\n return Object.entries(groupByClassName(cdkStacks)).reduce(\n (accClassName, [className, stacksGroupedByClassName]) => ({\n ...accClassName,\n [className]: Object.entries(groupByStackTag(stacksGroupedByClassName)).reduce(\n (accStackTag, [stackTag, stacksGroupedByStackTag]) => ({\n ...accStackTag,\n [stackTag]: Object.entries(groupByRegion(stacksGroupedByStackTag)).reduce(\n (accRegion, [region, stacksGroupedByRegion]) => ({\n ...accRegion,\n [region]: groupByStageTag(stacksGroupedByRegion),\n }),\n {}
|
|
1
|
+
{"version":3,"file":"group-by.js","sourceRoot":"","sources":["../../../src/experimental/riff-raff-yaml-file/group-by.ts"],"names":[],"mappings":";;;AACA,6CAA4C;AAG5C,SAAS,gBAAgB,CAAC,SAAoB;IAC5C,OAAO,IAAA,eAAO,EAAC,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,eAAe,CAAC,SAAoB;IAC3C,OAAO,IAAA,eAAO,EAAC,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,eAAe,CAAC,SAAoB;IAC3C,OAAO,IAAA,eAAO,EAAC,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,aAAa,CAAC,SAAoB;IACzC,OAAO,IAAA,eAAO,EAAC,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAoB;IACnE,OAAO,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CACvD,CAAC,YAAY,EAAE,CAAC,SAAS,EAAE,wBAAwB,CAAC,EAAE,EAAE,CAAC,CAAC;QACxD,GAAG,YAAY;QACf,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,wBAAwB,CAAC,CAAC,CAAC,MAAM,CAC3E,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,uBAAuB,CAAC,EAAE,EAAE,CAAC,CAAC;YACrD,GAAG,WAAW;YACd,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,uBAAuB,CAAC,CAAC,CAAC,MAAM,CACvE,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE,qBAAqB,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC/C,GAAG,SAAS;gBACZ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC,qBAAqB,CAAC;aACjD,CAAC,EACF,EAAE,CACH;SACF,CAAC,EACF,EAAE,CACH;KACF,CAAC,EACF,EAAE,CACH,CAAC;AACJ,CAAC;AApBD,4EAoBC","sourcesContent":["import type { GuStack } from \"../../constructs/core\";\nimport { groupBy } from \"../../utils/array\";\nimport type { ClassName, GroupedCdkStacks, Region, StackTag, StageTag } from \"./types\";\n\nfunction groupByClassName(cdkStacks: GuStack[]): Record<ClassName, GuStack[]> {\n return groupBy(cdkStacks, (stack) => stack.constructor.name);\n}\n\nfunction groupByStackTag(cdkStacks: GuStack[]): Record<StackTag, GuStack[]> {\n return groupBy(cdkStacks, ({ stack }) => stack);\n}\n\nfunction groupByStageTag(cdkStacks: GuStack[]): Record<StageTag, GuStack[]> {\n return groupBy(cdkStacks, ({ stage }) => stage);\n}\n\nfunction groupByRegion(cdkStacks: GuStack[]): Record<Region, GuStack[]> {\n return groupBy(cdkStacks, ({ region }) => region);\n}\n\nexport function groupByClassNameStackRegionStage(cdkStacks: GuStack[]): GroupedCdkStacks {\n return Object.entries(groupByClassName(cdkStacks)).reduce(\n (accClassName, [className, stacksGroupedByClassName]) => ({\n ...accClassName,\n [className]: Object.entries(groupByStackTag(stacksGroupedByClassName)).reduce(\n (accStackTag, [stackTag, stacksGroupedByStackTag]) => ({\n ...accStackTag,\n [stackTag]: Object.entries(groupByRegion(stacksGroupedByStackTag)).reduce(\n (accRegion, [region, stacksGroupedByRegion]) => ({\n ...accRegion,\n [region]: groupByStageTag(stacksGroupedByRegion),\n }),\n {},\n ),\n }),\n {},\n ),\n }),\n {},\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAmC;AACnC,gDAAwB;AAExB,6CAAoC;AACpC,qCAA+B;AAC/B,8DAAkE;AAClE,gDAAgD;AAChD,oDAA2D;AAC3D,2DAA6F;AAC7F,iEAAoH;AACpH,iDAAoF;AACpF,yCAA8D;AAY9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,4BAA4B;IAS/B,iBAAiB,CAAC,aAAuB,EAAE,aAAuB;QACxE,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,C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WAAW,CAAC,GAAG,CACb,aAAa,CAAC,IAAI,EAClB,IAAA,2DAA0C,EAAC,aAAa,EAAE,iBAAiB,CAAC,CAC7E,CAAC;gBACJ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG;YAClB,aAAa;YACb,WAAW;SACZ,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,MAAM;QACJ,qFAAqF;QACrF,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,KAAc,EAAE,EAAE;YAChD,IAAI,KAAK,YAAY,GAAG,EAAE;gBACxB,iGAAiG;gBACjG,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;aAC1B;YACD,IAAI,KAAK,YAAY,GAAG,EAAE;gBACxB,iGAAiG;gBACjG,OAAO,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;aAClC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;QAEF,OAAO,IAAA,cAAI,EAAC,IAAI,CAAC,YAAY,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACzD,IAAA,kBAAa,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACxC,CAAC;CACF;AA3ND,oEA2NC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../../constructs/autoscaling\";\nimport { GuStack } from \"../../constructs/core\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport { addAmiParametersToCloudFormationDeployment, cloudFormationDeployment } from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { groupByClassNameStackRegionStage } from \"./group-by\";\nimport type {\n GroupedCdkStacks,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFileExperimental {\n private readonly allCdkStacks: GuStack[];\n private readonly allStackTags: StackTag[];\n private readonly allStageTags: StageTag[];\n private readonly allRegions: Region[];\n\n private readonly riffRaffYaml: RiffRaffYaml;\n private readonly outdir: string;\n\n private isCdkStackPresent(expectedStack: StackTag, expectedStage: StageTag): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const { stack, stage } = cdkStack;\n return stack === expectedStack && stage === expectedStage;\n });\n\n return !!matches;\n }\n\n /**\n * Check there are the appropriate number of `GuStack`s.\n * Expect to find an instance for each combination of `stack`, and `stage`.\n *\n * If not valid, a message is logged describing what is missing to aid debugging.\n *\n * Given the following:\n *\n * ```ts\n * const app = new App();\n *\n * class MyApplicationStack extends GuStack { }\n *\n * new MyApplicationStack(app, \"App-CODE-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"CODE\"\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-media-service\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"media-service\",\n * stage: \"PROD\",\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"PROD\"\n * });\n * ```\n *\n * This will log a message like this, where ❌ denotes something missing,\n * specifically there is no `CODE` template for `media-service`.\n *\n * ```log\n * Unable to produce a working riff-raff.yaml file; missing 1 definitions (details below)\n *\n * ┌───────────────┬──────┬──────┐\n * │ (index) │ CODE │ PROD │\n * ├───────────────┼──────┼──────┤\n * │ deploy │ '✅' │ '✅' │\n * │ media-service │ '❌' │ '✅' │\n * └───────────────┴──────┴──────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<StackTag, Record<StageTag, Found | NotFound>>;\n\n const { allStackTags, allStageTags } = this;\n\n const checks: AppValidation = allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(stackTag, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions: Array<Found | NotFound> = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).filter((_) => _ === \"❌\");\n });\n\n if (missingDefinitions.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingDefinitions.length} definitions`;\n\n console.log(`${message} (details below)`);\n console.table(checks);\n\n throw new Error(message);\n }\n }\n\n private validateAllRegionsAreResolved(): void {\n const unresolved = this.allRegions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n }\n\n private getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n }\n\n private getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));\n this.allStageTags = Array.from(allowedStages);\n this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));\n this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));\n\n this.validateStacksInApp();\n this.validateAllRegionsAreResolved();\n\n this.outdir = app.outdir;\n\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n const groupedStacks: GroupedCdkStacks = groupByClassNameStackRegionStage(this.allCdkStacks);\n\n Object.values(groupedStacks).forEach((stackTagGroup) => {\n Object.values(stackTagGroup).forEach((regionGroup) => {\n Object.values(regionGroup).forEach((stageGroup) => {\n const stacks: GuStack[] = Object.values(stageGroup).flat();\n\n if (stacks.length === 0) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length of `stacks` is checked above\n const stack = stacks[0]!;\n\n const lambdas = this.getLambdas(stack);\n const autoscalingGroups = this.getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const cfnDeployment = cloudFormationDeployment(stacks, artifactUploads, this.outdir);\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n autoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n deployments.set(\n cfnDeployment.name,\n addAmiParametersToCloudFormationDeployment(cfnDeployment, autoscalingGroups)\n );\n });\n });\n });\n\n this.riffRaffYaml = {\n allowedStages,\n deployments,\n };\n }\n\n /**\n * The `riff-raff.yaml` file as a string.\n * Useful for testing.\n */\n toYAML(): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n return dump(this.riffRaffYaml, { replacer });\n }\n\n /**\n * Write the `riff-raff.yaml` file to disk.\n * It'll be located with the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n const outPath = path.join(this.outdir, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAmC;AACnC,gDAAwB;AAExB,6CAAoC;AACpC,qCAA+B;AAC/B,8DAAkE;AAClE,gDAAgD;AAChD,oDAA2D;AAC3D,2DAA6F;AAC7F,iEAAoH;AACpH,iDAAoF;AACpF,yCAA8D;AAY9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,4BAA4B;IAS/B,iBAAiB,CAAC,aAAuB,EAAE,aAAuB;QACxE,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE;YAClD,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC;YAClC,OAAO,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,aAAa,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAqDG;IACK,mBAAmB;QAKzB,MAAM,EAAE,YAAY,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;QAE5C,MAAM,MAAM,GAAkB,YAAY,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE;YAC1E,OAAO;gBACL,GAAG,WAAW;gBACd,CAAC,QAAQ,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE;oBACxD,OAAO;wBACL,GAAG,WAAW;wBACd,CAAC,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EF,OAAO,IAAA,cAAI,EAAC,IAAI,CAAC,YAAY,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACzD,IAAA,kBAAa,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACxC,CAAC;CACF;AA3ND,oEA2NC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../../constructs/autoscaling\";\nimport { GuStack } from \"../../constructs/core\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport { addAmiParametersToCloudFormationDeployment, cloudFormationDeployment } from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { groupByClassNameStackRegionStage } from \"./group-by\";\nimport type {\n GroupedCdkStacks,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFileExperimental {\n private readonly allCdkStacks: GuStack[];\n private readonly allStackTags: StackTag[];\n private readonly allStageTags: StageTag[];\n private readonly allRegions: Region[];\n\n private readonly riffRaffYaml: RiffRaffYaml;\n private readonly outdir: string;\n\n private isCdkStackPresent(expectedStack: StackTag, expectedStage: StageTag): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const { stack, stage } = cdkStack;\n return stack === expectedStack && stage === expectedStage;\n });\n\n return !!matches;\n }\n\n /**\n * Check there are the appropriate number of `GuStack`s.\n * Expect to find an instance for each combination of `stack`, and `stage`.\n *\n * If not valid, a message is logged describing what is missing to aid debugging.\n *\n * Given the following:\n *\n * ```ts\n * const app = new App();\n *\n * class MyApplicationStack extends GuStack { }\n *\n * new MyApplicationStack(app, \"App-CODE-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"CODE\"\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-media-service\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"media-service\",\n * stage: \"PROD\",\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"PROD\"\n * });\n * ```\n *\n * This will log a message like this, where ❌ denotes something missing,\n * specifically there is no `CODE` template for `media-service`.\n *\n * ```log\n * Unable to produce a working riff-raff.yaml file; missing 1 definitions (details below)\n *\n * ┌───────────────┬──────┬──────┐\n * │ (index) │ CODE │ PROD │\n * ├───────────────┼──────┼──────┤\n * │ deploy │ '✅' │ '✅' │\n * │ media-service │ '❌' │ '✅' │\n * └───────────────┴──────┴──────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<StackTag, Record<StageTag, Found | NotFound>>;\n\n const { allStackTags, allStageTags } = this;\n\n const checks: AppValidation = allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(stackTag, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions: Array<Found | NotFound> = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).filter((_) => _ === \"❌\");\n });\n\n if (missingDefinitions.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingDefinitions.length} definitions`;\n\n console.log(`${message} (details below)`);\n console.table(checks);\n\n throw new Error(message);\n }\n }\n\n private validateAllRegionsAreResolved(): void {\n const unresolved = this.allRegions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n }\n\n private getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n }\n\n private getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));\n this.allStageTags = Array.from(allowedStages);\n this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));\n this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));\n\n this.validateStacksInApp();\n this.validateAllRegionsAreResolved();\n\n this.outdir = app.outdir;\n\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n const groupedStacks: GroupedCdkStacks = groupByClassNameStackRegionStage(this.allCdkStacks);\n\n Object.values(groupedStacks).forEach((stackTagGroup) => {\n Object.values(stackTagGroup).forEach((regionGroup) => {\n Object.values(regionGroup).forEach((stageGroup) => {\n const stacks: GuStack[] = Object.values(stageGroup).flat();\n\n if (stacks.length === 0) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length of `stacks` is checked above\n const stack = stacks[0]!;\n\n const lambdas = this.getLambdas(stack);\n const autoscalingGroups = this.getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const cfnDeployment = cloudFormationDeployment(stacks, artifactUploads, this.outdir);\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n autoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n deployments.set(\n cfnDeployment.name,\n addAmiParametersToCloudFormationDeployment(cfnDeployment, autoscalingGroups),\n );\n });\n });\n });\n\n this.riffRaffYaml = {\n allowedStages,\n deployments,\n };\n }\n\n /**\n * The `riff-raff.yaml` file as a string.\n * Useful for testing.\n */\n toYAML(): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n return dump(this.riffRaffYaml, { replacer });\n }\n\n /**\n * Write the `riff-raff.yaml` file to disk.\n * It'll be located with the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n const outPath = path.join(this.outdir, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML());\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-multiple-lambdas.js","sourceRoot":"","sources":["../../src/patterns/api-multiple-lambdas.ts"],"names":[],"mappings":";;;AACA,+DAAwE;AACxE,2CAAuC;AAEvC,oFAA6F;AAiE7F,SAAS,cAAc,CACrB,uBAAwD;IAExD,OAAsB,uBAAwB,CAAC,YAAY,CAAC;AAC9D,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,MAAa,4BAA6B,SAAQ,sBAAS;IAGzD,YAAY,KAAc,EAAE,KAAwC;QAClE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,oCAAoC;QAC7D,MAAM,UAAU,GAAG,IAAI,wBAAO,CAAC,KAAK,EAAE,SAAS,EAAE;YAC/C,4FAA4F;YAC5F,WAAW,EAAE,GAAG,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,GAAG,EAAE;YACzD,GAAG,KAAK;SACT,CAAC,CAAC;QAEH,IAAI,CAAC,GAAG,GAAG,UAAU,CAAC;QACtB,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;YAC3B,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC9D,sGAAsG;YACtG,0DAA0D;YAC1D,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC;YAC1D,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,UAAU,EAAE,IAAI,kCAAiB,CAAC,YAAY,CAAC,EAAE;gBACzE,cAAc,EAAE,MAAM,CAAC,cAAc;aACtC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,uBAAuB,CAAC,EAAE;YAClD,IAAI,mDAA8B,CAAC,KAAK,EAAE;gBACxC,GAAG,EAAE,KAAK,CAAC,GAAG;gBACd,kBAAkB,EAAE,UAAU;gBAC9B,YAAY,EAAE,KAAK,CAAC,uBAAuB,CAAC,YAAY;gBACxD,GAAG,KAAK,CAAC,uBAAuB,CAAC,YAAY;aAC9C,CAAC,CAAC;SACJ;IACH,CAAC;CACF;AA9BD,oEA8BC","sourcesContent":["import type { RestApiProps } from \"aws-cdk-lib/aws-apigateway\";\nimport { LambdaIntegration, RestApi } from \"aws-cdk-lib/aws-apigateway\";\nimport { Construct } from \"constructs\";\nimport type { Http5xxAlarmProps, NoMonitoring } from \"../constructs/cloudwatch\";\nimport { GuApiGateway5xxPercentageAlarm } from \"../constructs/cloudwatch/api-gateway-alarms\";\nimport type { AppIdentity, GuStack } from \"../constructs/core\";\nimport type { GuLambdaFunction } from \"../constructs/lambda\";\n\n/**\n * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\n */\nexport type HttpMethod = \"GET\" | \"HEAD\" | \"POST\" | \"PUT\" | \"DELETE\" | \"CONNECT\" | \"OPTIONS\" | \"TRACE\" | \"PATCH\";\n\n/**\n * API target props.\n */\nexport interface ApiTarget {\n /**\n * The path for the request (e.g. /test).\n */\n path: string;\n /**\n * The [[`HttpMethod`]] for the target (e.g. GET, POST, PUT).\n */\n httpMethod: HttpMethod;\n /**\n * The Lambda function responsible for handling the request.\n */\n lambda: GuLambdaFunction;\n /**\n * Whether an apiKey is required for this method.\n */\n apiKeyRequired?: true;\n}\n\n/**\n * Alarm props.\n */\nexport interface ApiGatewayAlarms {\n /**\n * (SNS) Topic name where alarm notifications will be sent.\n */\n snsTopicName: string;\n /**\n * Configuration the 5xx alarm.\n */\n http5xxAlarm: Http5xxAlarmProps;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuApiGatewayWithLambdaByPathProps extends RestApiProps, AppIdentity {\n /**\n * A list of [[`ApiTarget`]]s to configure for the API Gateway instance.\n */\n targets: ApiTarget[];\n /**\n * Alarm configuration for your API. For more details, see [[`ApiGatewayAlarms`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true }\n * ```\n */\n monitoringConfiguration: NoMonitoring | ApiGatewayAlarms;\n}\n\nfunction isNoMonitoring(\n monitoringConfiguration: NoMonitoring | ApiGatewayAlarms
|
|
1
|
+
{"version":3,"file":"api-multiple-lambdas.js","sourceRoot":"","sources":["../../src/patterns/api-multiple-lambdas.ts"],"names":[],"mappings":";;;AACA,+DAAwE;AACxE,2CAAuC;AAEvC,oFAA6F;AAiE7F,SAAS,cAAc,CACrB,uBAAwD;IAExD,O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C9C,CAAC,CAAC;SACJ;IACH,CAAC;CACF;AA9BD,oEA8BC","sourcesContent":["import type { RestApiProps } from \"aws-cdk-lib/aws-apigateway\";\nimport { LambdaIntegration, RestApi } from \"aws-cdk-lib/aws-apigateway\";\nimport { Construct } from \"constructs\";\nimport type { Http5xxAlarmProps, NoMonitoring } from \"../constructs/cloudwatch\";\nimport { GuApiGateway5xxPercentageAlarm } from \"../constructs/cloudwatch/api-gateway-alarms\";\nimport type { AppIdentity, GuStack } from \"../constructs/core\";\nimport type { GuLambdaFunction } from \"../constructs/lambda\";\n\n/**\n * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\n */\nexport type HttpMethod = \"GET\" | \"HEAD\" | \"POST\" | \"PUT\" | \"DELETE\" | \"CONNECT\" | \"OPTIONS\" | \"TRACE\" | \"PATCH\";\n\n/**\n * API target props.\n */\nexport interface ApiTarget {\n /**\n * The path for the request (e.g. /test).\n */\n path: string;\n /**\n * The [[`HttpMethod`]] for the target (e.g. GET, POST, PUT).\n */\n httpMethod: HttpMethod;\n /**\n * The Lambda function responsible for handling the request.\n */\n lambda: GuLambdaFunction;\n /**\n * Whether an apiKey is required for this method.\n */\n apiKeyRequired?: true;\n}\n\n/**\n * Alarm props.\n */\nexport interface ApiGatewayAlarms {\n /**\n * (SNS) Topic name where alarm notifications will be sent.\n */\n snsTopicName: string;\n /**\n * Configuration the 5xx alarm.\n */\n http5xxAlarm: Http5xxAlarmProps;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuApiGatewayWithLambdaByPathProps extends RestApiProps, AppIdentity {\n /**\n * A list of [[`ApiTarget`]]s to configure for the API Gateway instance.\n */\n targets: ApiTarget[];\n /**\n * Alarm configuration for your API. For more details, see [[`ApiGatewayAlarms`]].\n *\n * If your team do not use CloudWatch, it's possible to opt-out with the following configuration:\n * ```typescript\n * monitoringConfiguration: { noMonitoring: true }\n * ```\n */\n monitoringConfiguration: NoMonitoring | ApiGatewayAlarms;\n}\n\nfunction isNoMonitoring(\n monitoringConfiguration: NoMonitoring | ApiGatewayAlarms,\n): monitoringConfiguration is NoMonitoring {\n return (<NoMonitoring>monitoringConfiguration).noMonitoring;\n}\n\n/**\n * A pattern to create an API Gateway instance which uses path-based routing to route requests\n * to two or more Lambda functions.\n *\n * This pattern should be used if you need to configure path-based routing to serve different\n * requests with different Lambdas. If you intend to serve all traffic via a single Lambda, use\n * the [[`GuApiLambda`]] pattern instead.\n *\n * Example usage:\n *\n * ```typescript\n * // Configure lambdas\n * const lambdaOne = new GuLambdaFunction(this, \"lambda-one\", {\n * app: \"example-lambda-one\",\n * runtime: Runtime.NODEJS_14_X,\n * handler: \"lambda-one.handler\",\n * fileName: \"lambda-one.zip\",\n * });\n * const lambdaTwo = new GuLambdaFunction(this, \"lambda-two\", {\n * app: \"example-lambda-two\",\n * runtime: Runtime.NODEJS_14_X,\n * handler: \"lambda-two.handler\",\n * fileName: \"lambda-two.zip\",\n * });\n *\n * // Wire up the API\n * new GuApiGatewayWithLambdaByPath(this, {\n * app: \"example-api-gateway-instance\",\n * targets: [\n * {\n * path: \"lambda-one\",\n * httpMethod: \"GET\",\n * lambda: lambdaOne,\n * },\n * {\n * path: \"lambda-two\",\n * httpMethod: \"GET\",\n * lambda: lambdaTwo,\n * },\n * ],\n * // Create an alarm\n * monitoringConfiguration: {\n * snsTopicName: \"my-topic-for-cloudwatch-alerts\",\n * http5xxAlarm: {\n * tolerated5xxPercentage: 1,\n * }\n * }\n * });\n * ```\n *\n * For all API configuration options, see [[`GuApiGatewayWithLambdaByPathProps`]].\n *\n * For details on configuring the individual Lambda functions, see [[`GuLambdaFunction`]].\n */\nexport class GuApiGatewayWithLambdaByPath extends Construct {\n public readonly api: RestApi;\n\n constructor(scope: GuStack, props: GuApiGatewayWithLambdaByPathProps) {\n super(scope, props.app); // The assumption is `app` is unique\n const apiGateway = new RestApi(scope, \"RestApi\", {\n // Override to avoid clashes as default is just api ID, which is often shared across stages.\n restApiName: `${scope.stack}-${scope.stage}-${props.app}`,\n ...props,\n });\n\n this.api = apiGateway;\n props.targets.map((target) => {\n const resource = apiGateway.root.resourceForPath(target.path);\n // If we have an alias, use this to ensure that all requests are routed to a published Lambda version.\n // Otherwise, use the latest unpublished version ($LATEST)\n const lambdaTarget = target.lambda.alias ?? target.lambda;\n resource.addMethod(target.httpMethod, new LambdaIntegration(lambdaTarget), {\n apiKeyRequired: target.apiKeyRequired,\n });\n });\n if (!isNoMonitoring(props.monitoringConfiguration)) {\n new GuApiGateway5xxPercentageAlarm(scope, {\n app: props.app,\n apiGatewayInstance: apiGateway,\n snsTopicName: props.monitoringConfiguration.snsTopicName,\n ...props.monitoringConfiguration.http5xxAlarm,\n });\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/patterns/ec2-app/base.ts"],"names":[],"mappings":";;;;;;AAAA,uGAAuG;AACvG,oDAA4B;AAC5B,6CAA0D;AAE1D,iEAA0D;AAC1D,yDAKiC;AAEjC,iDAA2C;AAE3C,uFAA6F;AAC7F,uGAA2F;AAC3F,iDAA8D;AAC9D,uDAA+D;AAC/D,+CAA4C;AAC5C,iDAAsD;AACtD,2CAAuC;AACvC,+CAAuF;AACvF,8CAAqD;AAErD,8DAA8E;AAE9E,4DAAiG;AAEjG,gDAAqG;AACrG,8CAAsG;AAEtG,8CAAgF;AAChF,oDAA2D;AAC3D,kEAIwC;AACxC,uCAAwC;AAuPxC,SAAS,oBAAoB,CAAC,MAAe;IAC3C,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5B,KAAK;QACL,IAAI,EAAE,cAAI,CAAC,GAAG,CAAC,GAAG,CAAC;QACnB,WAAW,EAAE,iCAAiC,KAAK,CAAC,QAAQ,EAAE;KAC/D,CAAC,CAAC,CAAC;AACN,CAAC;AAED;;;;;;GAMG;AACH,MAAa,QAAS,SAAQ,s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oBAC9B,cAAc,EAAE,cAAc;oBAC9B,IAAI,EAAE,2CAAc,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC;oBAC3C,cAAc,EAAE,sBAAQ,CAAC,OAAO,CAAC,uBAAuB,CAAC;iBAC1D,CAAC;aACH,CAAC,CAAC;YAEH,qEAAqE;YACrE,MAAM,sBAAsB,GAAG,IAAI,gCAA0B,CAAC,KAAK,EAAE,YAAY,EAAE;gBACjF,GAAG;gBACH,GAAG;aACJ,CAAC,CAAC;YAEH,YAAY,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;SACvD;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AApUD,4BAoUC","sourcesContent":["/* eslint \"@guardian/tsdoc-required/tsdoc-required\": 2 -- to begin rolling this out for public APIs. */\nimport crypto from \"crypto\";\nimport { Duration, SecretValue, Tags } from \"aws-cdk-lib\";\nimport type { BlockDevice } from \"aws-cdk-lib/aws-autoscaling\";\nimport { HealthCheck } from \"aws-cdk-lib/aws-autoscaling\";\nimport {\n ProviderAttribute,\n UserPool,\n UserPoolClientIdentityProvider,\n UserPoolIdentityProviderGoogle,\n} from \"aws-cdk-lib/aws-cognito\";\nimport type { InstanceType, IPeer, ISubnet, IVpc } from \"aws-cdk-lib/aws-ec2\";\nimport { Port } from \"aws-cdk-lib/aws-ec2\";\nimport type { HealthCheck as ALBHealthCheck } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { ApplicationProtocol, ListenerAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { AuthenticateCognitoAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2-actions\";\nimport { Effect, PolicyStatement } from \"aws-cdk-lib/aws-iam\";\nimport { Architecture, Runtime } from \"aws-cdk-lib/aws-lambda\";\nimport { Bucket } from \"aws-cdk-lib/aws-s3\";\nimport { StringParameter } from \"aws-cdk-lib/aws-ssm\";\nimport { Construct } from \"constructs\";\nimport { AccessScope, MetadataKeys, NAMED_SSM_PARAMETER_PATHS } from \"../../constants\";\nimport { GuCertificate } from \"../../constructs/acm\";\nimport type { GuUserDataProps } from \"../../constructs/autoscaling\";\nimport { GuAutoScalingGroup, GuUserData } from \"../../constructs/autoscaling\";\nimport type { Http5xxAlarmProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { GuAlb5xxPercentageAlarm, GuUnhealthyInstancesAlarm } from \"../../constructs/cloudwatch\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { AppIdentity, GuLoggingStreamNameParameter, GuStringParameter } from \"../../constructs/core\";\nimport { GuHttpsEgressSecurityGroup, GuSecurityGroup, GuVpc, SubnetType } from \"../../constructs/ec2\";\nimport type { GuInstanceRoleProps } from \"../../constructs/iam\";\nimport { GuGetPrivateConfigPolicy, GuInstanceRole } from \"../../constructs/iam\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport {\n GuApplicationLoadBalancer,\n GuApplicationTargetGroup,\n GuHttpsApplicationListener,\n} from \"../../constructs/loadbalancing\";\nimport { AppAccess } from \"../../types\";\nimport type { GuAsgCapacity, GuDomainName } from \"../../types\";\nimport type { AmigoProps } from \"../../types/amigo\";\n\nexport interface AccessLoggingProps {\n /**\n * Enable (load balancer) access logs.\n *\n * Note, you will need to specify a region in your stack declaration to use\n * this.\n * See`https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-elasticloadbalancingv2.ApplicationLoadBalancer.html#logwbraccesswbrlogsbucket-prefix`\n */\n enabled: boolean;\n /**\n * S3 prefix for the logs.\n *\n * @defaultValue no prefix\n */\n prefix?: string;\n}\n\n/**\n * To ship your application logs to ELK automatically, you must:\n *\n * 1. Set the `enabled` flag to true\n * 2. Include the `cdk-base` Amigo role in your AMI\n * 3. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 4. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for logging\n * to Kinesis will be configured automatically via the [[`GuEc2App`]] pattern.\n */\nexport interface ApplicationLoggingProps {\n /**\n * Enables forwarding of application logs to the Guardian ELK stack.\n *\n * Note, to work, you will need to also do the following non-CDK things:\n *\n * 1. Include the `cdk-base` Amigo role in your AMI.\n * 2. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 3. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for\n * logging to Kinesis will be configured automatically via the [[`GuEc2App`]]\n * pattern.\n *\n * @see https://github.com/guardian/amigo/tree/main/roles/cdk-base\n */\n enabled: boolean;\n /**\n * This needs to match the name of your SystemD unit.\n *\n * If your systemd unit is not `<app>.service` set this value.\n *\n * @defaultValue `<app>.service`\n */\n systemdUnitName?: string;\n}\n\n/**\n * @privateRemarks we should rename this to AlarmsProps.\n */\nexport interface Alarms {\n /**\n * Name of the target (SNS Topic) for alarm notifications.\n */\n snsTopicName: string;\n /**\n * Enable the 5xx alarm with settings.\n */\n http5xxAlarm: false | Http5xxAlarmProps;\n /**\n * Enable the unhealthy instances alarm.\n */\n unhealthyInstancesAlarm: boolean;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuEc2AppProps extends AppIdentity {\n /**\n * User data for the autoscaling group.\n */\n userData: GuUserDataProps | string;\n /**\n * Network access restrictions for your load balancer.\n *\n * Note, this merely provides defence in depth; you should, for example, limit\n * access to the VPN and then treat that as sufficient. Instead, use Google\n * Auth for human access, or a suitable machine auth mechanism.\n */\n access: AppAccess;\n /**\n * The port your application runs on.\n */\n applicationPort: number;\n /**\n * Configure IAM roles for autoscaling group EC2 instances.\n */\n roleConfiguration?: GuInstanceRoleProps;\n /**\n * Enable and configure alarms.\n */\n monitoringConfiguration: Alarms | NoMonitoring;\n /**\n * EC2 instance type. Note, ensure your code is built for the same\n * architecture family (arm64 - 'Graviton' instances - or x64).\n */\n instanceType: InstanceType;\n /**\n * Enable and configures application logs.\n */\n applicationLogging?: ApplicationLoggingProps;\n /**\n * Enable and configures access logs.\n */\n accessLogging?: AccessLoggingProps;\n /**\n * Add block devices (additional storage).\n */\n blockDevices?: BlockDevice[];\n /**\n * Autoscaling group min and max sizes.\n */\n scaling: GuAsgCapacity;\n /**\n * Specify certificate for the load balancer.\n */\n certificateProps?: GuDomainName;\n /**\n * Disable imdsv2. Most of the time you should not set this.\n *\n * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html\n */\n withoutImdsv2?: boolean;\n /**\n * Configure Amigo image recipe.\n */\n imageRecipe?: string | AmigoProps;\n /**\n * Specify the VPC to use.\n *\n * @see https://github.com/guardian/aws-account-setup\n */\n vpc?: IVpc;\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n privateSubnets?: ISubnet[];\n\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n publicSubnets?: ISubnet[];\n\n /**\n * Configure Google Auth.\n */\n googleAuth?: {\n /**\n * Enables Google Auth (via Cognito). **Additional MANUAL steps required -\n * see below.**\n *\n * Limits access to members of the allowed Google groups.\n *\n * Note, this does not currently support simultaneous machine access, so\n * only set to true if you only require staff access to your service, or are\n * supporting machine access in some other way.\n *\n * MANUAL STEPS: to get this to work, we need a Google Project and\n * associated credentials. Full instructions can be found here:\n *\n * https://docs.google.com/document/d/1_k1FSE52AZHXufWLTiKTI3xy5cGpziyHazSHTKrYfco/edit?usp=sharing\n *\n * DevX hope to automate this process in the near future.\n */\n enabled: true;\n /**\n * The domain users will access your service.\n *\n * Set this to the same as for certificateProps.\n */\n domain: string;\n /**\n * Groups used for membership checks.\n *\n * If specified, cannot be empty. Users must be a member of at least one\n * group to gain access.\n *\n * WARNING: groups must be specified with the `guardian.co.uk` domain, even\n * if that is the non-idiomatic choice for daily use.\n *\n * @defaultValue [`engineering@guardian.co.uk`]\n */\n allowedGroups?: string[];\n /**\n * The number of minutes before the session expires.\n *\n * Set this value to a safe period of time that revoked users\n * sessions will continue to function.\n *\n * NOTE: This value cannot be larger than 60 minutes.\n *\n * @defaultValue 15\n */\n sessionTimeoutInMinutes?: number;\n /**\n * Secrets Manager path containing Google OAuth2 Client credentials.\n *\n * NOTE: you do not need to set this value, but you DO need to generate and\n * store the associated credentials in Secrets Manager.\n *\n * Credentials should be stored in Secrets Manager as JSON:\n *\n * ```json\n * {\n * \"clientId\": \"my-client-id\",\n * \"clientSecret\": \"my-client-secret\"\n * }\n * ```\n *\n * @see `googleAuth.enabled` for how to generate.\n *\n * @defaultValue /:STAGE/:stack/:app/google-auth-credentials\n */\n credentialsSecretsManagerPath?: string;\n };\n\n /**\n * Specify custom healthcheck\n */\n healthcheck?: ALBHealthCheck;\n\n /**\n * Set http put response hop limit for the launch template.\n * It can be necessary to raise this value from the default of 1\n * for example when sharing the instance profile with a docker container running on the instance.\n */\n instanceMetadataHopLimit?: number;\n}\n\nfunction restrictedCidrRanges(ranges: IPeer[]) {\n return ranges.map((range) => ({\n range,\n port: Port.tcp(443),\n description: `Allow access on port 443 from ${range.uniqueId}`,\n }));\n}\n\n/**\n * Pattern which creates the resources needed to run an application on EC2\n * behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]\n * or [[`GuNodeApp`]], which extend this class.\n *\n * See props for further details.\n */\nexport class GuEc2App extends Construct {\n /*\n * These are public for now, as this allows users to\n * modify these constructs as desired to fit their\n * specific needs.\n * In the future, we might build functionality to better enable users\n * to access in-pattern constructs, but this would allow teams to be unblocked\n * in the short term.\n * */\n public readonly vpc: IVpc;\n public readonly certificate?: GuCertificate;\n public readonly loadBalancer: GuApplicationLoadBalancer;\n public readonly autoScalingGroup: GuAutoScalingGroup;\n public readonly listener: GuHttpsApplicationListener;\n public readonly targetGroup: GuApplicationTargetGroup;\n\n constructor(scope: GuStack, props: GuEc2AppProps) {\n const {\n access,\n accessLogging = { enabled: false },\n app,\n // We should update this default once a significant number of apps have migrated to devx-logs\n applicationLogging = { enabled: false },\n applicationPort,\n blockDevices,\n certificateProps,\n instanceType,\n monitoringConfiguration,\n roleConfiguration = { withoutLogShipping: false, additionalPolicies: [] },\n scaling: { minimumInstances, maximumInstances = minimumInstances * 2 },\n userData,\n withoutImdsv2,\n imageRecipe,\n vpc = GuVpc.fromIdParameter(scope, AppIdentity.suffixText({ app }, \"VPC\")),\n privateSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PRIVATE, app }),\n publicSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PUBLIC, app }),\n instanceMetadataHopLimit,\n } = props;\n\n super(scope, app); // The assumption is `app` is unique\n\n // We should really prevent users from doing this via the type system,\n // but that requires a breaking change to the API\n if (applicationLogging.enabled && roleConfiguration.withoutLogShipping) {\n throw new Error(\n \"Application logging has been enabled (via the `applicationLogging` prop) but your `roleConfiguration` sets \" +\n \"`withoutLogShipping` to true. Please turn off application logging or remove `withoutLogShipping`\"\n );\n }\n\n AppAccess.validate(access);\n\n const certificate =\n typeof certificateProps !== \"undefined\"\n ? new GuCertificate(scope, {\n app,\n domainName: certificateProps.domainName,\n hostedZoneId: certificateProps.hostedZoneId,\n })\n : undefined;\n\n const maybePrivateConfigPolicy =\n typeof userData !== \"string\" && userData.configuration\n ? [new GuGetPrivateConfigPolicy(scope, \"GetPrivateConfigFromS3Policy\", userData.configuration)]\n : [];\n\n const mergedRoleConfiguration: GuInstanceRoleProps = {\n withoutLogShipping: roleConfiguration.withoutLogShipping,\n additionalPolicies: maybePrivateConfigPolicy.concat(roleConfiguration.additionalPolicies ?? []),\n };\n\n const autoScalingGroup = new GuAutoScalingGroup(scope, \"AutoScalingGroup\", {\n app,\n vpc,\n instanceType,\n minimumInstances,\n maximumInstances,\n withoutImdsv2,\n role: new GuInstanceRole(scope, { app, ...mergedRoleConfiguration }),\n healthCheck: HealthCheck.elb({ grace: Duration.minutes(2) }), // should this be defaulted at pattern or construct level?\n userData: typeof userData !== \"string\" ? new GuUserData(scope, { app, ...userData }).userData : userData,\n vpcSubnets: { subnets: privateSubnets },\n ...(blockDevices && { blockDevices }),\n imageRecipe,\n httpPutResponseHopLimit: instanceMetadataHopLimit,\n });\n\n // This allows automatic shipping of instance Cloud Init logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.LOG_KINESIS_STREAM_NAME,\n GuLoggingStreamNameParameter.getInstance(scope).valueAsString\n );\n\n if (applicationLogging.enabled) {\n // This allows automatic shipping of application logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.SYSTEMD_UNIT,\n applicationLogging.systemdUnitName ? `${applicationLogging.systemdUnitName}.service` : `${app}.service`\n );\n }\n\n const loadBalancer = new GuApplicationLoadBalancer(scope, \"LoadBalancer\", {\n app,\n vpc,\n // Setting internetFacing to true does not necessarily allow public access to the load balancer itself. That is handled by the listener's `open` prop.\n internetFacing: access.scope !== AccessScope.INTERNAL,\n vpcSubnets: {\n subnets: access.scope === AccessScope.INTERNAL ? privateSubnets : publicSubnets,\n },\n });\n\n if (accessLogging.enabled) {\n const accessLoggingBucket = new GuStringParameter(scope, \"AccessLoggingBucket\", {\n description: NAMED_SSM_PARAMETER_PATHS.AccessLoggingBucket.description,\n default: NAMED_SSM_PARAMETER_PATHS.AccessLoggingBucket.path,\n fromSSM: true,\n });\n\n loadBalancer.logAccessLogs(\n Bucket.fromBucketName(\n scope,\n AppIdentity.suffixText(props, \"AccessLoggingBucket\"),\n accessLoggingBucket.valueAsString\n ),\n accessLogging.prefix\n );\n }\n\n const targetGroup = new GuApplicationTargetGroup(scope, \"TargetGroup\", {\n app,\n vpc,\n protocol: ApplicationProtocol.HTTP,\n targets: [autoScalingGroup],\n port: applicationPort,\n healthCheck: props.healthcheck,\n });\n\n const listener = new GuHttpsApplicationListener(scope, \"Listener\", {\n app,\n loadBalancer,\n certificate,\n targetGroup,\n // When open=true, AWS will create a security group which allows all inbound traffic over HTTPS\n open: access.scope === AccessScope.PUBLIC && typeof certificate !== \"undefined\",\n });\n\n // Since AWS won't create a security group automatically when open=false, we need to add our own\n if (access.scope !== AccessScope.PUBLIC) {\n loadBalancer.addSecurityGroup(\n new GuSecurityGroup(scope, `${access.scope}IngressSecurityGroup`, {\n app,\n vpc,\n description: \"Allow restricted ingress from CIDR ranges\",\n allowAllOutbound: false,\n ingresses: restrictedCidrRanges(access.cidrRanges),\n })\n );\n }\n\n if (!monitoringConfiguration.noMonitoring) {\n const { http5xxAlarm, snsTopicName, unhealthyInstancesAlarm } = monitoringConfiguration;\n\n if (http5xxAlarm) {\n new GuAlb5xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http5xxAlarm,\n });\n }\n if (unhealthyInstancesAlarm) {\n new GuUnhealthyInstancesAlarm(scope, {\n app,\n targetGroup,\n snsTopicName,\n });\n }\n }\n\n if (props.googleAuth?.enabled) {\n const prefix = `/${scope.stage}/${scope.stack}/${app}`;\n\n const {\n allowedGroups = [\"engineering@guardian.co.uk\"],\n sessionTimeoutInMinutes = 15,\n credentialsSecretsManagerPath = `${prefix}/google-auth-credentials`,\n } = props.googleAuth;\n\n if (sessionTimeoutInMinutes > 60) {\n throw new Error(\"googleAuth.sessionTimeoutInMinutes must be <= 60!\");\n }\n\n if (allowedGroups.length < 1) {\n throw new Error(\"googleAuth.allowedGroups cannot be empty!\");\n }\n\n if (allowedGroups.find((group) => !group.endsWith(\"@guardian.co.uk\"))) {\n throw new Error(\"googleAuth.allowedGroups must use the @guardian.co.uk domain.\");\n }\n\n const deployToolsAccountId = StringParameter.fromStringParameterName(\n scope,\n \"deploy-tools-account-id-parameter\",\n NAMED_SSM_PARAMETER_PATHS.DeployToolsAccountId.path\n );\n\n // See https://github.com/guardian/cognito-auth-lambdas for the source\n // code here. ARN format is:\n // arn:aws:lambda:aws-region:acct-id:function:helloworld.\n const gatekeeperFunctionArn = `arn:aws:lambda:eu-west-1:${deployToolsAccountId.stringValue}:function:deploy-PROD-gatekeeper-lambda`;\n\n // Note, handler and filename must match here:\n // https://github.com/guardian/cognito-auth-lambdas.\n const authLambda = new GuLambdaFunction(scope, \"auth-lambda\", {\n app: app,\n memorySize: 128,\n handler: \"devx-cognito-lambda-amd64-v1\",\n runtime: Runtime.GO_1_X,\n fileName: \"deploy/INFRA/cognito-lambda/devx-cognito-lambda-amd64-v1.zip\",\n withoutFilePrefix: true,\n withoutArtifactUpload: true,\n bucketNamePath: NAMED_SSM_PARAMETER_PATHS.OrganisationDistributionBucket.path,\n architecture: Architecture.X86_64,\n environment: {\n ALLOWED_GROUPS: allowedGroups.join(\",\"),\n GATEKEEPER_FUNCTION_ARN: gatekeeperFunctionArn,\n },\n });\n\n authLambda.addToRolePolicy(\n new PolicyStatement({\n effect: Effect.ALLOW,\n actions: [\"lambda:InvokeFunction\"],\n resources: [gatekeeperFunctionArn],\n })\n );\n\n // Cognito user pool. We require both lambdas: pre-sign-up runs the first\n // time a user attempts to authenticate (before they exist in the User\n // Pool); pre-auth runs in subsequent authentication flows.\n const userPool = new UserPool(this, \"user-pool\", {\n lambdaTriggers: {\n preAuthentication: authLambda,\n preSignUp: authLambda,\n },\n });\n\n // These help ensure domain is deterministic but also unique. Key\n // assumption is that app/stack/stage combo are unique within Guardian.\n const domainPrefix = `com-gu-${app.toLowerCase()}-${scope.stage.toLowerCase()}`;\n const suffix = crypto.createHash(\"md5\").update(domainPrefix).digest(\"hex\");\n\n const userPoolDomain = userPool.addDomain(\"domain\", {\n cognitoDomain: {\n domainPrefix: `${domainPrefix}-${suffix}`,\n },\n });\n\n const clientId = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientId\" });\n const clientSecret = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientSecret\" });\n\n const userPoolIdp = new UserPoolIdentityProviderGoogle(scope, \"google-idp\", {\n userPool: userPool,\n clientId: clientId.toString(),\n clientSecret: clientSecret.toString(),\n attributeMapping: {\n email: ProviderAttribute.GOOGLE_EMAIL,\n givenName: ProviderAttribute.GOOGLE_GIVEN_NAME,\n familyName: ProviderAttribute.GOOGLE_FAMILY_NAME,\n profilePicture: ProviderAttribute.GOOGLE_PICTURE,\n custom: {\n name: ProviderAttribute.GOOGLE_NAME,\n },\n },\n scopes: [\"openid\", \"email\", \"profile\"],\n });\n\n const userPoolClient = userPool.addClient(\"alb-client\", {\n supportedIdentityProviders: [UserPoolClientIdentityProvider.GOOGLE],\n generateSecret: true,\n oAuth: {\n callbackUrls: [`https://${props.googleAuth.domain}/oauth2/idpresponse`],\n },\n\n // Note: id and access validity token validity cannot be less than one\n // hour (this is the cognito cookie duration). To quickly invalidate\n // credentials, disable the user in Cognito. It might be that we want to\n // parameterise these going forward, but that would require Infosec\n // discussion.\n idTokenValidity: Duration.hours(1),\n accessTokenValidity: Duration.hours(1),\n refreshTokenValidity: Duration.days(7),\n });\n\n userPoolClient.node.addDependency(userPoolIdp);\n\n listener.addAction(\"CognitoAuth\", {\n action: new AuthenticateCognitoAction({\n userPool: userPool,\n userPoolClient: userPoolClient,\n userPoolDomain: userPoolDomain,\n next: ListenerAction.forward([targetGroup]),\n sessionTimeout: Duration.minutes(sessionTimeoutInMinutes),\n }),\n });\n\n // Need to give the ALB outbound access on 443 for the IdP endpoints.\n const idpEgressSecurityGroup = new GuHttpsEgressSecurityGroup(scope, \"ldp-access\", {\n app,\n vpc,\n });\n\n loadBalancer.addSecurityGroup(idpEgressSecurityGroup);\n }\n\n this.vpc = vpc;\n this.certificate = certificate;\n this.loadBalancer = loadBalancer;\n this.autoScalingGroup = autoScalingGroup;\n this.listener = listener;\n this.targetGroup = targetGroup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AC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AApUD,4BAoUC","sourcesContent":["/* eslint \"@guardian/tsdoc-required/tsdoc-required\": 2 -- to begin rolling this out for public APIs. */\nimport crypto from \"crypto\";\nimport { Duration, SecretValue, Tags } from \"aws-cdk-lib\";\nimport type { BlockDevice } from \"aws-cdk-lib/aws-autoscaling\";\nimport { HealthCheck } from \"aws-cdk-lib/aws-autoscaling\";\nimport {\n ProviderAttribute,\n UserPool,\n UserPoolClientIdentityProvider,\n UserPoolIdentityProviderGoogle,\n} from \"aws-cdk-lib/aws-cognito\";\nimport type { InstanceType, IPeer, ISubnet, IVpc } from \"aws-cdk-lib/aws-ec2\";\nimport { Port } from \"aws-cdk-lib/aws-ec2\";\nimport type { HealthCheck as ALBHealthCheck } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { ApplicationProtocol, ListenerAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { AuthenticateCognitoAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2-actions\";\nimport { Effect, PolicyStatement } from \"aws-cdk-lib/aws-iam\";\nimport { Architecture, Runtime } from \"aws-cdk-lib/aws-lambda\";\nimport { Bucket } from \"aws-cdk-lib/aws-s3\";\nimport { StringParameter } from \"aws-cdk-lib/aws-ssm\";\nimport { Construct } from \"constructs\";\nimport { AccessScope, MetadataKeys, NAMED_SSM_PARAMETER_PATHS } from \"../../constants\";\nimport { GuCertificate } from \"../../constructs/acm\";\nimport type { GuUserDataProps } from \"../../constructs/autoscaling\";\nimport { GuAutoScalingGroup, GuUserData } from \"../../constructs/autoscaling\";\nimport type { Http5xxAlarmProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport { GuAlb5xxPercentageAlarm, GuUnhealthyInstancesAlarm } from \"../../constructs/cloudwatch\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { AppIdentity, GuLoggingStreamNameParameter, GuStringParameter } from \"../../constructs/core\";\nimport { GuHttpsEgressSecurityGroup, GuSecurityGroup, GuVpc, SubnetType } from \"../../constructs/ec2\";\nimport type { GuInstanceRoleProps } from \"../../constructs/iam\";\nimport { GuGetPrivateConfigPolicy, GuInstanceRole } from \"../../constructs/iam\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport {\n GuApplicationLoadBalancer,\n GuApplicationTargetGroup,\n GuHttpsApplicationListener,\n} from \"../../constructs/loadbalancing\";\nimport { AppAccess } from \"../../types\";\nimport type { GuAsgCapacity, GuDomainName } from \"../../types\";\nimport type { AmigoProps } from \"../../types/amigo\";\n\nexport interface AccessLoggingProps {\n /**\n * Enable (load balancer) access logs.\n *\n * Note, you will need to specify a region in your stack declaration to use\n * this.\n * See`https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-elasticloadbalancingv2.ApplicationLoadBalancer.html#logwbraccesswbrlogsbucket-prefix`\n */\n enabled: boolean;\n /**\n * S3 prefix for the logs.\n *\n * @defaultValue no prefix\n */\n prefix?: string;\n}\n\n/**\n * To ship your application logs to ELK automatically, you must:\n *\n * 1. Set the `enabled` flag to true\n * 2. Include the `cdk-base` Amigo role in your AMI\n * 3. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 4. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for logging\n * to Kinesis will be configured automatically via the [[`GuEc2App`]] pattern.\n */\nexport interface ApplicationLoggingProps {\n /**\n * Enables forwarding of application logs to the Guardian ELK stack.\n *\n * Note, to work, you will need to also do the following non-CDK things:\n *\n * 1. Include the `cdk-base` Amigo role in your AMI.\n * 2. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 3. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for\n * logging to Kinesis will be configured automatically via the [[`GuEc2App`]]\n * pattern.\n *\n * @see https://github.com/guardian/amigo/tree/main/roles/cdk-base\n */\n enabled: boolean;\n /**\n * This needs to match the name of your SystemD unit.\n *\n * If your systemd unit is not `<app>.service` set this value.\n *\n * @defaultValue `<app>.service`\n */\n systemdUnitName?: string;\n}\n\n/**\n * @privateRemarks we should rename this to AlarmsProps.\n */\nexport interface Alarms {\n /**\n * Name of the target (SNS Topic) for alarm notifications.\n */\n snsTopicName: string;\n /**\n * Enable the 5xx alarm with settings.\n */\n http5xxAlarm: false | Http5xxAlarmProps;\n /**\n * Enable the unhealthy instances alarm.\n */\n unhealthyInstancesAlarm: boolean;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuEc2AppProps extends AppIdentity {\n /**\n * User data for the autoscaling group.\n */\n userData: GuUserDataProps | string;\n /**\n * Network access restrictions for your load balancer.\n *\n * Note, this merely provides defence in depth; you should, for example, limit\n * access to the VPN and then treat that as sufficient. Instead, use Google\n * Auth for human access, or a suitable machine auth mechanism.\n */\n access: AppAccess;\n /**\n * The port your application runs on.\n */\n applicationPort: number;\n /**\n * Configure IAM roles for autoscaling group EC2 instances.\n */\n roleConfiguration?: GuInstanceRoleProps;\n /**\n * Enable and configure alarms.\n */\n monitoringConfiguration: Alarms | NoMonitoring;\n /**\n * EC2 instance type. Note, ensure your code is built for the same\n * architecture family (arm64 - 'Graviton' instances - or x64).\n */\n instanceType: InstanceType;\n /**\n * Enable and configures application logs.\n */\n applicationLogging?: ApplicationLoggingProps;\n /**\n * Enable and configures access logs.\n */\n accessLogging?: AccessLoggingProps;\n /**\n * Add block devices (additional storage).\n */\n blockDevices?: BlockDevice[];\n /**\n * Autoscaling group min and max sizes.\n */\n scaling: GuAsgCapacity;\n /**\n * Specify certificate for the load balancer.\n */\n certificateProps?: GuDomainName;\n /**\n * Disable imdsv2. Most of the time you should not set this.\n *\n * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html\n */\n withoutImdsv2?: boolean;\n /**\n * Configure Amigo image recipe.\n */\n imageRecipe?: string | AmigoProps;\n /**\n * Specify the VPC to use.\n *\n * @see https://github.com/guardian/aws-account-setup\n */\n vpc?: IVpc;\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n privateSubnets?: ISubnet[];\n\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n publicSubnets?: ISubnet[];\n\n /**\n * Configure Google Auth.\n */\n googleAuth?: {\n /**\n * Enables Google Auth (via Cognito). **Additional MANUAL steps required -\n * see below.**\n *\n * Limits access to members of the allowed Google groups.\n *\n * Note, this does not currently support simultaneous machine access, so\n * only set to true if you only require staff access to your service, or are\n * supporting machine access in some other way.\n *\n * MANUAL STEPS: to get this to work, we need a Google Project and\n * associated credentials. Full instructions can be found here:\n *\n * https://docs.google.com/document/d/1_k1FSE52AZHXufWLTiKTI3xy5cGpziyHazSHTKrYfco/edit?usp=sharing\n *\n * DevX hope to automate this process in the near future.\n */\n enabled: true;\n /**\n * The domain users will access your service.\n *\n * Set this to the same as for certificateProps.\n */\n domain: string;\n /**\n * Groups used for membership checks.\n *\n * If specified, cannot be empty. Users must be a member of at least one\n * group to gain access.\n *\n * WARNING: groups must be specified with the `guardian.co.uk` domain, even\n * if that is the non-idiomatic choice for daily use.\n *\n * @defaultValue [`engineering@guardian.co.uk`]\n */\n allowedGroups?: string[];\n /**\n * The number of minutes before the session expires.\n *\n * Set this value to a safe period of time that revoked users\n * sessions will continue to function.\n *\n * NOTE: This value cannot be larger than 60 minutes.\n *\n * @defaultValue 15\n */\n sessionTimeoutInMinutes?: number;\n /**\n * Secrets Manager path containing Google OAuth2 Client credentials.\n *\n * NOTE: you do not need to set this value, but you DO need to generate and\n * store the associated credentials in Secrets Manager.\n *\n * Credentials should be stored in Secrets Manager as JSON:\n *\n * ```json\n * {\n * \"clientId\": \"my-client-id\",\n * \"clientSecret\": \"my-client-secret\"\n * }\n * ```\n *\n * @see `googleAuth.enabled` for how to generate.\n *\n * @defaultValue /:STAGE/:stack/:app/google-auth-credentials\n */\n credentialsSecretsManagerPath?: string;\n };\n\n /**\n * Specify custom healthcheck\n */\n healthcheck?: ALBHealthCheck;\n\n /**\n * Set http put response hop limit for the launch template.\n * It can be necessary to raise this value from the default of 1\n * for example when sharing the instance profile with a docker container running on the instance.\n */\n instanceMetadataHopLimit?: number;\n}\n\nfunction restrictedCidrRanges(ranges: IPeer[]) {\n return ranges.map((range) => ({\n range,\n port: Port.tcp(443),\n description: `Allow access on port 443 from ${range.uniqueId}`,\n }));\n}\n\n/**\n * Pattern which creates the resources needed to run an application on EC2\n * behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]\n * or [[`GuNodeApp`]], which extend this class.\n *\n * See props for further details.\n */\nexport class GuEc2App extends Construct {\n /*\n * These are public for now, as this allows users to\n * modify these constructs as desired to fit their\n * specific needs.\n * In the future, we might build functionality to better enable users\n * to access in-pattern constructs, but this would allow teams to be unblocked\n * in the short term.\n * */\n public readonly vpc: IVpc;\n public readonly certificate?: GuCertificate;\n public readonly loadBalancer: GuApplicationLoadBalancer;\n public readonly autoScalingGroup: GuAutoScalingGroup;\n public readonly listener: GuHttpsApplicationListener;\n public readonly targetGroup: GuApplicationTargetGroup;\n\n constructor(scope: GuStack, props: GuEc2AppProps) {\n const {\n access,\n accessLogging = { enabled: false },\n app,\n // We should update this default once a significant number of apps have migrated to devx-logs\n applicationLogging = { enabled: false },\n applicationPort,\n blockDevices,\n certificateProps,\n instanceType,\n monitoringConfiguration,\n roleConfiguration = { withoutLogShipping: false, additionalPolicies: [] },\n scaling: { minimumInstances, maximumInstances = minimumInstances * 2 },\n userData,\n withoutImdsv2,\n imageRecipe,\n vpc = GuVpc.fromIdParameter(scope, AppIdentity.suffixText({ app }, \"VPC\")),\n privateSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PRIVATE, app }),\n publicSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PUBLIC, app }),\n instanceMetadataHopLimit,\n } = props;\n\n super(scope, app); // The assumption is `app` is unique\n\n // We should really prevent users from doing this via the type system,\n // but that requires a breaking change to the API\n if (applicationLogging.enabled && roleConfiguration.withoutLogShipping) {\n throw new Error(\n \"Application logging has been enabled (via the `applicationLogging` prop) but your `roleConfiguration` sets \" +\n \"`withoutLogShipping` to true. Please turn off application logging or remove `withoutLogShipping`\",\n );\n }\n\n AppAccess.validate(access);\n\n const certificate =\n typeof certificateProps !== \"undefined\"\n ? new GuCertificate(scope, {\n app,\n domainName: certificateProps.domainName,\n hostedZoneId: certificateProps.hostedZoneId,\n })\n : undefined;\n\n const maybePrivateConfigPolicy =\n typeof userData !== \"string\" && userData.configuration\n ? [new GuGetPrivateConfigPolicy(scope, \"GetPrivateConfigFromS3Policy\", userData.configuration)]\n : [];\n\n const mergedRoleConfiguration: GuInstanceRoleProps = {\n withoutLogShipping: roleConfiguration.withoutLogShipping,\n additionalPolicies: maybePrivateConfigPolicy.concat(roleConfiguration.additionalPolicies ?? []),\n };\n\n const autoScalingGroup = new GuAutoScalingGroup(scope, \"AutoScalingGroup\", {\n app,\n vpc,\n instanceType,\n minimumInstances,\n maximumInstances,\n withoutImdsv2,\n role: new GuInstanceRole(scope, { app, ...mergedRoleConfiguration }),\n healthCheck: HealthCheck.elb({ grace: Duration.minutes(2) }), // should this be defaulted at pattern or construct level?\n userData: typeof userData !== \"string\" ? new GuUserData(scope, { app, ...userData }).userData : userData,\n vpcSubnets: { subnets: privateSubnets },\n ...(blockDevices && { blockDevices }),\n imageRecipe,\n httpPutResponseHopLimit: instanceMetadataHopLimit,\n });\n\n // This allows automatic shipping of instance Cloud Init logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.LOG_KINESIS_STREAM_NAME,\n GuLoggingStreamNameParameter.getInstance(scope).valueAsString,\n );\n\n if (applicationLogging.enabled) {\n // This allows automatic shipping of application logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.SYSTEMD_UNIT,\n applicationLogging.systemdUnitName ? `${applicationLogging.systemdUnitName}.service` : `${app}.service`,\n );\n }\n\n const loadBalancer = new GuApplicationLoadBalancer(scope, \"LoadBalancer\", {\n app,\n vpc,\n // Setting internetFacing to true does not necessarily allow public access to the load balancer itself. That is handled by the listener's `open` prop.\n internetFacing: access.scope !== AccessScope.INTERNAL,\n vpcSubnets: {\n subnets: access.scope === AccessScope.INTERNAL ? privateSubnets : publicSubnets,\n },\n });\n\n if (accessLogging.enabled) {\n const accessLoggingBucket = new GuStringParameter(scope, \"AccessLoggingBucket\", {\n description: NAMED_SSM_PARAMETER_PATHS.AccessLoggingBucket.description,\n default: NAMED_SSM_PARAMETER_PATHS.AccessLoggingBucket.path,\n fromSSM: true,\n });\n\n loadBalancer.logAccessLogs(\n Bucket.fromBucketName(\n scope,\n AppIdentity.suffixText(props, \"AccessLoggingBucket\"),\n accessLoggingBucket.valueAsString,\n ),\n accessLogging.prefix,\n );\n }\n\n const targetGroup = new GuApplicationTargetGroup(scope, \"TargetGroup\", {\n app,\n vpc,\n protocol: ApplicationProtocol.HTTP,\n targets: [autoScalingGroup],\n port: applicationPort,\n healthCheck: props.healthcheck,\n });\n\n const listener = new GuHttpsApplicationListener(scope, \"Listener\", {\n app,\n loadBalancer,\n certificate,\n targetGroup,\n // When open=true, AWS will create a security group which allows all inbound traffic over HTTPS\n open: access.scope === AccessScope.PUBLIC && typeof certificate !== \"undefined\",\n });\n\n // Since AWS won't create a security group automatically when open=false, we need to add our own\n if (access.scope !== AccessScope.PUBLIC) {\n loadBalancer.addSecurityGroup(\n new GuSecurityGroup(scope, `${access.scope}IngressSecurityGroup`, {\n app,\n vpc,\n description: \"Allow restricted ingress from CIDR ranges\",\n allowAllOutbound: false,\n ingresses: restrictedCidrRanges(access.cidrRanges),\n }),\n );\n }\n\n if (!monitoringConfiguration.noMonitoring) {\n const { http5xxAlarm, snsTopicName, unhealthyInstancesAlarm } = monitoringConfiguration;\n\n if (http5xxAlarm) {\n new GuAlb5xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http5xxAlarm,\n });\n }\n if (unhealthyInstancesAlarm) {\n new GuUnhealthyInstancesAlarm(scope, {\n app,\n targetGroup,\n snsTopicName,\n });\n }\n }\n\n if (props.googleAuth?.enabled) {\n const prefix = `/${scope.stage}/${scope.stack}/${app}`;\n\n const {\n allowedGroups = [\"engineering@guardian.co.uk\"],\n sessionTimeoutInMinutes = 15,\n credentialsSecretsManagerPath = `${prefix}/google-auth-credentials`,\n } = props.googleAuth;\n\n if (sessionTimeoutInMinutes > 60) {\n throw new Error(\"googleAuth.sessionTimeoutInMinutes must be <= 60!\");\n }\n\n if (allowedGroups.length < 1) {\n throw new Error(\"googleAuth.allowedGroups cannot be empty!\");\n }\n\n if (allowedGroups.find((group) => !group.endsWith(\"@guardian.co.uk\"))) {\n throw new Error(\"googleAuth.allowedGroups must use the @guardian.co.uk domain.\");\n }\n\n const deployToolsAccountId = StringParameter.fromStringParameterName(\n scope,\n \"deploy-tools-account-id-parameter\",\n NAMED_SSM_PARAMETER_PATHS.DeployToolsAccountId.path,\n );\n\n // See https://github.com/guardian/cognito-auth-lambdas for the source\n // code here. ARN format is:\n // arn:aws:lambda:aws-region:acct-id:function:helloworld.\n const gatekeeperFunctionArn = `arn:aws:lambda:eu-west-1:${deployToolsAccountId.stringValue}:function:deploy-PROD-gatekeeper-lambda`;\n\n // Note, handler and filename must match here:\n // https://github.com/guardian/cognito-auth-lambdas.\n const authLambda = new GuLambdaFunction(scope, \"auth-lambda\", {\n app: app,\n memorySize: 128,\n handler: \"devx-cognito-lambda-amd64-v1\",\n runtime: Runtime.GO_1_X,\n fileName: \"deploy/INFRA/cognito-lambda/devx-cognito-lambda-amd64-v1.zip\",\n withoutFilePrefix: true,\n withoutArtifactUpload: true,\n bucketNamePath: NAMED_SSM_PARAMETER_PATHS.OrganisationDistributionBucket.path,\n architecture: Architecture.X86_64,\n environment: {\n ALLOWED_GROUPS: allowedGroups.join(\",\"),\n GATEKEEPER_FUNCTION_ARN: gatekeeperFunctionArn,\n },\n });\n\n authLambda.addToRolePolicy(\n new PolicyStatement({\n effect: Effect.ALLOW,\n actions: [\"lambda:InvokeFunction\"],\n resources: [gatekeeperFunctionArn],\n }),\n );\n\n // Cognito user pool. We require both lambdas: pre-sign-up runs the first\n // time a user attempts to authenticate (before they exist in the User\n // Pool); pre-auth runs in subsequent authentication flows.\n const userPool = new UserPool(this, \"user-pool\", {\n lambdaTriggers: {\n preAuthentication: authLambda,\n preSignUp: authLambda,\n },\n });\n\n // These help ensure domain is deterministic but also unique. Key\n // assumption is that app/stack/stage combo are unique within Guardian.\n const domainPrefix = `com-gu-${app.toLowerCase()}-${scope.stage.toLowerCase()}`;\n const suffix = crypto.createHash(\"md5\").update(domainPrefix).digest(\"hex\");\n\n const userPoolDomain = userPool.addDomain(\"domain\", {\n cognitoDomain: {\n domainPrefix: `${domainPrefix}-${suffix}`,\n },\n });\n\n const clientId = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientId\" });\n const clientSecret = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientSecret\" });\n\n const userPoolIdp = new UserPoolIdentityProviderGoogle(scope, \"google-idp\", {\n userPool: userPool,\n clientId: clientId.toString(),\n clientSecret: clientSecret.toString(),\n attributeMapping: {\n email: ProviderAttribute.GOOGLE_EMAIL,\n givenName: ProviderAttribute.GOOGLE_GIVEN_NAME,\n familyName: ProviderAttribute.GOOGLE_FAMILY_NAME,\n profilePicture: ProviderAttribute.GOOGLE_PICTURE,\n custom: {\n name: ProviderAttribute.GOOGLE_NAME,\n },\n },\n scopes: [\"openid\", \"email\", \"profile\"],\n });\n\n const userPoolClient = userPool.addClient(\"alb-client\", {\n supportedIdentityProviders: [UserPoolClientIdentityProvider.GOOGLE],\n generateSecret: true,\n oAuth: {\n callbackUrls: [`https://${props.googleAuth.domain}/oauth2/idpresponse`],\n },\n\n // Note: id and access validity token validity cannot be less than one\n // hour (this is the cognito cookie duration). To quickly invalidate\n // credentials, disable the user in Cognito. It might be that we want to\n // parameterise these going forward, but that would require Infosec\n // discussion.\n idTokenValidity: Duration.hours(1),\n accessTokenValidity: Duration.hours(1),\n refreshTokenValidity: Duration.days(7),\n });\n\n userPoolClient.node.addDependency(userPoolIdp);\n\n listener.addAction(\"CognitoAuth\", {\n action: new AuthenticateCognitoAction({\n userPool: userPool,\n userPoolClient: userPoolClient,\n userPoolDomain: userPoolDomain,\n next: ListenerAction.forward([targetGroup]),\n sessionTimeout: Duration.minutes(sessionTimeoutInMinutes),\n }),\n });\n\n // Need to give the ALB outbound access on 443 for the IdP endpoints.\n const idpEgressSecurityGroup = new GuHttpsEgressSecurityGroup(scope, \"ldp-access\", {\n app,\n vpc,\n });\n\n loadBalancer.addSecurityGroup(idpEgressSecurityGroup);\n }\n\n this.vpc = vpc;\n this.certificate = certificate;\n this.loadBalancer = loadBalancer;\n this.autoScalingGroup = autoScalingGroup;\n this.listener = listener;\n this.targetGroup = targetGroup;\n }\n}\n"]}
|