From 843adadac2e223992c3a506952f144e31ccf2afe Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 28 Jul 2026 16:05:47 -0700 Subject: [PATCH] fix(mobile): deliver iOS websocket close events and load expo lazily Bots caught the emit-after-remove race: delegate callbacks deferred the emit onto the serial queue then removed the emitter synchronously, so close/error events never reached JS. Emits now run synchronously on the queue before removal. Also cleans up activeSockets when connect throws, and imports "expo" lazily so test import chains touching runtime.ts do not evaluate expo's dev-only setup (CI __DEV__ failure). Co-Authored-By: Claude Fable 5 --- .../t3-websocket/ios/T3WebSocketModule.swift | 57 ++++++++++--------- apps/mobile/src/lib/nativeWebSocket.test.ts | 34 +++++------ apps/mobile/src/lib/nativeWebSocket.ts | 32 ++++++++--- apps/mobile/src/lib/runtime.ts | 17 ++++-- 4 files changed, 80 insertions(+), 60 deletions(-) diff --git a/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift b/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift index f7d9ce9acd..1a5ae9cde6 100644 --- a/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift +++ b/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift @@ -82,8 +82,10 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat queue.async { guard let task = self.tasksById[id] else { return } task.send(message) { [weak self] error in - guard let error else { return } - self?.emit(id: id, event: "onError", payload: ["message": error.localizedDescription]) + guard let self, let error else { return } + self.queue.async { + self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription]) + } } } } @@ -110,35 +112,34 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat private func receiveLoop(id: Int, task: URLSessionWebSocketTask) { task.receive { [weak self] result in guard let self else { return } - switch result { - case .success(let message): - switch message { - case .string(let text): - self.emit(id: id, event: "onMessage", payload: ["data": text, "binary": false]) - case .data(let data): - self.emit(id: id, event: "onMessage", payload: ["data": data.base64EncodedString(), "binary": true]) - @unknown default: - break - } - self.queue.async { + self.queue.async { + switch result { + case .success(let message): + switch message { + case .string(let text): + self.emitLocked(id: id, event: "onMessage", payload: ["data": text, "binary": false]) + case .data(let data): + self.emitLocked(id: id, event: "onMessage", payload: ["data": data.base64EncodedString(), "binary": true]) + @unknown default: + break + } guard self.tasksById[id] != nil else { return } self.receiveLoop(id: id, task: task) + case .failure: + // The delegate close/error callbacks own failure reporting; the loop + // just stops so it does not spin on a dead task. + break } - case .failure: - // The delegate close/error callbacks own failure reporting; the loop - // just stops so it does not spin on a dead task. - break } } } - private func emit(id: Int, event: String, payload: [String: Any]) { - queue.async { - guard let emitter = self.emittersById[id] else { return } - var enriched = payload - enriched["id"] = id - emitter(event, enriched) - } + // Must be called on `queue`. + private func emitLocked(id: Int, event: String, payload: [String: Any]) { + guard let emitter = emittersById[id] else { return } + var enriched = payload + enriched["id"] = id + emitter(event, enriched) } private func remove(id: Int, taskIdentifier: Int) { @@ -156,7 +157,7 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat ) { queue.async { guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return } - self.emit(id: id, event: "onOpen", payload: ["protocol": `protocol` ?? ""]) + self.emitLocked(id: id, event: "onOpen", payload: ["protocol": `protocol` ?? ""]) } } @@ -169,7 +170,7 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat queue.async { guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return } let reasonText = reason.flatMap { String(data: $0, encoding: .utf8) } ?? "" - self.emit(id: id, event: "onClose", payload: ["code": closeCode.rawValue, "reason": reasonText]) + self.emitLocked(id: id, event: "onClose", payload: ["code": closeCode.rawValue, "reason": reasonText]) self.remove(id: id, taskIdentifier: webSocketTask.taskIdentifier) } } @@ -182,10 +183,10 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat queue.async { guard let id = self.idsByTaskIdentifier[task.taskIdentifier] else { return } if let error { - self.emit(id: id, event: "onError", payload: ["message": error.localizedDescription]) + self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription]) // Abnormal termination: no close frame arrived, mirror the browser's // 1006 so Effect's close-code classification treats it as an error. - self.emit(id: id, event: "onClose", payload: ["code": 1006, "reason": error.localizedDescription]) + self.emitLocked(id: id, event: "onClose", payload: ["code": 1006, "reason": error.localizedDescription]) } self.remove(id: id, taskIdentifier: task.taskIdentifier) } diff --git a/apps/mobile/src/lib/nativeWebSocket.test.ts b/apps/mobile/src/lib/nativeWebSocket.test.ts index 7a70e36d17..6c2c9b543f 100644 --- a/apps/mobile/src/lib/nativeWebSocket.test.ts +++ b/apps/mobile/src/lib/nativeWebSocket.test.ts @@ -54,10 +54,10 @@ vi.mock("expo", () => ({ requireOptionalNativeModule: () => mocks.getModule(), })); -import { nativeWebSocketConstructor } from "./nativeWebSocket"; +import { loadNativeWebSocketConstructor } from "./nativeWebSocket"; -function openSocket() { - const construct = nativeWebSocketConstructor(); +async function openSocket() { + const construct = await loadNativeWebSocketConstructor(); expect(construct).not.toBeNull(); return construct!("wss://example.test/ws"); } @@ -77,17 +77,17 @@ describe("nativeWebSocketConstructor", () => { mocks.reset(); }); - it("returns null on Android and when the native module is missing", () => { + it("resolves null on Android and when the native module is missing", async () => { mocks.setPlatform("android"); - expect(nativeWebSocketConstructor()).toBeNull(); + expect(await loadNativeWebSocketConstructor()).toBeNull(); mocks.setPlatform("ios"); mocks.setModuleAvailable(false); - expect(nativeWebSocketConstructor()).toBeNull(); + expect(await loadNativeWebSocketConstructor()).toBeNull(); }); - it("connects and transitions readyState on open", () => { - const socket = openSocket(); + it("connects and transitions readyState on open", async () => { + const socket = await openSocket(); const id = connectionIdOf(socket); expect(lastCall("connect")!.args).toEqual([id, "wss://example.test/ws", []]); expect(socket.readyState).toBe(0); @@ -103,8 +103,8 @@ describe("nativeWebSocketConstructor", () => { expect(opened).toHaveBeenCalledTimes(1); }); - it("delivers text messages as strings and binary messages as bytes", () => { - const socket = openSocket(); + it("delivers text messages as strings and binary messages as bytes", async () => { + const socket = await openSocket(); const id = connectionIdOf(socket); const received: unknown[] = []; socket.addEventListener("message", (event) => { @@ -119,8 +119,8 @@ describe("nativeWebSocketConstructor", () => { expect([...(received[1] as Uint8Array)]).toEqual([1, 2, 3]); }); - it("sends binary data base64-encoded and strings as text", () => { - const socket = openSocket(); + it("sends binary data base64-encoded and strings as text", async () => { + const socket = await openSocket(); const id = connectionIdOf(socket); socket.send("ping"); @@ -130,10 +130,10 @@ describe("nativeWebSocketConstructor", () => { expect(lastCall("sendBinary")!.args).toEqual([id, btoa("\x01\x02\x03")]); }); - it("dispatches close once and routes messages by connection id", () => { - const first = openSocket(); + it("dispatches close once and routes messages by connection id", async () => { + const first = await openSocket(); const firstId = connectionIdOf(first); - const second = openSocket(); + const second = await openSocket(); const secondId = connectionIdOf(second); expect(firstId).not.toBe(secondId); @@ -151,8 +151,8 @@ describe("nativeWebSocketConstructor", () => { expect(second.readyState).toBe(0); }); - it("close() is idempotent and forwards code and reason", () => { - const socket = openSocket(); + it("close() is idempotent and forwards code and reason", async () => { + const socket = await openSocket(); const id = connectionIdOf(socket); socket.close(4000, "bye"); diff --git a/apps/mobile/src/lib/nativeWebSocket.ts b/apps/mobile/src/lib/nativeWebSocket.ts index d77e81da0e..db73076b6a 100644 --- a/apps/mobile/src/lib/nativeWebSocket.ts +++ b/apps/mobile/src/lib/nativeWebSocket.ts @@ -1,4 +1,3 @@ -import { requireOptionalNativeModule } from "expo"; import { Platform } from "react-native"; // URLSession-backed WebSocket for iOS. React Native's built-in WebSocket uses @@ -100,7 +99,12 @@ class NativeWebSocket { attachNativeListeners(module); const protocolList = typeof protocols === "string" ? [protocols] : protocols ? [...protocols] : []; - module.connect(this.id, url, protocolList); + try { + module.connect(this.id, url, protocolList); + } catch (error) { + activeSockets.delete(this.id); + throw error; + } } addEventListener( @@ -185,17 +189,27 @@ class NativeWebSocket { } /** - * WebSocket constructor backed by URLSessionWebSocketTask, or `null` when - * unavailable (Android, or an iOS binary predating the native module). Callers - * fall back to the global WebSocket. + * Loads the WebSocket constructor backed by URLSessionWebSocketTask, resolving + * `null` when unavailable (Android, or an iOS binary predating the native + * module). Callers fall back to the global WebSocket. + * + * Async because "expo" is imported lazily: its module-scope setup code assumes + * a React Native environment, and this file's importer (runtime.ts) sits in + * many test import chains. */ -export function nativeWebSocketConstructor(): - | ((url: string, protocols?: string | Array) => globalThis.WebSocket) - | null { +export async function loadNativeWebSocketConstructor(): Promise< + ((url: string, protocols?: string | Array) => globalThis.WebSocket) | null +> { if (Platform.OS !== "ios") { return null; } - const module = requireOptionalNativeModule("T3WebSocket"); + let module: T3WebSocketNativeModule | null; + try { + const expo = await import("expo"); + module = expo.requireOptionalNativeModule("T3WebSocket"); + } catch { + return null; + } if (!module) { return null; } diff --git a/apps/mobile/src/lib/runtime.ts b/apps/mobile/src/lib/runtime.ts index 3c5fbd95d6..7349bab090 100644 --- a/apps/mobile/src/lib/runtime.ts +++ b/apps/mobile/src/lib/runtime.ts @@ -1,3 +1,4 @@ +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Socket from "effect/unstable/socket/Socket"; @@ -9,7 +10,7 @@ import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer"; import { resolveCloudPublicConfig } from "../features/cloud/publicConfig"; import { tracingLayer } from "../features/observability/tracing"; import * as Persistence from "../persistence/layer"; -import { nativeWebSocketConstructor } from "./nativeWebSocket"; +import { loadNativeWebSocketConstructor } from "./nativeWebSocket"; function configuredRelayUrl(): string { return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid"; @@ -20,11 +21,15 @@ const httpClientLayer = remoteHttpClientLayer(fetch); // iOS swaps in a URLSessionWebSocketTask-backed constructor so the socket // negotiates permessage-deflate (SocketRocket, behind the global WebSocket, // cannot). Android's global WebSocket (OkHttp) already negotiates it. -const nativeConstructor = nativeWebSocketConstructor(); -const webSocketConstructorLayer = - nativeConstructor === null - ? Socket.layerWebSocketConstructorGlobal - : Layer.succeed(Socket.WebSocketConstructor, nativeConstructor); +const webSocketConstructorLayer: Layer.Layer = Layer.unwrap( + Effect.promise(loadNativeWebSocketConstructor).pipe( + Effect.map((nativeConstructor) => + nativeConstructor === null + ? Socket.layerWebSocketConstructorGlobal + : Layer.succeed(Socket.WebSocketConstructor, nativeConstructor), + ), + ), +); type RuntimeLayerSource = | ReturnType