-
-
Notifications
You must be signed in to change notification settings - Fork 584
Added whatwg-node-server adapter for grafserv #2288
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
Changes from 2 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
296821f
Added whatwg-node-server adapter for grafserv
kzlar c2d085f
Updates based on review comments
kzlar 21f7464
Merge branch 'main' into feat/whatwh-node-server
benjie e0e28fb
Add server
benjie 6b5a368
Lint
benjie e089917
Prettier
benjie 8b7c314
Fix lint errors (refactor)
benjie 45695e7
Implement addTo, reduce diff
benjie bc0eb63
Tidy more
benjie d3391da
Handle different return types in Hono
benjie af5da7a
Address feedback
benjie ece71e1
Ability to run whatwg server
benjie ac569be
Version it
benjie ec93dad
Add export
benjie a6ecc5b
Add instructions
benjie eb771be
docs(changeset): Add `@whatwg-node/server` HTTP adaptor, thanks to @k…
benjie File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
154 changes: 154 additions & 0 deletions
154
grafast/grafserv/src/servers/whatwg-node-server/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
import { createServerAdapter } from '@whatwg-node/server' | ||
|
||
import { GrafservBase } from "../../core/base.js"; | ||
import type { | ||
GrafservBody, | ||
GrafservConfig, | ||
RequestDigest, | ||
Result, | ||
} from "../../interfaces.js"; | ||
|
||
import { OptionsFromConfig } from '../../options.js'; | ||
import { httpError } from '../../utils.js'; | ||
|
||
export function getBodyFromRequest( | ||
req: Request /* IncomingMessage */, | ||
maxLength: number, | ||
): Promise<GrafservBody> { | ||
return new Promise(async (resolve, reject) => { | ||
const chunks: Buffer[] = []; | ||
let len = 0; | ||
const handleDataCb = (chunk: Uint8Array<ArrayBufferLike>) => { | ||
chunks.push(Buffer.from(chunk)); | ||
len += chunk.length; | ||
if (len > maxLength) { | ||
reject(httpError(413, "Too much data")); | ||
} | ||
}; | ||
const doneCb = () => { | ||
resolve({ type: "buffer", buffer: Buffer.concat(chunks) }); | ||
}; | ||
const reader = req.body?.getReader() | ||
if (!reader) { | ||
return doneCb() | ||
} | ||
while (true) { | ||
const {done, value} = await reader?.read() | ||
if (value) { | ||
handleDataCb(value) | ||
} | ||
if (done) { | ||
return doneCb() | ||
} | ||
} | ||
}); | ||
} | ||
|
||
declare global { | ||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
namespace Grafast { | ||
interface RequestContext { | ||
whatwg: { | ||
version:string | ||
benjie marked this conversation as resolved.
Show resolved
Hide resolved
|
||
request: Request | ||
} | ||
} | ||
} | ||
} | ||
|
||
/** @experimental */ | ||
export class WhatwgGrafserv extends GrafservBase { | ||
protected whatwgRequestToGrafserv( | ||
dynamicOptions: OptionsFromConfig, | ||
request: Request | ||
): RequestDigest { | ||
const url = new URL(request.url); | ||
return { | ||
httpVersionMajor: 1, | ||
httpVersionMinor: 1, | ||
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() { | ||
return getBodyFromRequest(request, dynamicOptions.maxRequestLength) | ||
}, | ||
requestContext: { | ||
whatwg: { | ||
version:'whatwgv1', | ||
benjie marked this conversation as resolved.
Show resolved
Hide resolved
|
||
request | ||
} | ||
}, | ||
preferJSON: true, | ||
}; | ||
} | ||
|
||
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, {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> => { | ||
const dynamicOptions = this.dynamicOptions; | ||
return this.grafservResponseToWhatwg( | ||
await this.processWhatwgRequest( | ||
request, | ||
this.whatwgRequestToGrafserv(dynamicOptions, request), | ||
), | ||
); | ||
}) | ||
} | ||
|
||
protected processWhatwgRequest( | ||
_request: Request, | ||
request: RequestDigest, | ||
) { | ||
return this.processRequest(request); | ||
} | ||
} | ||
|
||
/** @experimental */ | ||
export function grafserv(config: GrafservConfig) { | ||
return new WhatwgGrafserv(config); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.