-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsnsUtils.ts
More file actions
232 lines (212 loc) · 6.84 KB
/
snsUtils.ts
File metadata and controls
232 lines (212 loc) · 6.84 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import {
type CreateTopicCommandInput,
ListTagsForResourceCommand,
type SNSClient,
TagResourceCommand,
paginateListTopics,
} from '@aws-sdk/client-sns'
import {
CreateTopicCommand,
DeleteTopicCommand,
GetSubscriptionAttributesCommand,
GetTopicAttributesCommand,
ListSubscriptionsByTopicCommand,
SetTopicAttributesCommand,
UnsubscribeCommand,
} from '@aws-sdk/client-sns'
import { type Either, InternalError, isError } from '@lokalise/node-core'
import { calculateOutgoingMessageSize as sqsCalculateOutgoingMessageSize } from '@message-queue-toolkit/sqs'
import type { ExtraSNSCreationParams } from '../sns/AbstractSnsService'
import type { STSClient } from '@aws-sdk/client-sts'
import { generateTopicSubscriptionPolicy } from './snsAttributeUtils'
import { buildTopicArn } from './stsUtils'
type AttributesResult = {
attributes?: Record<string, string>
}
export async function getTopicAttributes(
snsClient: SNSClient,
topicArn: string,
): Promise<Either<'not_found', AttributesResult>> {
const command = new GetTopicAttributesCommand({
TopicArn: topicArn,
})
try {
const response = await snsClient.send(command)
return {
result: {
attributes: response.Attributes,
},
}
} catch (err) {
// @ts-ignore
if (err.Code === 'AWS.SimpleQueueService.NonExistentQueue') {
return {
// @ts-ignore
error: 'not_found',
}
}
throw err
}
}
export async function getSubscriptionAttributes(
snsClient: SNSClient,
subscriptionArn: string,
): Promise<Either<'not_found', AttributesResult>> {
const command = new GetSubscriptionAttributesCommand({
SubscriptionArn: subscriptionArn,
})
try {
const response = await snsClient.send(command)
return {
result: {
attributes: response.Attributes,
},
}
} catch (err) {
// @ts-ignore
if (err.Code === 'AWS.SimpleQueueService.NonExistentQueue') {
return {
// @ts-ignore
error: 'not_found',
}
}
throw err
}
}
export async function assertTopic(
snsClient: SNSClient,
stsClient: STSClient,
topicOptions: CreateTopicCommandInput,
extraParams?: ExtraSNSCreationParams,
) {
let topicArn: string
try {
const command = new CreateTopicCommand(topicOptions)
const response = await snsClient.send(command)
if (!response.TopicArn) throw new Error('No topic arn in response')
topicArn = response.TopicArn
} catch (error) {
if (!isError(error)) throw error
// To build ARN we need topic name and error should be "topic already exist with different tags"
if (!topicOptions.Name || !isTopicAlreadyExistWithDifferentTagsError(error)) {
throw new InternalError({
message: `${topicOptions.Name} - ${error.message}`,
cause: error,
details: { topicName: topicOptions.Name },
errorCode: 'SNS_CREATE_TOPIC_COMMAND_UNEXPECTED_ERROR',
})
}
topicArn = await buildTopicArn(stsClient, topicOptions.Name)
if (!extraParams?.forceTagUpdate) {
const currentTags = await snsClient.send(
new ListTagsForResourceCommand({ ResourceArn: topicArn }),
)
throw new InternalError({
message: `${topicOptions.Name} - ${error.message}`,
details: {
topicName: topicOptions.Name,
currentTags: JSON.stringify(currentTags),
newTags: JSON.stringify(topicOptions.Tags),
},
errorCode: 'SNS_TOPIC_ALREADY_EXISTS_WITH_DIFFERENT_TAGS',
cause: error,
})
}
}
if (extraParams?.queueUrlsWithSubscribePermissionsPrefix || extraParams?.allowedSourceOwner) {
const setTopicAttributesCommand = new SetTopicAttributesCommand({
TopicArn: topicArn,
AttributeName: 'Policy',
AttributeValue: generateTopicSubscriptionPolicy({
topicArn,
allowedSqsQueueUrlPrefix: extraParams.queueUrlsWithSubscribePermissionsPrefix,
allowedSourceOwner: extraParams.allowedSourceOwner,
}),
})
await snsClient.send(setTopicAttributesCommand)
}
if (extraParams?.forceTagUpdate && topicOptions.Tags) {
const tagTopicCommand = new TagResourceCommand({
ResourceArn: topicArn,
Tags: topicOptions.Tags,
})
await snsClient.send(tagTopicCommand)
}
return topicArn
}
export async function deleteTopic(snsClient: SNSClient, stsClient: STSClient, topicName: string) {
try {
const topicArn = await assertTopic(snsClient, stsClient, {
Name: topicName,
})
await snsClient.send(
new DeleteTopicCommand({
TopicArn: topicArn,
}),
)
} catch (_) {
// we don't care it operation has failed
}
}
export async function deleteSubscription(client: SNSClient, subscriptionArn: string) {
const command = new UnsubscribeCommand({
SubscriptionArn: subscriptionArn,
})
try {
await client.send(command)
} catch (_) {
// we don't care it operation has failed
}
}
export async function findSubscriptionByTopicAndQueue(
snsClient: SNSClient,
topicArn: string,
queueArn: string,
) {
const listSubscriptionsCommand = new ListSubscriptionsByTopicCommand({
TopicArn: topicArn,
})
const listSubscriptionResult = await snsClient.send(listSubscriptionsCommand)
return listSubscriptionResult.Subscriptions?.find((entry) => {
return entry.Endpoint === queueArn
})
}
export async function getTopicArnByName(snsClient: SNSClient, topicName?: string): Promise<string> {
if (!topicName) {
throw new Error('topicName is not provided')
}
// Use paginator to automatically handle NextToken
const paginator = paginateListTopics({ client: snsClient }, {})
for await (const page of paginator) {
for (const topic of page.Topics || []) {
if (topic.TopicArn?.includes(topicName)) {
return topic.TopicArn
}
}
}
throw new Error(`Failed to resolve topic by name ${topicName}`)
}
/**
* Calculates the size of an outgoing SNS message.
*
* SNS imposes a 256 KB limit on the total size of a message, which includes both the message body and any metadata (attributes).
* This function currently computes the size based solely on the message body, as no attributes are included at this time.
* For future updates, if message attributes are added, their sizes should also be considered.
*
* Reference: https://docs.aws.amazon.com/sns/latest/dg/sns-message-attributes.html
*
* A wrapper around the equivalent function in the SQS package.
*/
export const calculateOutgoingMessageSize = (message: unknown) =>
sqsCalculateOutgoingMessageSize(message)
const isTopicAlreadyExistWithDifferentTagsError = (error: unknown) =>
!!error &&
isError(error) &&
'Error' in error &&
!!error.Error &&
typeof error.Error === 'object' &&
'Code' in error.Error &&
'Message' in error.Error &&
typeof error.Error.Message === 'string' &&
error.Error.Code === 'InvalidParameter' &&
error.Error.Message.includes('already exists with different tags')