Repository navigation
fix(client): abort JSONL stream on httpBatchStreamLink unsubscribe - #7390
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:
📝 WalkthroughWalkthroughCreates a per-subscription AbortController in httpBatchStreamLink, races its signal with the operation signal when calling loader.load, aborts that controller on observable teardown (and marks subscription done on errors), and adds a test asserting fetch's AbortSignal is aborted after unsubscribe. Tests package deps are bumped. ChangeshttpBatchStreamLink Unsubscribe Abort Handling
Sequence Diagram(s)sequenceDiagram
participant Subscriber
participant httpBatchStreamLink
participant Loader
participant fetch
Subscriber->>httpBatchStreamLink: subscribe()
httpBatchStreamLink->>Loader: loader.load(op, { signal: raceAbortSignals(op.signal, ac.signal) })
Loader->>fetch: globalThis.fetch(..., { signal })
Subscriber->>httpBatchStreamLink: unsubscribe()
httpBatchStreamLink->>httpBatchStreamLink: ac.abort()
Loader->>fetch: fetch signal aborted
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1001-1044: The test currently sets a global fetch mock and calls
vi.restoreAllMocks() only on the success path which can leak the mock; replace
the global mock with a factory-scoped mock (use a helper like getMockFetch())
and ensure teardown always runs by registering restoration in a
finally/afterEach-style cleanup so globalThis.fetch is restored regardless of
test outcome; update the test that constructs the mock used by
httpBatchStreamLink/mockRuntime (references: globalThis.fetch mock,
fetchCalled/fetchSignal, httpBatchStreamLink, createChain, chain.subscribe,
sub.unsubscribe) to obtain the mock from getMockFetch() and restore it in
guaranteed cleanup rather than calling vi.restoreAllMocks() only at the end.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ab85d44f-4f0f-4409-82db-6ebc6db2ee35
📒 Files selected for processing (2)
packages/client/src/links/httpBatchStreamLink.tspackages/tests/server/links.test.ts
24bb263 to
78acc26
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/tests/server/links.test.ts (1)
1001-1043:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMake fetch mock cleanup guaranteed and factory-scoped.
The current cleanup at Line 1043 only runs on the success path; if the test fails earlier,
globalThis.fetchcan remain mocked and bleed into later tests. Use a per-test mock factory and restore infinally.As per coding guidelines, "Create fresh mock instances per test using a factory (e.g., `getMockFetch()`)" and "Do not use global mocks that persist across tests".Suggested patch
test('httpBatchStreamLink - unsubscribe aborts fetch', async () => { let fetchSignal: AbortSignal | undefined; - const fetchCalled = new Promise<void>((resolve) => { - vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => { - fetchSignal = init?.signal ?? undefined; - resolve(); - return new Response( - new ReadableStream({ - start() { - // never enqueue or close - keeps the stream open - }, - }), - { status: 200 }, - ); - }); - }); + let resolveFetchCalled: (() => void) | undefined; + const fetchCalled = new Promise<void>((resolve) => { + resolveFetchCalled = resolve; + }); + const getMockFetch = () => + vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => { + fetchSignal = init?.signal ?? undefined; + resolveFetchCalled?.(); + return new Response( + new ReadableStream({ + start() { + // never enqueue or close - keeps the stream open + }, + }), + { status: 200 }, + ); + }); + const mockFetch = getMockFetch(); - const links = [ - httpBatchStreamLink({ - url: 'http://localhost:9999', - })(mockRuntime), - ]; + try { + const links = [ + httpBatchStreamLink({ + url: 'http://localhost:9999', + })(mockRuntime), + ]; - const chain = createChain({ - links, - op: { - id: 1, - type: 'query', - path: 'hello', - input: null, - context: {}, - signal: null, - }, - }); + const chain = createChain({ + links, + op: { + id: 1, + type: 'query', + path: 'hello', + input: null, + context: {}, + signal: null, + }, + }); - const sub = chain.subscribe({}); + const sub = chain.subscribe({}); - await fetchCalled; + await fetchCalled; - expect(fetchSignal!.aborted).toBe(false); + expect(fetchSignal!.aborted).toBe(false); - sub.unsubscribe(); + sub.unsubscribe(); - expect(fetchSignal!.aborted).toBe(true); - - vi.restoreAllMocks(); + expect(fetchSignal!.aborted).toBe(true); + } finally { + mockFetch.mockRestore(); + } });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/links.test.ts` around lines 1001 - 1043, The test currently spies on globalThis.fetch directly and only restores mocks on the success path; replace the direct spy with a per-test mock factory (e.g., call getMockFetch() to create the mocked fetch and capture fetchSignal) and ensure the mock is restored in a finally block (or use try/finally with vi.restoreAllMocks() or mock.restore()) so globalThis.fetch cannot leak to other tests; update the section that sets fetchSignal (formerly inside vi.spyOn(globalThis, 'fetch').mockImplementation(...)) to use the factory's implementation and call the factory-provided restore in finally after sub.unsubscribe().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1001-1043: The test currently spies on globalThis.fetch directly
and only restores mocks on the success path; replace the direct spy with a
per-test mock factory (e.g., call getMockFetch() to create the mocked fetch and
capture fetchSignal) and ensure the mock is restored in a finally block (or use
try/finally with vi.restoreAllMocks() or mock.restore()) so globalThis.fetch
cannot leak to other tests; update the section that sets fetchSignal (formerly
inside vi.spyOn(globalThis, 'fetch').mockImplementation(...)) to use the
factory's implementation and call the factory-provided restore in finally after
sub.unsubscribe().
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c58355e7-61ea-4170-ada9-e0b37e7c4dd5
📒 Files selected for processing (3)
packages/client/src/links/httpBatchStreamLink.tspackages/tests/package.jsonpackages/tests/server/links.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/tests/package.json
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
The observable's cleanup function was a noop, so unsubscribing from a batch stream link observable left the underlying fetch and JSONL stream consuming data indefinitely. Now each observable creates an AbortController whose signal is raced with the operation's existing signal; unsubscribe calls abort(), propagating through allAbortSignals to cancel the fetch once all subscribers in a batch have disconnected.
78acc26 to
5106b1b
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/tests/server/links.test.ts (1)
1000-1043:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMake fetch mock cleanup failure-safe and factory-scoped.
vi.restoreAllMocks()only runs on the success path here; if the test fails earlier, theglobalThis.fetchmock can leak across tests.As per coding guidelines, "Create fresh mock instances per test using a factory (e.g., `getMockFetch()`)" and "Do not use global mocks that persist across tests".Proposed fix
test('httpBatchStreamLink - unsubscribe aborts fetch', async () => { let fetchSignal: AbortSignal | undefined; - const fetchCalled = new Promise<void>((resolve) => { - vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => { + let resolveFetchCalled: (() => void) | undefined; + const fetchCalled = new Promise<void>((resolve) => { + resolveFetchCalled = resolve; + }); + const getMockFetch = () => + vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => { fetchSignal = init?.signal ?? undefined; - resolve(); + resolveFetchCalled?.(); return new Response( new ReadableStream({ start() { // never enqueue or close - keeps the stream open }, }), { status: 200 }, ); }); - }); + const mockFetch = getMockFetch(); - const links = [ - httpBatchStreamLink({ - url: 'http://localhost:9999', - })(mockRuntime), - ]; + try { + const links = [ + httpBatchStreamLink({ + url: 'http://localhost:9999', + })(mockRuntime), + ]; - const chain = createChain({ - links, - op: { - id: 1, - type: 'query', - path: 'hello', - input: null, - context: {}, - signal: null, - }, - }); + const chain = createChain({ + links, + op: { + id: 1, + type: 'query', + path: 'hello', + input: null, + context: {}, + signal: null, + }, + }); - const sub = chain.subscribe({}); + const sub = chain.subscribe({}); - await fetchCalled; + await fetchCalled; - expect(fetchSignal!.aborted).toBe(false); + expect(fetchSignal!.aborted).toBe(false); - sub.unsubscribe(); + sub.unsubscribe(); - expect(fetchSignal!.aborted).toBe(true); - - vi.restoreAllMocks(); + expect(fetchSignal!.aborted).toBe(true); + } finally { + mockFetch.mockRestore(); + } });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/links.test.ts` around lines 1000 - 1043, Replace the global, test-wide fetch spy with a factory-scoped mock and guarantee cleanup in a finally block: create a getMockFetch() helper that installs a mock implementation on globalThis.fetch (capturing fetchSignal and resolving fetchCalled as in the diff) and returns a restore function; in the test, call const restore = getMockFetch(...) before creating links (instead of vi.spyOn/globalThis.fetch) and then use try { ... the existing assertions and sub.unsubscribe() } finally { restore() } (remove the vi.restoreAllMocks call). This ensures the mock is fresh per test and always restored even if the test fails; reference: getMockFetch, fetchCalled, fetchSignal, httpBatchStreamLink, createChain, sub.unsubscribe.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1000-1043: Replace the global, test-wide fetch spy with a
factory-scoped mock and guarantee cleanup in a finally block: create a
getMockFetch() helper that installs a mock implementation on globalThis.fetch
(capturing fetchSignal and resolving fetchCalled as in the diff) and returns a
restore function; in the test, call const restore = getMockFetch(...) before
creating links (instead of vi.spyOn/globalThis.fetch) and then use try { ... the
existing assertions and sub.unsubscribe() } finally { restore() } (remove the
vi.restoreAllMocks call). This ensures the mock is fresh per test and always
restored even if the test fails; reference: getMockFetch, fetchCalled,
fetchSignal, httpBatchStreamLink, createChain, sub.unsubscribe.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6d57a84b-d674-4c91-b990-583456c17b02
📒 Files selected for processing (3)
packages/client/src/links/httpBatchStreamLink.tspackages/tests/package.jsonpackages/tests/server/links.test.ts
|
The Bun E2E failure is in |
|
@daltino Thanks for the thorough review! 1. Cleanup return block with the return () => {
if (!isDone) {
ac.abort();
}
};This ensures 2. promise
.then((res) => {
isDone = true;
// ... observer.next() + observer.complete()
})
.catch((err) => {
isDone = true;
observer.error(...);
});Since 3. Confirmed. 4. Will add an 5. 6. Acknowledged — 7. |
|
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. |
Closes #7389
What changed
httpBatchStreamLinkcreates anAbortControllerand passes it tojsonlStreamConsumeron every request, but the observable's cleanup function was a noopabortController.abort()was never called on unsubscribe.This meant the underlying JSONL response stream continued consuming data from the server even after the subscriber disconnected (component unmount, navigation, query cancellation).
Fix
Call
abortController.abort()in the cleanup function so the stream is cancelled when the observable is unsubscribed.Tests
Added a test that subscribes to a batch stream observable, unsubscribes before the response completes, and asserts the fetch was aborted.
Summary by CodeRabbit
Bug Fixes
Tests
Chores