Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/broadcast-client-post-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-broadcast-client-experimental': patch
---

Handle broadcast `postMessage` failures without surfacing unhandled rejections.
Original file line number Diff line number Diff line change
@@ -1,17 +1,49 @@
import { QueryClient } from '@tanstack/query-core'
import { beforeEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { broadcastQueryClient } from '..'
import type { QueryCache } from '@tanstack/query-core'

const broadcastChannelMock = vi.hoisted(() => {
const channels: Array<{
postMessage: ReturnType<typeof vi.fn>
close: ReturnType<typeof vi.fn>
onmessage: ((message: unknown) => void) | null
}> = []

class BroadcastChannel {
onmessage: ((message: unknown) => void) | null = null
postMessage = vi.fn(() => Promise.resolve())
close = vi.fn()

constructor(_name: string, _options: unknown) {
channels.push(this)
}
}

return {
BroadcastChannel,
channels,
}
})

vi.mock('broadcast-channel', () => ({
BroadcastChannel: broadcastChannelMock.BroadcastChannel,
}))

describe('broadcastQueryClient', () => {
let queryClient: QueryClient
let queryCache: QueryCache

beforeEach(() => {
broadcastChannelMock.channels.length = 0
queryClient = new QueryClient()
queryCache = queryClient.getQueryCache()
})

afterEach(() => {
vi.restoreAllMocks()
})

it('should subscribe to the query cache', () => {
broadcastQueryClient({
queryClient,
Expand All @@ -28,4 +60,81 @@ describe('broadcastQueryClient', () => {
unsubscribe()
expect(queryCache.hasListeners()).toBe(false)
})

it('should report postMessage rejections without unhandled rejections', 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((message: { type: string }) =>
message.type === 'updated' ? Promise.reject(error) : Promise.resolve(),
)

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,
)
})

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((message: { type: string }) => {
if (message.type === 'updated') {
throw error
}
return Promise.resolve()
})

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,
)
})
})
44 changes: 40 additions & 4 deletions packages/query-broadcast-client-experimental/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import { BroadcastChannel } from 'broadcast-channel'
import type { BroadcastChannelOptions } from 'broadcast-channel'
import type { QueryClient } from '@tanstack/query-core'
import type { QueryClient, QueryKey, QueryState } from '@tanstack/query-core'

interface BroadcastQueryClientOptions {
queryClient: QueryClient
broadcastChannel?: string
options?: BroadcastChannelOptions
onBroadcastError?: (error: unknown, message: BroadcastMessage) => void
}

type BroadcastMessage =
| {
type: 'updated'
queryHash: string
queryKey: QueryKey
state: QueryState
}
| {
type: 'removed' | 'added'
queryHash: string
queryKey: QueryKey
}

export function broadcastQueryClient({
queryClient,
broadcastChannel = 'tanstack-query',
options,
onBroadcastError,
}: BroadcastQueryClientOptions): () => void {
let transaction = false
const tx = (cb: () => void) => {
Expand All @@ -27,6 +42,27 @@ export function broadcastQueryClient({

const queryCache = queryClient.getQueryCache()

const handleBroadcastError = (error: unknown, message: BroadcastMessage) => {
onBroadcastError?.(error, message)

if (process.env.NODE_ENV !== 'production') {
console.warn(
`[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}"`,
error,
)
}
}

const postMessage = (message: BroadcastMessage) => {
try {
void channel
.postMessage(message)
.catch((error) => handleBroadcastError(error, message))
} catch (error) {
handleBroadcastError(error, message)
}
}

const unsubscribe = queryClient.getQueryCache().subscribe((queryEvent) => {
if (transaction) {
return
Expand All @@ -37,7 +73,7 @@ export function broadcastQueryClient({
} = queryEvent

if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
channel.postMessage({
postMessage({
type: 'updated',
queryHash,
queryKey,
Expand All @@ -46,15 +82,15 @@ export function broadcastQueryClient({
}

if (queryEvent.type === 'removed' && observers.length > 0) {
channel.postMessage({
postMessage({
type: 'removed',
queryHash,
queryKey,
})
}

if (queryEvent.type === 'added') {
channel.postMessage({
postMessage({
type: 'added',
queryHash,
queryKey,
Expand Down