diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index f267c0e80f..bae5d698b0 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -131,13 +131,16 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, func initialSnapshot() async throws -> FeatureSnapshot { let environments = try await runtime.environments() - guard let environment = try await runtime.activeEnvironment(), - let activeClient = try await runtime.activeClient() else { + guard let activeClient = try await runtime.activeClient() else { await clearActiveEnvironment() let snapshot = disconnectedSnapshot(environments: environments) latestSnapshot = snapshot return snapshot } + // The runtime actor can change its active selection at any suspension + // point. Derive both values from one client so the snapshot cannot pair + // one environment with another environment's connection. + let environment = activeClient.environment await adoptEnvironment(environment, client: activeClient) let generation = environmentGeneration diff --git a/apps/swift-ios/Core/WebSocketRPC.swift b/apps/swift-ios/Core/WebSocketRPC.swift index 7e975c8255..c7a101bbb8 100644 --- a/apps/swift-ios/Core/WebSocketRPC.swift +++ b/apps/swift-ios/Core/WebSocketRPC.swift @@ -177,6 +177,7 @@ public actor WebSocketRPCClient { private var connection: (any WebSocketConnection)? private var connectionID: UUID? private var loopTask: Task? + private var loopID: UUID? private var keepaliveTask: Task? private var desired = false private var nextRequestID = 1 @@ -204,7 +205,9 @@ public actor WebSocketRPCClient { public func start() { desired = true guard loopTask == nil else { return } - loopTask = Task { await self.connectionLoop() } + let id = UUID() + loopID = id + loopTask = Task { await self.connectionLoop(id: id) } } public func isConnected() -> Bool { @@ -212,21 +215,23 @@ public actor WebSocketRPCClient { } public func stop() async { + let closingConnection = connection desired = false + loopID = nil loopTask?.cancel() loopTask = nil keepaliveTask?.cancel() keepaliveTask = nil - if let connection { - await connection.close() - } connection = nil connectionID = nil failUnary(RPCError.disconnected, includingUnsent: true) - let active = subscriptions.values + let active = Array(subscriptions.values) subscriptions.removeAll() subscriptionByRequestID.removeAll() active.forEach { $0.finish(RPCError.disconnected) } + // Publish the stopped state before suspension. A new start while the + // old socket closes owns independent state and must survive this call. + await closingConnection?.close() } public func request( @@ -312,33 +317,53 @@ public actor WebSocketRPCClient { } } - private func connectionLoop() async { + private func connectionLoop(id loopID: UUID) async { var retry = 0 - while desired, !Task.isCancelled { + while isCurrentConnectionLoop(loopID), !Task.isCancelled { + var openedID: UUID? do { let url = try await endpointProvider() + guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { break } let opened = try await connector.connect(to: url) - let openedID = UUID() + guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { + await opened.close() + break + } + let id = UUID() + openedID = id connection = opened - connectionID = openedID + connectionID = id retry = 0 await connected() // Sending queued work during setup is actor-reentrant. A send // failure can discard this socket before setup completes, so // never enter its receive loop after ownership has moved on. - guard connectionID == openedID else { + guard isCurrentConnectionLoop(loopID), connectionID == id else { + await disconnected(expectedConnectionID: id) + guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { break } throw RPCError.disconnected } try await receiveLoop(opened) + await disconnected(expectedConnectionID: id) + guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { break } } catch { - await disconnected() - guard desired, !Task.isCancelled else { break } + if let openedID { + await disconnected(expectedConnectionID: openedID) + } + guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { break } retry += 1 let delay = min(5.0, 0.35 * pow(1.7, Double(retry - 1))) try? await Task.sleep(for: .seconds(delay)) } } - loopTask = nil + if self.loopID == loopID { + self.loopID = nil + loopTask = nil + } + } + + private func isCurrentConnectionLoop(_ id: UUID) -> Bool { + desired && loopID == id } private func connected() async { diff --git a/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift index 02342bac4c..11dbab136a 100644 --- a/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift +++ b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift @@ -198,6 +198,145 @@ final class WebSocketRPCRaceTests: XCTestCase { await client.stop() await first.releaseSend() } + + func testStopDuringConnectClosesTheLateSocketWithoutPublishingIt() async { + let lateConnection = CloseTrackingConnection() + let connector = GatedConnector(connection: lateConnection) + let client = WebSocketRPCClient( + connector: connector, + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + await client.start() + await connector.waitUntilConnectStarted() + await client.stop() + await connector.release() + await lateConnection.waitUntilClosed() + + let isConnected = await client.isConnected() + XCTAssertFalse(isConnected, "A socket returned after stop must never become active.") + let receiveCount = await lateConnection.receiveCallCount() + XCTAssertEqual(receiveCount, 0) + } + + func testRestartWhileOldSocketClosesKeepsTheNewConnection() async throws { + let closing = BlockingStopConnection() + let recovered = AutoReplyConnection() + let connector = SequencedConnector(connections: [closing, recovered]) + let client = WebSocketRPCClient( + connector: connector, + connectionWaitTimeout: .seconds(2), + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + await client.start() + await closing.waitUntilReceiving() + + let stop = Task { await client.stop() } + await closing.waitUntilCloseStarted() + let request = Task { + try await client.request("server.afterRestart", as: JSONValue.self) + } + await connector.waitUntilConnectionCount(2) + await closing.releaseClose() + await stop.value + + let response = try await request.value + XCTAssertEqual(response, .object([:])) + let isConnected = await client.isConnected() + XCTAssertTrue(isConnected, "Completing an old stop must not clear a newer socket.") + await client.stop() + } +} + +private actor CloseTrackingConnection: WebSocketConnection { + private var closed = false + private var closeWaiters: [CheckedContinuation] = [] + private var receives = 0 + + func send(_: Data) {} + + func receive() throws -> Data { + receives += 1 + throw URLError(.cannotLoadFromNetwork) + } + + func close() { + closed = true + let waiters = closeWaiters + closeWaiters.removeAll() + waiters.forEach { $0.resume() } + } + + func waitUntilClosed() async { + guard !closed else { return } + await withCheckedContinuation { continuation in + closeWaiters.append(continuation) + } + } + + func receiveCallCount() -> Int { + receives + } +} + +private actor BlockingStopConnection: WebSocketConnection { + private var receiveContinuation: CheckedContinuation? + private var receiveWaiters: [CheckedContinuation] = [] + private var closeStarted = false + private var closeReleased = false + private var closeStartWaiters: [CheckedContinuation] = [] + private var closeReleaseWaiters: [CheckedContinuation] = [] + + func send(_: Data) throws { + throw URLError(.networkConnectionLost) + } + + func receive() async throws -> Data { + let waiters = receiveWaiters + receiveWaiters.removeAll() + waiters.forEach { $0.resume() } + return try await withCheckedThrowingContinuation { continuation in + receiveContinuation = continuation + } + } + + func close() async { + if !closeStarted { + closeStarted = true + let waiters = closeStartWaiters + closeStartWaiters.removeAll() + waiters.forEach { $0.resume() } + } + if !closeReleased { + await withCheckedContinuation { continuation in + closeReleaseWaiters.append(continuation) + } + } + receiveContinuation?.resume(throwing: CancellationError()) + receiveContinuation = nil + } + + func waitUntilReceiving() async { + guard receiveContinuation == nil else { return } + await withCheckedContinuation { continuation in + receiveWaiters.append(continuation) + } + } + + func waitUntilCloseStarted() async { + guard !closeStarted else { return } + await withCheckedContinuation { continuation in + closeStartWaiters.append(continuation) + } + } + + func releaseClose() { + closeReleased = true + let waiters = closeReleaseWaiters + closeReleaseWaiters.removeAll() + waiters.forEach { $0.resume() } + } } private actor DeadlineWebSocketConnection: WebSocketConnection {