-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathnotifications-resource.ts
216 lines (184 loc) · 6.97 KB
/
notifications-resource.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { Construct } from 'constructs';
import { NotificationsResourceHandler } from './notifications-resource-handler';
import * as iam from '../../../aws-iam';
import * as cdk from '../../../core';
import { Bucket, IBucket, EventType, NotificationKeyFilter } from '../bucket';
import { BucketNotificationDestinationType, IBucketNotificationDestination } from '../destination';
interface NotificationsProps {
/**
* The bucket to manage notifications for.
*/
bucket: IBucket;
/**
* The role to be used by the lambda handler
*/
handlerRole?: iam.IRole;
}
/**
* A custom CloudFormation resource that updates bucket notifications for a
* bucket. The reason we need it is because the AWS::S3::Bucket notification
* configuration is defined on the bucket itself, which makes it impossible to
* provision notifications at the same time as the target (since
* PutBucketNotifications validates the targets).
*
* Since only a single BucketNotifications resource is allowed for each Bucket,
* this construct is not exported in the public API of this module. Instead, it
* is created just-in-time by `s3.Bucket.onEvent`, so a 1:1 relationship is
* ensured.
*
* @see
* https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig.html
*/
export class BucketNotifications extends Construct {
private eventBridgeEnabled = false;
private readonly lambdaNotifications = new Array<LambdaFunctionConfiguration>();
private readonly queueNotifications = new Array<QueueConfiguration>();
private readonly topicNotifications = new Array<TopicConfiguration>();
private resource?: cdk.CfnResource;
private readonly bucket: IBucket;
private readonly handlerRole?: iam.IRole;
constructor(scope: Construct, id: string, props: NotificationsProps) {
super(scope, id);
this.bucket = props.bucket;
this.handlerRole = props.handlerRole;
}
/**
* Adds a notification subscription for this bucket.
* If this is the first notification, a BucketNotification resource is added to the stack.
*
* @param event The type of event
* @param target The target construct
* @param filters A set of S3 key filters
*/
public addNotification(event: EventType, target: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]) {
const resource = this.createResourceOnce();
// resolve target. this also provides an opportunity for the target to e.g. update
// policies to allow this notification to happen.
const targetProps = target.bind(this, this.bucket);
const commonConfig: CommonConfiguration = {
Events: [event],
Filter: renderFilters(filters),
};
// if the target specifies any dependencies, add them to the custom resource.
// for example, the SNS topic policy must be created /before/ the notification resource.
// otherwise, S3 won't be able to confirm the subscription.
if (targetProps.dependencies) {
resource.node.addDependency(...targetProps.dependencies);
}
// based on the target type, add the the correct configurations array
switch (targetProps.type) {
case BucketNotificationDestinationType.LAMBDA:
this.lambdaNotifications.push({ ...commonConfig, LambdaFunctionArn: targetProps.arn });
break;
case BucketNotificationDestinationType.QUEUE:
this.queueNotifications.push({ ...commonConfig, QueueArn: targetProps.arn });
break;
case BucketNotificationDestinationType.TOPIC:
this.topicNotifications.push({ ...commonConfig, TopicArn: targetProps.arn });
break;
default:
throw new Error('Unsupported notification target type:' + BucketNotificationDestinationType[targetProps.type]);
}
}
public enableEventBridgeNotification() {
this.createResourceOnce();
this.eventBridgeEnabled = true;
}
private renderNotificationConfiguration(): NotificationConfiguration {
return {
EventBridgeConfiguration: this.eventBridgeEnabled ? {} : undefined,
LambdaFunctionConfigurations: this.lambdaNotifications.length > 0 ? this.lambdaNotifications : undefined,
QueueConfigurations: this.queueNotifications.length > 0 ? this.queueNotifications : undefined,
TopicConfigurations: this.topicNotifications.length > 0 ? this.topicNotifications : undefined,
};
}
/**
* Defines the bucket notifications resources in the stack only once.
* This is called lazily as we add notifications, so that if notifications are not added,
* there is no notifications resource.
*/
private createResourceOnce() {
if (!this.resource) {
const handler = NotificationsResourceHandler.singleton(this, {
role: this.handlerRole,
});
const managed = this.bucket instanceof Bucket;
if (!managed) {
handler.addToRolePolicy(new iam.PolicyStatement({
actions: ['s3:GetBucketNotification'],
resources: ['*'],
}));
}
this.resource = new cdk.CfnResource(this, 'Resource', {
type: 'Custom::S3BucketNotifications',
properties: {
ServiceToken: handler.functionArn,
BucketName: this.bucket.bucketName,
NotificationConfiguration: cdk.Lazy.any({ produce: () => this.renderNotificationConfiguration() }),
Managed: managed,
},
});
}
return this.resource;
}
}
function renderFilters(filters?: NotificationKeyFilter[]): Filter | undefined {
if (!filters || filters.length === 0) {
return undefined;
}
const renderedRules = new Array<FilterRule>();
let hasPrefix = false;
let hasSuffix = false;
for (const rule of filters) {
if (!rule.suffix && !rule.prefix) {
throw new Error('NotificationKeyFilter must specify `prefix` and/or `suffix`');
}
if (rule.suffix) {
if (hasSuffix) {
throw new Error('Cannot specify more than one suffix rule in a filter.');
}
renderedRules.push({ Name: 'suffix', Value: rule.suffix });
hasSuffix = true;
}
if (rule.prefix) {
if (hasPrefix) {
throw new Error('Cannot specify more than one prefix rule in a filter.');
}
renderedRules.push({ Name: 'prefix', Value: rule.prefix });
hasPrefix = true;
}
}
return {
Key: {
FilterRules: renderedRules,
},
};
}
interface NotificationConfiguration {
EventBridgeConfiguration?: EventBridgeConfiguration;
LambdaFunctionConfigurations?: LambdaFunctionConfiguration[];
QueueConfigurations?: QueueConfiguration[];
TopicConfigurations?: TopicConfiguration[];
}
interface CommonConfiguration {
Id?: string;
Events: EventType[];
Filter?: Filter
}
interface EventBridgeConfiguration { }
interface LambdaFunctionConfiguration extends CommonConfiguration {
LambdaFunctionArn: string;
}
interface QueueConfiguration extends CommonConfiguration {
QueueArn: string;
}
interface TopicConfiguration extends CommonConfiguration {
TopicArn: string;
}
interface FilterRule {
Name: 'prefix' | 'suffix';
Value: string;
}
interface Filter {
Key: { FilterRules: FilterRule[] }
}