Repository navigation
fix: SSE subscriptions don't reconnect after maxDurationMs (#7094) - #7207
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds a per-call abort signal to streaming RPC results and wires it into SSE/ReadableStream handling so subscription streams are wrapped with an abortable mirror and cancelled when the per-call (client disconnect + maxDurationMs) aborts, enabling reconnection/resume. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Resolve as resolveResponse
participant Stream as SSE_ReadableStream
participant CallAbort as Per-call_AbortController
Client->>Resolve: initiate subscription request
Resolve->>CallAbort: create/compose per-call abort (client disconnect + maxDurationMs)
Resolve->>Stream: wrap underlying ReadableStream with abortable mirror
Resolve-->>Client: return abortable stream response
Note right of CallAbort: timeout or client disconnect triggers abort
CallAbort-->>Stream: abort -> cancel reader (stream closed)
Stream-->>Resolve: reader canceled/ended
Resolve-->>Client: connection ends (client may reconnect/resume)
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~20 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
π₯ Pre-merge checks | β 4 | β 1β Failed checks (1 warning)
β Passed checks (4 passed)
βοΈ Tip: You can configure your own custom pre-merge checks in the settings. β¨ Finishing Touchesπ§ͺ Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/tests/server/httpSubscriptionLink.test.ts`:
- Around line 1528-1601: The test currently wraps setup in run(() => { ... })
and returns a resource; replace that with direct resource usage by creating the
router, onConnection, deferred and results as local variables first, then call
await using ctx = testServerAndClientResource(router, { server: {}, client(opts)
{ return { links: [linkSpy, httpSubscriptionLink({ url: opts.httpUrl,
transformer: superjson })] } } }); keep deferred, results and onConnection as
local closures/helpers (e.g. deferred = createDeferred(), results: number[] =
[], onConnection = vi.fn()) and expose them from the test context if needed
(e.g. add deferred: () => deferred, results, onConnection to the returned ctx),
removing the run(...) wrapper and its returned object.
βΉοΈ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (2)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.tspackages/tests/server/httpSubscriptionLink.test.ts
40c8c8f to
221f72a
Compare
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts (1)
549-559: Redundant type assertion after truthy check.After the
if (subscriptionAbortSignal)check, TypeScript narrows the type fromAbortSignal | nulltoAbortSignal. The explicit cast is unnecessary.π§ Suggested simplification
if (subscriptionAbortSignal) { - const signal = subscriptionAbortSignal as AbortSignal; - const onAbort = () => void reader.cancel(); - if (signal.aborted) { + const onAbort = () => void reader.cancel(); + if (subscriptionAbortSignal.aborted) { onAbort(); } else { - signal.addEventListener('abort', onAbort, { + subscriptionAbortSignal.addEventListener('abort', onAbort, { once: true, }); } }π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts` around lines 549 - 559, The variable subscriptionAbortSignal is already narrowed by the if (subscriptionAbortSignal) check, so remove the redundant type assertion (as AbortSignal); change const signal = subscriptionAbortSignal as AbortSignal; to const signal = subscriptionAbortSignal; and keep the rest of the logic (onAbort -> reader.cancel(), signal.aborted check and addEventListener) unchanged in the same block (refer to symbols subscriptionAbortSignal, signal, onAbort, reader.cancel).
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`:
- Around line 549-559: The variable subscriptionAbortSignal is already narrowed
by the if (subscriptionAbortSignal) check, so remove the redundant type
assertion (as AbortSignal); change const signal = subscriptionAbortSignal as
AbortSignal; to const signal = subscriptionAbortSignal; and keep the rest of the
logic (onAbort -> reader.cancel(), signal.aborted check and addEventListener)
unchanged in the same block (refer to symbols subscriptionAbortSignal, signal,
onAbort, reader.cancel).
βΉοΈ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (2)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.tspackages/tests/server/httpSubscriptionLink.test.ts
π§ Files skipped from review as they are similar to previous changes (1)
- packages/tests/server/httpSubscriptionLink.test.ts
@trpc/client
@trpc/next
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
| // but writeResponse uses request.signal for pipeTo() β which | ||
| // only fires on client disconnect. We need maxDurationMs abort | ||
| // to also terminate the SSE response body (fixes #7094). | ||
| const reader = stream.getReader(); |
There was a problem hiding this comment.
Hey thanks for the contribution, still getting my head around it as I'm not really our expert in this bit of the codebase, but a couple questions:
- Is there some reason we can't just call
stream.cancel()instead of setting up another stream? Perhaps even pass the combinedSignal to sseStreamProducer and contain the abort checks inside there? This file is getting quite convoluted so the more we can push out the better - storing subscriptionAbortSignal outside the calls map seems a bit fragile, and while subscription connections aren't typically batches so calls shouldn't be >1 I do wonder if there's a more elegant and future-safe way to write this?
There was a problem hiding this comment.
Thanks for taking a look!
Tried both ideas. stream.cancel() doesn't work because pipeTo() in writeResponse locks the reader β once that happens you can't cancel from outside.
I also went down the path of passing the signal into sseStreamProducer β readableStreamFrom to call iterator.return() on abort. That seemed like it should work, but it turns out async generators serialize .next() and .return() β so when pull() is already stuck at await iterator.next() (generator waiting on user code), .return() just queues behind it and never fires. That's exactly the deadlock we're trying to break. So the wrapper stream approach is unfortunately necessary β reader.cancel() bypasses the generator entirely.
Good call on the hoisted variable though, that was definitely fragile. I replaced it by threading the signal through RPCResultOk instead (added signal?: AbortSignal), so the subscription handler just reads result?.signal. No mutable outer variable, no cast.
While I was at it I also tightened things up:
- Only subscriptions get the signal on
RPCResultOk, queries/mutations getundefined - The wrapper stream is only created when there's actually a signal to listen on (i.e. when
maxDurationMsis configured), otherwise it just passes the stream through directly - Renamed a variable inside
pull()that was shadowing the outerresult - Added
removeEventListenercleanup in the wrapper'scancel()to avoid leaking the listener
There was a problem hiding this comment.
Great, thank you! It looks good. Just pushing a couple small convention adjustments, and addressing 1 ai review comment that looks valid
da3b8cb to
2adcc0e
Compare
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts (1)
544-551: Remove the abort listener when the stream completes normally.The
addEventListener(..., { once: true })pattern only removes the listener if an abort event fires. If the stream ends normally (whenresult.doneis true or the stream is cancelled), the abort listener remains attached. MoveonAbortoutside the signal conditional and explicitly callremoveEventListenerin the stream'spull()callback (when done) andcancel()callback to ensure proper cleanup.β»οΈ Proposed cleanup
const signal = result?.signal; const reader = stream.getReader(); + const onAbort = signal ? () => void reader.cancel() : null; const abortableStream = new ReadableStream({ async pull(controller) { const result = await reader.read(); if (result.done) { + if (signal && onAbort) { + signal.removeEventListener('abort', onAbort); + } controller.close(); } else { controller.enqueue(result.value); } }, cancel() { + if (signal && onAbort) { + signal.removeEventListener('abort', onAbort); + } void reader.cancel(); }, }); - if (signal) { - const onAbort = () => void reader.cancel(); + if (signal && onAbort) { if (signal.aborted) { onAbort(); } else { signal.addEventListener('abort', onAbort, { once: true }); } }π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts` around lines 544 - 551, The abort listener isn't removed when the stream completes normally; move the onAbort handler declaration out of the if (signal) block so it can be referenced for removal, register it only if signal exists, and then explicitly call signal.removeEventListener('abort', onAbort) from the stream's pull() path when result.done is true and from the stream cancel() callback (the same places that finish or cancel the reader) to ensure the listener is cleaned up; reference the onAbort function, the signal object, reader.cancel(), the stream's pull() callback and cancel() callback in your changes.
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`:
- Around line 544-551: The abort listener isn't removed when the stream
completes normally; move the onAbort handler declaration out of the if (signal)
block so it can be referenced for removal, register it only if signal exists,
and then explicitly call signal.removeEventListener('abort', onAbort) from the
stream's pull() path when result.done is true and from the stream cancel()
callback (the same places that finish or cancel the reader) to ensure the
listener is cleaned up; reference the onAbort function, the signal object,
reader.cancel(), the stream's pull() callback and cancel() callback in your
changes.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7407fd02-588c-41be-843d-7b7dffcb7825
π Files selected for processing (2)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.tspackages/tests/server/httpSubscriptionLink.test.ts
π§ Files skipped from review as they are similar to previous changes (1)
- packages/tests/server/httpSubscriptionLink.test.ts
6fe1b61 to
59aa6bb
Compare
Nick-Lucas
left a comment
There was a problem hiding this comment.
Thank you for this, it's a solid fix and you've helped me understand some bits I didn't build too!
6c10390 to
cd82c58
Compare
|
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. |
Fixes #7094
When
maxDurationMsis set, SSE subscriptions should end after the timeout and the client should reconnect automatically. Instead, the connection hangs silently and the client never reconnects.Root cause
The server never actually ends the HTTP response. When
maxDurationMsfires, it abortscombinedAbort.signalinresolveResponse.tsβ butwriteResponse.tspassesrequest.signal(client disconnect) topipeTo(), not the combined signal. So the abort has no effect on the response pipe.Meanwhile the subscription generator is typically blocked on an
await(waiting for the next event), soreadableStreamFrom.pull()hangs oniterator.next()indefinitely. The response stays open, the client never sees an error, EventSource never retries.I confirmed this by writing a standalone script with
EventSourcePolyfill+ a plain HTTP server that callsres.end()after 500ms β the polyfill reconnected fine, 4 times in 5 seconds. The polyfill was never the problem.Fix
I wrap the SSE ReadableStream in
resolveResponse.tswith a reader that listens tocombinedAbort.signal. WhenmaxDurationMsfires, it cancels the reader directly, which unblocks the pipe and lets the response end. After that, EventSource's built-in retry does its thing β new connection,lastEventIdresumption viatracked(), everything works.I also considered modifying
writeResponse.tsto take an extra abort signal and useAbortSignal.any(), which would be a bit cleaner architecturally. Happy to refactor if you'd prefer that approach.Regression test sets
maxDurationMs: 500, sends tracked data, waits for the reconnect, then verifies the client got[1, 2]across two connections. Completes in ~1.5s. All existing tests still pass.Summary by CodeRabbit
Bug Fixes
Tests