@guardian/cdk 49.0.0-beta.1 → 49.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/lib/aspects/cfn-parameter-reporter.d.ts +9 -0
  2. package/lib/aspects/cfn-parameter-reporter.d.ts.map +1 -0
  3. package/lib/aspects/cfn-parameter-reporter.js +21 -0
  4. package/lib/aspects/cfn-parameter-reporter.js.map +1 -0
  5. package/lib/bin/commands/new-project/index.d.ts +1 -1
  6. package/lib/bin/commands/new-project/index.d.ts.map +1 -1
  7. package/lib/constants/metadata-keys.d.ts +0 -1
  8. package/lib/constants/metadata-keys.d.ts.map +1 -1
  9. package/lib/constants/metadata-keys.js +0 -1
  10. package/lib/constants/metadata-keys.js.map +1 -1
  11. package/lib/constructs/acm/certificate.d.ts +1 -1
  12. package/lib/constructs/acm/certificate.d.ts.map +1 -1
  13. package/lib/constructs/autoscaling/user-data.d.ts +1 -1
  14. package/lib/constructs/autoscaling/user-data.d.ts.map +1 -1
  15. package/lib/constructs/autoscaling/user-data.js +8 -8
  16. package/lib/constructs/autoscaling/user-data.js.map +1 -1
  17. package/lib/constructs/core/parameters/base.d.ts +2 -2
  18. package/lib/constructs/core/parameters/base.d.ts.map +1 -1
  19. package/lib/constructs/core/stack.d.ts +7 -1
  20. package/lib/constructs/core/stack.d.ts.map +1 -1
  21. package/lib/constructs/core/stack.js +31 -23
  22. package/lib/constructs/core/stack.js.map +1 -1
  23. package/lib/constructs/dns/dns-records.js +1 -1
  24. package/lib/constructs/dns/dns-records.js.map +1 -1
  25. package/lib/constructs/ec2/vpc.d.ts +1 -1
  26. package/lib/constructs/ec2/vpc.d.ts.map +1 -1
  27. package/lib/constructs/ecs/ecs-task.d.ts +4 -4
  28. package/lib/constructs/ecs/ecs-task.d.ts.map +1 -1
  29. package/lib/constructs/iam/policies/base-policy.d.ts +3 -3
  30. package/lib/constructs/iam/policies/base-policy.d.ts.map +1 -1
  31. package/lib/constructs/iam/roles/instance-role.d.ts +1 -1
  32. package/lib/constructs/iam/roles/instance-role.d.ts.map +1 -1
  33. package/lib/constructs/iam/roles/roles.d.ts +1 -1
  34. package/lib/constructs/iam/roles/roles.d.ts.map +1 -1
  35. package/lib/constructs/kinesis/kinesis-stream.d.ts +1 -1
  36. package/lib/constructs/kinesis/kinesis-stream.d.ts.map +1 -1
  37. package/lib/constructs/vpc/vpc.d.ts +1 -1
  38. package/lib/constructs/vpc/vpc.d.ts.map +1 -1
  39. package/lib/constructs/vpc/vpc.js +1 -1
  40. package/lib/constructs/vpc/vpc.js.map +1 -1
  41. package/lib/experimental/constructs/error-budget-alarm.d.ts +47 -2
  42. package/lib/experimental/constructs/error-budget-alarm.d.ts.map +1 -1
  43. package/lib/experimental/constructs/error-budget-alarm.js +84 -42
  44. package/lib/experimental/constructs/error-budget-alarm.js.map +1 -1
  45. package/lib/experimental/constructs/index.d.ts +3 -0
  46. package/lib/experimental/constructs/index.d.ts.map +1 -0
  47. package/lib/{constructs/sns → experimental/constructs}/index.js +2 -1
  48. package/lib/experimental/constructs/index.js.map +1 -0
  49. package/lib/experimental/patterns/sns-lambda.d.ts.map +1 -1
  50. package/lib/experimental/patterns/sns-lambda.js +1 -2
  51. package/lib/experimental/patterns/sns-lambda.js.map +1 -1
  52. package/lib/experimental/riff-raff-yaml-file/index.js +48 -48
  53. package/lib/experimental/riff-raff-yaml-file/index.js.map +1 -1
  54. package/lib/experimental/riff-raff-yaml-file/types.d.ts +7 -7
  55. package/lib/experimental/riff-raff-yaml-file/types.d.ts.map +1 -1
  56. package/lib/patterns/api-multiple-lambdas.d.ts +5 -1
  57. package/lib/patterns/api-multiple-lambdas.d.ts.map +1 -1
  58. package/lib/patterns/api-multiple-lambdas.js +3 -1
  59. package/lib/patterns/api-multiple-lambdas.js.map +1 -1
  60. package/lib/patterns/ec2-app/base.d.ts.map +1 -1
  61. package/lib/patterns/ec2-app/base.js +0 -5
  62. package/lib/patterns/ec2-app/base.js.map +1 -1
  63. package/lib/patterns/ec2-app/framework.d.ts +1 -1
  64. package/lib/patterns/ec2-app/framework.d.ts.map +1 -1
  65. package/lib/types/access.d.ts +1 -1
  66. package/lib/types/access.d.ts.map +1 -1
  67. package/lib/types/cli.d.ts +1 -1
  68. package/lib/types/cli.d.ts.map +1 -1
  69. package/lib/utils/lambda/event-source.d.ts +4 -4
  70. package/lib/utils/lambda/event-source.d.ts.map +1 -1
  71. package/lib/utils/lambda/event-source.js +4 -4
  72. package/lib/utils/lambda/event-source.js.map +1 -1
  73. package/lib/utils/mixin/types.d.ts +1 -1
  74. package/lib/utils/mixin/types.d.ts.map +1 -1
  75. package/package.json +21 -21
  76. package/lib/constructs/sns/index.d.ts +0 -2
  77. package/lib/constructs/sns/index.d.ts.map +0 -1
  78. package/lib/constructs/sns/index.js.map +0 -1
  79. package/lib/constructs/sns/sns-topic.d.ts +0 -15
  80. package/lib/constructs/sns/sns-topic.d.ts.map +0 -1
  81. package/lib/constructs/sns/sns-topic.js +0 -17
  82. package/lib/constructs/sns/sns-topic.js.map +0 -1
@@ -1,12 +1,57 @@
1
1
  import type { IMetric } from "aws-cdk-lib/aws-cloudwatch";
2
+ import { Construct } from "constructs";
2
3
  import type { GuStack } from "../../constructs/core";
3
4
  export interface ErrorBudgetAlarmProps {
4
- snsTopicNameForAlerts: string;
5
+ /**
6
+ * The name of the SLO. Assumed to be unique per stack.
7
+ */
8
+ sloName: string;
9
+ /**
10
+ * The percentange target for the SLO, expressed as a decimal floating point number. Must be between 0.95 and 0.995.
11
+ */
5
12
  sloTarget: number;
13
+ /**
14
+ * The metric representing the bad events. Can be any IMetric type, like Metric or MathExpression.
15
+ */
6
16
  badEvents: IMetric;
17
+ /**
18
+ * The metric representing the events to be considered. Can be any IMetric type, like Metric or MathExpression.
19
+ */
7
20
  validEvents: IMetric;
21
+ /**
22
+ * The sns topic name (not the full arn) used by the alarm to send email alerts.
23
+ */
24
+ snsTopicNameForAlerts: string;
8
25
  }
9
- export declare class ErrorBudgetAlarmExperimental {
26
+ /**
27
+ * Use this construct to create alarms that will notify you when you are at risk of missing your SLO targets.
28
+ *
29
+ * These alarms follow the recommendations in the [SRE Workbook](https://sre.google/workbook/alerting-on-slos/) to
30
+ * implement Multiwindow, Multi-Burn-Rate Alerts.
31
+ *
32
+ * The CloudWatch implementation of this strategy creates nine separate CloudWatch alarms. The main alarms that users
33
+ * need to care about are the three composite alarms. These track different burn rates of error budget consumption:
34
+ * fast (e.g. complete outages), medium (e.g. moderate error percentage over hours, rather than minutes) and slow (e.g.
35
+ * a small percentage of errors sustained over a much longer period). Multiple burn rates are used to ensure that
36
+ * we are able to pick up all scenarios which could threaten the SLO, without interrupting developers with an
37
+ * unnecessary level of urgency.
38
+ *
39
+ * Each composite alarm creates two child alarms; these are used to support multiple windows (or periods in CloudWatch
40
+ * terminology). A composite alarm is configured to send notifications if both of its child alarms are in an alarm state.
41
+ * The child alarms themselves have no actions/notifications configured and users should not need to interact with them
42
+ * directly. Multiple windows are helpful for accuracy and reset time. The long window helps us to avoid sending an
43
+ * alert in scenarios where no intervention is required, for example a very brief spike in errors that is resolved
44
+ * automatically (e.g. when AWS replaces a 'bad' EC2 instance). The short window helps to ensure that the alert is reset
45
+ * (or moved back into OK state, in CloudWatch terminology) promptly once a problem has been resolved.
46
+ *
47
+ * The composite alarms have an awareness of priority, meaning that low priority alarm notifications are suppressed if
48
+ * a higher priority alarm is already firing. That is, if you receive an alert about fast error budget consumption, you
49
+ * should not receive an alert from the medium or slow versions of the alarm.
50
+ *
51
+ * For how to instantiate an ErrorBudgetAlarm check the unit-test in error-budget-alarm.test.ts,
52
+ * and for a description of the props that need to be passed see [[ErrorBudgetAlarmProps]]
53
+ */
54
+ export declare class GuErrorBudgetAlarmExperimental extends Construct {
10
55
  constructor(scope: GuStack, props: ErrorBudgetAlarmProps);
11
56
  }
12
57
  //# sourceMappingURL=error-budget-alarm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-budget-alarm.d.ts","sourceRoot":"","sources":["../../../src/experimental/constructs/error-budget-alarm.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,OAAO,EAAC,MAAM,4BAA4B,CAAC;AAW7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAErD,MAAM,WAAW,qBAAqB;IACpC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,OAAO,CAAC;CAEtB;AAwCD,qBAAa,4BAA4B;gBAE3B,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,qBAAqB;CAqEzD"}
1
+ {"version":3,"file":"error-budget-alarm.d.ts","sourceRoot":"","sources":["../../../src/experimental/constructs/error-budget-alarm.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAqB,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAa7E,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAErD,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,EAAE,OAAO,CAAC;IACnB;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB;;OAEG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AA+BD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,qBAAa,8BAA+B,SAAQ,SAAS;gBAC/C,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,qBAAqB;CAsEzD"}
@@ -1,77 +1,110 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ErrorBudgetAlarmExperimental = void 0;
3
+ exports.GuErrorBudgetAlarmExperimental = void 0;
4
4
  const aws_cdk_lib_1 = require("aws-cdk-lib");
5
5
  const aws_cloudwatch_1 = require("aws-cdk-lib/aws-cloudwatch");
6
6
  const aws_cloudwatch_actions_1 = require("aws-cdk-lib/aws-cloudwatch-actions");
7
7
  const aws_sns_1 = require("aws-cdk-lib/aws-sns");
8
- function applySuppression(alarmToSuppress, suppressingAlarm, shortWindow) {
9
- const cfnAlarm = alarmToSuppress.node.defaultChild;
10
- cfnAlarm.actionsSuppressor = suppressingAlarm.alarmArn;
11
- cfnAlarm.actionsSuppressorWaitPeriod = 120;
12
- cfnAlarm.actionsSuppressorExtensionPeriod = shortWindow.toSeconds();
13
- }
14
- // Do we need to extend construct here?
15
- class ErrorBudgetAlarmExperimental {
8
+ const constructs_1 = require("constructs");
9
+ /**
10
+ * Use this construct to create alarms that will notify you when you are at risk of missing your SLO targets.
11
+ *
12
+ * These alarms follow the recommendations in the [SRE Workbook](https://sre.google/workbook/alerting-on-slos/) to
13
+ * implement Multiwindow, Multi-Burn-Rate Alerts.
14
+ *
15
+ * The CloudWatch implementation of this strategy creates nine separate CloudWatch alarms. The main alarms that users
16
+ * need to care about are the three composite alarms. These track different burn rates of error budget consumption:
17
+ * fast (e.g. complete outages), medium (e.g. moderate error percentage over hours, rather than minutes) and slow (e.g.
18
+ * a small percentage of errors sustained over a much longer period). Multiple burn rates are used to ensure that
19
+ * we are able to pick up all scenarios which could threaten the SLO, without interrupting developers with an
20
+ * unnecessary level of urgency.
21
+ *
22
+ * Each composite alarm creates two child alarms; these are used to support multiple windows (or periods in CloudWatch
23
+ * terminology). A composite alarm is configured to send notifications if both of its child alarms are in an alarm state.
24
+ * The child alarms themselves have no actions/notifications configured and users should not need to interact with them
25
+ * directly. Multiple windows are helpful for accuracy and reset time. The long window helps us to avoid sending an
26
+ * alert in scenarios where no intervention is required, for example a very brief spike in errors that is resolved
27
+ * automatically (e.g. when AWS replaces a 'bad' EC2 instance). The short window helps to ensure that the alert is reset
28
+ * (or moved back into OK state, in CloudWatch terminology) promptly once a problem has been resolved.
29
+ *
30
+ * The composite alarms have an awareness of priority, meaning that low priority alarm notifications are suppressed if
31
+ * a higher priority alarm is already firing. That is, if you receive an alert about fast error budget consumption, you
32
+ * should not receive an alert from the medium or slow versions of the alarm.
33
+ *
34
+ * For how to instantiate an ErrorBudgetAlarm check the unit-test in error-budget-alarm.test.ts,
35
+ * and for a description of the props that need to be passed see [[ErrorBudgetAlarmProps]]
36
+ */
37
+ class GuErrorBudgetAlarmExperimental extends constructs_1.Construct {
16
38
  constructor(scope, props) {
39
+ const lowestTargetAllowed = 0.95;
40
+ const highestTargetAllowed = 0.9995;
41
+ if (!(props.sloTarget >= lowestTargetAllowed && props.sloTarget <= highestTargetAllowed)) {
42
+ throw new Error(`ErrorBudgetAlarm only works with SLO targets between ${lowestTargetAllowed} and ${highestTargetAllowed}`);
43
+ }
44
+ super(scope, props.sloName); // The assumption here is that `sloName` will be unique (per stack)
17
45
  const errorBudget = 1 - props.sloTarget;
18
- const snsTopic = aws_sns_1.Topic.fromTopicArn(scope, 'SnsSloAlarms', `arn:aws:sns:${scope.region}:${scope.account}:${props.snsTopicNameForAlerts}`);
46
+ const snsTopic = aws_sns_1.Topic.fromTopicArn(scope, `SnsSloAlarmsFor${props.sloName}`, `arn:aws:sns:${scope.region}:${scope.account}:${props.snsTopicNameForAlerts}`);
19
47
  const fastBurnRate = {
20
- speed: 'Fast',
21
- burnRate: 15,
22
- longWindow: aws_cdk_lib_1.Duration.hours(1),
23
- shortWindow: aws_cdk_lib_1.Duration.minutes(5),
48
+ speed: "Fast",
49
+ burnRate: 14.4,
50
+ longPeriod: aws_cdk_lib_1.Duration.hours(1),
51
+ shortPeriod: aws_cdk_lib_1.Duration.minutes(5),
24
52
  };
25
53
  const fastBurnAlarm = new CompositeBurnRateAlarm(scope, {
54
+ sloName: props.sloName,
26
55
  badEvents: props.badEvents,
27
- burnRate: fastBurnRate,
56
+ burnRateMonitoring: fastBurnRate,
28
57
  errorBudget,
29
58
  snsTopic,
30
59
  validEvents: props.validEvents,
31
60
  });
32
- const moderateBurnRate = {
33
- speed: 'Moderate',
61
+ const mediumBurnRateMonitoring = {
62
+ speed: "Medium",
34
63
  burnRate: 6,
35
- longWindow: aws_cdk_lib_1.Duration.hours(6),
36
- shortWindow: aws_cdk_lib_1.Duration.minutes(30),
64
+ longPeriod: aws_cdk_lib_1.Duration.hours(6),
65
+ shortPeriod: aws_cdk_lib_1.Duration.minutes(30),
37
66
  };
38
- const moderateBurnAlarm = new CompositeBurnRateAlarm(scope, {
67
+ const mediumBurnRateAlarm = new CompositeBurnRateAlarm(scope, {
68
+ sloName: props.sloName,
39
69
  badEvents: props.badEvents,
40
- burnRate: moderateBurnRate,
70
+ burnRateMonitoring: mediumBurnRateMonitoring,
41
71
  errorBudget,
42
72
  snsTopic,
43
73
  validEvents: props.validEvents,
74
+ suppressorAlarm: fastBurnAlarm,
44
75
  });
45
- applySuppression(moderateBurnAlarm, fastBurnAlarm, moderateBurnRate.shortWindow);
46
76
  const slowBurnRate = {
47
- speed: 'Slow',
77
+ speed: "Slow",
48
78
  burnRate: 3,
49
- longWindow: aws_cdk_lib_1.Duration.days(1),
50
- shortWindow: aws_cdk_lib_1.Duration.hours(2),
79
+ longPeriod: aws_cdk_lib_1.Duration.days(1),
80
+ shortPeriod: aws_cdk_lib_1.Duration.hours(2),
51
81
  };
52
- const slowBurnAlarm = new CompositeBurnRateAlarm(scope, {
82
+ new CompositeBurnRateAlarm(scope, {
83
+ sloName: props.sloName,
53
84
  badEvents: props.badEvents,
54
- burnRate: slowBurnRate,
85
+ burnRateMonitoring: slowBurnRate,
55
86
  errorBudget,
87
+ // TODO - use a different topic for tickets or figure out how to route notifications vs tickets using a single topic
56
88
  snsTopic,
57
89
  validEvents: props.validEvents,
90
+ suppressorAlarm: mediumBurnRateAlarm,
58
91
  });
59
- applySuppression(slowBurnAlarm, moderateBurnAlarm, slowBurnRate.shortWindow);
60
92
  }
61
93
  }
62
- exports.ErrorBudgetAlarmExperimental = ErrorBudgetAlarmExperimental;
63
- class IndividualBurnRateAlarm extends aws_cloudwatch_1.Alarm {
94
+ exports.GuErrorBudgetAlarmExperimental = GuErrorBudgetAlarmExperimental;
95
+ class MonitorBurnRateForPeriod extends aws_cloudwatch_1.Alarm {
64
96
  constructor(scope, props) {
65
97
  const undesirableErrorBudgetConsumption = props.errorBudget * props.burnRateSpeed.burnRate;
66
- super(scope, `${props.burnRateSpeed.speed}BurnOver${props.window.toHumanString()}`, {
98
+ super(scope, props.alarmName, {
99
+ alarmName: props.alarmName,
67
100
  metric: new aws_cloudwatch_1.MathExpression({
68
- expression: `badEvents/validEvents`,
69
- label: 'Observed failure rate',
101
+ expression: "badEvents/validEvents",
102
+ label: "Observed failure rate",
70
103
  usingMetrics: {
71
104
  badEvents: props.badEvents,
72
105
  validEvents: props.validEvents,
73
106
  },
74
- period: props.window,
107
+ period: props.period,
75
108
  }),
76
109
  evaluationPeriods: 1,
77
110
  threshold: undesirableErrorBudgetConsumption,
@@ -82,25 +115,34 @@ class IndividualBurnRateAlarm extends aws_cloudwatch_1.Alarm {
82
115
  }
83
116
  class CompositeBurnRateAlarm extends aws_cloudwatch_1.CompositeAlarm {
84
117
  constructor(scope, props) {
118
+ const alarmName = `${props.sloName}${props.burnRateMonitoring.speed}BurnCompositeAlarm`;
85
119
  const sharedIndividualAlarmProps = {
86
120
  badEvents: props.badEvents,
87
121
  burnRateSpeed: {
88
- speed: props.burnRate.speed,
89
- burnRate: props.burnRate.burnRate,
122
+ speed: props.burnRateMonitoring.speed,
123
+ burnRate: props.burnRateMonitoring.burnRate,
90
124
  },
91
125
  errorBudget: props.errorBudget,
92
- validEvents: props.validEvents
126
+ validEvents: props.validEvents,
93
127
  };
94
- super(scope, `${props.burnRate.speed}BurnCompositeAlarm`, {
95
- alarmRule: aws_cloudwatch_1.AlarmRule.allOf(aws_cloudwatch_1.AlarmRule.fromAlarm(new IndividualBurnRateAlarm(scope, {
128
+ super(scope, alarmName, {
129
+ alarmRule: aws_cloudwatch_1.AlarmRule.allOf(aws_cloudwatch_1.AlarmRule.fromAlarm(new MonitorBurnRateForPeriod(scope, {
96
130
  ...sharedIndividualAlarmProps,
97
- window: props.burnRate.longWindow,
98
- }), aws_cloudwatch_1.AlarmState.ALARM), aws_cloudwatch_1.AlarmRule.fromAlarm(new IndividualBurnRateAlarm(scope, {
131
+ alarmName: `ChildAlarmLongPeriod${alarmName}`,
132
+ period: props.burnRateMonitoring.longPeriod,
133
+ }), aws_cloudwatch_1.AlarmState.ALARM), aws_cloudwatch_1.AlarmRule.fromAlarm(new MonitorBurnRateForPeriod(scope, {
99
134
  ...sharedIndividualAlarmProps,
100
- window: props.burnRate.shortWindow,
135
+ alarmName: `ChildAlarmShortPeriod${alarmName}`,
136
+ period: props.burnRateMonitoring.shortPeriod,
101
137
  }), aws_cloudwatch_1.AlarmState.ALARM)),
102
138
  });
103
139
  this.addAlarmAction(new aws_cloudwatch_actions_1.SnsAction(props.snsTopic));
140
+ if (props.suppressorAlarm) {
141
+ const cfnAlarm = this.node.defaultChild;
142
+ cfnAlarm.actionsSuppressor = props.suppressorAlarm.alarmArn;
143
+ cfnAlarm.actionsSuppressorWaitPeriod = 120;
144
+ cfnAlarm.actionsSuppressorExtensionPeriod = props.burnRateMonitoring.shortPeriod.toSeconds();
145
+ }
104
146
  }
105
147
  }
106
148
  //# sourceMappingURL=error-budget-alarm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-budget-alarm.js","sourceRoot":"","sources":["../../../src/experimental/constructs/error-budget-alarm.ts"],"names":[],"mappings":";;;AAAA,6CAAuC;AAGvC,+DAMoC;AACpC,+EAA+D;AAE/D,iDAA4C;AAqC5C,SAAS,gBAAgB,CACvB,eAA+B,EAC/B,gBAAgC,EAChC,WAAqB;IAErB,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,CAAC,YAAiC,CAAC;IACxE,QAAQ,CAAC,iBAAiB,GAAG,gBAAgB,CAAC,QAAQ,CAAC;IACvD,QAAQ,CAAC,2BAA2B,GAAG,GAAG,C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AuB,SAAQ,+BAAc;IACjD,YAAY,KAAc,EAAE,KAAkC;QAC5D,MAAM,0BAA0B,GAAG;YACjC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,aAAa,EAAE;gBACb,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK;gBAC3B,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ;aAClC;YACD,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,WAAW,EAAE,KAAK,CAAC,WAAW;SAC/B,CAAC;QACF,KAAK,CAAC,KAAK,EACT,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,oBAAoB,EAC3C;YACE,SAAS,EAAE,0BAAS,CAAC,KAAK,CACxB,0BAAS,CAAC,SAAS,CACjB,IAAI,uBAAuB,CAAC,KAAK,EAAE;gBACjC,GAAG,0BAA0B;gBAC7B,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;aAClC,CAAC,EACF,2BAAU,CAAC,KAAK,CACjB,EACD,0BAAS,CAAC,SAAS,CACjB,IAAI,uBAAuB,CAAC,KAAK,EAAE;gBACjC,GAAG,0BAA0B;gBAC7B,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,WAAW;aACnC,CAAC,EACF,2BAAU,CAAC,KAAK,CACjB,CACF;SACF,CACF,CAAC;QACF,IAAI,CAAC,cAAc,CAAC,IAAI,kCAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["import { Duration } from \"aws-cdk-lib\";\nimport type { CfnCompositeAlarm,\n IMetric} from \"aws-cdk-lib/aws-cloudwatch\";\nimport {\n Alarm, AlarmRule, 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 type { GuStack } from \"../../constructs/core\";\n\nexport interface ErrorBudgetAlarmProps {\n snsTopicNameForAlerts: string;\n sloTarget: number;\n badEvents: IMetric; // Should this be IMetric[]?\n validEvents: IMetric; // Should this be IMetric[]?\n // Could accept a MathExpression for more complicated cases?\n}\n\ninterface BurnRateSpeed {\n speed: 'Fast' | 'Moderate' | 'Slow';\n burnRate: number;\n}\n\ninterface BurnRate extends BurnRateSpeed {\n longWindow: Duration;\n shortWindow: Duration;\n}\n\ninterface IndividualBurnRateAlarmProps {\n burnRateSpeed: BurnRateSpeed;\n window: Duration;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n}\n\ninterface CompositeBurnRateAlarmProps {\n burnRate: BurnRate;\n errorBudget: number;\n badEvents: IMetric;\n validEvents: IMetric;\n snsTopic: ITopic;\n}\n\nfunction applySuppression(\n alarmToSuppress: CompositeAlarm,\n suppressingAlarm: CompositeAlarm,\n shortWindow: Duration,\n) {\n const cfnAlarm = alarmToSuppress.node.defaultChild as CfnCompositeAlarm;\n cfnAlarm.actionsSuppressor = suppressingAlarm.alarmArn;\n cfnAlarm.actionsSuppressorWaitPeriod = 120;\n cfnAlarm.actionsSuppressorExtensionPeriod = shortWindow.toSeconds();\n}\n\n// Do we need to extend construct here?\nexport class ErrorBudgetAlarmExperimental {\n\n constructor(scope: GuStack, props: ErrorBudgetAlarmProps) {\n\n const errorBudget = 1 - props.sloTarget;\n\n const snsTopic: ITopic = Topic.fromTopicArn(\n scope,\n 'SnsSloAlarms',\n `arn:aws:sns:${scope.region}:${scope.account}:${props.snsTopicNameForAlerts}`,\n );\n\n const fastBurnRate: BurnRate = {\n speed: 'Fast',\n burnRate: 15,\n longWindow: Duration.hours(1),\n shortWindow: Duration.minutes(5),\n };\n\n const fastBurnAlarm = new CompositeBurnRateAlarm(scope, {\n badEvents: props.badEvents,\n burnRate: fastBurnRate,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n });\n\n const moderateBurnRate: BurnRate = {\n speed: 'Moderate',\n burnRate: 6,\n longWindow: Duration.hours(6),\n shortWindow: Duration.minutes(30),\n };\n\n const moderateBurnAlarm = new CompositeBurnRateAlarm(scope, {\n badEvents: props.badEvents,\n burnRate: moderateBurnRate,\n errorBudget,\n snsTopic,\n validEvents: props.validEvents,\n });\n\n applySuppression(\n moderateBurnAlarm,\n fastBurnAlarm,\n moderateBurnRate.shortWindow,\n );\n\n const slowBurnRate: BurnRate = {\n speed: 'Slow',\n burnRate: 3,\n longWindow: Duration.days(1),\n shortWindow: Duration.hours(2),\n };\n\n const slowBurnAlarm = new CompositeBurnRateAlarm(scope, {\n badEvents: props.badEvents,\n burnRate: slowBurnRate,\n errorBudget,\n snsTopic, // TODO - use a different topic for tickets or figure out how to route notifications vs tickets using a single topic\n validEvents: props.validEvents,\n });\n\n applySuppression(\n slowBurnAlarm,\n moderateBurnAlarm,\n slowBurnRate.shortWindow,\n );\n\n }\n\n}\n\nclass IndividualBurnRateAlarm extends Alarm {\n constructor(scope: GuStack, props: IndividualBurnRateAlarmProps) {\n const undesirableErrorBudgetConsumption = props.errorBudget * props.burnRateSpeed.burnRate;\n super(\n scope,\n `${props.burnRateSpeed.speed}BurnOver${props.window.toHumanString()}`,\n {\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.window,\n }),\n evaluationPeriods: 1,\n threshold: undesirableErrorBudgetConsumption,\n comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,\n treatMissingData: TreatMissingData.NOT_BREACHING,\n },\n );\n }\n}\n\nclass CompositeBurnRateAlarm extends CompositeAlarm {\n constructor(scope: GuStack, props: CompositeBurnRateAlarmProps) {\n const sharedIndividualAlarmProps = {\n badEvents: props.badEvents,\n burnRateSpeed: {\n speed: props.burnRate.speed,\n burnRate: props.burnRate.burnRate,\n },\n errorBudget: props.errorBudget,\n validEvents: props.validEvents\n };\n super(scope,\n `${props.burnRate.speed}BurnCompositeAlarm`,\n {\n alarmRule: AlarmRule.allOf(\n AlarmRule.fromAlarm(\n new IndividualBurnRateAlarm(scope, {\n ...sharedIndividualAlarmProps,\n window: props.burnRate.longWindow,\n }),\n AlarmState.ALARM,\n ),\n AlarmRule.fromAlarm(\n new IndividualBurnRateAlarm(scope, {\n ...sharedIndividualAlarmProps,\n window: props.burnRate.shortWindow,\n }),\n AlarmState.ALARM,\n ),\n ),\n },\n );\n this.addAlarmAction(new SnsAction(props.snsTopic));\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;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;YACxF,MAAM,IAAI,KAAK,CACb,wDAAwD,mBAAmB,QAAQ,oBAAoB,EAAE,CAC1G,CAAC;SACH;QAED,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,mEAAmE;QAEhG,MAAM,WAAW,GAAG,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC;QAExC,MAAM,QAAQ,GAAW,eAAK,CAAC,YAAY,CACzC,KAAK,EACL,kBAAkB,KAAK,CAAC,OAAO,EAAE,EACjC,eAAe,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,qBAAqB,EAAE,CAC9E,CAAC;QA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AAE,KAAK,CAAC,WAAW;SAC/B,CAAC;QACF,KAAK,CAAC,KAAK,EAAE,SAAS,EAAE;YACtB,SAAS,EAAE,0BAAS,CAAC,KAAK,CACxB,0BAAS,CAAC,SAAS,CACjB,IAAI,wBAAwB,CAAC,KAAK,EAAE;gBAClC,GAAG,0BAA0B;gBAC7B,SAAS,EAAE,uBAAuB,SAAS,EAAE;gBAC7C,MAAM,EAAE,KAAK,CAAC,kBAAkB,CAAC,UAAU;aAC5C,CAAC,EACF,2BAAU,CAAC,KAAK,CACjB,EACD,0BAAS,CAAC,SAAS,CACjB,IAAI,wBAAwB,CAAC,KAAK,EAAE;gBAClC,GAAG,0BAA0B;gBAC7B,SAAS,EAAE,wBAAwB,SAAS,EAAE;gBAC9C,MAAM,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"]}
@@ -0,0 +1,3 @@
1
+ export * from "./error-budget-alarm";
2
+ export * from "./root";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/experimental/constructs/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,QAAQ,CAAC"}
@@ -14,5 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./sns-topic"), exports);
17
+ __exportStar(require("./error-budget-alarm"), exports);
18
+ __exportStar(require("./root"), exports);
18
19
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/constructs/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uDAAqC;AACrC,yCAAuB","sourcesContent":["export * from \"./error-budget-alarm\";\nexport * from \"./root\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"sns-lambda.d.ts","sourceRoot":"","sources":["../../../src/experimental/patterns/sns-lambda.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,KAAK,EAAE,sCAAsC,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAExG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG/D;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,eAAe,EAAE,2BAA2B,CAAC;IAC1F,uBAAuB,EAAE,YAAY,GAAG,sCAAsC,CAAC;IAC/E,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,uBAAwB,SAAQ,gBAAgB;IAC3D,SAAgB,QAAQ,EAAE,MAAM,CAAC;gBAErB,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB;CAoBhE"}
1
+ {"version":3,"file":"sns-lambda.d.ts","sourceRoot":"","sources":["../../../src/experimental/patterns/sns-lambda.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,KAAK,EAAE,sCAAsC,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAExG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,eAAe,EAAE,2BAA2B,CAAC;IAC1F,uBAAuB,EAAE,YAAY,GAAG,sCAAsC,CAAC;IAC/E,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,uBAAwB,SAAQ,gBAAgB;IAC3D,SAAgB,QAAQ,EAAE,MAAM,CAAC;gBAErB,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB;CAoBhE"}
@@ -6,7 +6,6 @@ const aws_lambda_event_sources_1 = require("aws-cdk-lib/aws-lambda-event-sources
6
6
  const aws_sns_1 = require("aws-cdk-lib/aws-sns");
7
7
  const core_1 = require("../../constructs/core");
8
8
  const lambda_1 = require("../../constructs/lambda");
9
- const sns_1 = require("../../constructs/sns");
10
9
  /**
11
10
  * Pattern which creates all of the resources needed to invoke a lambda function whenever a message
12
11
  * is published onto an SNS topic.
@@ -30,7 +29,7 @@ class GuSnsLambdaExperimental extends lambda_1.GuLambdaFunction {
30
29
  const { existingSnsTopic } = props;
31
30
  this.snsTopic = existingSnsTopic
32
31
  ? aws_sns_1.Topic.fromTopicArn(scope, `${id}-SnsExistingIncomingEventsTopic`, `arn:aws:sns:${region}:${account}:${existingSnsTopic.externalTopicName}`)
33
- : core_1.AppIdentity.taggedConstruct(props, new sns_1.GuSnsTopic(scope, "SnsIncomingEventsTopic"));
32
+ : core_1.AppIdentity.taggedConstruct(props, new aws_sns_1.Topic(scope, "SnsIncomingEventsTopic"));
34
33
  this.addEventSource(new aws_lambda_event_sources_1.SnsEventSource(this.snsTopic));
35
34
  new aws_cdk_lib_1.CfnOutput(this, "TopicName", { value: this.snsTopic.topicName });
36
35
  }
@@ -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;AAE3D,8CAAkD;AA2ClD;;;;;;;;;;;;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,gBAAU,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAExF,IAAI,CAAC,cAAc,CAAC,IAAI,yCAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,IAAI,uBAAS,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC;IACvE,CAAC;CACF;AAvBD,0DAuBC","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\";\nimport { GuSnsTopic } from \"../../constructs/sns\";\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 GuSnsTopic(scope, \"SnsIncomingEventsTopic\"));\n\n this.addEventSource(new SnsEventSource(this.snsTopic));\n new CfnOutput(this, \"TopicName\", { value: this.snsTopic.topicName });\n }\n}\n"]}
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,IAAI,CAAC,cAAc,CAAC,IAAI,yCAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,IAAI,uBAAS,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC;IACvE,CAAC;CACF;AAvBD,0DAuBC","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 this.addEventSource(new SnsEventSource(this.snsTopic));\n new CfnOutput(this, \"TopicName\", { value: this.snsTopic.topicName });\n }\n}\n"]}
@@ -60,54 +60,6 @@ const group_by_1 = require("./group-by");
60
60
  * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types
61
61
  */
62
62
  class RiffRaffYamlFileExperimental {
63
- // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree
64
- constructor(app) {
65
- this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof core_1.GuStack);
66
- const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));
67
- this.allStageTags = Array.from(allowedStages);
68
- this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));
69
- this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));
70
- this.validateStacksInApp();
71
- this.validateAllRegionsAreResolved();
72
- this.outdir = app.outdir;
73
- const deployments = new Map();
74
- const groupedStacks = (0, group_by_1.groupByClassNameStackRegionStage)(this.allCdkStacks);
75
- Object.values(groupedStacks).forEach((stackTagGroup) => {
76
- Object.values(stackTagGroup).forEach((regionGroup) => {
77
- Object.values(regionGroup).forEach((stageGroup) => {
78
- const stacks = Object.values(stageGroup).flat();
79
- if (stacks.length === 0) {
80
- throw new Error("Unable to produce a working riff-raff.yaml file; there are no stacks!");
81
- }
82
- // The items in `stacks` only differ by stage, so we can just use the first item in the list.
83
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length of `stacks` is checked above
84
- const stack = stacks[0];
85
- const lambdas = this.getLambdas(stack);
86
- const autoscalingGroups = this.getAutoScalingGroups(stack);
87
- const artifactUploads = [
88
- lambdas.map(lambda_2.uploadLambdaArtifact),
89
- autoscalingGroups.map(autoscaling_2.uploadAutoscalingArtifact),
90
- ].flat();
91
- artifactUploads.forEach(({ name, props }) => deployments.set(name, props));
92
- const cfnDeployment = (0, cloudformation_1.cloudFormationDeployment)(stacks, artifactUploads, this.outdir);
93
- deployments.set(cfnDeployment.name, cfnDeployment.props);
94
- lambdas.forEach((lambda) => {
95
- const lambdaDeployment = (0, lambda_2.updateLambdaDeployment)(lambda, cfnDeployment);
96
- deployments.set(lambdaDeployment.name, lambdaDeployment.props);
97
- });
98
- autoscalingGroups.forEach((asg) => {
99
- const asgDeployment = (0, autoscaling_2.autoscalingDeployment)(asg, cfnDeployment);
100
- deployments.set(asgDeployment.name, asgDeployment.props);
101
- deployments.set(cfnDeployment.name, (0, cloudformation_1.addAmiParametersToCloudFormationDeployment)(cfnDeployment, asg));
102
- });
103
- });
104
- });
105
- });
106
- this.riffRaffYaml = {
107
- allowedStages,
108
- deployments,
109
- };
110
- }
111
63
  isCdkStackPresent(expectedClassName, expectedStack, expectedRegion, expectedStage) {
112
64
  const matches = this.allCdkStacks.find((cdkStack) => {
113
65
  const { constructor: { name }, stack, stage, region, } = cdkStack;
@@ -223,6 +175,54 @@ class RiffRaffYamlFileExperimental {
223
175
  getAutoScalingGroups(cdkStack) {
224
176
  return cdkStack.node.findAll().filter((_) => _ instanceof autoscaling_1.GuAutoScalingGroup);
225
177
  }
178
+ // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree
179
+ constructor(app) {
180
+ this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof core_1.GuStack);
181
+ const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));
182
+ this.allStageTags = Array.from(allowedStages);
183
+ this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));
184
+ this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));
185
+ this.validateStacksInApp();
186
+ this.validateAllRegionsAreResolved();
187
+ this.outdir = app.outdir;
188
+ const deployments = new Map();
189
+ const groupedStacks = (0, group_by_1.groupByClassNameStackRegionStage)(this.allCdkStacks);
190
+ Object.values(groupedStacks).forEach((stackTagGroup) => {
191
+ Object.values(stackTagGroup).forEach((regionGroup) => {
192
+ Object.values(regionGroup).forEach((stageGroup) => {
193
+ const stacks = Object.values(stageGroup).flat();
194
+ if (stacks.length === 0) {
195
+ throw new Error("Unable to produce a working riff-raff.yaml file; there are no stacks!");
196
+ }
197
+ // The items in `stacks` only differ by stage, so we can just use the first item in the list.
198
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length of `stacks` is checked above
199
+ const stack = stacks[0];
200
+ const lambdas = this.getLambdas(stack);
201
+ const autoscalingGroups = this.getAutoScalingGroups(stack);
202
+ const artifactUploads = [
203
+ lambdas.map(lambda_2.uploadLambdaArtifact),
204
+ autoscalingGroups.map(autoscaling_2.uploadAutoscalingArtifact),
205
+ ].flat();
206
+ artifactUploads.forEach(({ name, props }) => deployments.set(name, props));
207
+ const cfnDeployment = (0, cloudformation_1.cloudFormationDeployment)(stacks, artifactUploads, this.outdir);
208
+ deployments.set(cfnDeployment.name, cfnDeployment.props);
209
+ lambdas.forEach((lambda) => {
210
+ const lambdaDeployment = (0, lambda_2.updateLambdaDeployment)(lambda, cfnDeployment);
211
+ deployments.set(lambdaDeployment.name, lambdaDeployment.props);
212
+ });
213
+ autoscalingGroups.forEach((asg) => {
214
+ const asgDeployment = (0, autoscaling_2.autoscalingDeployment)(asg, cfnDeployment);
215
+ deployments.set(asgDeployment.name, asgDeployment.props);
216
+ deployments.set(cfnDeployment.name, (0, cloudformation_1.addAmiParametersToCloudFormationDeployment)(cfnDeployment, asg));
217
+ });
218
+ });
219
+ });
220
+ });
221
+ this.riffRaffYaml = {
222
+ allowedStages,
223
+ deployments,
224
+ };
225
+ }
226
226
  /**
227
227
  * The `riff-raff.yaml` file as a string.
228
228
  * Use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,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,yBAAgB,CAAuB,CAAC;IACpG,CAAC;IAEO,oBAAoB,CAAC,QAAiB;QAC5C,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,gCAAkB,CAAyB,CAAC;IACxG,CAAC;IAiED;;;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;AApPD,oEAoPC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport chalk from \"chalk\";\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 ClassName,\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(\n expectedClassName: ClassName,\n expectedStack: StackTag,\n expectedRegion: Region,\n expectedStage: StageTag\n ): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const {\n constructor: { name },\n stack,\n stage,\n region,\n } = cdkStack;\n return (\n name === expectedClassName && stack === expectedStack && stage === expectedStage && region === expectedRegion\n );\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 `GuStack`, `stack`, `region`, 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 * For the class: MyApplicationStack\n *\n * ┌───────────────┬────────────────────────────┐\n * │ (index) │ eu-west-1 │\n * ├───────────────┼────────────────────────────┤\n * │ deploy │ { CODE: '✅', PROD: '✅' } │\n * │ media-service │ { CODE: '❌', PROD: '✅' } │\n * └───────────────┴────────────────────────────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<ClassName, Record<StackTag, Record<Region, Record<StageTag, Found | NotFound>>>>;\n\n const { allCdkStacks, allStackTags, allStageTags, allRegions } = this;\n\n const checks: AppValidation = allCdkStacks.reduce((accClassName, { constructor: { name } }) => {\n return {\n ...accClassName,\n [name]: allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allRegions.reduce((accRegion, region) => {\n return {\n ...accRegion,\n [region]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(name, stackTag, region, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {}),\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).flatMap((groupedByRegion) => {\n return Object.values(groupedByRegion).flatMap((groupedByStage) => {\n return Object.values(groupedByStage).filter((_) => _ === \"❌\");\n });\n });\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 Object.entries(checks).forEach(([className, detail]) => {\n console.log(`For the class: ${chalk.yellow(className)}`);\n console.table(detail);\n });\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.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 lambdas.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 deployments.set(cfnDeployment.name, addAmiParametersToCloudFormationDeployment(cfnDeployment, asg));\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,kDAA0B;AAC1B,qCAA+B;AAC/B,8DAAkE;AAClE,gDAAgD;AAChD,oDAA2D;AAC3D,2DAA6F;AAC7F,iEAAoH;AACpH,iDAAoF;AACpF,yCAA8D;AAa9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,4BAA4B;IAS/B,iBAAiB,CACvB,iBAA4B,EAC5B,aAAuB,EACvB,cAAsB,EACtB,aAAuB;QAEvB,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE;YAClD,MAAM,EACJ,WAAW,EAAE,EAAE,IAAI,EAAE,EACrB,KAAK,EACL,KAAK,EACL,MAAM,GACP,GAAG,QAAQ,CAAC;YACb,OAAO,CACL,IAAI,KAAK,iBAAiB,IAAI,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,aAAa,IAAI,MAAM,KAAK,cAAc,CAC9G,CAAC;QACJ,CAAC,CAA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AG,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;AApPD,oEAoPC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport chalk from \"chalk\";\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 ClassName,\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(\n expectedClassName: ClassName,\n expectedStack: StackTag,\n expectedRegion: Region,\n expectedStage: StageTag\n ): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const {\n constructor: { name },\n stack,\n stage,\n region,\n } = cdkStack;\n return (\n name === expectedClassName && stack === expectedStack && stage === expectedStage && region === expectedRegion\n );\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 `GuStack`, `stack`, `region`, 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 * For the class: MyApplicationStack\n *\n * ┌───────────────┬────────────────────────────┐\n * │ (index) │ eu-west-1 │\n * ├───────────────┼────────────────────────────┤\n * │ deploy │ { CODE: '✅', PROD: '✅' } │\n * │ media-service │ { CODE: '❌', PROD: '✅' } │\n * └───────────────┴────────────────────────────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<ClassName, Record<StackTag, Record<Region, Record<StageTag, Found | NotFound>>>>;\n\n const { allCdkStacks, allStackTags, allStageTags, allRegions } = this;\n\n const checks: AppValidation = allCdkStacks.reduce((accClassName, { constructor: { name } }) => {\n return {\n ...accClassName,\n [name]: allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allRegions.reduce((accRegion, region) => {\n return {\n ...accRegion,\n [region]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(name, stackTag, region, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {}),\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).flatMap((groupedByRegion) => {\n return Object.values(groupedByRegion).flatMap((groupedByStage) => {\n return Object.values(groupedByStage).filter((_) => _ === \"❌\");\n });\n });\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 Object.entries(checks).forEach(([className, detail]) => {\n console.log(`For the class: ${chalk.yellow(className)}`);\n console.table(detail);\n });\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.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 lambdas.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 deployments.set(cfnDeployment.name, addAmiParametersToCloudFormationDeployment(cfnDeployment, asg));\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,14 +1,14 @@
1
1
  import type { GuStack } from "../../constructs/core";
2
- export declare type ClassName = string;
3
- export declare type StackTag = string;
4
- export declare type StageTag = string;
5
- export declare type Region = string;
6
- export declare type CdkStacksDifferingOnlyByStage = GuStack[];
2
+ export type ClassName = string;
3
+ export type StackTag = string;
4
+ export type StageTag = string;
5
+ export type Region = string;
6
+ export type CdkStacksDifferingOnlyByStage = GuStack[];
7
7
  export interface RiffRaffYaml {
8
8
  allowedStages: Set<StageTag>;
9
9
  deployments: Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>;
10
10
  }
11
- export declare type RiffRaffDeploymentName = string;
11
+ export type RiffRaffDeploymentName = string;
12
12
  export interface RiffRaffDeploymentProps {
13
13
  type: string;
14
14
  regions: Set<Region>;
@@ -23,5 +23,5 @@ export interface RiffRaffDeployment {
23
23
  name: RiffRaffDeploymentName;
24
24
  props: RiffRaffDeploymentProps;
25
25
  }
26
- export declare type GroupedCdkStacks = Record<ClassName, Record<StackTag, Record<Region, Record<StageTag, CdkStacksDifferingOnlyByStage>>>>;
26
+ export type GroupedCdkStacks = Record<ClassName, Record<StackTag, Record<Region, Record<StageTag, CdkStacksDifferingOnlyByStage>>>>;
27
27
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/experimental/riff-raff-yaml-file/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAErD,oBAAY,SAAS,GAAG,MAAM,CAAC;AAC/B,oBAAY,QAAQ,GAAG,MAAM,CAAC;AAC9B,oBAAY,QAAQ,GAAG,MAAM,CAAC;AAC9B,oBAAY,MAAM,GAAG,MAAM,CAAC;AAC5B,oBAAY,6BAA6B,GAAG,OAAO,EAAE,CAAC;AAEtD,MAAM,WAAW,YAAY;IAC3B,aAAa,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7B,WAAW,EAAE,GAAG,CAAC,sBAAsB,EAAE,uBAAuB,CAAC,CAAC;CACnE;AAED,oBAAY,sBAAsB,GAAG,MAAM,CAAC;AAE5C,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,gBAAgB,EAAE,MAA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