Skip to content

Abort SSE when ReadableStream is cancelled - #6228

Closed
tarekwiz wants to merge 4 commits into
trpc:nextfrom
tarekwiz:next
Closed

tarekwiz wants to merge 4 commits into
trpc:nextfrom
tarekwiz:next

Conversation

@tarekwiz

Copy link
Copy Markdown

🎯 Changes

Added AbortController to the createReadableStream function, allowing it to abort once the request is cancelled.
This is to fix an issue with SSE where the server would never send an abort signal when the client closes the connection.

#6193

✅ 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.

@tarekwiz
tarekwiz requested a review from a team as a code owner November 13, 2024 09:12
@vercel

vercel Bot commented Nov 13, 2024 •

Copy link
Copy Markdown

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

Name Status Preview Comments Updated (UTC)
www ❌ Failed (Inspect) Nov 13, 2024 11:35pm

@vercel

vercel Bot commented Nov 13, 2024

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the trpc Team on Vercel.

A member of the Team first needs to authorize it.

@pkg-pr-new

pkg-pr-new Bot commented Nov 13, 2024 •

Copy link
Copy Markdown

Open in Stackblitz

pnpm add https://pkg.pr.new/trpc/trpc/@trpc/client@6228
pnpm add https://pkg.pr.new/trpc/trpc/@trpc/server@6228
pnpm add https://pkg.pr.new/trpc/trpc/@trpc/react-query@6228
pnpm add https://pkg.pr.new/trpc/trpc/@trpc/next@6228

commit: ae419d0

@paradoxloop

Copy link
Copy Markdown

@tarekwiz is this meant to solve the problem of a client not being able to reconnect to a stream if it (the client) cancelled the stream (e.g reloading page)? An issue that resulting on this kind error on front end:

Uncaught TypeError: ReadableStreamDefaultController.close: Cannot close a stream that has errored.

We applied your code changes as a patch and it didn't solve this issue.

@tarekwiz

Copy link
Copy Markdown
Author

@tarekwiz is this meant to solve the problem of a client not being able to reconnect to a stream if it (the client) cancelled the stream (e.g reloading page)? An issue that resulting on this kind error on front end:

Uncaught TypeError: ReadableStreamDefaultController.close: Cannot close a stream that has errored.

We applied your code changes as a patch and it didn't solve this issue.

No this is not meant to fix that issue. This is meant to fix an issue on the server where the server would not call abort on the abortcontroller when the connection is dropped

@KATT

KATT commented Nov 13, 2024

Copy link
Copy Markdown
Member

@tarekwiz is this meant to solve the problem of a client not being able to reconnect to a stream if it (the client) cancelled the stream (e.g reloading page)? An issue that resulting on this kind error on front end:

Uncaught TypeError: ReadableStreamDefaultController.close: Cannot close a stream that has errored.

We applied your code changes as a patch and it didn't solve this issue.

@paradoxloop I've not experienced this - could you please try the latest release and see? We made some changes to client's stream as part of #6214. If not, please create a new issue

@paradoxloop

paradoxloop commented Nov 14, 2024 •

Copy link
Copy Markdown

thanks @KATT just tried the latest release "633" and this does not make the issue go away.

Will try to create a MVR early next week however this work is attempt to move away from websockets for a particular tool and there seems to be lots of footguns and the tooling/documentation around SSE is limited (more generally not specifically TRPC) so might have to pause it.

@tarekwiz

Copy link
Copy Markdown
Author

@KATT #6193 Was closed but this PR that fixes it was never merged.

@KATT

KATT commented Nov 14, 2024

Copy link
Copy Markdown
Member

@KATT #6193 Was closed but this PR that fixes it was never merged.

@tarekwiz see #6193 (comment)

I don't think #6228 changes anything - what it aims to fix should have been a symptom of us not triggering the abort signal correctly, but the stream itself should be canceled as long as you listen to the abort signals as defined in the docs.

@tarekwiz

tarekwiz commented Nov 14, 2024 via email •

Copy link
Copy Markdown
Author

@KATT

KATT commented Nov 15, 2024 •

Copy link
Copy Markdown
Member

Nope the abort controller is never called in the latest next release. This fix is needed. You can reproduce it by using Astro’s fetch implementation

Please give us better steps to reproduce it or supply a reproduction repo - we can't merge this as-is without tests or anything as we then can't guarantee we won't break it in the future

@KATT

KATT commented Nov 15, 2024

Copy link
Copy Markdown
Member

In the last PR we made, we deleted the signal on the sseStreamProducer as we abort the stream when we write the response:

So there's no signal needed on the readable stream itself.

We trigger the abort signal like this:

res.once('close', onAbort);
req.socket.once('end', onAbort);

This should be sufficient. If it isn't in your environment, please add logs to all possible close-events akin to the above and let us know which trigger

Docs in Node.js:

Again, we need easier steps to reproduce than "You can reproduce it by using Astro’s fetch implementation" - make a reproduction repro and tell us how to reproduce it in your repo 🙏

@tarekwiz

Copy link
Copy Markdown
Author

There you go https://github.com/tarekwiz/trpc-sse-bug
If you open the page, then close the browser, the loop never finishes and abort controller is never aborted.

@KATT

KATT commented Nov 17, 2024 •

Copy link
Copy Markdown
Member

Abort signal is not triggered, no, but the stream ends as expected:

tarekwiz/trpc-sse-bug#1

Abort signal should likely be triggered as well, but if you use generators everywhere it's not an issue

@tarekwiz

Copy link
Copy Markdown
Author

Ok let's fix the abort controller not being aborted

@KATT KATT mentioned this pull request Nov 22, 2024
3 tasks done
@KATT

KATT commented Nov 23, 2024

Copy link
Copy Markdown
Member

Ok let's fix the abort controller not being aborted

I'm honestly unsure how to do this nicely - the signal is there to handle aborts and it does that reliably now.

We'd have to add a new abort controller inside of resolveResponse that was able to sniff when any new Response()'s body stream eventually ends.

Your PR added this for one of our possibly Responses but we'd need to do it for all of them

We could do some sort of wrapper of response in resolveResponse like

function createResponse(
  body: BodyInit | null,
  init: ResponseInit,
  onEndController: AbortController,
) {
  const response = new Response(body, init);

  // Somehow sniff when `response.body`'s stream has ended - unsure how?

  return response;
}

Unsure how to do it. Ideas?

Also unsure what you need this for?

@tarekwiz

Copy link
Copy Markdown
Author

So basically the current situation is that the function inside the subscription would only reach the "finally" or error state when the server tries to send a message but the connection is closed. We need the abort controller to be able to save up on server resources so that once the request is closed, we can cleanup the resources used by that user. Otherwise we would have to wait for the server to send information to the client. Maybe adding ping would solve that but I haven't tested it.

@tarekwiz

Copy link
Copy Markdown
Author

By the way, when sse.ping is enabled, the finally block is never reached. This took me 2 hours of debugging to find @KATT

@tarekwiz

Copy link
Copy Markdown
Author

Also, how does this look to you

function createResponse(
  body: BodyInit | null,
  init: ResponseInit,
  onEndController: AbortController,
) {
  // check if body is a stream
  if (body instanceof ReadableStream) {
   // override the cancel function of the ReadableStream to cancel the abort controller.
    body.cancel = async () => {
      onEndController.abort();
    };
  }

  return new Response(body, init);
}```

@KATT

KATT commented Nov 28, 2024 •

Copy link
Copy Markdown
Member

Also, how does this look to you

function createResponse(
  body: BodyInit | null,
  init: ResponseInit,
  onEndController: AbortController,
) {
  // check if body is a stream
  if (body instanceof ReadableStream) {
   // override the cancel function of the ReadableStream to cancel the abort controller.
    body.cancel = async () => {
      onEndController.abort();
    };
  }

  return new Response(body, init);
}```

Feels wrong but maybe it could work... but the signal would still wouldn't be triggered if the body just ended "normally"

@tarekwiz

Copy link
Copy Markdown
Author

What is a "normal" way of closing a readable stream?

KATT added a commit that referenced this pull request Nov 29, 2024
@KATT

KATT commented Nov 29, 2024 •

Copy link
Copy Markdown
Member

What is a "normal" way of closing a readable stream?

When the stream is done but wasn't actually cancelled - 43a2b37

KATT added a commit that referenced this pull request Nov 29, 2024
@tarekwiz

Copy link
Copy Markdown
Author

Hmmm not sure tbh..

@KATT

KATT commented Nov 29, 2024

Copy link
Copy Markdown
Member

This could maybe work:

function streamWithEndCallback<T>(
stream: ReadableStream<T>,
onEnd: () => void,
) {
const reader = stream.getReader();
return new ReadableStream({
async pull(controller) {
const result = await reader.read();
if (result.done) {
controller.close();
onEnd();
return;
}
controller.enqueue(result.value);
},
async cancel() {
await reader.cancel();
onEnd();
},
});
}

@tarekwiz

Copy link
Copy Markdown
Author

Yeah that looks solid.

@KATT

KATT commented Nov 29, 2024

Copy link
Copy Markdown
Member

There's more to it most likely, but feel to do a PR using this code, I don't know when I'll have more time for this

@KATT KATT added the ❄️ icebox features / PRs that might be pick up in the future and can be handy to keep track of label Nov 29, 2024
@KATT

KATT commented Nov 29, 2024

Copy link
Copy Markdown
Member

Will close this PR now. The issues around finally not being reached should have been solved in withPing etc

Please open a feature request with your desire to have the abort controller to be invoked in the Fetch adapter. Or go straight to a PR.

I personally don't see the need for this to exist, but I might be missing something.

@KATT KATT closed this Nov 29, 2024
@KATT KATT mentioned this pull request Nov 29, 2024
@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.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Nov 30, 2024

This branch had an error being deployed

1 failed and 1 active deployments
Preview – www — ae419d0a Deployed Nov 13, 2024 by vercel[bot]
Preview – trpc-next-app-dir — ae419d0a Deployed Nov 13, 2024 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

❄️ icebox features / PRs that might be pick up in the future and can be handy to keep track of

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants