Skip to content

Swap AsyncResource with ALS.snapshot #3433

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
May 19, 2025
Merged
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
13 changes: 8 additions & 5 deletions src/core/graphql/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
type YogaServerInstance,
type YogaServerOptions,
} from 'graphql-yoga';
import { AsyncResource } from 'node:async_hooks';
import { AsyncLocalStorage } from 'node:async_hooks';
import type { WebSocket } from 'ws';
import { type GqlContextType } from '~/common';
import { HttpAdapter, type IRequest } from '../http';
Expand Down Expand Up @@ -105,7 +105,10 @@ export class Driver extends AbstractDriver<DriverConfig> {
* So this allows our "yoga" plugins to be executed.
*/
private makeWsHandler(options: DriverConfig) {
const asyncContextBySocket = new WeakMap<WebSocket, AsyncResource>();
const asyncContextBySocket = new WeakMap<
WebSocket,
<R>(fn: () => R) => R
>();
interface WsExecutionArgs extends ExecutionArgs {
socket: WebSocket;
envelop: ReturnType<ReturnType<typeof envelop>>;
Expand All @@ -125,7 +128,7 @@ export class Driver extends AbstractDriver<DriverConfig> {
// unique envelop (yoga) instance per request.
execute: (wsArgs) => {
const { envelop, socket, ...args } = wsArgs as WsExecutionArgs;
return asyncContextBySocket.get(socket)!.runInAsyncScope(() => {
return asyncContextBySocket.get(socket)!(() => {
return envelop.execute(args);
});
},
Expand All @@ -134,7 +137,7 @@ export class Driver extends AbstractDriver<DriverConfig> {
// Because this is called via socket.onmessage, we don't have
// the same async context we started with.
// Grab and resume it.
return asyncContextBySocket.get(socket)!.runInAsyncScope(() => {
return asyncContextBySocket.get(socket)!(() => {
return envelop.subscribe(args);
});
},
Expand Down Expand Up @@ -174,7 +177,7 @@ export class Driver extends AbstractDriver<DriverConfig> {

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