Skip to content

Commit

Permalink
fix: Memoize AsyncLocalStorage instance (#8831)
Browse files Browse the repository at this point in the history
  • Loading branch information
lforst committed Aug 17, 2023
1 parent a6e2642 commit e5a3885
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
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

0 comments on commit e5a3885

Please sign in to comment.