From 4225dea2a4c5bf98be0003511cda020812e29b8c Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 1 Aug 2026 09:56:59 -0700 Subject: [PATCH] fix(swift-ios): harden transport and persistence --- .../Cloud/T3ConnectManagedAuthorization.swift | 37 ++-- apps/swift-ios/Core/JSONValue.swift | 14 ++ apps/swift-ios/Core/T3Client.swift | 21 +- apps/swift-ios/Core/WebSocketRPC.swift | 90 +++++++-- .../Tests/CoreTests/CoreContractTests.swift | 82 ++++++++ .../CoreTests/T3ConnectRuntimeTests.swift | 181 +++++++++++++++++ .../CoreTests/WebSocketRPCRaceTests.swift | 185 ++++++++++++++++++ .../NativeRetryIdentityTests.swift | 76 +++++-- 8 files changed, 641 insertions(+), 45 deletions(-) diff --git a/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift b/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift index 06a6af440a..0a3d6f5509 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift @@ -221,7 +221,12 @@ public actor T3ConnectManagedEnvironmentAuthorizer { } private func endpoint(_ baseURL: URL, path: [String]) -> URL { - path.reduce(baseURL) { partial, component in + var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) + components?.path = "" + components?.query = nil + components?.fragment = nil + let origin = components?.url ?? baseURL + return path.reduce(origin) { partial, component in partial.appendingPathComponent(component) } } @@ -262,9 +267,14 @@ public actor T3ConnectRuntimeAuthorization: ManagedEnvironmentAuthorizing { public typealias BootstrapProvider = @Sendable (String) async throws -> T3ConnectManagedEnvironmentCredential + private struct InFlightRefresh: Sendable { + let id: UUID + let task: Task + } + private let authorizer: T3ConnectManagedEnvironmentAuthorizer private let bootstrapProvider: BootstrapProvider - private var refreshTasks: [String: Task] = [:] + private var refreshTasks: [String: InFlightRefresh] = [:] @MainActor public init(controller: T3ConnectController) { @@ -307,8 +317,8 @@ public actor T3ConnectRuntimeAuthorization: ManagedEnvironmentAuthorizing { replacing credential: EnvironmentCredential ) async throws -> EnvironmentCredential { _ = try Self.authorization(environment: environment, credential: credential) - if let task = refreshTasks[environment.id] { - return try await task.value + if let refresh = refreshTasks[environment.id] { + return try await refresh.task.value } let authorizer = self.authorizer @@ -332,15 +342,18 @@ public actor T3ConnectRuntimeAuthorization: ManagedEnvironmentAuthorizing { environment: environment ) } - refreshTasks[environment.id] = task - do { - let refreshed = try await task.value - refreshTasks.removeValue(forKey: environment.id) - return refreshed - } catch { - refreshTasks.removeValue(forKey: environment.id) - throw error + let refreshID = UUID() + refreshTasks[environment.id] = InFlightRefresh(id: refreshID, task: task) + Task.detached { [weak self] in + _ = await task.result + await self?.finishRefresh(environmentID: environment.id, id: refreshID) } + return try await task.value + } + + private func finishRefresh(environmentID: String, id: UUID) { + guard refreshTasks[environmentID]?.id == id else { return } + refreshTasks.removeValue(forKey: environmentID) } private static func authorization( diff --git a/apps/swift-ios/Core/JSONValue.swift b/apps/swift-ios/Core/JSONValue.swift index 16ba8ad98b..afe65c00b0 100644 --- a/apps/swift-ios/Core/JSONValue.swift +++ b/apps/swift-ios/Core/JSONValue.swift @@ -5,6 +5,8 @@ import Foundation public enum JSONValue: Codable, Equatable, Sendable { case null case bool(Bool) + case integer(Int64) + case unsignedInteger(UInt64) case number(Double) case string(String) case array([JSONValue]) @@ -16,6 +18,14 @@ public enum JSONValue: Codable, Equatable, Sendable { self = .null } else if let value = try? container.decode(Bool.self) { self = .bool(value) + } else if let value = try? container.decode(Int64.self) { + let double = Double(value) + self = Int64(exactly: double) == value ? .number(double) : .integer(value) + } else if let value = try? container.decode(UInt64.self) { + let double = Double(value) + self = UInt64(exactly: double) == value + ? .number(double) + : .unsignedInteger(value) } else if let value = try? container.decode(Double.self) { self = .number(value) } else if let value = try? container.decode(String.self) { @@ -34,6 +44,10 @@ public enum JSONValue: Codable, Equatable, Sendable { try container.encodeNil() case let .bool(value): try container.encode(value) + case let .integer(value): + try container.encode(value) + case let .unsignedInteger(value): + try container.encode(value) case let .number(value): try container.encode(value) case let .string(value): diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift index 93ee0350f5..de9fb56318 100644 --- a/apps/swift-ios/Core/T3Client.swift +++ b/apps/swift-ios/Core/T3Client.swift @@ -1009,7 +1009,8 @@ public actor EnvironmentRuntime { throw HTTPError.incompatibleCredential } - let previousEnvironments = try await environmentStore.load() + let previousEnvironment = try await environmentStore.load() + .first(where: { $0.id == environment.id }) let previousActiveID = try await environmentStore.activeEnvironmentID() let previousCredential = try await credentialStore.credential(for: environment.id) try await credentialStore.setCredential(credential, for: environment.id) @@ -1025,8 +1026,18 @@ public actor EnvironmentRuntime { } else { try? await credentialStore.removeCredential(for: environment.id) } - try? await environmentStore.save(previousEnvironments) - try? await environmentStore.setActiveEnvironment(id: previousActiveID) + // EnvironmentStore's individual mutations are actor-atomic. Undo + // only this record so a concurrent save for another environment + // cannot be lost while this actor is reentrant across awaits. + let activeIDAfterFailure = try? await environmentStore.activeEnvironmentID() + if let previousEnvironment { + _ = try? await environmentStore.upsert(previousEnvironment) + } else { + _ = try? await environmentStore.remove(id: environment.id) + } + if activeIDAfterFailure == environment.id { + try? await environmentStore.setActiveEnvironment(id: previousActiveID) + } throw error } return await client(for: environment) @@ -1036,8 +1047,10 @@ public actor EnvironmentRuntime { if let client = clients.removeValue(forKey: id) { await client.disconnect() } - try await credentialStore.removeCredential(for: id) + // Never leave a catalog entry pointing at a credential that was + // already destroyed when the catalog write itself fails. try await environmentStore.remove(id: id) + try await credentialStore.removeCredential(for: id) } /// Returns the cached client for a saved environment without changing the diff --git a/apps/swift-ios/Core/WebSocketRPC.swift b/apps/swift-ios/Core/WebSocketRPC.swift index 0c86060f85..7e975c8255 100644 --- a/apps/swift-ios/Core/WebSocketRPC.swift +++ b/apps/swift-ios/Core/WebSocketRPC.swift @@ -156,6 +156,7 @@ public actor WebSocketRPCClient { let envelope: RPCRequestEnvelope var sent: Bool var connectionWaitTask: Task? + var sendDeadlineTask: Task? var responseDeadlineTask: Task? let resume: @Sendable (Result) -> Void } @@ -174,6 +175,7 @@ public actor WebSocketRPCClient { private let connectionWaitTimeout: Duration private let responseTimeout: Duration private var connection: (any WebSocketConnection)? + private var connectionID: UUID? private var loopTask: Task? private var keepaliveTask: Task? private var desired = false @@ -219,6 +221,7 @@ public actor WebSocketRPCClient { await connection.close() } connection = nil + connectionID = nil failUnary(RPCError.disconnected, includingUnsent: true) let active = subscriptions.values subscriptions.removeAll() @@ -295,6 +298,7 @@ public actor WebSocketRPCClient { envelope: envelope, sent: false, connectionWaitTask: nil, + sendDeadlineTask: nil, responseDeadlineTask: nil, resume: { continuation.resume(with: $0) } ) @@ -314,12 +318,18 @@ public actor WebSocketRPCClient { do { let url = try await endpointProvider() let opened = try await connector.connect(to: url) + let openedID = UUID() connection = opened + connectionID = openedID 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 { + throw RPCError.disconnected + } try await receiveLoop(opened) - } catch is CancellationError { - break } catch { await disconnected() guard desired, !Task.isCancelled else { break } @@ -343,10 +353,15 @@ public actor WebSocketRPCClient { } } - private func disconnected() async { + private func disconnected(expectedConnectionID: UUID? = nil) async { + if let expectedConnectionID, connectionID != expectedConnectionID { + return + } + let closingConnection = connection keepaliveTask?.cancel() keepaliveTask = nil connection = nil + connectionID = nil failUnary(RPCError.disconnected, includingUnsent: false) subscriptionByRequestID.removeAll() let oneShotSubscriptions = subscriptions.filter { !$0.value.reconnect } @@ -357,6 +372,7 @@ public actor WebSocketRPCClient { for id in subscriptions.keys { subscriptions[id]?.requestID = nil } + await closingConnection?.close() } private func receiveLoop(_ opened: any WebSocketConnection) async throws { @@ -402,23 +418,31 @@ public actor WebSocketRPCClient { } private func sendUnary(_ id: Int) async { - guard let connection, var request = unary[id], !request.sent else { return } + guard let connection, + let connectionID, + var request = unary[id], + !request.sent else { return } // Actor methods are reentrant at the send below. Record that this // command crossed the socket boundary first so a concurrent // disconnect fails it instead of replaying an ambiguous mutation. request.sent = true unary[id] = request + startUnarySendDeadline(id, connectionID: connectionID) do { try await connection.send(JSONEncoder.t3.encode(request.envelope)) + startUnaryResponseDeadline(id) } catch { // A response, disconnect, or stop may have completed the request // while send was suspended. Only its current owner may resume it. - completeUnary(id, with: .failure(error)) + completeUnary(id, with: .failure(RPCError.disconnected)) + await disconnected(expectedConnectionID: connectionID) } } private func sendSubscription(_ subscriptionID: UUID) async { - guard let connection, var subscription = subscriptions[subscriptionID] else { return } + guard let connection, + let connectionID, + var subscription = subscriptions[subscriptionID] else { return } let requestID = allocateRequestID() let envelope = RPCRequestEnvelope( id: requestID, @@ -432,8 +456,9 @@ public actor WebSocketRPCClient { subscriptions[subscriptionID] = subscription subscriptionByRequestID[requestID] = subscriptionID } catch { - // The connection loop owns retries; retaining this subscription is - // enough for it to be sent on the next socket. + // Retain the subscription for the next socket, but make the send + // failure visible to the connection loop by closing this socket. + await disconnected(expectedConnectionID: connectionID) } } @@ -454,10 +479,15 @@ public actor WebSocketRPCClient { } private func sendControl(_ tag: String, requestID: Int?) async throws { - guard let connection else { throw RPCError.disconnected } - try await connection.send( - JSONEncoder.t3.encode(RPCControlEnvelope(tag, requestID: requestID)) - ) + guard let connection, let connectionID else { throw RPCError.disconnected } + do { + try await connection.send( + JSONEncoder.t3.encode(RPCControlEnvelope(tag, requestID: requestID)) + ) + } catch { + await disconnected(expectedConnectionID: connectionID) + throw RPCError.disconnected + } } private func failUnary(_ error: Error, includingUnsent: Bool) { @@ -477,7 +507,6 @@ public actor WebSocketRPCClient { private func installUnaryDeadlines(_ id: Int) { guard var request = unary[id] else { return } let connectionWaitTimeout = connectionWaitTimeout - let responseTimeout = responseTimeout request.connectionWaitTask = Task { [weak self] in do { try await Task.sleep(for: connectionWaitTimeout) @@ -486,6 +515,16 @@ public actor WebSocketRPCClient { } await self?.failUnaryIfUnsent(id) } + unary[id] = request + } + + private func startUnaryResponseDeadline(_ id: Int) { + guard var request = unary[id], request.sent else { return } + request.connectionWaitTask?.cancel() + request.connectionWaitTask = nil + request.sendDeadlineTask?.cancel() + request.sendDeadlineTask = nil + let responseTimeout = responseTimeout request.responseDeadlineTask = Task { [weak self] in do { try await Task.sleep(for: responseTimeout) @@ -497,6 +536,30 @@ public actor WebSocketRPCClient { unary[id] = request } + private func startUnarySendDeadline(_ id: Int, connectionID: UUID) { + guard var request = unary[id], request.sent else { return } + request.connectionWaitTask?.cancel() + request.connectionWaitTask = nil + let sendTimeout = responseTimeout + request.sendDeadlineTask = Task { [weak self] in + do { + try await Task.sleep(for: sendTimeout) + } catch { + return + } + await self?.failUnaryOnSendDeadline(id, connectionID: connectionID) + } + unary[id] = request + } + + private func failUnaryOnSendDeadline(_ id: Int, connectionID: UUID) async { + guard let request = unary[id], + request.sent, + request.responseDeadlineTask == nil else { return } + completeUnary(id, with: .failure(RPCError.responseTimedOut)) + await disconnected(expectedConnectionID: connectionID) + } + private func failUnaryOnResponseDeadline(_ id: Int) async { guard let request = unary[id] else { return } let sent = request.sent @@ -518,6 +581,7 @@ public actor WebSocketRPCClient { private func completeUnary(_ id: Int, with result: Result) { guard let request = unary.removeValue(forKey: id) else { return } request.connectionWaitTask?.cancel() + request.sendDeadlineTask?.cancel() request.responseDeadlineTask?.cancel() request.resume(result) } diff --git a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift index bcd8a2553a..1bc223c2d8 100644 --- a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift +++ b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift @@ -3,6 +3,18 @@ import XCTest @MainActor final class CoreContractTests: XCTestCase { + func testJSONValueRoundTripsLargeIntegersWithoutDoubleRounding() throws { + let signedData = Data("9007199254740993".utf8) + let signed = try JSONDecoder.t3.decode(JSONValue.self, from: signedData) + XCTAssertEqual(signed, .integer(9_007_199_254_740_993)) + XCTAssertEqual(try JSONEncoder.t3.encode(signed), signedData) + + let unsignedData = Data("18446744073709551615".utf8) + let unsigned = try JSONDecoder.t3.decode(JSONValue.self, from: unsignedData) + XCTAssertEqual(unsigned, .unsignedInteger(UInt64.max)) + XCTAssertEqual(try JSONEncoder.t3.encode(unsigned), unsignedData) + } + func testDirectAndHostedPairingURLsResolveLikeExistingClients() throws { let direct = try PairingURL.resolve("https://studio.example/pair#token=secret") XCTAssertEqual(direct.credential, "secret") @@ -195,4 +207,74 @@ final class CoreContractTests: XCTestCase { XCTAssertEqual(movedEnvironment.httpBaseURL, moved.httpBaseURL) XCTAssertEqual(movedEnvironment.webSocketBaseURL, moved.webSocketBaseURL) } + + func testRuntimeRemovesCatalogEntryBeforeDestroyingCredential() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-swift-removal-\(UUID().uuidString)", isDirectory: true) + let file = directory.appendingPathComponent("environments.json") + defer { try? FileManager.default.removeItem(at: directory) } + + let environment = Environment( + id: "removable", + label: "Removable", + httpBaseURL: URL(string: "https://remove.example")!, + webSocketBaseURL: URL(string: "wss://remove.example")! + ) + let store = EnvironmentStore(fileURL: file) + try await store.save([environment]) + let credentials = RemovalOrderCredentialStore( + environmentStore: store, + environmentID: environment.id, + credential: EnvironmentCredential(accessToken: "secret") + ) + let runtime = EnvironmentRuntime( + environmentStore: store, + credentialStore: credentials + ) + + try await runtime.remove(id: environment.id) + + let catalogContainedEnvironment = await credentials.catalogContainedEnvironmentOnRemoval + XCTAssertEqual(catalogContainedEnvironment, false) + let remaining = try await store.load() + XCTAssertTrue(remaining.isEmpty) + let credential = await credentials.credential(for: environment.id) + XCTAssertNil(credential) + } +} + +private actor RemovalOrderCredentialStore: CredentialStore { + let environmentStore: EnvironmentStore + let environmentID: String + var storedCredential: EnvironmentCredential? + private(set) var catalogContainedEnvironmentOnRemoval: Bool? + + init( + environmentStore: EnvironmentStore, + environmentID: String, + credential: EnvironmentCredential + ) { + self.environmentStore = environmentStore + self.environmentID = environmentID + storedCredential = credential + } + + func credential(for environmentID: String) -> EnvironmentCredential? { + environmentID == self.environmentID ? storedCredential : nil + } + + func setCredential( + _ credential: EnvironmentCredential, + for environmentID: String + ) { + guard environmentID == self.environmentID else { return } + storedCredential = credential + } + + func removeCredential(for environmentID: String) async throws { + guard environmentID == self.environmentID else { return } + catalogContainedEnvironmentOnRemoval = try await environmentStore.load() + .contains(where: { $0.id == environmentID }) + storedCredential = nil + } } diff --git a/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift b/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift index a26b081a45..6e4a4d8e2e 100644 --- a/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift +++ b/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift @@ -96,6 +96,60 @@ final class T3ConnectRuntimeTests: XCTestCase { }) } + func testManagedRoutesReplaceAdvertisedBasePath() async throws { + let signer = try testSigner() + let transport = T3ConnectScriptedHTTPTransport { request, ordinal in + switch ordinal { + case 1: + return (.descriptor, 200) + case 2: + return ( + .token( + scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes + .joined(separator: " ") + ), + 200 + ) + case 3: + return (.webSocketTicket("canonical-ticket"), 200) + default: + throw T3ConnectTestError.unexpectedPath(request.url?.path) + } + } + let authorizer = T3ConnectManagedEnvironmentAuthorizer( + transport: transport, + signer: signer + ) + let endpoint = T3ConnectManagedEndpoint( + httpBaseUrl: "https://managed.example/advertised/prefix?stale=true", + wsBaseUrl: "wss://managed.example/ws", + providerKind: .t3Relay + ) + let bootstrap = T3ConnectManagedEnvironmentCredential( + environmentID: "managed-1", + label: "Managed Studio", + endpoint: endpoint, + bootstrapCredential: "one-use-bootstrap", + bootstrapExpiresAt: "2026-08-01T12:00:00.000Z", + proofKeyThumbprint: try await signer.thumbprint() + ) + + _ = try await authorizer.descriptor(at: try XCTUnwrap(endpoint.httpBaseURL)) + let authorization = try await authorizer.exchange(bootstrap) + _ = try await authorizer.webSocketURL(using: authorization) + + let requests = await transport.requests + XCTAssertEqual( + requests.map(\.url?.path), + [ + "/.well-known/t3/environment", + "/oauth/token", + "/api/auth/websocket-ticket", + ] + ) + XCTAssertTrue(requests.allSatisfy { $0.url?.query == nil }) + } + func testSixtySecondMarginRefreshesAndPersistsBeforeFirstRequest() async throws { let fixture = try await refreshFixture( savedThumbprint: nil, @@ -138,6 +192,70 @@ final class T3ConnectRuntimeTests: XCTestCase { XCTAssertEqual(paths.filter { $0 == "/api/auth/session" }.count, 2) } + func testCancellingRefreshWaiterDoesNotBreakSingleFlight() async throws { + let signer = try testSigner() + let environment = managedEnvironment(descriptor: descriptor()) + let replacing = EnvironmentCredential.managedDPoP( + accessToken: "expired-token", + expiresAt: Date().addingTimeInterval(-1), + scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes, + environmentID: environment.id, + proofKeyThumbprint: try await signer.thumbprint() + ) + let source = BlockingT3ConnectBootstrapSource( + credential: try await bootstrapCredential(signer: signer) + ) + let transport = T3ConnectScriptedHTTPTransport { request, _ in + switch request.url?.path { + case "/.well-known/t3/environment": + return (.descriptor, 200) + case "/oauth/token": + return ( + .token( + scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes + .joined(separator: " ") + ), + 200 + ) + default: + throw T3ConnectTestError.unexpectedPath(request.url?.path) + } + } + let authorization = T3ConnectRuntimeAuthorization( + authorizer: T3ConnectManagedEnvironmentAuthorizer( + transport: transport, + signer: signer + ), + bootstrapProvider: { id in try await source.value(for: id) } + ) + + let first = Task { + try await authorization.refreshCredential( + for: environment, + replacing: replacing + ) + } + await source.waitUntilCallCount(1) + first.cancel() + let secondStarted = AsyncTestMarker() + let second = Task { + await secondStarted.mark() + return try await authorization.refreshCredential( + for: environment, + replacing: replacing + ) + } + await secondStarted.waitUntilMarked() + await Task.yield() + await source.release() + + let firstCredential = try await first.value + let secondCredential = try await second.value + XCTAssertEqual(firstCredential, secondCredential) + let calls = await source.calls + XCTAssertEqual(calls, 1) + } + func testRotatedProofKeyRebindsFreshCredential() async throws { let fixture = try await refreshFixture( savedThumbprint: "stale-proof-key", @@ -645,6 +763,69 @@ private actor T3ConnectBootstrapSource { } } +private actor BlockingT3ConnectBootstrapSource { + private let credential: T3ConnectManagedEnvironmentCredential + private var released = false + private var releaseWaiters: [CheckedContinuation] = [] + private var callWaiters: [(Int, CheckedContinuation)] = [] + private(set) var calls = 0 + + init(credential: T3ConnectManagedEnvironmentCredential) { + self.credential = credential + } + + func value(for environmentID: String) async throws + -> T3ConnectManagedEnvironmentCredential + { + guard environmentID == credential.environmentID else { + throw T3ConnectTestError.unexpectedPath(environmentID) + } + calls += 1 + let ready = callWaiters.filter { calls >= $0.0 } + callWaiters.removeAll { calls >= $0.0 } + ready.forEach { $0.1.resume() } + if !released { + await withCheckedContinuation { continuation in + releaseWaiters.append(continuation) + } + } + return credential + } + + func waitUntilCallCount(_ count: Int) async { + guard calls < count else { return } + await withCheckedContinuation { continuation in + callWaiters.append((count, continuation)) + } + } + + func release() { + released = true + let waiters = releaseWaiters + releaseWaiters.removeAll() + waiters.forEach { $0.resume() } + } +} + +private actor AsyncTestMarker { + private var marked = false + private var waiters: [CheckedContinuation] = [] + + func mark() { + marked = true + let pending = waiters + waiters.removeAll() + pending.forEach { $0.resume() } + } + + func waitUntilMarked() async { + guard !marked else { return } + await withCheckedContinuation { continuation in + waiters.append(continuation) + } + } +} + private actor T3ConnectScriptedHTTPTransport: HTTPTransport { typealias Handler = @Sendable (URLRequest, Int) throws -> (Data, Int) diff --git a/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift index 32264b80f6..02342bac4c 100644 --- a/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift +++ b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift @@ -3,6 +3,93 @@ import XCTest @MainActor final class WebSocketRPCRaceTests: XCTestCase { + func testResponseDeadlineStartsAfterConnectionAndSend() async throws { + let connection = AutoReplyConnection() + let connector = GatedConnector(connection: connection) + let client = WebSocketRPCClient( + connector: connector, + connectionWaitTimeout: .seconds(1), + responseTimeout: .milliseconds(40), + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + let request = Task { + try await client.request("server.repliesAfterConnect", as: JSONValue.self) + } + await connector.waitUntilConnectStarted() + try await Task.sleep(for: .milliseconds(80)) + await connector.release() + + let response = try await request.value + XCTAssertEqual(response, .object([:])) + await client.stop() + } + + func testSendFailureDropsDeadSocketAndReconnects() async throws { + let failed = SendFailingConnection() + let recovered = AutoReplyConnection() + let connector = SequencedConnector(connections: [failed, recovered]) + let client = WebSocketRPCClient( + connector: connector, + connectionWaitTimeout: .seconds(2), + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + do { + _ = try await client.request("server.firstSendFails", as: JSONValue.self) + XCTFail("A failed socket send must fail its unary request.") + } catch let error as RPCError { + guard case .disconnected = error else { + await client.stop() + return XCTFail("Unexpected RPC error: \(error)") + } + } + + await connector.waitUntilConnectionCount(2) + let discardedReceiveCount = await failed.receiveCallCount() + XCTAssertEqual( + discardedReceiveCount, + 0, + "Setup must not start receiving on a socket discarded by a queued send." + ) + let isConnected = await client.isConnected() + XCTAssertTrue(isConnected) + let response = try await client.request("server.afterReconnect", as: JSONValue.self) + XCTAssertEqual(response, .object([:])) + await client.stop() + } + + func testHungSendTimesOutAndReconnectsWithAFreshResponseWindow() async throws { + let hung = HungSendConnection() + let recovered = AutoReplyConnection() + let connector = SequencedConnector(connections: [hung, recovered]) + let client = WebSocketRPCClient( + connector: connector, + connectionWaitTimeout: .seconds(2), + responseTimeout: .milliseconds(40), + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + let first = Task { + try await client.request("server.sendNeverReturns", as: JSONValue.self) + } + await hung.waitUntilSending() + do { + _ = try await first.value + XCTFail("A send that never completes must have an in-flight deadline.") + } catch let error as RPCError { + guard case .responseTimedOut = error else { + await client.stop() + return XCTFail("Unexpected RPC error: \(error)") + } + } + + await connector.waitUntilConnectionCount(2) + let response = try await client.request("server.afterHungSend", as: JSONValue.self) + XCTAssertEqual(response, .object([:])) + await client.stop() + } + func testSentUnaryTimesOutAndLateTrafficCannotCompleteItTwice() async throws { let connection = DeadlineWebSocketConnection() let client = WebSocketRPCClient( @@ -242,6 +329,104 @@ private actor SequencedConnector: WebSocketConnecting { } } +private actor GatedConnector: WebSocketConnecting { + private let connection: any WebSocketConnection + private var releaseContinuation: CheckedContinuation? + private var connectWaiters: [CheckedContinuation] = [] + private var connectStarted = false + private var released = false + + init(connection: any WebSocketConnection) { + self.connection = connection + } + + func connect(to _: URL) async -> any WebSocketConnection { + connectStarted = true + let waiters = connectWaiters + connectWaiters.removeAll() + waiters.forEach { $0.resume() } + if !released { + await withCheckedContinuation { continuation in + releaseContinuation = continuation + } + } + return connection + } + + func waitUntilConnectStarted() async { + guard !connectStarted else { return } + await withCheckedContinuation { continuation in + connectWaiters.append(continuation) + } + } + + func release() { + released = true + releaseContinuation?.resume() + releaseContinuation = nil + } +} + +private actor SendFailingConnection: WebSocketConnection { + private var closed = false + private var receives = 0 + private var receiver: CheckedContinuation? + + func send(_: Data) throws { + throw URLError(.networkConnectionLost) + } + + func receive() async throws -> Data { + receives += 1 + if closed { throw URLError(.networkConnectionLost) } + return try await withCheckedThrowingContinuation { continuation in + receiver = continuation + } + } + + func close() { + closed = true + receiver?.resume(throwing: URLError(.networkConnectionLost)) + receiver = nil + } + + func receiveCallCount() -> Int { + receives + } +} + +private actor HungSendConnection: WebSocketConnection { + private var closed = false + private var sendContinuation: CheckedContinuation? + private var sendWaiters: [CheckedContinuation] = [] + + func send(_: Data) async throws { + let waiters = sendWaiters + sendWaiters.removeAll() + waiters.forEach { $0.resume() } + try await withCheckedThrowingContinuation { continuation in + sendContinuation = continuation + } + } + + func receive() throws -> Data { + throw URLError(closed ? .networkConnectionLost : .cannotLoadFromNetwork) + } + + func close() { + closed = true + sendContinuation?.resume(throwing: URLError(.networkConnectionLost)) + sendContinuation = nil + } + + func waitUntilSending() async { + guard sendContinuation == nil else { return } + await withCheckedContinuation { continuation in + sendWaiters.append(continuation) + } + } +} + private actor SuspendedSendConnection: WebSocketConnection { private var sendContinuation: CheckedContinuation? private var receiveContinuation: CheckedContinuation? diff --git a/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift b/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift index 0195e420c5..c001856c00 100644 --- a/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift @@ -82,6 +82,7 @@ final class NativeRetryIdentityTests: XCTestCase { try await store.setActiveEnvironment(id: environment.id) let connection = AmbiguousDispatchWebSocketConnection() + let transport = RetryIdentityHTTPTransport(shell: retryShellSnapshot()) let runtime = EnvironmentRuntime( environmentStore: store, credentialStore: InMemoryCredentialStore( @@ -89,7 +90,7 @@ final class NativeRetryIdentityTests: XCTestCase { environment.id: EnvironmentCredential(accessToken: "token"), ] ), - httpTransport: RetryIdentityHTTPTransport(shell: retryShellSnapshot()), + httpTransport: transport, webSocketConnector: RetryIdentityWebSocketConnector(connection: connection) ) let settings = UserDefaults( @@ -135,19 +136,32 @@ final class NativeRetryIdentityTests: XCTestCase { } let commands = await connection.dispatchCommands() + + transport.dispatchCommands() XCTAssertEqual(commands.count, 4) - assertStableIdentity(commands[0], commands[1], includesThreadID: false) - XCTAssertEqual(commands[0]["commandId"]?.stringValue, turnIdentity.commandID) + let turnCommands = commands.filter { + $0["message"]?["text"]?.stringValue == "Retry without duplicating" + } + XCTAssertEqual(turnCommands.count, 2) + let initialTurn = try XCTUnwrap(turnCommands.first) + let retriedTurn = try XCTUnwrap(turnCommands.dropFirst().first) + assertStableIdentity(initialTurn, retriedTurn, includesThreadID: false) + XCTAssertEqual(initialTurn["commandId"]?.stringValue, turnIdentity.commandID) XCTAssertEqual( - commands[0]["message"]?["messageId"]?.stringValue, + initialTurn["message"]?["messageId"]?.stringValue, turnIdentity.messageID ) - XCTAssertNotEqual(commands[2]["commandId"], commands[3]["commandId"]) + let bootstrapCommands = commands.filter { + $0["message"]?["text"]?.stringValue == "Create exactly one task" + } + XCTAssertEqual(bootstrapCommands.count, 2) + let initialBootstrap = try XCTUnwrap(bootstrapCommands.first) + let retriedBootstrap = try XCTUnwrap(bootstrapCommands.dropFirst().first) + XCTAssertNotEqual(initialBootstrap["commandId"], retriedBootstrap["commandId"]) XCTAssertNotEqual( - commands[2]["message"]?["messageId"], - commands[3]["message"]?["messageId"] + initialBootstrap["message"]?["messageId"], + retriedBootstrap["message"]?["messageId"] ) - XCTAssertNotEqual(commands[2]["threadId"], commands[3]["threadId"]) + XCTAssertNotEqual(initialBootstrap["threadId"], retriedBootstrap["threadId"]) for command in commands { XCTAssertEqual(command["runtimeMode"]?.stringValue, "full-access") XCTAssertEqual(command["interactionMode"]?.stringValue, "default") @@ -173,6 +187,7 @@ final class NativeRetryIdentityTests: XCTestCase { try await store.setActiveEnvironment(id: environment.id) let connection = PartialBootstrapWebSocketConnection() + let transport = PartialBootstrapHTTPTransport(shell: retryShellSnapshot()) let runtime = EnvironmentRuntime( environmentStore: store, credentialStore: InMemoryCredentialStore( @@ -180,7 +195,7 @@ final class NativeRetryIdentityTests: XCTestCase { environment.id: EnvironmentCredential(accessToken: "token"), ] ), - httpTransport: PartialBootstrapHTTPTransport(shell: retryShellSnapshot()), + httpTransport: transport, webSocketConnector: PartialBootstrapWebSocketConnector(connection: connection) ) let settings = UserDefaults( @@ -211,17 +226,18 @@ final class NativeRetryIdentityTests: XCTestCase { ) let commands = await connection.dispatchCommands() + + transport.dispatchCommands() XCTAssertEqual(commands.count, 2) - XCTAssertNotNil(commands[0]["bootstrap"]) - XCTAssertNil(commands[1]["bootstrap"]) - assertStableIdentity(commands[0], commands[1], includesThreadID: true) - XCTAssertEqual(commands[0]["threadId"]?.stringValue, identity.threadID) - XCTAssertEqual(commands[0]["commandId"]?.stringValue, identity.commandID) + let bootstrap = try XCTUnwrap(commands.first { $0["bootstrap"] != nil }) + let finalTurn = try XCTUnwrap(commands.first { $0["bootstrap"] == nil }) + assertStableIdentity(bootstrap, finalTurn, includesThreadID: true) + XCTAssertEqual(bootstrap["threadId"]?.stringValue, identity.threadID) + XCTAssertEqual(bootstrap["commandId"]?.stringValue, identity.commandID) XCTAssertEqual( - commands[0]["message"]?["messageId"]?.stringValue, + bootstrap["message"]?["messageId"]?.stringValue, identity.messageID ) - let wireID = try XCTUnwrap(commands[0]["threadId"]?.stringValue) + let wireID = try XCTUnwrap(bootstrap["threadId"]?.stringValue) XCTAssertEqual(created.wireID, wireID) XCTAssertEqual( created.id, @@ -427,6 +443,7 @@ private func retryShellSnapshot() -> OrchestrationShellSnapshot { private actor RetryIdentityHTTPTransport: HTTPTransport { private let shellData: Data + private var commands: [JSONValue] = [] init(shell: OrchestrationShellSnapshot) { shellData = try! JSONEncoder.t3.encode(shell) @@ -453,8 +470,16 @@ private actor RetryIdentityHTTPTransport: HTTPTransport { if path.hasPrefix("/api/orchestration/threads/") { throw URLError(.networkConnectionLost) } + if path == "/api/orchestration/dispatch" { + commands.append(try retryDispatchCommand(from: request)) + throw URLError(.networkConnectionLost) + } throw URLError(.unsupportedURL) } + + func dispatchCommands() -> [JSONValue] { + commands + } } private struct RetryIdentityWebSocketConnector: WebSocketConnecting { @@ -467,6 +492,7 @@ private struct RetryIdentityWebSocketConnector: WebSocketConnecting { private actor PartialBootstrapHTTPTransport: HTTPTransport { private let shellData: Data + private var commands: [JSONValue] = [] init(shell: OrchestrationShellSnapshot) { shellData = try! JSONEncoder.t3.encode(shell) @@ -495,8 +521,19 @@ private actor PartialBootstrapHTTPTransport: HTTPTransport { let snapshot = retryEmptyThreadDetail(id: threadID) return (try JSONEncoder.t3.encode(snapshot), retryHTTPResponse(request)) } + if path == "/api/orchestration/dispatch" { + commands.append(try retryDispatchCommand(from: request)) + return ( + Data("{\"sequence\":42}".utf8), + retryHTTPResponse(request) + ) + } throw URLError(.unsupportedURL) } + + func dispatchCommands() -> [JSONValue] { + commands + } } private struct PartialBootstrapWebSocketConnector: WebSocketConnecting { @@ -693,3 +730,10 @@ private func retryHTTPResponse(_ request: URLRequest) -> HTTPURLResponse { headerFields: ["Content-Type": "application/json"] )! } + +private func retryDispatchCommand(from request: URLRequest) throws -> JSONValue { + guard let body = request.httpBody else { + throw URLError(.cannotDecodeContentData) + } + return try JSONDecoder.t3.decode(JSONValue.self, from: body) +}