fix(query-broadcast-client): handle postMessage errors #10770
main fromrefs/pull/10770/head·opened View on GitHubSummary#
broadcastQueryClient now sends cache events through a guarded postMessage helper. If the underlying broadcast-channel implementation rejects or throws for a non-cloneable payload, the rejection is handled instead of surfacing as an unhandled rejection. Consumers can also pass onBroadcastError to log the offending broadcast message in production, while development still gets a queryHash-aware warning.
Testing#
corepack pnpm --filter @tanstack/query-broadcast-client-experimental exec vitest run src/__tests__/index.test.tscorepack pnpm exec prettier --check .changeset/broadcast-client-post-errors.md packages/query-broadcast-client-experimental/src/index.ts packages/query-broadcast-client-experimental/src/__tests__/index.test.tscorepack pnpm exec eslint --concurrency=auto -c eslint.config.js packages/query-broadcast-client-experimental/src/index.ts packages/query-broadcast-client-experimental/src/__tests__/index.test.tscorepack pnpm exec tsc -p packages/query-broadcast-client-experimental/tsconfig.prod.json --noEmit --pretty falsecorepack pnpm exec tsup src/index.ts --no-config --format cjs,esm --target es2020,node16 --dts --sourcemap --clean --out-dir build/legacy --tsconfig tsconfig.prod.jsongit diff --check
Note: the package test:types:tscurrent and build scripts still hit the existing Windows symlink-placeholder checkout issue for root.eslint.config.js / root.tsup.config.js, so I validated the changed source with the direct TypeScript and tsup --no-config commands above.
Summary by CodeRabbit#
New Features
- Added an
onBroadcastErrorcallback option to surface broadcast transmission failures. - Added development-time warnings for failed broadcasts including message type and query identifier.
- Added an
Bug Fixes
- Prevented unhandled rejections from broadcast message posting failures.
Tests
- Added regression tests validating error reporting and warnings when broadcasts fail.
Documentation
- Added a changeset documenting the patch release handling broadcast postMessage failures.
- 1
🧹 Nitpick comments (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
64-99: ⚡ Quick winAdd a regression test for synchronous
postMessagethrows.This test only exercises promise rejection. Adding a sibling case where
channel.postMessagethrows synchronously would lock in the try/catch path in the helper.Suggested test addition
+ it('should report synchronous postMessage throws', async () => { + const error = new DOMException('cannot clone', 'DataCloneError') + const onBroadcastError = vi.fn() + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + broadcastQueryClient({ + queryClient, + broadcastChannel: 'test_channel', + onBroadcastError, + }) + + const channel = broadcastChannelMock.channels[0]! + channel.postMessage.mockImplementation(() => { + throw error + }) + + queryClient.setQueryData(['stream'], new ReadableStream()) + + await vi.waitFor(() => { + expect(onBroadcastError).toHaveBeenCalledWith( + error, + expect.objectContaining({ + type: 'updated', + queryHash: '["stream"]', + queryKey: ['stream'], + }), + ) + }) + + expect(consoleWarnSpy).toHaveBeenCalledWith( + '[broadcastQueryClient] failed to broadcast "updated" for queryHash "["stream"]"', + error, + ) + })🤖 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/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 64 - 99, Add a sibling test in the same file that mirrors the existing "should report postMessage rejections..." spec but simulates a synchronous throw from channel.postMessage instead of returning a rejected Promise: create a DOMException, spy on console.warn, call broadcastQueryClient(...) (same args), find broadcastChannelMock.channels[0], set channel.postMessage to a function that throws the error immediately, invoke queryClient.setQueryData(['stream'], new ReadableStream()), then await vi.waitFor to assert onBroadcastError was called with the error and message shape (type: 'updated', queryHash: '["stream"]', queryKey: ['stream']), and assert console.warn was called with the same failure message and error—this locks in the helper's try/catch path for synchronous throws (reference symbols: broadcastQueryClient, broadcastChannelMock, channel.postMessage, onBroadcastError, queryClient.setQueryData).🤖 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. Nitpick comments: In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 64-99: Add a sibling test in the same file that mirrors the existing "should report postMessage rejections..." spec but simulates a synchronous throw from channel.postMessage instead of returning a rejected Promise: create a DOMException, spy on console.warn, call broadcastQueryClient(...) (same args), find broadcastChannelMock.channels[0], set channel.postMessage to a function that throws the error immediately, invoke queryClient.setQueryData(['stream'], new ReadableStream()), then await vi.waitFor to assert onBroadcastError was called with the error and message shape (type: 'updated', queryHash: '["stream"]', queryKey: ['stream']), and assert console.warn was called with the same failure message and error—this locks in the helper's try/catch path for synchronous throws (reference symbols: broadcastQueryClient, broadcastChannelMock, channel.postMessage, onBroadcastError, queryClient.setQueryData).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e0417935-b2d1-4c3a-b58f-940a70816dc6📥 Commits
Reviewing files that changed from the base of the PR and between ba6e7beebd50143408f01fcf5d9aee2ec1486f60 and c543e8c3c560a4cba04b9c0127ad658f3534b6ee.
📒 Files selected for processing (3)
.changeset/broadcast-client-post-errors.mdpackages/query-broadcast-client-experimental/src/__tests__/index.test.tspackages/query-broadcast-client-experimental/src/index.ts
TkDodo closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
f9855aef-a549-4acf-9c06-a975d1d325c6📥 Commits
Reviewing files that changed from the base of the PR and between c543e8c3c560a4cba04b9c0127ad658f3534b6ee and e11f99464c5b52a78e71ea8090bc21205cec40de.
📒 Files selected for processing (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts📝 Walkthrough
Walkthrough#
Wraps BroadcastChannel.postMessage calls in a helper that catches sync throws and promise rejections, invokes an optional onBroadcastError callback with the error and message, logs a dev warning with message type and queryHash, adds tests simulating rejection/sync-throw, and adds a changeset for a patch release.
Changes#
Broadcast postMessage Error Handling
packages/query-broadcast-client-experimental/src/index.tsBroadcastQueryClientOptionsnow includesonBroadcastError?: (error: unknown, message: BroadcastMessage) => void; introducesBroadcastMessageunion forupdated/removed/addedpayloads.packages/query-broadcast-client-experimental/src/index.tshandleBroadcastErrorandpostMessagehelper catch sync throws and promise rejections fromchannel.postMessage, callonBroadcastErrorwhen provided, and emit a development-timeconsole.warnincluding message type andqueryHash.packages/query-broadcast-client-experimental/src/index.tschannel.postMessage(...)calls forupdated,removed, andaddedbroadcasts with thepostMessage(...)helper to ensure uniform error handling.packages/query-broadcast-client-experimental/src/__tests__/index.test.ts,.changeset/broadcast-client-post-errors.mdBroadcastChannelmock, two regression tests that simulatepostMessagerejection and synchronous throws verifyingonBroadcastErrorand dev warnings, and a changeset documenting the patch release.Sequence Diagram#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#10542,#10543), explains the implementation (guarded postMessage helper, onBroadcastError callback), and details comprehensive testing steps. However, the checklist items are not marked as completed.#10542: prevents unhandled rejections via try/catch in a postMessage helper, adds onBroadcastError callback for consumer logging, includes regression tests for both sync and async broadcast failures, and provides queryHash-aware warnings in development.✨ 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.
❤️ Share