-
Notifications
You must be signed in to change notification settings - Fork 405
feat: seroval json mode #2042
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
Open
lxsmnsyc
wants to merge
8
commits into
main
Choose a base branch
from
feat-seroval-json
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: seroval json mode #2042
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1676d44
add seroval json mode
lxsmnsyc aa2b7e7
Update server-runtime.ts
lxsmnsyc 9480de8
Create plenty-geese-enter.md
lxsmnsyc a67dfdd
Fix client-server comms
lxsmnsyc 3b184d3
Add tests
lxsmnsyc f279845
Add new header
lxsmnsyc d3548b3
Update server-functions-handler.ts
lxsmnsyc db4c511
Clone requests/responses
lxsmnsyc 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@solidjs/start": minor | ||
| --- | ||
|
|
||
| seroval json mode |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { createEffect, createSignal } from "solid-js"; | ||
|
|
||
| async function ping(value: string) { | ||
| "use server"; | ||
|
|
||
| return await Promise.resolve(value); | ||
| } | ||
|
|
||
| export default function App() { | ||
| const [output, setOutput] = createSignal<{ result?: boolean }>({}); | ||
|
|
||
| createEffect(async () => { | ||
| const value = `${Math.random() * 1000}`; | ||
| const result = await ping(value); | ||
| setOutput(prev => ({ ...prev, result: value === result })); | ||
| }); | ||
|
|
||
| return ( | ||
| <main> | ||
| <span id="server-fn-test">{JSON.stringify(output())}</span> | ||
| </main> | ||
| ); | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,253 @@ | ||
| import { | ||
| crossSerializeStream, | ||
| deserialize, | ||
| Feature, | ||
| fromCrossJSON, | ||
| getCrossReferenceHeader, | ||
| type SerovalNode, | ||
| toCrossJSONStream, | ||
| } from "seroval"; | ||
| import { | ||
| AbortSignalPlugin, | ||
| CustomEventPlugin, | ||
| DOMExceptionPlugin, | ||
| EventPlugin, | ||
| FormDataPlugin, | ||
| HeadersPlugin, | ||
| ReadableStreamPlugin, | ||
| RequestPlugin, | ||
| ResponsePlugin, | ||
| URLPlugin, | ||
| URLSearchParamsPlugin, | ||
| } from "seroval-plugins/web"; | ||
|
|
||
| // TODO(Alexis): if we can, allow providing an option to extend these. | ||
| const DEFAULT_PLUGINS = [ | ||
| AbortSignalPlugin, | ||
| CustomEventPlugin, | ||
| DOMExceptionPlugin, | ||
| EventPlugin, | ||
| FormDataPlugin, | ||
| HeadersPlugin, | ||
| ReadableStreamPlugin, | ||
| RequestPlugin, | ||
| ResponsePlugin, | ||
| URLSearchParamsPlugin, | ||
| URLPlugin, | ||
| ]; | ||
| const MAX_SERIALIZATION_DEPTH_LIMIT = 64; | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seroval has a default limit of 1000, but that's because of my poor judgment. Will probably port this default back. |
||
| const DISABLED_FEATURES = Feature.RegExp; | ||
|
|
||
| /** | ||
| * Alexis: | ||
| * | ||
| * A "chunk" is a piece of data emitted by the streaming serializer. | ||
| * Each chunk is represented by a 32-bit value (encoded in hexadecimal), | ||
| * followed by the encoded string (8-bit representation). This format | ||
| * is important so we know how much of the chunk being streamed we | ||
| * are expecting before parsing the entire string data. | ||
| * | ||
| * This is sort of a bootleg "multipart/form-data" except it's bad at | ||
| * handling File/Blob LOL | ||
| * | ||
| * The format is as follows: | ||
| * ;0xFFFFFFFF;<string data> | ||
| */ | ||
| function createChunk(data: string): Uint8Array { | ||
| const encodeData = new TextEncoder().encode(data); | ||
| const bytes = encodeData.length; | ||
| const baseHex = bytes.toString(16); | ||
| const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex; // 32-bit | ||
| const head = new TextEncoder().encode(`;0x${totalHex};`); | ||
|
|
||
| const chunk = new Uint8Array(12 + bytes); | ||
| chunk.set(head); | ||
| chunk.set(encodeData, 12); | ||
| return chunk; | ||
| } | ||
|
|
||
| export function serializeToJSStream(id: string, value: any) { | ||
| return new ReadableStream({ | ||
| start(controller) { | ||
| crossSerializeStream(value, { | ||
| scopeId: id, | ||
| plugins: DEFAULT_PLUGINS, | ||
| onSerialize(data: string, initial: boolean) { | ||
| controller.enqueue( | ||
| createChunk( | ||
| initial ? `(${getCrossReferenceHeader(id)},${data})` : data, | ||
| ), | ||
| ); | ||
| }, | ||
| onDone() { | ||
| controller.close(); | ||
| }, | ||
| onError(error: any) { | ||
| controller.error(error); | ||
| }, | ||
| }); | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| export function serializeToJSONStream(value: any) { | ||
| return new ReadableStream({ | ||
| start(controller) { | ||
| toCrossJSONStream(value, { | ||
| disabledFeatures: DISABLED_FEATURES, | ||
| depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT, | ||
| plugins: DEFAULT_PLUGINS, | ||
| onParse(node) { | ||
| controller.enqueue(createChunk(JSON.stringify(node))); | ||
| }, | ||
| onDone() { | ||
| controller.close(); | ||
| }, | ||
| onError(error) { | ||
| controller.error(error); | ||
| }, | ||
| }); | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| class SerovalChunkReader { | ||
| reader: ReadableStreamDefaultReader<Uint8Array>; | ||
| buffer: Uint8Array; | ||
| done: boolean; | ||
| constructor(stream: ReadableStream<Uint8Array>) { | ||
| this.reader = stream.getReader(); | ||
| this.buffer = new Uint8Array(0); | ||
| this.done = false; | ||
| } | ||
|
|
||
| async readChunk() { | ||
| // if there's no chunk, read again | ||
| const chunk = await this.reader.read(); | ||
| if (!chunk.done) { | ||
| // repopulate the buffer | ||
| const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length); | ||
| newBuffer.set(this.buffer); | ||
| newBuffer.set(chunk.value, this.buffer.length); | ||
| this.buffer = newBuffer; | ||
| } else { | ||
| this.done = true; | ||
| } | ||
| } | ||
|
|
||
| async next(): Promise< | ||
| { done: true; value: undefined } | { done: false; value: string } | ||
| > { | ||
| // Check if the buffer is empty | ||
| if (this.buffer.length === 0) { | ||
| // if we are already done... | ||
| if (this.done) { | ||
| return { | ||
| done: true, | ||
| value: undefined, | ||
| }; | ||
| } | ||
| // Otherwise, read a new chunk | ||
| await this.readChunk(); | ||
| return await this.next(); | ||
| } | ||
| // Read the "byte header" | ||
| // The byte header tells us how big the expected data is | ||
| // so we know how much data we should wait before we | ||
| // deserialize the data | ||
| const head = new TextDecoder().decode(this.buffer.subarray(1, 11)); | ||
| const bytes = Number.parseInt(head, 16); // ;0x00000000; | ||
| // Check if the buffer has enough bytes to be parsed | ||
| while (bytes > this.buffer.length - 12) { | ||
| // If it's not enough, and the reader is done | ||
| // then the chunk is invalid. | ||
| if (this.done) { | ||
| throw new Error("Malformed server function stream."); | ||
| } | ||
| // Otherwise, we read more chunks | ||
| await this.readChunk(); | ||
| } | ||
| // Extract the exact chunk as defined by the byte header | ||
| const partial = new TextDecoder().decode( | ||
| this.buffer.subarray(12, 12 + bytes), | ||
| ); | ||
| // The rest goes to the buffer | ||
| this.buffer = this.buffer.subarray(12 + bytes); | ||
|
|
||
| // Deserialize the chunk | ||
| return { | ||
| done: false, | ||
| value: partial, | ||
| }; | ||
| } | ||
|
|
||
| async drain(interpret: (chunk: string) => void) { | ||
| while (true) { | ||
| const result = await this.next(); | ||
| if (result.done) { | ||
| break; | ||
| } else { | ||
| interpret(result.value); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export async function serializeToJSONString(value: any) { | ||
| const response = new Response(serializeToJSONStream(value)); | ||
| return await response.text(); | ||
| } | ||
|
|
||
| export async function deserializeFromJSONString(json: string) { | ||
| const blob = new Response(json); | ||
| return await deserializeJSONStream(blob); | ||
| } | ||
|
|
||
| export async function deserializeJSONStream(response: Response | Request) { | ||
| if (!response.body) { | ||
| throw new Error("missing body"); | ||
| } | ||
| const reader = new SerovalChunkReader(response.body); | ||
| const result = await reader.next(); | ||
| if (!result.done) { | ||
| const refs = new Map(); | ||
|
|
||
| function interpretChunk(chunk: string): unknown { | ||
| const value = fromCrossJSON(JSON.parse(chunk) as SerovalNode, { | ||
| refs, | ||
| disabledFeatures: DISABLED_FEATURES, | ||
| depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT, | ||
| plugins: DEFAULT_PLUGINS, | ||
| }); | ||
| return value; | ||
| } | ||
|
|
||
| void reader.drain(interpretChunk); | ||
|
|
||
| return interpretChunk(result.value); | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| export async function deserializeJSStream(id: string, response: Response) { | ||
| if (!response.body) { | ||
| throw new Error("missing body"); | ||
| } | ||
| const reader = new SerovalChunkReader(response.body); | ||
|
|
||
| const result = await reader.next(); | ||
|
|
||
| if (!result.done) { | ||
| reader.drain(deserialize).then( | ||
| () => { | ||
| // @ts-ignore | ||
| delete $R[id]; | ||
| }, | ||
| () => { | ||
| // no-op | ||
| }, | ||
| ); | ||
| return deserialize(result.value); | ||
| } | ||
| return undefined; | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When possible, add a
pluginsoption here that we can load into the serializer. The only problem is how do we bridge it from the config to the runtime (do we need a "runtime" config API?)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The non-magical way I could think of is to add this as an option to
createHandlerinentry-server.tsx🤔There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
either that or an "entry" file for configs I suppose.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldn't we be able to set an environment variable, then use something like
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@atk Not exactly this API in mind. I'm not trying to override seroval, I'm more of trying to think of an idea to allow incorporating 3P seroval plugins