effect icon indicating copy to clipboard operation
effect copied to clipboard

From Discord: Issue with SSE Stream and Bun Platform Not Sending Events

Open effect-bot opened this issue 6 months ago • 6 comments

Summary

The user is experiencing an issue with sending Server-Sent Events (SSE) on the Bun platform. They have provided a link to their code and mentioned that when using BunRuntime and BunHttpServer, events are not being sent as expected when they hit the notify endpoint. To test the issue, the user suggests opening the SSE connection in the browser via /api/sse/connect and sending a POST request to /api/sse/notify, expecting the event to appear among the keep-alive messages.

Key takeaways:

  1. The issue is specific to the Bun platform with SSE communication.
  2. The user provided steps to reproduce the issue using certain endpoints.
  3. The problem arises with sending events, not with the initial connection or keep-alive messages.

Discord thread

https://discord.com/channels/795981131316985866/1386450105132908635

effect-bot avatar Jun 23 '25 14:06 effect-bot

Link to code: https://effect.website/play#edabab86d8bd

NotLuksus avatar Jun 23 '25 14:06 NotLuksus

You will need to embed the finalizers into the stream itself, as bun consumes the stream after the response headers are sent.

tim-smart avatar Jun 23 '25 22:06 tim-smart

@tim-smart Could you provide a snippet? I'm not quite sure what you mean

NotLuksus avatar Jun 24 '25 15:06 NotLuksus

So, instead of registering the finalizer within the handler, like this:

yield* Effect.addFinalizer(() =>
  sseManager.unregisterConnection({ connectionId, userId })
)

You'd move it to the stream itself:

const bodyStream = Stream.merge(keepAliveStream, eventsStream).pipe(
  Stream.map((line) => textEncoder.encode(`${line}\n\n`)),
  Stream.ensuring(sseManager.unregisterConnection({ connectionId, userId }))
)

This means you can't tie anything to the handler's scope, unfortunately. So, if you were to Effect.forkScoped there, they'd be interrupted immediately after.

lucas-barake avatar Jun 24 '25 19:06 lucas-barake

You can also use .unwrapScoped https://effect.website/play#5c892bc6d169

tim-smart avatar Jun 24 '25 21:06 tim-smart

Ah, nice. That's much cleaner. Thanks Tim.

lucas-barake avatar Jun 24 '25 21:06 lucas-barake