diff --git a/package-lock.json b/package-lock.json index 5bf9dd74bb3..ab658686d4b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7092,9 +7092,9 @@ "link": true }, "node_modules/@supabase/phoenix": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.0.tgz", - "integrity": "sha512-RHSx8bHS02xwfHdAbX5Lpbo6PXbgyf7lTaXTlwtFDPwOIw64NnVRwFAXGojHhjtVYI+PEPNSWwkL90f4agN3bw==", + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.1.tgz", + "integrity": "sha512-hWGJkDAfWUNY8k0C080u3sGNFd2ncl9erhKgP7hnGkgJWEfT5Pd/SXal4QmWXBECVlZrannMAc9sBaaRyWpiUA==", "license": "MIT" }, "node_modules/@supabase/postgrest-js": { @@ -28449,7 +28449,7 @@ "version": "0.0.0-automated", "license": "MIT", "dependencies": { - "@supabase/phoenix": "^0.4.0", + "@supabase/phoenix": "^0.4.1", "@types/ws": "^8.18.1", "tslib": "2.8.1", "ws": "^8.18.2" diff --git a/packages/core/realtime-js/package.json b/packages/core/realtime-js/package.json index 2d2d3153ec5..798d7eaa3fe 100644 --- a/packages/core/realtime-js/package.json +++ b/packages/core/realtime-js/package.json @@ -40,7 +40,7 @@ "test:ci": "vitest run --coverage" }, "dependencies": { - "@supabase/phoenix": "^0.4.0", + "@supabase/phoenix": "^0.4.1", "@types/ws": "^8.18.1", "tslib": "2.8.1", "ws": "^8.18.2" diff --git a/packages/core/realtime-js/src/RealtimeChannel.ts b/packages/core/realtime-js/src/RealtimeChannel.ts index 64001cde572..cb1c004e793 100644 --- a/packages/core/realtime-js/src/RealtimeChannel.ts +++ b/packages/core/realtime-js/src/RealtimeChannel.ts @@ -9,6 +9,7 @@ import type { } from './RealtimePresence' import * as Transformers from './lib/transformers' import { httpEndpointURL } from './lib/transformers' +import { normalizeChannelError } from './lib/normalizeChannelError' import ChannelAdapter from './phoenix/channelAdapter' import { ChannelBindingCallback, ChannelOnErrorCallback } from './phoenix/types' import type { Timer } from './phoenix/types' @@ -304,7 +305,7 @@ export default class RealtimeChannel { } this._onError((reason: unknown) => { - callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, reason as Error) + callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, normalizeChannelError(reason)) }) this._onClose(() => callback?.(REALTIME_SUBSCRIBE_STATES.CLOSED)) @@ -329,10 +330,8 @@ export default class RealtimeChannel { }) .receive('error', (error: { [key: string]: any }) => { this.state = CHANNEL_STATES.errored - callback?.( - REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, - new Error(JSON.stringify(Object.values(error).join(', ') || 'error')) - ) + const message = Object.values(error).join(', ') || 'error' + callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(message, { cause: error })) }) .receive('timeout', () => { callback?.(REALTIME_SUBSCRIBE_STATES.TIMED_OUT) diff --git a/packages/core/realtime-js/src/lib/normalizeChannelError.ts b/packages/core/realtime-js/src/lib/normalizeChannelError.ts new file mode 100644 index 00000000000..e3954371e3e --- /dev/null +++ b/packages/core/realtime-js/src/lib/normalizeChannelError.ts @@ -0,0 +1,30 @@ +/** + * Normalize the various shapes a channel error reason can take into a real `Error`. + * + * Transport-level channel errors arrive as a `CloseEvent`, a transport `Event`, an `Error`, + * a string, or `undefined` depending on which path in the underlying socket fired. Server-reply + * errors arrive as a payload object. This helper produces a consistent `Error` for every case + * and preserves the original via `cause` so callers can still inspect the raw event. + */ +export function normalizeChannelError(reason: unknown): Error { + if (reason instanceof Error) { + return reason + } + + if (typeof reason === 'string') { + return new Error(reason) + } + + if (reason && typeof reason === 'object') { + const obj = reason as Record + + if (typeof obj.code === 'number') { + const detail = typeof obj.reason === 'string' && obj.reason ? ` (${obj.reason})` : '' + return new Error(`socket closed: ${obj.code}${detail}`, { cause: reason }) + } + + return new Error('channel error: transport failure', { cause: reason }) + } + + return new Error('channel error: connection lost') +} diff --git a/packages/core/realtime-js/test/RealtimeChannel.errors.test.ts b/packages/core/realtime-js/test/RealtimeChannel.errors.test.ts index e6246fc24c6..8c756e7fc0c 100644 --- a/packages/core/realtime-js/test/RealtimeChannel.errors.test.ts +++ b/packages/core/realtime-js/test/RealtimeChannel.errors.test.ts @@ -573,3 +573,72 @@ describe('Trigger Function Error Handling', () => { }) }) }) + +describe('CHANNEL_ERROR callback receives a real Error', () => { + beforeEach(async () => { + testSetup.connect() + await testSetup.socketConnected() + }) + + test('transport phx_error with a CloseEvent payload yields a real Error with cause', () => { + const callback = vi.fn() + channel = testSetup.client.channel('test-transport-close') + channel.subscribe(callback) + + const closeEvent = { code: 1006, reason: 'Network Failure' } + channel.channelAdapter.getChannel().trigger('phx_error', closeEvent) + + expect(callback).toHaveBeenCalledWith('CHANNEL_ERROR', expect.any(Error)) + const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')! + const err = errorCall[1] as Error + expect(err.message).toBe('socket closed: 1006 (Network Failure)') + expect(err.cause).toBe(closeEvent) + }) + + test('transport phx_error with an Error payload (heartbeat timeout) is forwarded as-is', () => { + const callback = vi.fn() + channel = testSetup.client.channel('test-heartbeat-timeout') + channel.subscribe(callback) + + const heartbeatErr = new Error('heartbeat timeout') + channel.channelAdapter.getChannel().trigger('phx_error', heartbeatErr) + + const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')! + expect(errorCall[1]).toBe(heartbeatErr) + }) + + test('transport phx_error with no payload still produces a real Error (defensive)', () => { + const callback = vi.fn() + channel = testSetup.client.channel('test-undefined-reason') + channel.subscribe(callback) + + channel.channelAdapter.getChannel().trigger('phx_error') + + const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')! + const err = errorCall[1] as Error + expect(err).toBeInstanceOf(Error) + expect(err.message).toBe('channel error: connection lost') + }) + + test('server-reply error path produces an Error with the joined message and cause', () => { + const callback = vi.fn() + channel = testSetup.client.channel('test-server-error') + channel.subscribe(callback) + + channel.joinPush.trigger('error', { + reason: 'Authentication failed', + details: 'Invalid API key', + }) + + const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')! + const err = errorCall[1] as Error + expect(err).toBeInstanceOf(Error) + expect(err.message).toContain('Authentication failed') + expect(err.message).toContain('Invalid API key') + expect(err.message).not.toMatch(/^"/) + expect(err.cause).toEqual({ + reason: 'Authentication failed', + details: 'Invalid API key', + }) + }) +}) diff --git a/packages/core/realtime-js/test/RealtimeClient.resilience.test.ts b/packages/core/realtime-js/test/RealtimeClient.resilience.test.ts index 2d031a28c46..d9d76c14241 100644 --- a/packages/core/realtime-js/test/RealtimeClient.resilience.test.ts +++ b/packages/core/realtime-js/test/RealtimeClient.resilience.test.ts @@ -114,7 +114,10 @@ describe('socket close event', () => { testClient.mockServer.close({ code: 1000, reason: '', wasClean: true }) await testClient.socketClosed() - expect(spy).toHaveBeenCalledWith(CHANNEL_EVENTS.error) + expect(spy).toHaveBeenCalledWith( + CHANNEL_EVENTS.error, + expect.objectContaining({ type: 'close', code: 1000, wasClean: true }) + ) }) }) @@ -129,6 +132,9 @@ describe('_onConnError', () => { const spy = vi.spyOn(channel.channelAdapter.getChannel(), 'trigger') testClient.mockServer.simulate('error') - expect(spy).toHaveBeenCalledWith(CHANNEL_EVENTS.error) + expect(spy).toHaveBeenCalledWith( + CHANNEL_EVENTS.error, + expect.objectContaining({ type: 'error' }) + ) }) }) diff --git a/packages/core/realtime-js/test/normalizeChannelError.test.ts b/packages/core/realtime-js/test/normalizeChannelError.test.ts new file mode 100644 index 00000000000..8652043220f --- /dev/null +++ b/packages/core/realtime-js/test/normalizeChannelError.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'vitest' +import { normalizeChannelError } from '../src/lib/normalizeChannelError' + +describe('normalizeChannelError', () => { + test('returns the original Error untouched', () => { + const original = new Error('boom') + expect(normalizeChannelError(original)).toBe(original) + }) + + test('preserves Error subclasses', () => { + class CustomError extends Error {} + const original = new CustomError('custom') + const normalized = normalizeChannelError(original) + expect(normalized).toBe(original) + expect(normalized).toBeInstanceOf(CustomError) + }) + + test('wraps a string into an Error with the same message', () => { + const result = normalizeChannelError('something failed') + expect(result).toBeInstanceOf(Error) + expect(result.message).toBe('something failed') + }) + + test('formats a CloseEvent-shaped object with code and reason', () => { + const closeEvent = { code: 1006, reason: 'abnormal closure' } + const result = normalizeChannelError(closeEvent) + expect(result).toBeInstanceOf(Error) + expect(result.message).toBe('socket closed: 1006 (abnormal closure)') + expect(result.cause).toBe(closeEvent) + }) + + test('formats a CloseEvent without reason', () => { + const closeEvent = { code: 1000 } + const result = normalizeChannelError(closeEvent) + expect(result.message).toBe('socket closed: 1000') + expect(result.cause).toBe(closeEvent) + }) + + test('treats an empty reason string as missing detail', () => { + const closeEvent = { code: 1011, reason: '' } + const result = normalizeChannelError(closeEvent) + expect(result.message).toBe('socket closed: 1011') + }) + + test('falls back to a generic transport message for plain objects', () => { + const event = { type: 'error', target: {} } + const result = normalizeChannelError(event) + expect(result.message).toBe('channel error: transport failure') + expect(result.cause).toBe(event) + }) + + test('returns a default Error for undefined', () => { + const result = normalizeChannelError(undefined) + expect(result).toBeInstanceOf(Error) + expect(result.message).toBe('channel error: connection lost') + }) + + test('returns a default Error for null', () => { + const result = normalizeChannelError(null) + expect(result).toBeInstanceOf(Error) + expect(result.message).toBe('channel error: connection lost') + }) +})