Skip to content

feat(server + client): streaming mutations and queries over HTTP - #5700

Merged
KATT merged 91 commits into
nextfrom
05-01-stream
May 19, 2024
Merged

KATT merged 91 commits into
nextfrom
05-01-stream

Conversation

@KATT

@KATT KATT commented May 3, 2024 •

Copy link
Copy Markdown
Member

🎯 Changes

  • Replace httpBatchStreamLink with an implementation that also handles async generators and deferred promise
  • Colocate the serializer and deserialize so it's not spread across @trpc/client and @trpc/server
  • it's basically a simplified variant of tupleson that should be easier to fit in with fewer edge-cases

Other stuff / notes

@github-actions

github-actions Bot commented May 3, 2024 •

Copy link
Copy Markdown
Contributor

Diagnostics Comparison

Details

Numbers

Metric PR next
Files 798 798 (➖ 0)
Lines of Library 40,640 40,640 (➖ 0)
Lines of Definitions 120,184 120,086 (🔺 98)
Lines of TypeScript 4,967 4,967 (➖ 0)
Lines of JavaScript 0 0 (➖ 0)
Lines of JSON 0 0 (➖ 0)
Lines of Other 0 0 (➖ 0)
Identifiers 175,981 175,837 (🔺 144)
Symbols 109,421 109,350 (🔺 71)
Types 89 89 (➖ 0)
Instantiations 0 0 (➖ 0)
Memory used 174,212 177,313 (🔽🟢 -3,101)
Assignability cache size 0 0 (➖ 0)
Identity cache size 0 0 (➖ 0)
Subtype cache size 0 0 (➖ 0)
Strict subtype cache size 0 0 (➖ 0)

Timings and averages

Metric PR next
max (s) 4.353 4.314 (🔺 0.04)
min (s) 4.353 4.314 (🔺 0.04)
avg (s) 4.353 4.314 (🔺 0.04)
median (s) 4.353 4.314 (🔺 0.04)
length 1 1 (➖ 0)
unstable timings

Unstable

Timings are not reliable in here

Metric PR next
I/O Read time 0.05 0.04 (🔺 0.01)
Parse time 0.7 0.72 (🔽🟢 -0.02)
ResolveTypeReference time 0.03 0.03 (➖ 0)
ResolveModule time 0.11 0.1 (🔺 0.01)
ResolveLibrary time 0.01 0.02 (🔽🟢 -0.01)
Program time 1.02 1.04 (🔽🟢 -0.02)
Bind time 0.42 0.41 (🔺 0.01)
Total time 1.43 1.45 (🔽🟢 -0.02)

@vercel

vercel Bot commented May 3, 2024 •

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 May 19, 2024 4:08pm
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 19, 2024 4:08pm
trpc-sse ❌ Failed (Inspect) May 19, 2024 4:08pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 19, 2024 4:08pm

Comment on lines +135 to +137
if (pending.size === 0) {
controller.close();
}

Copy link
Copy Markdown
Member 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 if there's a race condition in which this could be called prematurely

@iamnafets

Copy link
Copy Markdown
Contributor

Super, super cool!

Some high-level thoughts from running this in prod:

  1. I needed to add some sort of heartbeat which was sent every few seconds and just ignored by the client. This will obviously vary based on the infra you're hosting with, but many load balancers will close the socket if nothing is being sent for a few seconds whereas it wouldn't if you just passed a few bytes.
  2. The socket being closed from the client/server was annoying. I needed to race with the socket closed event inside the iterators. There were a ton of edge cases around this which ended up being a pain to debug. Not sure if you've seen them all.

@iamnafets

Copy link
Copy Markdown
Contributor

Another thing I found useful was retaining the query and mutation methods in the client, but having them instead just use the last value. This meant I could re-use the same methods for streaming and non-streaming applications. I instead had mutateGenerator and queryGenerator for when I explicitly needed to use those.

I don't feel strongly about this, but just a thought.

@KATT

KATT commented May 17, 2024

Copy link
Copy Markdown
Member Author

Hey thanks @iamnafets

Some high-level thoughts from running this in prod:

  1. I needed to add some sort of heartbeat which was sent every few seconds and just ignored by the client. This will obviously vary based on the infra you're hosting with, but many load balancers will close the socket if nothing is being sent for a few seconds whereas it wouldn't if you just passed a few bytes.

The idea is not to use queries and mutations for "infinite" iterators - we expect them to stream continuously and then end. What you're describing is a subscription (I think) which is implemented in #5713

  1. The socket being closed from the client/server was annoying. I needed to race with the socket closed event inside the iterators. There were a ton of edge cases around this which ended up being a pain to debug. Not sure if you've seen them all.

I know. I've seen some, maybe not all 😬

Another thing I found useful was retaining the query and mutation methods in the client, but having them instead just use the last value. This meant I could re-use the same methods for streaming and non-streaming applications. I instead had mutateGenerator and queryGenerator for when I explicitly needed to use those.

I don't feel strongly about this, but just a thought.

Again, this feels like a subscription and not a query/mutaiton

@iamnafets

Copy link
Copy Markdown
Contributor

Hey thanks @iamnafets

Some high-level thoughts from running this in prod:

  1. I needed to add some sort of heartbeat which was sent every few seconds and just ignored by the client. This will obviously vary based on the infra you're hosting with, but many load balancers will close the socket if nothing is being sent for a few seconds whereas it wouldn't if you just passed a few bytes.

The idea is not to use queries and mutations for "infinite" iterators - we expect them to stream continuously and then end. What you're describing is a subscription (I think) which is implemented in #5713

Yeah, I’m still talking about finite queries here. We saw hangups happening as soon as 15s which was quite annoying to debug. You can of course just handle this as a user but it’s not exactly a user concern.

@Sheraff Sheraff left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Wow that's tough to review. Just a few notes

  • I haven't looked at the follow up PR yet at the time of writing this review (#5713)
  • maybe minor but this was initially messing with my head: to me "hydrate" and "dehydrate" would be the opposite of how they're used here. In my mind you dehydrate to send over the network, and hydrate on the client to "revive" the objects
  • as always with these streaming things, I feel like we should test more things but I don't know how to / what exactly. For example
    • does this work correctly in ≠ environments? (for example the nodeJsStreamToReaderEsque was missing an error event listener, so maybe we're missing tests for a "node client")
    • does this implementation leak memory? I know with node + promises + streams there are edge-cases where we can have dangling objects without references that still occupy memory, but I'm not really sure how to test for this
  • most of this review is nitpicks, the implementation seems solid, and the few tests I tried to write "just to see" all seemed to pass correctly

result.map(async (valueOrPromise, index) => {
const item = batch.items[index]!;
try {
const value = await Promise.resolve(valueOrPromise);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: I don't think we need a Promise.resolve() here to use await. It's allowed to await regular values.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Linter complained b/c i was lazy with the types

Comment on lines +118 to +121
const result = await Promise.resolve(json.result);
json = {
result: {
data: await Promise.resolve(result.data),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same comment, though it's still a nitpick. I just don't know whether this matters or not (as in "does this add a microtask loop or not")

Suggested change
const result = await Promise.resolve(json.result);
json = {
result: {
data: await Promise.resolve(result.data),
const result = await json.result;
json = {
result: {
data: await result.data,

Comment on lines +356 to +366
/**
* Not very pretty, but we need to wrap nested data in promises
* Our stream producer will only resolve top-level async values or async values that are directly nested in another async value
*/
return {
...response,
result: Promise.resolve({
...response.result,
data: Promise.resolve(response.result.data),
}),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Here I'm less sure. Why do we need to wrap in Promise.resolve()?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Because the "serializer" only looks one level deep of async values

It's smelly

Comment on lines +219 to +222
if (isAsyncIterable(value)) {
if (opts.maxDepth && path.length >= opts.maxDepth) {
throw new Error('Max depth reached');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isn't this check already included in the hydrateAsyncIterable call?

Suggested change
if (isAsyncIterable(value)) {
if (opts.maxDepth && path.length >= opts.maxDepth) {
throw new Error('Max depth reached');
}
if (isAsyncIterable(value)) {

And if not, is there a reason not to use the checkMaxDepth function here?

Suggested change
if (isAsyncIterable(value)) {
if (opts.maxDepth && path.length >= opts.maxDepth) {
throw new Error('Max depth reached');
}
if (isAsyncIterable(value)) {
const error = checkMaxDepth(path)
if (error) {
throw error
}

const reader =
'getReader' in from
? from.getReader()
: nodeJsStreamToReaderEsque(from).getReader();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: if we're always immediately calling .getReader() we could return the reader instead of an object with a method to be called.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

This branch had an error being deployed

1 failed (outdated) and 5 active deployments
Preview – www — 5535248c Deployed May 19, 2024 by vercel[bot]
Preview – todomvc — 5535248c Deployed May 19, 2024 by vercel[bot]
Preview – trpc-next-app-dir — 5535248c Deployed May 19, 2024 by vercel[bot]
Preview – next-prisma-starter — 5535248c Deployed May 19, 2024 by vercel[bot]
Preview – og-image — 5535248c Deployed May 19, 2024 by vercel[bot]
Preview – trpc-sse — 3a1cab66 Deployed May 13, 2024 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Streaming Mutations / Queries

3 participants