forked from awslabs/aws-lambda-invoke-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke-store.ts
More file actions
194 lines (163 loc) · 5.15 KB
/
invoke-store.ts
File metadata and controls
194 lines (163 loc) · 5.15 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
import type { AsyncLocalStorage } from "node:async_hooks";
interface Context {
[key: string]: unknown;
[key: symbol]: unknown;
}
declare global {
namespace awslambda {
let InvokeStore: InvokeStoreBase | undefined;
}
}
const PROTECTED_KEYS = {
REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"),
X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),
TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID"),
} as const;
const NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(
process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? "",
);
if (!NO_GLOBAL_AWS_LAMBDA) {
globalThis.awslambda = globalThis.awslambda || {};
}
/**
* Base class for AWS Lambda context storage implementations.
* Provides core functionality for managing Lambda execution context.
*
* Implementations handle either single-context (InvokeStoreSingle) or
* multi-context (InvokeStoreMulti) scenarios based on Lambda's execution environment.
*
* @public
*/
export abstract class InvokeStoreBase {
public static readonly PROTECTED_KEYS = PROTECTED_KEYS;
abstract getContext(): Context | undefined;
abstract hasContext(): boolean;
abstract get<T = unknown>(key: string | symbol): T | undefined;
abstract set<T = unknown>(key: string | symbol, value: T): void;
abstract run<T>(context: Context, fn: () => T): T;
protected isProtectedKey(key: string | symbol): boolean {
return Object.values(PROTECTED_KEYS).includes(key as symbol);
}
getRequestId(): string {
return this.get<string>(PROTECTED_KEYS.REQUEST_ID) ?? "-";
}
getXRayTraceId(): string | undefined {
return this.get<string>(PROTECTED_KEYS.X_RAY_TRACE_ID);
}
getTenantId(): string | undefined {
return this.get<string>(PROTECTED_KEYS.TENANT_ID);
}
}
/**
* Single Context Implementation
* @internal
*/
class InvokeStoreSingle extends InvokeStoreBase {
private currentContext?: Context;
getContext(): Context | undefined {
return this.currentContext;
}
hasContext(): boolean {
return this.currentContext !== undefined;
}
get<T = unknown>(key: string | symbol): T | undefined {
return this.currentContext?.[key] as T | undefined;
}
set<T = unknown>(key: string | symbol, value: T): void {
if (this.isProtectedKey(key)) {
throw new Error(
`Cannot modify protected Lambda context field: ${String(key)}`,
);
}
this.currentContext = this.currentContext || {};
this.currentContext[key] = value;
}
run<T>(context: Context, fn: () => T): T {
this.currentContext = context;
try {
return fn();
} finally {
this.currentContext = undefined;
}
}
}
/**
* Multi Context Implementation
* @internal
*/
class InvokeStoreMulti extends InvokeStoreBase {
private als!: AsyncLocalStorage<Context>;
static async create(): Promise<InvokeStoreMulti> {
const instance = new InvokeStoreMulti();
const asyncHooks = await import("node:async_hooks");
instance.als = new asyncHooks.AsyncLocalStorage<Context>();
return instance;
}
getContext(): Context | undefined {
return this.als.getStore();
}
hasContext(): boolean {
return this.als.getStore() !== undefined;
}
get<T = unknown>(key: string | symbol): T | undefined {
return this.als.getStore()?.[key] as T | undefined;
}
set<T = unknown>(key: string | symbol, value: T): void {
if (this.isProtectedKey(key)) {
throw new Error(
`Cannot modify protected Lambda context field: ${String(key)}`,
);
}
const store = this.als.getStore();
if (!store) {
throw new Error("No context available");
}
store[key] = value;
}
run<T>(context: Context, fn: () => T): T {
return this.als.run(context, fn);
}
}
/**
* Provides access to AWS Lambda execution context storage.
* Supports both single-context and multi-context environments through different implementations.
*
* The store manages protected Lambda context fields and allows storing/retrieving custom values
* within the execution context.
* @public
*/
export namespace InvokeStore {
let instance: Promise<InvokeStoreBase> | null = null;
export async function getInstanceAsync(): Promise<InvokeStoreBase> {
if (!instance) {
// Lock synchronously on first invoke by immediately assigning the promise
instance = (async () => {
const isMulti = "AWS_LAMBDA_MAX_CONCURRENCY" in process.env;
const newInstance = isMulti
? await InvokeStoreMulti.create()
: new InvokeStoreSingle();
if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {
return globalThis.awslambda.InvokeStore;
} else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {
globalThis.awslambda.InvokeStore = newInstance;
return newInstance;
} else {
return newInstance;
}
})();
}
return instance;
}
export const _testing =
process.env.AWS_LAMBDA_BENCHMARK_MODE === "1"
? {
reset: () => {
instance = null;
if (globalThis.awslambda?.InvokeStore) {
delete globalThis.awslambda.InvokeStore;
}
globalThis.awslambda = {InvokeStore: undefined};
},
}
: undefined;
}