Skip to content

Commit 0e38bd8

Browse files
dinwwwhclaude
andauthored
fix(publisher): isolate listener errors in Upstash and memory adapters (#2375)
## Problem **Upstash adapter.** A subscriber whose `onError` throws breaks delivery for every other subscriber on the channel: - `@upstash/redis` calls the `message` handler inside its own try/catch and re-emits any throw as an `error` event. - The adapter forwards `error` events to every registered `onError`, so the error is broadcast to all of them. - Iterator subscribers terminate on `onError`. - The throw also stops delivery to the remaining listeners for that message. **Memory adapter.** `publish()` calls listeners with no try/catch, so one throwing listener stops delivery to later subscribers and rejects `publish()`. The Redis and Durable adapters already isolate per-listener errors. ## Changes - **Upstash:** each listener call in message dispatch is wrapped in `tryOrUndefined`, so a throw neither reaches Upstash nor stops the other listeners. Listeners already send their own failures to `onError` in `BaseRedisPublisher`, so in practice this guards against an `onError` that throws. - **Memory:** each listener is wrapped at subscribe time, and a throw goes to that subscriber's `onError`. ## Tests - **Upstash:** a credential-free fake-client test mimics how Upstash re-emits a handler throw as `error`. It checks that a second subscriber still receives the message and that its `onError` is not called. - **Memory:** a test checks that a throwing listener doesn't stop delivery or reject `publish()`. Both tests fail without the fix. `pnpm vitest run packages/publisher`, `pnpm type:check` and `pnpm lint` pass. ## Not in this PR - **Silent stream drops:** `@upstash/redis` never reports that an established stream has dropped. `command.exec()` resolves once the SSE response headers arrive, and the body is read in a detached task that only logs read failures with `console.error`. So a dropped stream stays in `subscriptionMap` unnoticed. Detecting that needs either a liveness check or an upstream change, and is left for a follow-up. - **Other adapters:** they still isolate listener errors in their own ways. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01VVaw7Pcdx6NZtoSRJNFXRZ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f59a986 commit 0e38bd8

4 files changed

Lines changed: 74 additions & 4 deletions

File tree

‎packages/publisher/src/adapters/memory.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,24 @@ describe('memoryPublisher', () => {
284284
await unsubscribeSecond()
285285
})
286286
})
287+
288+
it('keeps delivering to other listeners when one throws', async () => {
289+
const publisher = new MemoryPublisher<TestEvents>()
290+
const error = new Error('listener failed')
291+
const onError = vi.fn()
292+
const listener = vi.fn()
293+
294+
const unsubscribe1 = await publisher.subscribe('message', () => {
295+
throw error
296+
}, { onError })
297+
const unsubscribe2 = await publisher.subscribe('message', listener)
298+
299+
await expect(publisher.publish('message', { text: 'hello' })).resolves.toBeUndefined()
300+
301+
expect(onError).toHaveBeenCalledExactlyOnceWith(error)
302+
expect(listener).toHaveBeenCalledExactlyOnceWith({ text: 'hello' })
303+
304+
await unsubscribe1()
305+
await unsubscribe2()
306+
})
287307
})

‎packages/publisher/src/adapters/memory.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { ThrowableError } from '@orpc/shared'
12
import type { PublisherOptions, PublisherResumeOptions, PublisherSubscribeListenerOptions } from '../publisher'
23
import { compareSequentialIds, once, SequentialIdGenerator } from '@orpc/shared'
34
import { getEventMeta, unwrapEvent, withEventMeta } from '@standard-server/core'
@@ -77,17 +78,26 @@ export class MemoryPublisher<T extends Record<string, object>> extends Publisher
7778
}
7879
}
7980

81+
const isolatedListener = (payload: T[K]) => {
82+
try {
83+
listener(payload)
84+
}
85+
catch (error) {
86+
options?.onError?.(error as ThrowableError)
87+
}
88+
}
89+
8090
let listeners = this.listenersMap.get(event)
8191
if (!listeners) {
8292
this.listenersMap.set(event, listeners = [])
8393
}
8494

85-
listeners.push(listener)
95+
listeners.push(isolatedListener)
8696

8797
// Ensure the returned cleanup function is safe to call multiple times.
8898
return once(async () => {
8999
const current = this.listenersMap.get(event)!
90-
const index = current.indexOf(listener)
100+
const index = current.indexOf(isolatedListener)
91101
const remaining = current.filter((_, i) => i !== index)
92102

93103
if (remaining.length === 0) {

‎packages/publisher/src/adapters/upstash.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,3 +706,43 @@ it('prefix creates a publisher that appends the prefix and shares the client', a
706706
await publisher.publish('event', { order: 1 })
707707
expect(redis.publish).toHaveBeenCalledWith('tenant:event', expect.any(String))
708708
})
709+
710+
it('does not broadcast a throwing onError to other subscribers', async () => {
711+
const subscription = createFakeSubscription()
712+
const messages: string[] = []
713+
const redis = {
714+
publish: async (_channel: string, message: string) => messages.push(message),
715+
subscribe: () => {
716+
queueMicrotask(() => subscription.emit('subscribe', 1))
717+
return subscription
718+
},
719+
}
720+
const publisher = new UpstashPublisher<Record<string, object>>(redis as unknown as Redis)
721+
const listener2 = vi.fn()
722+
const onError2 = vi.fn()
723+
724+
const unsubscribe1 = await publisher.subscribe('room', () => {
725+
throw new Error('listener failed')
726+
}, {
727+
onError: () => {
728+
throw new Error('onError failed')
729+
},
730+
})
731+
const unsubscribe2 = await publisher.subscribe('room', listener2, { onError: onError2 })
732+
733+
await publisher.publish('room', { order: 1 })
734+
735+
// Like Upstash, which emits a throw from a message handler as an `error` event.
736+
try {
737+
subscription.emit('message', { channel: 'room', message: messages[0] })
738+
}
739+
catch (error) {
740+
subscription.emit('error', error)
741+
}
742+
743+
expect(listener2).toHaveBeenCalledExactlyOnceWith({ order: 1 })
744+
expect(onError2).not.toHaveBeenCalled()
745+
746+
await unsubscribe1()
747+
await unsubscribe2()
748+
})

‎packages/publisher/src/adapters/upstash.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { ThrowableError } from '@orpc/shared'
22
import type { Redis } from '@upstash/redis'
33
import type { BaseRedisPublisherOptions, RedisStreamEntry } from './base-redis'
4-
import { promiseWithResolvers } from '@orpc/shared'
4+
import { promiseWithResolvers, tryOrUndefined } from '@orpc/shared'
55
import { BaseRedisPublisher } from './base-redis'
66

77
export interface UpstashPublisherOptions extends BaseRedisPublisherOptions {}
@@ -103,7 +103,7 @@ export class UpstashPublisher<T extends Record<string, object>> extends BaseRedi
103103
})
104104
subscription.on('message', ({ message }) => {
105105
// Snapshot, since a listener may unsubscribe itself mid-dispatch.
106-
this.listenersMap.get(channel)?.slice().forEach(listener => listener(message))
106+
this.listenersMap.get(channel)?.slice().forEach(listener => tryOrUndefined(() => listener(message)))
107107
})
108108

109109
this.pendingSubscriptionsMap.set(channel, promise)

0 commit comments

Comments
 (0)