Skip to content
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

Added whatwg-node-server adapter for grafserv #2288

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 2 additions & 3 deletions grafast/grafserv/__tests__/exampleServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { AddressInfo } from "node:net";
import { constant, error, makeGrafastSchema } from "grafast";
import { resolvePreset } from "graphile-config";

import { grafserv } from "../src/servers/node/index.js";
import { grafserv } from "../src/servers/whtatwg-node-server";

export async function makeExampleServer(
preset: GraphileConfig.Preset = {
Expand Down Expand Up @@ -36,8 +36,7 @@ export async function makeExampleServer(
});

const serv = grafserv({ schema, preset });
const server = createServer();
serv.addTo(server);
const server = createServer(serv.createHandler());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't make this change, it does not handle websockets and other concerns. It means that serv is not passed an instance of server and thus cannot add any event listeners.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this would work, wouldn't that make the WHATWG adapter reliant on node types?
I also see that the lambda adapter does not have an addTo implementation.

For now I changed the makeExampleServer function to receive a type parameter to revert the node behavior to addTo while keeping the different behavior for whatwg. Let me know if that works.

Copy link
Member

@benjie benjie Jan 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also see that the lambda adapter does not have an addTo implementation.

I think Lambda does not support addTo since there is no server to add it to - the handler is used directly by lambda. That's not the case for this though?

wouldn't that make the WHATWG adapter reliant on node types?

Are there alternatives to createServer() you'd use here? Perhaps you can expand the examples to show why this would be a concern?

const promise = new Promise<void>((resolve, reject) => {
server.on("listening", () => {
server.off("error", reject);
Expand Down
1 change: 1 addition & 0 deletions grafast/grafserv/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@whatwg-node/fetch": "^0.9.10",
"@whatwg-node/server": "^0.9.64",
"express": "^4.20.0",
"fastify": "^4.22.1",
"grafast": "workspace:^",
Expand Down
115 changes: 115 additions & 0 deletions grafast/grafserv/src/servers/whtatwg-node-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { createServerAdapter } from '@whatwg-node/server'

import { GrafservBase } from "../../core/base.js";
import type {
GrafservConfig,
RequestDigest,
Result,
} from "../../interfaces.js";

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Grafast {
interface RequestContext {
whatwg: {
request: Request
}
}
}
}

/** @experimental */
export class WhatwgGrafserv extends GrafservBase {
protected whatwgRequestToGrafserv(
request: Request
): RequestDigest {
const url = new URL(request.url);
return {
httpVersionMajor: 1,
httpVersionMinor: 0,
isSecure: url.protocol === 'https://',
method: request.method,
path: url.pathname,
headers: this.processHeaders(request.headers),
getQueryParams() {
return Object.fromEntries(url.searchParams.entries()) as Record<string, string>;
},
async getBody() {
const text = await request.text()
return {
type: "text",
text,
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we certain the body will always be text?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tried changing this based on the other adapters, let me know if this looks better.

},
requestContext: {
whatwg: {request}
},
preferJSON: true,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disappointing, this opts out of some performance enhancements.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm honestly not sure about this. How can I tell if this can be set to false?

};
}

protected processHeaders(headers: Headers): Record<string, string> {
const headerDigest: Record<string, string> = Object.create(null);
headers.forEach((v,k)=> {
headerDigest[k]= v
})
return headerDigest
}

protected grafservResponseToWhatwg(response: Result | null): Response {
if (response === null) {
return new Response("¯\\_(ツ)_/¯", {status: 404, headers: new Headers({"Content-Type": "text/plain"})})
}

switch (response.type) {
case "error": {
const { statusCode, headers, error } = response;
const respHeaders = new Headers(headers)
respHeaders.append("Content-Type", "text/plain")
return new Response(error.message, {status: statusCode, headers:respHeaders})
}

case "buffer": {
const { statusCode, headers, buffer } = response;
const respHeaders = new Headers(headers)
return new Response(buffer.toString('utf8'), {status: statusCode, headers:respHeaders})
}

case "json": {
const { statusCode, headers, json } = response;
const respHeaders = new Headers(headers)
return new Response(JSON.stringify(json), {status: statusCode, headers:respHeaders})
}

default: {
console.log("Unhandled:");
console.dir(response);
return new Response("Server hasn't implemented this yet", {status: 501, headers: new Headers({"Content-Type": "text/plain"})})
}
}
}

createHandler() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
return createServerAdapter(async (request: Request): Promise<Response> => {
return this.grafservResponseToWhatwg(
await this.processWhatwgRequest(
request,
this.whatwgRequestToGrafserv(request),
),
);
})
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also implement an addTo method to follow convention; e.g.:

async addTo(
server: HTTPServer | HTTPSServer,
addExclusiveWebsocketHandler = true,
) {
const handler = this._createHandler();
server.on("request", handler);
this.onRelease(() => {
server.off("request", handler);
});

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See this comment #2288 (comment)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a common interface that all the servers support that would allow for this? I'd rather consistency if possible, but if we have to do it a different way for this one adaptor that's fine. Another option would be to have addTo only support Node-like servers, and other servers would need to use a lower level API.


protected processWhatwgRequest(
_request: Request,
request: RequestDigest,
) {
return this.processRequest(request);
}
}

/** @experimental */
export function grafserv(config: GrafservConfig) {
return new WhatwgGrafserv(config);
}
Loading