Skip to content

Commit d37dd5e

Browse files
authored
Swap AsyncResource with ALS.snapshot (#3433)
1 parent 0ccfb17 commit d37dd5e

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/core/graphql/driver.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
type YogaServerInstance,
1414
type YogaServerOptions,
1515
} from 'graphql-yoga';
16-
import { AsyncResource } from 'node:async_hooks';
16+
import { AsyncLocalStorage } from 'node:async_hooks';
1717
import type { WebSocket } from 'ws';
1818
import { type GqlContextType } from '~/common';
1919
import { HttpAdapter, type IRequest } from '../http';
@@ -105,7 +105,10 @@ export class Driver extends AbstractDriver<DriverConfig> {
105105
* So this allows our "yoga" plugins to be executed.
106106
*/
107107
private makeWsHandler(options: DriverConfig) {
108-
const asyncContextBySocket = new WeakMap<WebSocket, AsyncResource>();
108+
const asyncContextBySocket = new WeakMap<
109+
WebSocket,
110+
<R>(fn: () => R) => R
111+
>();
109112
interface WsExecutionArgs extends ExecutionArgs {
110113
socket: WebSocket;
111114
envelop: ReturnType<ReturnType<typeof envelop>>;
@@ -125,7 +128,7 @@ export class Driver extends AbstractDriver<DriverConfig> {
125128
// unique envelop (yoga) instance per request.
126129
execute: (wsArgs) => {
127130
const { envelop, socket, ...args } = wsArgs as WsExecutionArgs;
128-
return asyncContextBySocket.get(socket)!.runInAsyncScope(() => {
131+
return asyncContextBySocket.get(socket)!(() => {
129132
return envelop.execute(args);
130133
});
131134
},
@@ -134,7 +137,7 @@ export class Driver extends AbstractDriver<DriverConfig> {
134137
// Because this is called via socket.onmessage, we don't have
135138
// the same async context we started with.
136139
// Grab and resume it.
137-
return asyncContextBySocket.get(socket)!.runInAsyncScope(() => {
140+
return asyncContextBySocket.get(socket)!(() => {
138141
return envelop.subscribe(args);
139142
});
140143
},
@@ -174,7 +177,7 @@ export class Driver extends AbstractDriver<DriverConfig> {
174177

175178
const wsHandler: FastifyRoute['wsHandler'] = function (socket, req) {
176179
// Save a reference to the current async context, so we can resume it.
177-
asyncContextBySocket.set(socket, new AsyncResource('graphql-ws'));
180+
asyncContextBySocket.set(socket, AsyncLocalStorage.snapshot());
178181
return fastifyWsHandler.call(this, socket, req);
179182
};
180183
return wsHandler;

0 commit comments

Comments
 (0)