-
Notifications
You must be signed in to change notification settings - Fork 677
Expand file tree
/
Copy pathrecursionDetectionMiddleware.ts
More file actions
50 lines (45 loc) · 1.7 KB
/
recursionDetectionMiddleware.ts
File metadata and controls
50 lines (45 loc) · 1.7 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
// @ts-ignore
import { InvokeStore } from "@aws/lambda-invoke-store";
import { HttpRequest } from "@smithy/protocol-http";
import type {
BuildHandler,
BuildHandlerArguments,
BuildHandlerOutput,
BuildMiddleware,
MetadataBearer,
} from "@smithy/types";
const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
const ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
/**
* Inject to trace ID to request header to detect recursion invocation in Lambda.
* @internal
*/
export const recursionDetectionMiddleware =
(): BuildMiddleware<any, any> =>
<Output extends MetadataBearer>(next: BuildHandler<any, Output>): BuildHandler<any, Output> =>
async (args: BuildHandlerArguments<any>): Promise<BuildHandlerOutput<Output>> => {
const { request } = args;
if (!HttpRequest.isInstance(request)) {
return next(args);
}
const traceIdHeader =
Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ??
TRACE_ID_HEADER_NAME;
if (request.headers.hasOwnProperty(traceIdHeader)) {
return next(args);
}
const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
const traceIdFromEnv = process.env[ENV_TRACE_ID];
const invokeStore = await InvokeStore.getInstanceAsync();
const traceIdFromInvokeStore = invokeStore?.getXRayTraceId();
const traceId = traceIdFromInvokeStore ?? traceIdFromEnv;
const nonEmptyString = (str: unknown): str is string => typeof str === "string" && str.length > 0;
if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
request.headers[TRACE_ID_HEADER_NAME] = traceId;
}
return next({
...args,
request,
});
};