-
Notifications
You must be signed in to change notification settings - Fork 1
New: [AEA-6520] - SnsAlarm #708
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tstephen-nhs
wants to merge
7
commits into
main
Choose a base branch
from
aea-0000-sns-alarm
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+300
−8
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1413033
feat: SnsAlarm
tstephen-nhs a53a342
Merge branch 'main' into aea-0000-sns-alarm
tstephen-nhs bd1aa48
fix: use modify standard for construct
tstephen-nhs e256d1a
fix: spread override properties, reexport sns alarm
tstephen-nhs 5b11d7f
fix: generalise topic name
tstephen-nhs 34eb255
test: bound actions
tstephen-nhs 0d439a0
fix: generalise topic name
tstephen-nhs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| import {Duration} from "aws-cdk-lib" | ||
| import {Construct} from "constructs" | ||
| import { | ||
| Alarm, | ||
| ComparisonOperator, | ||
| CreateAlarmOptions, | ||
| Metric, | ||
| MetricStatConfig, | ||
| TreatMissingData, | ||
| Unit | ||
| } from "aws-cdk-lib/aws-cloudwatch" | ||
| import {SnsAction} from "aws-cdk-lib/aws-cloudwatch-actions" | ||
| import {ITopic} from "aws-cdk-lib/aws-sns" | ||
|
|
||
| /** | ||
| * Alarm definition for SnsAlarm with defaults applied by the construct. | ||
| */ | ||
| export interface SnsAlarmDefinition | ||
| extends Omit<CreateAlarmOptions, "threshold" | "evaluationPeriods"> { | ||
| /** | ||
| * The value against which the specified statistic is compared. | ||
| * | ||
| * @default 1 | ||
| */ | ||
| readonly threshold?: number | ||
|
|
||
| /** | ||
| * The number of periods over which data is compared to the specified threshold. | ||
| * | ||
| * @default 1 | ||
| */ | ||
| readonly evaluationPeriods?: number | ||
| } | ||
|
|
||
| /** | ||
| * Metric stat configuration for SnsAlarm with defaults applied by the construct. | ||
| */ | ||
| export interface SnsMetricStatConfig extends Omit<MetricStatConfig, "period" | "statistic"> { | ||
| /** | ||
| * How many seconds to aggregate over. | ||
| * | ||
| * @default Duration.minutes(1) | ||
| */ | ||
| readonly period?: Duration | ||
|
|
||
| /** | ||
| * Aggregation function to use. | ||
| * | ||
| * @default "Sum" | ||
| */ | ||
| readonly statistic?: string | ||
| } | ||
|
|
||
| const toDimensionsMap = ( | ||
| dimensions: MetricStatConfig["dimensions"] | ||
| ): {[dimensionName: string]: string} | undefined => { | ||
| if (!dimensions || dimensions.length === 0) { | ||
| return undefined | ||
| } | ||
|
|
||
| const dimensionMap: {[dimensionName: string]: string} = {} | ||
| dimensions.forEach((dimension) => { | ||
| dimensionMap[dimension.name] = String(dimension.value) | ||
| }) | ||
| return dimensionMap | ||
| } | ||
|
|
||
| /** | ||
| * Constructs a concrete CloudWatch Metric from a MetricStatConfig. | ||
| * @see {@link import("aws-cdk-lib/aws-cloudwatch").MetricConfig} for alternate concrete metric configs. | ||
| */ | ||
| export const metricFromStatConfig = ( | ||
| metricStatConfig: MetricStatConfig | ||
| ): Metric => | ||
| new Metric({ | ||
| namespace: metricStatConfig.namespace, | ||
| metricName: metricStatConfig.metricName, | ||
| dimensionsMap: toDimensionsMap(metricStatConfig.dimensions), | ||
| statistic: metricStatConfig.statistic, | ||
| period: metricStatConfig.period, | ||
| unit: metricStatConfig.unitFilter, | ||
| account: metricStatConfig.accountOverride ?? metricStatConfig.account, | ||
| region: metricStatConfig.regionOverride ?? metricStatConfig.region | ||
| }) | ||
|
|
||
| /** | ||
| * Configuration for creating a CloudWatch metric alarm with SNS publication construct. | ||
| */ | ||
| export interface SnsAlarmProps { | ||
|
|
||
| /** Prefix used in the generated CloudWatch alarm name. */ | ||
| readonly stackName: string | ||
| /** Enables alarm actions when true, disabling notifications when false. */ | ||
| readonly enableAlerts: boolean | ||
| /** CloudWatch metric and threshold settings for the alarm. */ | ||
| readonly alarmDefinition: SnsAlarmDefinition | ||
| /** Defines the metric configuration to be monitored by the alarm. */ | ||
| readonly metricStatConfig: SnsMetricStatConfig | ||
| /** SNS topic that receives alarm, OK, and insufficient data notifications. Common example is for Slack alerts. */ | ||
| readonly snsTopic: ITopic | ||
| } | ||
|
tstephen-nhs marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * Creates a single CloudWatch alarm and wires all alarm state changes to an SNS topic. | ||
| */ | ||
| export class SnsAlarm extends Construct { | ||
|
tstephen-nhs marked this conversation as resolved.
|
||
| public readonly alarm: Alarm | ||
|
|
||
| /** | ||
| * Creates a CloudWatch alarm and publishes alarm state changes to the provided SNS topic. | ||
| * | ||
| * @param props Alarm configuration including metric settings, threshold settings, and notification topic. | ||
| * @example | ||
| * new SnsAlarm(this, 'MyApiErrorAlarm', { | ||
| * stackName: 'pfp-prod', | ||
| * enableAlerts: true, | ||
| * alarmDefinition: { | ||
| * alarmDescription: 'API errors detected', | ||
| * threshold: 1 | ||
| * }, | ||
| * metricStatConfig: { | ||
| * namespace: 'LambdaLogFilterMetrics', | ||
| * metricName: 'ErrorCount' | ||
| * }, | ||
| * snsTopic: slackAlertTopic | ||
| * }) | ||
| */ | ||
| public constructor(scope: Construct, id: string, props: SnsAlarmProps) { | ||
| super(scope, id) | ||
|
|
||
| const generatedAlarmName = props.alarmDefinition.alarmName ?? id | ||
| const { | ||
| threshold, | ||
| evaluationPeriods, | ||
| comparisonOperator, | ||
| treatMissingData, | ||
| ...supportedAlarmDefinitionProps | ||
| } = props.alarmDefinition | ||
|
|
||
| const alarm = new Alarm(this, `${generatedAlarmName}Alarm`, { | ||
| ...supportedAlarmDefinitionProps, | ||
| alarmName: `${props.stackName}-${generatedAlarmName}`, | ||
| metric: metricFromStatConfig({ | ||
| ...props.metricStatConfig, | ||
| unitFilter: props.metricStatConfig.unitFilter ?? Unit.COUNT, | ||
| statistic: props.metricStatConfig.statistic ?? "Sum", | ||
| period: props.metricStatConfig.period ?? Duration.minutes(1) | ||
| }), | ||
| threshold: threshold ?? 1, | ||
| evaluationPeriods: evaluationPeriods ?? 1, | ||
| comparisonOperator: comparisonOperator ?? ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, | ||
| treatMissingData: treatMissingData ?? TreatMissingData.NOT_BREACHING, | ||
| actionsEnabled: props.enableAlerts | ||
| }) | ||
|
|
||
| const snsAction = new SnsAction(props.snsTopic) | ||
| alarm.addAlarmAction(snsAction) | ||
| alarm.addOkAction(snsAction) | ||
| alarm.addInsufficientDataAction(snsAction) | ||
|
|
||
| this.alarm = alarm | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
111 changes: 111 additions & 0 deletions
111
packages/cdkConstructs/tests/constructs/SnsAlarm.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import {App, Duration, Stack} from "aws-cdk-lib" | ||
| import {Template} from "aws-cdk-lib/assertions" | ||
| import {ComparisonOperator, Unit} from "aws-cdk-lib/aws-cloudwatch" | ||
| import {Topic} from "aws-cdk-lib/aws-sns" | ||
| import {describe, expect, it} from "vitest" | ||
| import {SnsAlarm} from "../../src/constructs/SnsAlarm" | ||
|
|
||
| const importedSlackTopicArn = "arn:aws:sns:eu-west-2:111111111111:SlackAlertsTopic" | ||
|
|
||
| describe("SnsAlarm construct", () => { | ||
| it("applies sane defaults for simple alarm definitions", () => { | ||
| const app = new App() | ||
| const stack = new Stack(app, "TestStack") | ||
| const slackAlertTopic = Topic.fromTopicArn(stack, "SlackAlertsTopic", importedSlackTopicArn) | ||
|
|
||
| const metricAlarm = new SnsAlarm(stack, "SimpleMetricAlarm", { | ||
| stackName: "pfp-test-stack", | ||
| enableAlerts: true, | ||
| alarmDefinition: { | ||
| alarmName: "MySimpleAlarm", | ||
| alarmDescription: "An alarm for any breach (threshold 1) in a single period" | ||
| }, | ||
| metricStatConfig: { | ||
| namespace: "LambdaLogFilterMetrics", | ||
| metricName: "ErrorCount" | ||
| }, | ||
| snsTopic: slackAlertTopic | ||
| }) | ||
|
|
||
| expect(metricAlarm.alarm).toBeDefined() | ||
|
|
||
| const template = Template.fromStack(stack) | ||
| template.resourceCountIs("AWS::SNS::Topic", 0) | ||
|
|
||
| template.hasResourceProperties("AWS::CloudWatch::Alarm", { | ||
| AlarmName: "pfp-test-stack-MySimpleAlarm", | ||
| Namespace: "LambdaLogFilterMetrics", | ||
| MetricName: "ErrorCount", | ||
| Threshold: 1, | ||
|
tstephen-nhs marked this conversation as resolved.
|
||
| ComparisonOperator: "GreaterThanOrEqualToThreshold", | ||
| Unit: "Count", | ||
| Statistic: "Sum", | ||
| Period: 60, | ||
| EvaluationPeriods: 1, | ||
| TreatMissingData: "notBreaching", | ||
| AlarmDescription: "An alarm for any breach (threshold 1) in a single period", | ||
| AlarmActions: [importedSlackTopicArn], | ||
| OKActions: [importedSlackTopicArn], | ||
| InsufficientDataActions: [importedSlackTopicArn], | ||
| ActionsEnabled: true | ||
| }) | ||
| }) | ||
|
|
||
| it("allows overriding threshold, comparison operator, unit and dimensions", () => { | ||
| const app = new App() | ||
| const stack = new Stack(app, "OverrideStack") | ||
| const slackAlertTopic = Topic.fromTopicArn(stack, "SlackAlertsTopic", importedSlackTopicArn) | ||
|
|
||
| const metricAlarm = new SnsAlarm(stack, "OverrideMetricAlarm", { | ||
| stackName: "pfp-test-stack", | ||
| enableAlerts: false, | ||
| alarmDefinition: { | ||
| alarmName: "MyOverrideAlarm", | ||
| alarmDescription: "Override alarm", | ||
| threshold: 250, | ||
| comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD, | ||
| evaluationPeriods: 3, | ||
| datapointsToAlarm: 2 | ||
| }, | ||
| metricStatConfig: { | ||
| namespace: "CustomNamespace", | ||
| metricName: "Latency", | ||
| unitFilter: Unit.MILLISECONDS, | ||
| dimensions: [ | ||
| { | ||
| name: "FunctionName", | ||
| value: "my-function" | ||
| } | ||
| ], | ||
| period: Duration.minutes(1), | ||
| statistic: "Sum" | ||
| }, | ||
| snsTopic: slackAlertTopic | ||
| }) | ||
|
|
||
| expect(metricAlarm.alarm).toBeDefined() | ||
|
|
||
| const template = Template.fromStack(stack) | ||
|
|
||
| template.hasResourceProperties("AWS::CloudWatch::Alarm", { | ||
| AlarmName: "pfp-test-stack-MyOverrideAlarm", | ||
| Namespace: "CustomNamespace", | ||
| MetricName: "Latency", | ||
| Threshold: 250, | ||
| ComparisonOperator: "GreaterThanThreshold", | ||
| DatapointsToAlarm: 2, | ||
| Unit: "Milliseconds", | ||
| Dimensions: [ | ||
| { | ||
| Name: "FunctionName", | ||
| Value: "my-function" | ||
| } | ||
| ], | ||
| AlarmDescription: "Override alarm", | ||
| AlarmActions: [importedSlackTopicArn], | ||
| OKActions: [importedSlackTopicArn], | ||
| InsufficientDataActions: [importedSlackTopicArn], | ||
| ActionsEnabled: false | ||
| }) | ||
| }) | ||
| }) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.