Skip to content

fix: Memoize AsyncLocalStorage instance #8831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ interface AsyncLocalStorage<T> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as any).AsyncLocalStorage;

let asyncStorage: AsyncLocalStorage<Hub>;

/**
* Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime.
*/
Expand All @@ -23,7 +25,9 @@ export function setAsyncLocalStorageAsyncContextStrategy(): void {
return;
}

const asyncStorage: AsyncLocalStorage<Hub> = new MaybeGlobalAsyncLocalStorage();
if (!asyncStorage) {
asyncStorage = new MaybeGlobalAsyncLocalStorage();
}

function getCurrentHub(): Hub | undefined {
return asyncStorage.getStore();
Expand Down
6 changes: 5 additions & 1 deletion packages/node/src/async/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ type AsyncLocalStorageConstructor = { new <T>(): AsyncLocalStorage<T> };
// AsyncLocalStorage only exists in async_hook after Node v12.17.0 or v13.10.0
type NewerAsyncHooks = typeof async_hooks & { AsyncLocalStorage: AsyncLocalStorageConstructor };

let asyncStorage: AsyncLocalStorage<Hub>;

/**
* Sets the async context strategy to use AsyncLocalStorage which requires Node v12.17.0 or v13.10.0.
*/
export function setHooksAsyncContextStrategy(): void {
const asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage<Hub>();
if (!asyncStorage) {
asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage<Hub>();
}

function getCurrentHub(): Hub | undefined {
return asyncStorage.getStore();
Expand Down