Skip to content

feat(server + client): adding a streaming option for batched requests - #4347

Merged
KATT merged 164 commits into
mainfrom
feat/out-of-order-batch-response
Jun 2, 2023
Merged

KATT merged 164 commits into
mainfrom
feat/out-of-order-batch-response

Conversation

@Sheraff

@Sheraff Sheraff commented May 11, 2023 •

Copy link
Copy Markdown
Contributor

Closes #4343
Closes T-35

Continuation of #4346
Related to #4365 (to measure bundle size changes)
Alternative DX proposal #4403
Removing async generators / iterators client-side #4424
Removing async generators / iterators server-side #4433

📰 Update

Everything detailed below is still valid, but instead of adding unstable_mode: 'stream' as an option on httpBatchLink, the streaming feature was made into its own link unstable_httpBatchStreamLink that's functionally identical to httpBatchLink except for the streaming part.

🎯 Changes

Add unstable_mode?: 'standard' | 'stream' option to httpBatchLink. When 'stream' is selected, the server should stream the response, making it so that a slow request in a batch does not prevent the faster ones from being returned quickly.

  • the client will send a trpc-batch-mode: stream header
  • when receiving this header, if the batch contains 2 or more procedures, the server will setup a streamed response
    • nodeHTTPRequestHandler uses the "express-like" api and streams by simply writing several times to the response
    • fastifyRequestHandler uses a nodeJs Stream.Readable stream and pushes several times into it
    • fetchRequestHandler uses the web APIs TextEncoder and ReadableStream to enqueue several times
    • aws-lamba/index does not support streaming (could be implemented in the future), requesting a stream will have no impact and a regular JSON response will still be sent.
  • since the streamed response is generated after the headers are sent, the responseMeta callback does not receive the data key (only in the case of a streamed response). This key has thus been made optional everywhere (because I didn't manage to type it correctly)
  • 2 headers are added to the streamed response:
    • Transfer-Encoding: chunked
    • Vary: trpc-batch-mode (this is concatenated with other potential vary headers added by other means)
  • The resulting response body is a string that is still a valid JSON, though because we respond out of order, we've replaced the "array of results" by an "object of results, whose keys are indexes":
    {"2": { "foo": "bar" }
    ,"0": { "hello": "world" }
    ,"1": { "q": "a" }
    }
  • the client knows that it "requested a stream" and so will try to parse the response it receives as such:
    • if the first line of the response string (delimited by \n) is not a single character {, the client reverts to parsing the entire body as a regular JSON (reverts to default httpBatchLink behavior)
    • if the first line matches the expected format, subsequent lines are parsed individually, transformed, and promises are resolved immediately without waiting for the stream to close

❗️ Caveats

  • streaming was not implemented for the aws / lambda adapter. Though it seems possible, I don't know enough about AWS to feel confident implementing it.
  • for a cloudflare worker server (fetchRequestHandler) we rely on Web APIs that are not necessarily available in the JS runtime of the worker. Namely ReadableStream should be explicitly enabled through the streams_enable_constructors flag in the .toml config
  • the client supports several possible Response objects: that of Web APIs (all browsers), that of undici, and that of node-fetch. This should cover most uses of tRPC. Lack of support would have no effect as long as unstable_mode isn't set to 'stream'.
  • both client and server use AsyncGenerator and AsyncIterator. These seem to be widely supported, but I don't have much more information than that. Also, generators used to not be very performant, but as-far-as-I-can-tell™ it seems okay nowadays.

✅ Checklist

  • I have followed the steps listed in the Contributing guide.
  • If necessary, I have added documentation related to the changes made.
  • I have added or updated the tests related to the changes made.

🚧 TODO

@vercel

vercel Bot commented May 11, 2023 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-prisma-starter ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2023 1:18pm
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2023 1:18pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2023 1:18pm

Comment on lines +49 to +65
/**
* Called as soon as the response head is known,
* with headers that were generated **without** knowing the response body.
*
* Without this callback, streaming is disabled.
*/
onHead: (headResponse: Omit<HTTPResponse, 'body'>) => void;
/**
* Called for every procedure with `[index, result]`.
*
* Will be called a single time with `index = -1` if
* - response is an error
* - response is empty (HEAD request)
*
* Without this callback, streaming is disabled.
*/
onChunk: (chunk: ResponseChunk) => void;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hmmmmm, isn't this a breaking change?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Oh no I read this wrong, you did it nicely

Comment on lines +370 to +376
const headResponse = initResponse({
ctx,
paths,
type,
responseMeta: opts.responseMeta,
});
onHead(headResponse);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's fine if this fails through the "normal" error handling

Comment on lines +385 to +388
const [index, untransformedJSON] = await Promise.race(
indexedPromises.values(),
);
for (let i = 0; i < paths.length; i++) {
const [index, untransformedJSON] = await Promise.race(
indexedPromises.values(),
);
indexedPromises.delete(index);
indexedPromises.delete(index);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We know this can't fail since all procedure calls are wrapped inside a try/catch themselves

@iamnafets

Copy link
Copy Markdown
Contributor

This is epic @Sheraff and @KATT ! Was literally starting to put this together last night. Nice win for performance but also opens up some new options for streaming through the stack.

@helmturner

helmturner commented Jun 3, 2023 •

Copy link
Copy Markdown

@Sheraff @KATT I have a question the answer to which may break me...

Does the use of streaming here only affect batched requests by returning individual requests through the stream? For example, if I'm using this link and send a singular request that calls a procedure that returns a ReadableStream of Server-Sent Events, will the data property returned by the hook be populated before or after all chunks have been streamed? If before, what would the value be?

Or, put another way - is each chunk a procedure result, or a piece of a procedure result?

I ask because I was attempting to implement the GPT-4 API and, to avoid waiting actual minutes for a response, I'm streaming the chunks over SSE via a NextJS/Vercel Edge Route and concatenating them in component state.

The reason I say it might break me... I literally just implemented a link and an adapter for exactly my use case. When I installed @trpc/server as a peer-dep, I noticed the new version introduced a type error about a missing eagerGeneration key, which is how I found out this shipped the same day 😵‍💫

EDIT: Thinking about it further, I'm not sure it's possible to achieve what I'm going for without returning a subscription from the procedure (which previously would throw if not piped through the WebSockets Link - not sure if it still does). That's how I implemented it, at least - basically, it's a subscription over SSE instead of WS.

@Sheraff

Sheraff commented Jun 3, 2023 •

Copy link
Copy Markdown
Contributor Author

@helmturner

Or, put another way - is each chunk a procedure result, or a piece of a procedure result?

Each chunk is a procedure result, sorry... We were trying not to break the code, didn't think not to break people! You can see the chunks in the network tabs of your devtools: we're doing a form of "line delimited json" so each line is a chunk.

But we've marked this link as "unstable" because, even though it works and the functionality is here to stay, we're still open to making changes to the underlying implementation so we're open to good ideas.

There were talks of implementing streaming within individual procedures, but we couldn't think of a clean way to present the data client-side. Do we want promises inside the returned object? If it's a "stream of events" (like in the case you're describing) do we want a promise inside a promise inside a promise... And then you have to use() them in your react components. It's basically what you said: "If before, what would the value be?" and I couldn't think of a good answer to that question.

I noticed the new version introduced a type error about a missing eagerGeneration key

Could you tell me more about this type error? eagerGeneration is indeed a new key, but we were trying to ship this feature without any breaking change so if you had an error we might have failed on that front and I'd love to rectify that.

@ItsWendell

Copy link
Copy Markdown

@Sheraff this breaks on React Native (without polyfills) since TextDecoder is not available in the hermes engine.

@Sheraff

Sheraff commented Jun 3, 2023

Copy link
Copy Markdown
Contributor Author

@Sheraff this breaks on React Native (without polyfills) since TextDecoder is not available in the hermes engine.

Good to know. I have a few questions then:

  • Does tRPC as a whole still work normally (if you don't import the unstable_httpBatchStreamLink and use another terminating link instead)?
  • Is there another native API that exists in place of TextDecoder?
  • Did you try it with a polyfill then? Did that work ok?

Right now I'm thinking all I can do is mention this in the docs, and maybe provide a hook to replace TextDecoder (the same way there are hooks to replace fetch for example) for those who don't want to add globals to their runtime. But I'm open to ideas.

@ItsWendell

ItsWendell commented Jun 3, 2023 •

Copy link
Copy Markdown

@Sheraff Currently, const textDecoder = new TextDecoder(); is defined in the global scope within parseJsonStream, which seems to be causing the entire app to crash.

The error message I'm getting is as follows:

ReferenceError: Property 'TextDecoder' doesn't exist, js engine: hermes 
    at RootRouteNodeProvider (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:118657:23)
    at ContextNavigator (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:123320:24)
    at RNCSafeAreaProvider
    at SafeAreaProvider (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:112450:24)
    at RNGestureHandlerRootView
    at GestureHandlerRootView
    at GestureHandler
    at ExpoRoot (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:123307:24)
    at App
    at withDevTools(App) (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:105050:27)
    at RCTView
    at View (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:48075:43)
    at RCTView
    at View (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:48075:43)
    at AppContainer (http://192.168.2.25:19000/index.bundle?platform=android&dev=true&hot=false:47952:36)

const textDecoder = new TextDecoder();

Here's the link to the code file where the issue is occurring: parseJSONStream.ts.

This error message appears multiple times. The intention behind placing the encoder in the global scope was probably to optimize performance by avoiding multiple initializations. However, moving it into the function that actually uses it would fix the issue, as it wouldn't be called for people who don't use the batch stream link. I'm uncertain about the exact performance impact of re-initializing it there.

Regarding a native approach for this API, I did a quick Google search and couldn't find a simple built-in solution for text encoding/decoding in React Native/Hermes (other than polyfills).

I haven't tried using a polyfill yet and haven't use the batch functionality yet, I just saw that this pull requests was probably the one to break TRPC for us.

@Sheraff

Sheraff commented Jun 3, 2023

Copy link
Copy Markdown
Contributor Author

seems to be causing the entire app to crash

Damn I'm sorry. It is declared outside of a function, but still in a module that shouldn't be imported (and can even be tree-shaken out) if you don't use it. So I'm surprised the consequences are so radical, but I'll try and fix this asap.

@ItsWendell

Copy link
Copy Markdown

@Sheraff Thanks for your quick replies! I made a pull requests for a potential (temporary) solution here: #4480 that would fix it.

I'm not sure why it's not being tree-shaken, might not happen properly in development, we were importing TRPC in our Provider like this:

import {
  createTRPCProxyClient,
  httpBatchLink,
  httpLink,
  inferRouterProxyClient,
} from "@trpc/client";

@helmturner

Copy link
Copy Markdown

@Sheraff The type error is specific to my custom adapter. I was importing some types from the HTTP utils, while others were customized - so the new required property caused a mismatch between an imported interface and a custom interface.

I have the adapter up at github.com/alecvision/trpc-sse-adapter and the link will follow soon.

It's largely based off of the HTTP link and fetch adapter, but I'm using subscription procedures and applying a bit of a hack to route requests around the websocket link (pattern-matching procedures, which requires the hack to be applied in both the server and client configs).

The only clean API I could think of involves adding a new procedure type with the exact same semantics as a subscription, but that uses a header or HTTP method (I'm using both, and I picked PATCH). Requests that include the correct method or header are then routed through a link/adapter like the one I hacked together.

Unfortunately, while I'm pretty handy with TypeScript, the types involved in procedures would take more time to grock than I can afford ATM. If you can provide any insight on how I might implement a new procedure type, I'd be happy to give it a shot and put in a PR!

@Sheraff

Sheraff commented Jun 4, 2023

Copy link
Copy Markdown
Contributor Author

@helmturner helmturner mentioned this pull request Jun 4, 2023
1 task done

This branch was successfully deployed

4 active deployments
Preview – www — f14b4daa Deployed Jun 2, 2023 by vercel[bot]
Preview – todomvc — f14b4daa Deployed Jun 2, 2023 by vercel[bot]
Preview – next-prisma-starter — f14b4daa Deployed Jun 2, 2023 by vercel[bot]
Preview – og-image — f14b4daa Deployed Jun 2, 2023 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

@trpc/client @trpc/server 🕸 www Stuff to do with the website (`/www` folder)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: out-of-order batch response streaming

6 participants