query icon indicating copy to clipboard operation
query copied to clipboard

fix(broadcast-client): handle unhandled postMessage rejections

Open n-satoshi061 opened this issue 6 months ago โ€ข 6 comments

Summary

Fixes #10543

broadcastQueryClient calls channel.postMessage() three times (on updated, removed, added) without .catch()-ing the returned promise. When query data contains a non-cloneable value (ReadableStream, Response, File, functions, Vue/MobX reactive proxies, etc.), the rejection becomes an unhandled DataCloneError with a stack pointing into node_modules โ€” effectively unactionable in Sentry/Datadog.

Changes

  • Wrap all channel.postMessage() calls in a safePost() helper that catches rejections
  • Add optional onBroadcastError callback to BroadcastQueryClientOptions so consumers can route errors to their own error tracker with the offending queryHash
  • Fall back to console.warn in development when onBroadcastError is not provided
  • Silent in production (no unhandled rejection, no console noise)

Usage

broadcastQueryClient({
  queryClient,
  broadcastChannel: 'my-app',
  onBroadcastError: (error, message) => {
    Sentry.captureException(error, {
      extra: { queryHash: message.queryHash, type: message.type },
    })
  },
})

Test plan

  • [x] onBroadcastError is called with the error and message when postMessage rejects
  • [x] console.warn is emitted in development when no onBroadcastError is provided
  • [x] No warning in production when postMessage fails
  • [x] Existing tests still pass
  • [x] ESLint passes

๐Ÿค– Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Prevented unhandled rejections when cross-tab broadcast fails due to non-serializable data; failures are now caught to avoid noisy errors.
  • New Features

    • Added an optional broadcast-error callback so apps can handle broadcast failures explicitly; when omitted, development builds emit console warnings.
    • Reduced broadcast payload size by omitting state for removed items.
  • Documentation

    • Added guidance and examples for handling broadcast errors.
  • Tests

    • Expanded tests to cover broadcast error handling and warning behavior.

Review Change Stack

n-satoshi061 avatar May 24 '26 11:05 n-satoshi061

No actionable comments were generated in the recent review. ๐ŸŽ‰

โ„น๏ธ Recent review info
โš™๏ธ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b48a45c-71ca-4d47-b171-5934da15836c

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between b32ff8ea9bcbd6627c8b44a758857f3c1586b513 and 52d17622dbcd1c7f89bd274ce8a994b496b9a4fb.

๐Ÿ“’ Files selected for processing (1)
  • packages/query-broadcast-client-experimental/src/__tests__/index.test.ts

๐Ÿ“ Walkthrough

Walkthrough

broadcastQueryClient wraps outbound BroadcastChannel.postMessage in safePost and accepts an optional onBroadcastError(error, event); failures invoke the callback (handling throws/rejections) or emit a development-only console.warn. updated/added include state; removed omits state. Tests, docs, and a changeset were added.

Changes

Broadcast error handling and recovery

Layer / File(s) Summary
Options interface and callback setup
packages/query-broadcast-client-experimental/src/index.ts
Adds exported BroadcastErrorEvent and an optional `onBroadcastError?: (error: unknown, event: BroadcastErrorEvent) => void
Safe post helper with error handling
packages/query-broadcast-client-experimental/src/index.ts
Introduces safePost wrapping channel.postMessage to catch rejections and call onBroadcastError(error, event) when provided; tolerates sync throws and promise rejections and falls back to a development-only console.warn.
Integrate safePost into broadcast paths
packages/query-broadcast-client-experimental/src/index.ts
Replaces direct postMessage calls for updated, removed, and added with safePost; updated/added payloads include state, removed omits state.
Test mock setup and error handling scenarios
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts
Adds controllable postMessage/close spies, resets them between tests, and adds a postMessage error handling suite forcing rejections to verify onBroadcastError invocation, no unhandledRejection when handler throws/rejects, and environment-dependent console.warn behavior.
Docs: API and handling section
docs/framework/react/plugins/broadcastQueryClient.md
Documents onBroadcastError and BroadcastErrorEvent; adds a "Handling broadcast errors" section with explanation and an example (Sentry integration).
Release notes
.changeset/fix-broadcast-client-unhandled-rejection.md
Patch changeset documenting the fix for unhandled DataCloneError rejections, the new optional onBroadcastError callback, and the development fallback to console.warn.
sequenceDiagram
  participant BroadcastQueryClient
  participant BroadcastChannel
  participant onBroadcastError
  participant Console
  BroadcastQueryClient->>BroadcastChannel: safePost(message) -> postMessage(message)
  BroadcastChannel--xBroadcastQueryClient: rejection (DataCloneError)
  BroadcastQueryClient->>onBroadcastError: onBroadcastError(error, event)
  onBroadcastError-->>BroadcastQueryClient: may throw / reject
  BroadcastQueryClient->>Console: console.warn(type, queryHash, error) (dev-only fallback)

๐ŸŽฏ 3 (Moderate) | โฑ๏ธ ~20 minutes

  • TkDodo

๐Ÿฐ I hopped through code with care and cheer,
When messages failed, I caught them near.
Errors routed, no noisy fright,
Callbacks listen, devs see light.
Broadcasts hum softly through the night.

๐Ÿšฅ Pre-merge checks | โœ… 4 | โŒ 1

โŒ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage โš ๏ธ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
โœ… Passed checks (4 passed)
Check name Status Explanation
Title check โœ… Passed The title accurately and concisely summarizes the main change: fixing unhandled postMessage rejections in the broadcast client.
Description check โœ… Passed The description covers the motivation (issue #10543), key changes (safePost helper, onBroadcastError callback), usage example, and confirms test coverage and linting checks.
Linked Issues check โœ… Passed The implementation comprehensively addresses #10543: wraps postMessage calls in safePost, provides optional onBroadcastError callback with BroadcastErrorEvent, uses console.warn in dev when no callback, and maintains silence in production.
Out of Scope Changes check โœ… Passed All changes directly support the primary objective of handling postMessage rejections; the state inclusion fix in 'added' broadcasts is a related bug fix identified during implementation.

โœ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.

โœจ Finishing Touches
๐Ÿงช Generate unit tests (beta)
  • [ ] Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 24 '26 11:05 coderabbitai[bot]

Fixed in the latest commit: wrapped both unhandledRejection listener tests in try/finally so process.off() is always called even if an assertion throws.

n-satoshi061 avatar May 24 '26 13:05 n-satoshi061

Update summary

After reviewing other PRs addressing the same issue (#10569, #10770, #10697) and the CodeRabbit feedback, I've made additional improvements beyond the initial unhandled-rejection fix. Here's a full summary of what's in the branch now.


Changes from the original PR

Types

  • Exported BroadcastErrorEvent interface (with queryKey: QueryKey) so consumers can import and reference the type directly:
    import type { BroadcastErrorEvent } from '@tanstack/query-broadcast-client-experimental'
    
  • Replaced the flat BroadcastMessage interface with a discriminated union โ€” state is now only present on updated and added (not removed), which matches the actual wire protocol
  • onBroadcastError now receives BroadcastErrorEvent (no internal state field) rather than the raw message object
  • onBroadcastError return type is void | Promise<void> to explicitly support async callbacks

Error handling in safePost

Case Behaviour
postMessage rejects onBroadcastError called with error + event; or dev console.warn if no callback
onBroadcastError throws synchronously Caught by try/catch; dev console.warn with callback error
onBroadcastError returns a rejecting Promise Caught by result?.catch(); dev console.warn with callback error
Production, no callback Silent โ€” no unhandled rejection, no console noise

Warning messages

Two distinct messages to make debugging easier:

  • Broadcast failure (no callback): [broadcastQueryClient] Failed to broadcast "X" event for query Y. The query value could not be structured-cloned; cross-tab sync for this query was skipped.
  • Callback itself failed: [broadcastQueryClient] onBroadcastError threw while handling "X" for query Y.

Bug fix: state missing from 'added' broadcasts

The receiver's onmessage handler reads state for added events (query.setState(state) / queryCache.build(..., state)), but the sender was omitting it โ€” causing receiving tabs to apply undefined state. Fixed by including state in the outbound added message and updating the discriminated union accordingly.

Other

  • Replaced queryClient.getQueryCache().subscribe() with queryCache.subscribe() (variable already in scope)
  • Added JSDoc to all BroadcastQueryClientOptions fields
  • Added "Handling broadcast errors" section to the docs with a Sentry example

CodeRabbit review responses

Comment Resolution
onBroadcastError throwing causes a new unhandled rejection Wrapped callback in try/catch; added test asserting zero unhandledRejection events when callback throws
Async onBroadcastError rejecting causes unhandled rejection Extended type to void | Promise<void>; added result?.catch() guard; added test for async rejection path
'added' broadcasts omit state, breaking receiver contract Added state to the added discriminated union variant and to the safePost call site; confirmed with existing tests

Test coverage (9 tests)

  • subscribe / unsubscribe (existing)
  • onBroadcastError called when postMessage rejects
  • No unhandled rejection when callback throws synchronously
  • Dev console.warn emitted when callback throws (asserts message contains "onBroadcastError threw while handling")
  • No unhandled rejection when async callback rejects
  • Dev console.warn emitted when async callback rejects
  • Dev console.warn emitted when no callback provided (asserts "cross-tab sync for this query was skipped")
  • No console.warn in production

n-satoshi061 avatar May 26 '26 01:05 n-satoshi061

@coderabbitai resume

n-satoshi061 avatar May 26 '26 01:05 n-satoshi061

โœ… Actions performed

Reviews resumed.

coderabbitai[bot] avatar May 26 '26 01:05 coderabbitai[bot]

Addressed in the latest commit (52d17622d).

All four tests that call vi.spyOn(console, 'warn') now wrap their assertions in try/finally so mockRestore() is guaranteed to run even if an assertion fails โ€” preventing the spy from leaking into subsequent tests.

const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
  // ...test body and assertions...
} finally {
  warnSpy.mockRestore()
}

Applied to:

  • should warn in dev when onBroadcastError itself throws
  • should warn in dev when async onBroadcastError rejects
  • should warn in dev when postMessage fails and onBroadcastError is not provided
  • should not warn in production when postMessage fails

n-satoshi061 avatar May 26 '26 01:05 n-satoshi061