-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtrigger.ts
403 lines (348 loc) · 11.5 KB
/
trigger.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import {
Context,
APIGatewayEvent,
APIGatewayProxyEventV2,
ALBEvent,
CloudWatchLogsEvent,
ScheduledEvent,
CloudFrontRequestEvent,
DynamoDBStreamEvent,
KinesisStreamEvent,
S3Event,
SNSEvent,
SQSEvent,
EventBridgeEvent,
} from "aws-lambda";
import * as eventType from "../utils/event-type-guards";
import { logDebug } from "../utils";
import { gunzipSync } from "zlib";
type LambdaURLEvent = {
headers: { [name: string]: string | undefined };
requestContext: {
domainName?: string | undefined;
http: {
method: string;
path: string;
};
};
};
function isHTTPTriggerEvent(eventSource: string | undefined) {
return (
eventSource === "api-gateway" ||
eventSource === "application-load-balancer" ||
eventSource === "lambda-function-url"
);
}
function getAWSPartitionByRegion(region: string) {
if (region.startsWith("us-gov-")) {
return "aws-us-gov";
} else if (region.startsWith("cn-")) {
return "aws-cn";
} else {
return "aws";
}
}
function extractAPIGatewayRequestContext(event: APIGatewayEvent | APIGatewayProxyEventV2) {
return event.requestContext;
}
function extractCloudFrontRequestEventDistributionId(event: CloudFrontRequestEvent) {
return event.Records[0].cf.config.distributionId;
}
function extractCloudWatchLogsEventDecodedLogs(event: CloudWatchLogsEvent) {
const buffer = Buffer.from(event.awslogs.data, "base64");
const decompressed = gunzipSync(buffer).toString();
return JSON.parse(decompressed);
}
function extractALBEventARN(event: ALBEvent) {
return event.requestContext.elb.targetGroupArn;
}
function extractCloudWatchEventARN(event: ScheduledEvent) {
return event.resources[0];
}
function extractDynamoDBStreamEventARN(event: DynamoDBStreamEvent) {
return event.Records[0].eventSourceARN;
}
function extractKinesisStreamEventARN(event: KinesisStreamEvent) {
return event.Records[0].eventSourceARN;
}
function extractS3EventARN(event: S3Event) {
return event.Records[0].s3.bucket.arn;
}
function extractSNSEventARN(event: SNSEvent) {
return event.Records[0].Sns.TopicArn;
}
function extractSQSEventARN(event: SQSEvent) {
return event.Records[0].eventSourceARN;
}
function extractEventBridgeARN(event: EventBridgeEvent<any, any>) {
return event.source;
}
function extractStateMachineARN(event: any) {
// Extract Payload if available (Legacy lambda parsing)
if (typeof event.Payload === "object") {
event = event.Payload;
}
// Extract _datadog if available (JSONata v1 parsing)
if (typeof event._datadog === "object") {
event = event._datadog;
}
return event.StateMachine.Id;
}
export enum eventTypes {
apiGateway = "api-gateway",
applicationLoadBalancer = "application-load-balancer",
cloudFront = "cloudfront",
cloudWatchEvents = "cloudwatch-events",
cloudWatchLogs = "cloudwatch-logs",
cloudWatch = "cloudwatch",
dynamoDB = "dynamodb",
eventBridge = "eventbridge",
kinesis = "kinesis",
lambdaUrl = "lambda-function-url",
s3 = "s3",
sns = "sns",
sqs = "sqs",
stepFunctions = "states",
}
export enum eventSubTypes {
apiGatewayV1 = "api-gateway-rest-api",
apiGatewayV2 = "api-gateway-http-api",
apiGatewayWebsocket = "api-gateway-websocket",
unknown = "unknown-sub-type",
}
export function parseEventSourceSubType(event: any): eventSubTypes {
if (eventType.isAPIGatewayEvent(event)) {
return eventSubTypes.apiGatewayV1;
}
if (eventType.isAPIGatewayEventV2(event)) {
return eventSubTypes.apiGatewayV2;
}
if (eventType.isAPIGatewayWebsocketEvent(event)) {
return eventSubTypes.apiGatewayWebsocket;
}
return eventSubTypes.unknown;
}
/**
* parseEventSource parses the triggering event to determine the source
* Possible Returns:
* api-gateway | application-load-balancer | cloudwatch-logs |
* cloudwatch-events | cloudfront | dynamodb | kinesis | s3 | sns | sqs | states
*/
export function parseEventSource(event: any) {
if (eventType.isLambdaUrlEvent(event)) {
return eventTypes.lambdaUrl;
}
if (
eventType.isAPIGatewayEvent(event) ||
eventType.isAPIGatewayEventV2(event) ||
eventType.isAPIGatewayWebsocketEvent(event)
) {
return eventTypes.apiGateway;
}
if (eventType.isALBEvent(event)) {
return eventTypes.applicationLoadBalancer;
}
if (eventType.isCloudWatchLogsEvent(event)) {
return eventTypes.cloudWatchLogs;
}
if (eventType.isCloudWatchEvent(event)) {
return eventTypes.cloudWatchEvents;
}
if (eventType.isCloudFrontRequestEvent(event)) {
return eventTypes.cloudFront;
}
if (eventType.isDynamoDBStreamEvent(event)) {
return eventTypes.dynamoDB;
}
if (eventType.isKinesisStreamEvent(event)) {
return eventTypes.kinesis;
}
if (eventType.isS3Event(event)) {
return eventTypes.s3;
}
if (eventType.isSNSEvent(event)) {
return eventTypes.sns;
}
if (eventType.isSQSEvent(event)) {
return eventTypes.sqs;
}
if (eventType.isEventBridgeEvent(event)) {
return eventTypes.eventBridge;
}
if (eventType.isStepFunctionsEvent(event)) {
return eventTypes.stepFunctions;
}
}
/**
* parseEventSourceARN parses the triggering event to determine the event source's
* ARN if available. Otherwise we stitch together the ARN
*/
export function parseEventSourceARN(source: string | undefined, event: any, context: Context) {
const splitFunctionArn = context.invokedFunctionArn.split(":");
const region = splitFunctionArn[3];
const accountId = splitFunctionArn[4];
const awsARN = getAWSPartitionByRegion(region);
let eventSourceARN: string | undefined;
// e.g. arn:aws:s3:::lambda-xyz123-abc890
if (source === "s3") {
eventSourceARN = extractS3EventARN(event);
}
// e.g. arn:aws:sns:us-east-1:123456789012:sns-lambda
if (source === "sns") {
eventSourceARN = extractSNSEventARN(event);
}
// // e.g. arn:aws:sqs:us-east-1:123456789012:MyQueue
if (source === "sqs") {
eventSourceARN = extractSQSEventARN(event);
}
// e.g. arn:aws:cloudfront::123456789012:distribution/ABC123XYZ
if (source === "cloudfront") {
const distributionId = extractCloudFrontRequestEventDistributionId(event);
eventSourceARN = `arn:${awsARN}:cloudfront::${accountId}:distribution/${distributionId}`;
}
// e.g. arn:aws:apigateway:us-east-1::/restapis/xyz123/stages/default
if (source === "api-gateway") {
const requestContext = extractAPIGatewayRequestContext(event);
eventSourceARN = `arn:${awsARN}:apigateway:${region}::/restapis/${requestContext.apiId}/stages/${requestContext.stage}`;
}
// e.g. arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-xyz/123
if (source === "application-load-balancer") {
eventSourceARN = extractALBEventARN(event);
}
// e.g. arn:aws:logs:us-west-1:123456789012:log-group:/my-log-group-xyz
if (source === "cloudwatch-logs") {
const logs = extractCloudWatchLogsEventDecodedLogs(event);
eventSourceARN = `arn:${awsARN}:logs:${region}:${accountId}:log-group:${logs.logGroup}`;
}
// e.g. arn:aws:events:us-east-1:123456789012:rule/my-schedule
if (source === "cloudwatch-events") {
eventSourceARN = extractCloudWatchEventARN(event);
}
// arn:aws:dynamodb:us-east-1:123456789012:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899
if (source === "dynamodb") {
eventSourceARN = extractDynamoDBStreamEventARN(event);
}
// arn:aws:kinesis:EXAMPLE
if (source === "kinesis") {
eventSourceARN = extractKinesisStreamEventARN(event);
}
if (source === "eventbridge") {
eventSourceARN = extractEventBridgeARN(event);
}
if (source === "states") {
eventSourceARN = extractStateMachineARN(event);
}
return eventSourceARN;
}
/**
* extractHTTPTags extracts HTTP facet tags from the triggering event
*/
function extractHTTPTags(event: APIGatewayEvent | APIGatewayProxyEventV2 | ALBEvent | LambdaURLEvent) {
const httpTags: { [key: string]: string } = {};
if (eventType.isAPIGatewayEvent(event)) {
const requestContext = event.requestContext;
if (requestContext.domainName) {
httpTags["http.url"] = requestContext.domainName;
}
httpTags["http.url_details.path"] = requestContext.path;
httpTags["http.method"] = requestContext.httpMethod;
if (event.headers?.Referer) {
httpTags["http.referer"] = event.headers.Referer;
}
if (event.resource) {
httpTags["http.route"] = event.resource;
}
return httpTags;
}
if (eventType.isAPIGatewayEventV2(event)) {
const requestContext = event.requestContext;
httpTags["http.url"] = requestContext.domainName;
httpTags["http.url_details.path"] = requestContext.http.path;
httpTags["http.method"] = requestContext.http.method;
if (event.headers?.Referer) {
httpTags["http.referer"] = event.headers.Referer;
}
if (event.routeKey) {
// "GET /my/endpoint" => "/my/endpoint"
const array = event.routeKey.split(" ");
httpTags["http.route"] = array[array.length - 1];
}
return httpTags;
}
if (eventType.isALBEvent(event)) {
httpTags["http.url_details.path"] = event.path;
httpTags["http.method"] = event.httpMethod;
if (event.headers && event.headers.Referer) {
httpTags["http.referer"] = event.headers.Referer;
}
return httpTags;
}
if (eventType.isLambdaUrlEvent(event)) {
const requestContext = event.requestContext;
if (requestContext.domainName) {
httpTags["http.url"] = requestContext.domainName;
}
httpTags["http.url_details.path"] = requestContext.http.path;
httpTags["http.method"] = requestContext.http.method;
if (event.headers?.Referer) {
httpTags["http.referer"] = event.headers.Referer;
}
return httpTags;
}
}
/**
* extractTriggerTags parses the trigger event object for tags to be added to the span metadata
*/
export function extractTriggerTags(event: any, context: Context) {
let triggerTags: { [key: string]: string } = {};
const eventSource = parseEventSource(event);
if (eventSource) {
triggerTags["function_trigger.event_source"] = eventSource;
let eventSourceARN: string | undefined;
try {
eventSourceARN = parseEventSourceARN(eventSource, event, context);
} catch (error) {
logDebug(`failed to extract ${eventSource} arn from the event`, { error });
}
if (eventSourceARN) {
triggerTags["function_trigger.event_source_arn"] = eventSourceARN;
}
}
if (isHTTPTriggerEvent(eventSource)) {
try {
triggerTags = { ...triggerTags, ...extractHTTPTags(event) };
} catch (error) {
logDebug(`failed to extract http tags from ${eventSource} event`);
}
}
return triggerTags;
}
/**
* extractHTTPStatusCode extracts a status code from the response if the Lambda was triggered
* by API Gateway, ALB, or Lambda Function URL
*/
export function extractHTTPStatusCodeTag(
triggerTags: { [key: string]: string } | undefined,
result: any,
isResponseStreamFunction: boolean,
): string | undefined {
let eventSource: string | undefined;
triggerTags ? (eventSource = triggerTags["function_trigger.event_source"]) : (eventSource = undefined);
if (!isHTTPTriggerEvent(eventSource)) {
return;
}
const resultStatusCode = result?.statusCode;
// Return a 502 status if no response is found in
// any buffered function. Streaming functions returning
// undefined results will be marked as 200.
if (result === undefined && !isResponseStreamFunction) {
return "502";
} else if (resultStatusCode) {
// Type check the statusCode if available
if (typeof resultStatusCode === "number") {
return resultStatusCode.toString();
}
} else {
return "200";
}
}