Repository navigation
feat(server + client): adding a streaming option for batched requests - #4347
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
…pc into feat/out-of-order-batch-response
Co-authored-by: Flo <[email protected]>
Co-authored-by: Flo <[email protected]>
| /** | ||
| * 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; |
There was a problem hiding this comment.
Hmmmmm, isn't this a breaking change?
There was a problem hiding this comment.
Oh no I read this wrong, you did it nicely
…pc into feat/out-of-order-batch-response
| const headResponse = initResponse({ | ||
| ctx, | ||
| paths, | ||
| type, | ||
| responseMeta: opts.responseMeta, | ||
| }); | ||
| onHead(headResponse); |
There was a problem hiding this comment.
It's fine if this fails through the "normal" error handling
| 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); |
There was a problem hiding this comment.
We know this can't fail since all procedure calls are wrapped inside a try/catch themselves
|
@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 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 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. |
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
Could you tell me more about this type error? |
|
@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:
Right now I'm thinking all I can do is mention this in the docs, and maybe provide a hook to replace |
|
@Sheraff Currently, The error message I'm getting is as follows: 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. |
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. |
|
@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: |
|
@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! |
|
Reported issues have been fixed in the latest release https://github.com/trpc/trpc/releases/tag/v10.29.1 |
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 onhttpBatchLink, the streaming feature was made into its own linkunstable_httpBatchStreamLinkthat's functionally identical tohttpBatchLinkexcept for the streaming part.🎯 Changes
Add
unstable_mode?: 'standard' | 'stream'option tohttpBatchLink. 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.trpc-batch-mode: streamheadernodeHTTPRequestHandleruses the "express-like" api and streams by simply writing several times to the responsefastifyRequestHandleruses a nodeJsStream.Readablestream and pushes several times into itfetchRequestHandleruses the web APIsTextEncoderandReadableStreamto enqueue several timesaws-lamba/indexdoes 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.responseMetacallback does not receive thedatakey (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)Transfer-Encoding: chunkedVary: trpc-batch-mode(this is concatenated with other potentialvaryheaders added by other means){"2": { "foo": "bar" } ,"0": { "hello": "world" } ,"1": { "q": "a" } }\n) is not a single character{, the client reverts to parsing the entire body as a regular JSON (reverts to defaulthttpBatchLinkbehavior)❗️ Caveats
fetchRequestHandler) we rely on Web APIs that are not necessarily available in the JS runtime of the worker. NamelyReadableStreamshould be explicitly enabled through thestreams_enable_constructorsflag in the .toml configResponseobjects: that of Web APIs (all browsers), that ofundici, and that ofnode-fetch. This should cover most uses of tRPC. Lack of support would have no effect as long asunstable_modeisn't set to'stream'.AsyncGeneratorandAsyncIterator. 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
🚧 TODO
Transfer-Encoding: chunkedresponse header (stream parsing logic is available here: https://github.com/Sheraff/trpc-stream-poc/blob/master/public/script.js)nodeHTTPRequestHandlerrollup-plugin-analyzerfor monitoring bundle size #4365)correctly typeresponseMetacallback so thatdatakey of object param is only optional in the case of an httpBatchLink with unstable_mode = 'stream'