-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathsns-adapter.ts
355 lines (329 loc) · 10 KB
/
sns-adapter.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import { ListSubscriptionsResponse, ListTopicsResponse, MessageAttributeValue, SNSClient, ListTopicsCommand, ListSubscriptionsCommand, UnsubscribeCommand, CreateTopicCommand, SubscribeCommand, PublishCommand } from "@aws-sdk/client-sns";
import _ from "lodash";
import fetch from "node-fetch";
import { createMessageId, createSnsLambdaEvent } from "./helpers.js";
import { IDebug, ISNSAdapter } from "./types.js";
export class SNSAdapter implements ISNSAdapter {
private sns: SNSClient;
private pluginDebug: IDebug;
private port: number;
private server: any;
private app: any;
private serviceName: string;
private stage: string;
private endpoint: string;
private adapterEndpoint: string;
private baseSubscribeEndpoint: string;
private accountId: string;
constructor(
localPort,
remotePort,
region,
snsEndpoint,
debug,
app,
serviceName,
stage,
accountId,
host,
subscribeEndpoint
) {
this.pluginDebug = debug;
this.app = app;
this.serviceName = serviceName;
this.stage = stage;
this.adapterEndpoint = `http://${host || "127.0.0.1"}:${localPort}`;
this.baseSubscribeEndpoint = subscribeEndpoint
? `http://${subscribeEndpoint}:${remotePort}`
: this.adapterEndpoint;
this.endpoint = snsEndpoint || `http://127.0.0.1:${localPort}`;
this.debug("using endpoint: " + this.endpoint);
this.accountId = accountId;
this.sns = new SNSClient({
credentials: {
accessKeyId: "AKID",
secretAccessKey: "SECRET",
},
endpoint: this.endpoint,
region,
});
}
public async listTopics(): Promise<ListTopicsResponse> {
this.debug("listing topics");
const req = new ListTopicsCommand({});
this.debug(JSON.stringify(req.input));
return await new Promise((res) => {
this.sns.send(req, (err, topics) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug(JSON.stringify(topics));
}
res(topics);
});
});
}
public async listSubscriptions(): Promise<ListSubscriptionsResponse> {
this.debug("listing subs");
const req = new ListSubscriptionsCommand({});
this.debug(JSON.stringify(req.input));
return await new Promise((res) => {
this.sns.send(req, (err, subs) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug(JSON.stringify(subs));
}
res(subs);
});
});
}
public async unsubscribe(arn) {
this.debug("unsubscribing: " + arn);
const unsubscribeReq = new UnsubscribeCommand({ SubscriptionArn: arn });
await new Promise((res) => {
this.sns.send(
unsubscribeReq,
(err, data) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug("unsubscribed: " + JSON.stringify(data));
}
res(true);
}
);
});
}
public async createTopic(topicName) {
const createTopicReq = new CreateTopicCommand({ Name: topicName });
return new Promise((res) =>
this.sns.send(createTopicReq, (err, data) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug("arn: " + JSON.stringify(data));
}
res(data);
})
);
}
private sent: (data) => void;
public Deferred = new Promise((res) => (this.sent = res));
public async subscribe(fn, getHandler, arn, snsConfig) {
arn = this.convertPseudoParams(arn);
const subscribeEndpoint = this.baseSubscribeEndpoint + "/" + fn.name;
this.debug("subscribe: " + fn.name + " " + arn);
this.debug("subscribeEndpoint: " + subscribeEndpoint);
this.app.post("/" + fn.name, (req, res) => {
this.debug("calling fn: " + fn.name + " 1");
const oldEnv = _.extend({}, process.env);
process.env = _.extend({}, process.env, fn.environment);
let event = req.body;
if (req.is("text/plain") && req.get("x-amz-sns-rawdelivery") !== "true") {
const msg =
event.MessageStructure === "json"
? JSON.parse(event.Message).default
: event.Message;
event = createSnsLambdaEvent(
event.TopicArn,
"EXAMPLE",
event.Subject || "",
msg,
event.MessageId || createMessageId(),
event.MessageAttributes || {},
event.MessageGroupId
);
}
if (req.body.SubscribeURL) {
this.debug("Visiting subscribe url: " + req.body.SubscribeURL);
return fetch(req.body.SubscribeURL, {
method: "GET"
}).then((fetchResponse) => this.debug("Subscribed: " + fetchResponse));
}
const sendIt = (err, response) => {
process.env = oldEnv;
if (err) {
res.status(500).send(err);
this.sent(err);
} else {
res.send(response);
this.sent(response);
}
};
const maybePromise = getHandler(
event,
this.createLambdaContext(fn, sendIt),
sendIt
);
if (maybePromise && maybePromise.then) {
maybePromise
.then((response) => sendIt(null, response))
.catch((error) => sendIt(error, null));
}
});
const params = {
Protocol: snsConfig.protocol || "http",
TopicArn: arn,
Endpoint: subscribeEndpoint,
Attributes: {},
};
if (snsConfig.rawMessageDelivery === "true") {
params.Attributes["RawMessageDelivery"] = "true";
}
if (snsConfig.filterPolicy) {
params.Attributes["FilterPolicy"] = JSON.stringify(
snsConfig.filterPolicy
);
}
const subscribeRequest = new SubscribeCommand(params);
await new Promise((res) => {
this.sns.send(subscribeRequest, (err, data) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug(
`successfully subscribed fn "${fn.name}" to topic: "${arn}"`
);
}
res(true);
});
});
}
public async subscribeQueue(queueUrl, arn, snsConfig) {
arn = this.convertPseudoParams(arn);
this.debug("subscribe: " + queueUrl + " " + arn);
const params = {
Protocol: snsConfig.protocol || "sqs",
TopicArn: arn,
Endpoint: queueUrl,
Attributes: {},
};
if (snsConfig.rawMessageDelivery === "true") {
params.Attributes["RawMessageDelivery"] = "true";
}
if (snsConfig.filterPolicy) {
params.Attributes["FilterPolicy"] = JSON.stringify(
snsConfig.filterPolicy
);
}
const subscribeRequest = new SubscribeCommand(params);
await new Promise((res) => {
this.sns.send(subscribeRequest, (err, data) => {
if (err) {
this.debug(err, err.stack);
} else {
this.debug(
`successfully subscribed queue "${queueUrl}" to topic: "${arn}"`
);
}
res(true);
});
});
}
public convertPseudoParams(topicArn) {
const awsRegex = /#{AWS::([a-zA-Z]+)}/g;
return topicArn.replace(awsRegex, this.accountId);
}
public async publish(
topicArn: string,
message: string,
type: string = "",
messageAttributes: Record<string, MessageAttributeValue> = {},
subject: string = "",
messageGroupId?: string
) {
topicArn = this.convertPseudoParams(topicArn);
const publishReq = new PublishCommand({
Message: message,
Subject: subject,
MessageStructure: type,
TopicArn: topicArn,
MessageAttributes: messageAttributes,
...(messageGroupId && { MessageGroupId: messageGroupId }),
});
return await new Promise((resolve, reject) =>
this.sns.send(
publishReq,
(err, result) => {
resolve(result);
}
)
);
}
public async publishToTargetArn(
targetArn: string,
message: string,
type: string = "",
messageAttributes: Record<string, MessageAttributeValue> = {},
messageGroupId?: string
) {
targetArn = this.convertPseudoParams(targetArn);
const publishReq = new PublishCommand({
Message: message,
MessageStructure: type,
TargetArn: targetArn,
MessageAttributes: messageAttributes,
...(messageGroupId && { MessageGroupId: messageGroupId }),
});
return await new Promise((resolve, reject) =>
this.sns.send(
publishReq,
(err, result) => {
resolve(result);
}
)
);
}
public async publishToPhoneNumber(
phoneNumber: string,
message: string,
type: string = "",
messageAttributes: Record<string, MessageAttributeValue> = {},
messageGroupId?: string
) {
const publishReq = new PublishCommand({
Message: message,
MessageStructure: type,
PhoneNumber: phoneNumber,
MessageAttributes: messageAttributes,
...(messageGroupId && { MessageGroupId: messageGroupId }),
});
return await new Promise((resolve, reject) =>
this.sns.send(
publishReq,
(err, result) => {
resolve(result);
}
)
);
}
public debug(msg, stack?: any) {
this.pluginDebug(msg, "adapter");
}
private createLambdaContext(fun, cb?) {
const functionName = `${this.serviceName}-${this.stage}-${fun.name}`;
const endTime =
new Date().getTime() + (fun.timeout ? fun.timeout * 1000 : 6000);
const done = typeof cb === "function" ? cb : (x, y) => x || y; // eslint-disable-line no-extra-parens
return {
/* Methods */
done,
succeed: (res) => done(null, res),
fail: (err) => done(err, null),
getRemainingTimeInMillis: () => endTime - new Date().getTime(),
/* Properties */
functionName,
memoryLimitInMB: fun.memorySize || 1536,
functionVersion: `offline_functionVersion_for_${functionName}`,
invokedFunctionArn: `offline_invokedFunctionArn_for_${functionName}`,
awsRequestId: `offline_awsRequestId_${Math.random()
.toString(10)
.slice(2)}`,
logGroupName: `offline_logGroupName_for_${functionName}`,
logStreamName: `offline_logStreamName_for_${functionName}`,
identity: {},
clientContext: {},
};
}
}