From 66b08d6b3978cc9f524bd5bf348b7c4c57589637 Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:53:46 +0900 Subject: [PATCH] Carry the server request timeout as one type ProxyRuntimeConfiguration stores the timeout as Duration?, so nil is the only encoding of no timeout and the broker no longer converts through TimeInterval and NIO TimeAmount. Co-Authored-By: Claude Mythos 5.2 --- .../XcodeMCPProxyServer.swift | 13 ++----- .../Broker/NativeHostBroker.swift | 36 ++++++++++--------- .../ProxyRuntimeConfiguration.swift | 5 +-- .../Support/MCPMethodDispatcher.swift | 35 ------------------ .../Support/TimeoutSupport.swift | 10 ------ .../DocumentationSearchRoutingTests.swift | 6 ++-- .../HTTPConcurrencyTests.swift | 26 +++++++------- .../HTTPHandlerTestSupport.swift | 4 +-- .../HTTPHandlerTests.swift | 20 +++++------ .../DocumentationSearchStressTests.swift | 2 +- .../NativeHostBrokerTests.swift | 10 +++--- .../NativeHostRuntimeTests.swift | 8 ++--- .../NativeHostTestSupport.swift | 2 +- 13 files changed, 64 insertions(+), 113 deletions(-) delete mode 100644 Sources/XcodeMCPProxyRuntime/Support/MCPMethodDispatcher.swift delete mode 100644 Sources/XcodeMCPProxyRuntime/Support/TimeoutSupport.swift diff --git a/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift b/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift index 91ee8c3e..b87231b9 100644 --- a/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift +++ b/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift @@ -478,22 +478,15 @@ extension XcodeMCPProxyServerConfiguration { guard maxBodyBytes > 0 else { throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("maxBodyBytes must be greater than zero") } - let timeout: TimeInterval - if let requestTimeout { - let components = requestTimeout.components - timeout = Double(components.seconds) + Double(components.attoseconds) / 1_000_000_000_000_000_000 - guard timeout > 0 else { - throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("requestTimeout must be positive; use nil to disable it") - } - } else { - timeout = 0 + if let requestTimeout, requestTimeout <= .zero { + throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("requestTimeout must be positive; use nil to disable it") } let configuration = ProxyRuntimeConfiguration( nativeHostBundleURL: nativeHostBundleURL, developerDirectoryURL: developerDirectoryURL, sharesCompilationCache: sharesCompilationCache, maxMessageBytes: maxBodyBytes, - requestTimeout: timeout, + requestTimeout: requestTimeout, prewarmToolsList: prewarmToolsList, initializeParamsOverride: initializeHandshake.map { handshake in .init( diff --git a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift index f760ff6c..a1266f83 100644 --- a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift +++ b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift @@ -1,6 +1,5 @@ import Foundation import Logging -import NIOCore import NIOConcurrencyHelpers import XcodeMCPCore import XcodeMCPProxyRuntimeContract @@ -44,7 +43,11 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { private static let guiHostIdentifier = "gui-xcode" /// Bounds a cleanup close while client requests have no timeout, so a host that never answers /// does not keep the model from being bound again. - static let cleanupFallbackTimeout: TimeInterval = 60 + static let cleanupFallbackTimeout: Duration = .seconds(60) + /// Bounds a host's initialize handshake even when client requests have no timeout. + private static let handshakeTimeoutLimit: Duration = .seconds(60) + /// Bounds an internal catalog load even when client requests have no timeout. + private static let catalogTimeoutLimit: Duration = .seconds(10) private struct Admission: Sendable { let hostIdentifier: String @@ -91,14 +94,11 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { developerDirectoryURL: installation.developerDirectory, sharesCompilationCache: configuration.sharesCompilationCache, maxBodyBytes: configuration.maxMessageBytes) - let timeout = configuration.requestTimeout let connection = NativeHostConnection( factory: sessionFactory(processConfiguration), handshake: .object(InitializeHandshakeJSON.resolved( initializeParamsOverride: configuration.initializeParamsOverride)), - handshakeTimeout: MCP.MethodDispatcher.timeoutForInitialize(defaultSeconds: timeout).map(Self.duration), - // An internal catalog load stays bounded even when client request timeouts are disabled. - catalogTimeout: MCP.MethodDispatcher.timeoutForControlPlane(defaultSeconds: timeout).map(Self.duration), + handshakeTimeout: handshakeTimeout, catalogTimeout: catalogTimeout, prewarmsCatalog: configuration.prewarmToolsList, clock: clock, logger: ProxyLogging.make("native-host"), onEvent: { [weak self] event in self?.receive(event, from: id) }) @@ -110,18 +110,22 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { } } - private static func duration(_ amount: TimeAmount) -> Duration { .nanoseconds(amount.nanoseconds) } + private var handshakeTimeout: Duration { + min(configuration.requestTimeout ?? Self.handshakeTimeoutLimit, Self.handshakeTimeoutLimit) + } + + private var catalogTimeout: Duration { + min(configuration.requestTimeout ?? Self.catalogTimeoutLimit, Self.catalogTimeoutLimit) + } private func guiConnection() throws -> NativeHostConnection { try state.withLockedValue { storage in guard !storage.stopped, storage.resetsInProgress == 0 else { throw CancellationError() } if let connection = storage.guiConnection { return connection } - let timeout = configuration.requestTimeout let connection = NativeHostConnection(factory: guiSessionFactory, handshake: .object(InitializeHandshakeJSON.resolved( initializeParamsOverride: configuration.initializeParamsOverride)), - handshakeTimeout: MCP.MethodDispatcher.timeoutForInitialize(defaultSeconds: timeout).map(Self.duration), - catalogTimeout: MCP.MethodDispatcher.timeoutForControlPlane(defaultSeconds: timeout).map(Self.duration), + handshakeTimeout: handshakeTimeout, catalogTimeout: catalogTimeout, prewarmsCatalog: false, clock: clock, logger: ProxyLogging.make("mcpbridge"), onEvent: { [weak self] event in self?.receive(event, from: Self.guiHostIdentifier) }) storage.guiConnection = connection @@ -182,8 +186,8 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { let cancelled = NativeBrokerReply.error(id: requestID, code: -32800, message: "request cancelled").clientReply var deadline: Date? if let object, case .request = JSONRPC.Message.Inspector.kind(of: object), - let timeout = makeRequestTimeout(configuration.requestTimeout) { - deadline = clock.now().addingTimeInterval(Double(timeout.nanoseconds) / 1_000_000_000) + let timeout = configuration.requestTimeout { + deadline = clock.now().addingTimeInterval(timeout / .seconds(1)) } // Admission pins the host under the broker lock, which the unused-host scan also holds, // so a host is kept for this request before idle retirement can stop its process. @@ -565,8 +569,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { "workspaceIdentifier": .string(workspace.nativeIdentifier), ])]), ]) - let timeout = makeRequestTimeout( - configuration.requestTimeout > 0 ? configuration.requestTimeout : Self.cleanupFallbackTimeout) + let timeout = configuration.requestTimeout ?? Self.cleanupFallbackTimeout do { let reply = try await withDeadline(timeout) { try await host.connection.sendToRunningProcess(request, generation: workspace.generation) @@ -587,14 +590,13 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { } /// Runs `operation`, failing it with `CancellationError` once `timeout` elapses. - private func withDeadline(_ timeout: TimeAmount?, + private func withDeadline(_ timeout: Duration, _ operation: @escaping @Sendable () async throws -> T) async throws -> T { - guard let timeout else { return try await operation() } let clock = clock return try await withThrowingTaskGroup(of: T.self) { group in group.addTask { try await operation() } group.addTask { - await clock.sleep(.nanoseconds(timeout.nanoseconds)) + await clock.sleep(timeout) throw CancellationError() } defer { group.cancelAll() } diff --git a/Sources/XcodeMCPProxyRuntime/Configuration/ProxyRuntimeConfiguration.swift b/Sources/XcodeMCPProxyRuntime/Configuration/ProxyRuntimeConfiguration.swift index 12e8a04d..b5bc2b56 100644 --- a/Sources/XcodeMCPProxyRuntime/Configuration/ProxyRuntimeConfiguration.swift +++ b/Sources/XcodeMCPProxyRuntime/Configuration/ProxyRuntimeConfiguration.swift @@ -59,7 +59,8 @@ package struct ProxyRuntimeConfiguration: Sendable { package var developerDirectoryURL: URL? package var sharesCompilationCache: Bool package var maxMessageBytes: Int - package var requestTimeout: TimeInterval + /// The limit for one client request, or `nil` for none. + package var requestTimeout: Duration? package var prewarmToolsList: Bool package var initializeParamsOverride: InitializeHandshakeOverride? @@ -68,7 +69,7 @@ package struct ProxyRuntimeConfiguration: Sendable { developerDirectoryURL: URL? = nil, sharesCompilationCache: Bool = false, maxMessageBytes: Int, - requestTimeout: TimeInterval, + requestTimeout: Duration?, prewarmToolsList: Bool = true, initializeParamsOverride: InitializeHandshakeOverride? = nil ) { diff --git a/Sources/XcodeMCPProxyRuntime/Support/MCPMethodDispatcher.swift b/Sources/XcodeMCPProxyRuntime/Support/MCPMethodDispatcher.swift deleted file mode 100644 index 4b186c84..00000000 --- a/Sources/XcodeMCPProxyRuntime/Support/MCPMethodDispatcher.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation -import NIOCore -import XcodeMCPWire - -extension MCP { - enum MethodDispatcher { - private static let initializeFallbackTimeoutSeconds: TimeInterval = 60 - private static let controlPlaneFallbackTimeoutSeconds: TimeInterval = 10 - - static func timeoutForInitialize(defaultSeconds: TimeInterval) -> TimeAmount? { - let effectiveDefault = defaultSeconds > 0 ? defaultSeconds : initializeFallbackTimeoutSeconds - return timeout(defaultSeconds: effectiveDefault, capSeconds: initializeFallbackTimeoutSeconds) - } - - static func timeoutForControlPlane( - defaultSeconds: TimeInterval - ) -> TimeAmount? { - let effectiveDefault = defaultSeconds > 0 - ? defaultSeconds - : controlPlaneFallbackTimeoutSeconds - return timeout( - defaultSeconds: effectiveDefault, - capSeconds: controlPlaneFallbackTimeoutSeconds - ) - } - - private static func timeout( - defaultSeconds: TimeInterval, - capSeconds: TimeInterval - ) -> TimeAmount? { - guard defaultSeconds > 0 else { return nil } - return makeRequestTimeout(min(defaultSeconds, capSeconds)) - } - } -} diff --git a/Sources/XcodeMCPProxyRuntime/Support/TimeoutSupport.swift b/Sources/XcodeMCPProxyRuntime/Support/TimeoutSupport.swift deleted file mode 100644 index 3bf5bd84..00000000 --- a/Sources/XcodeMCPProxyRuntime/Support/TimeoutSupport.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Foundation -import NIOCore - -func makeRequestTimeout(_ seconds: TimeInterval) -> TimeAmount? { - guard seconds > 0 else { return nil } - let whole = Int64(seconds) - let fractional = seconds - Double(whole) - let nanos = Int64((fractional * 1_000_000_000).rounded()) - return .seconds(whole) + .nanoseconds(nanos) -} diff --git a/Tests/ProxyIntegrationTests/DocumentationSearchRoutingTests.swift b/Tests/ProxyIntegrationTests/DocumentationSearchRoutingTests.swift index ef03ba3b..06b0b889 100644 --- a/Tests/ProxyIntegrationTests/DocumentationSearchRoutingTests.swift +++ b/Tests/ProxyIntegrationTests/DocumentationSearchRoutingTests.swift @@ -13,7 +13,7 @@ import XcodeMCPProxyTestSupport extension HTTPHandlerTests { @Test func httpDocumentationSearchIsForwardedToNativeHost() async throws { - let config = makeHTTPConfig(requestTimeout: 2) + let config = makeHTTPConfig(requestTimeout: .seconds(2)) let runtime = try HTTPTestRuntime(config: config) { method, params in #expect(method == "tools/call") #expect(params["name"] == .string("DocumentationSearch")) @@ -53,7 +53,7 @@ extension HTTPHandlerTests { } @Test func httpBatchDocumentationSearchIsForwardedToNativeHost() async throws { - let config = makeHTTPConfig(requestTimeout: 2) + let config = makeHTTPConfig(requestTimeout: .seconds(2)) let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) @@ -87,7 +87,7 @@ extension HTTPHandlerTests { } @Test func httpBatchToolsListUsesLocalToolSurfaceAndForwardsOtherCalls() async throws { - let config = makeHTTPConfig(requestTimeout: 2) + let config = makeHTTPConfig(requestTimeout: .seconds(2)) let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) diff --git a/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift b/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift index c8e4dad9..3f1127cd 100644 --- a/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift +++ b/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift @@ -15,7 +15,7 @@ import XcodeMCPProxyTestSupport struct HTTPConcurrencyTests { @Test(arguments: ["BuildProject", "FutureNativeTool"]) func nativeToolCallsResolveWorkspacePathsAndPreserveProviderErrors(toolName: String) async throws { - let config = makeHTTPConfig(requestTimeout: 5) + let config = makeHTTPConfig(requestTimeout: .seconds(5)) let tools = JSONValue.object(["tools": .array([.object([ "name": .string("BuildProject"), "inputSchema": .object([ @@ -74,7 +74,7 @@ struct HTTPConcurrencyTests { } @Test func httpAndSwiftClientExposeTheCompleteCatalog() async throws { - var config = makeHTTPConfig(requestTimeout: 5) + var config = makeHTTPConfig(requestTimeout: .seconds(5)) config.prewarmToolsList = false let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) @@ -111,7 +111,7 @@ struct HTTPConcurrencyTests { @Test(arguments: ["DocumentationSearch", "XcodeListWorkspaces"]) func httpCancellationDoesNotWaitBehindTheRequest(toolName: String) async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) do { @@ -153,7 +153,7 @@ struct HTTPConcurrencyTests { /// A request's progress opens its own POST response as an event stream that ends with the /// reply; a request that reports no progress still gets JSON. @Test func progressStreamsOnlyOnItsRequestsResponse() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) do { @@ -209,7 +209,7 @@ struct HTTPConcurrencyTests { } @Test func multiplexedCancellationPreservesOtherSessionsAndIDScalarTypes() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) do { @@ -269,7 +269,7 @@ struct HTTPConcurrencyTests { } @Test func httpConcurrentInitializeRequests() async throws { - let config = makeHTTPConfig(requestTimeout: 5) + let config = makeHTTPConfig(requestTimeout: .seconds(5)) let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let url = server.url @@ -289,7 +289,7 @@ struct HTTPConcurrencyTests { @Test func httpConcurrentInitializeStress() async throws { let count = 10 - let config = makeHTTPConfig(requestTimeout: 5) + let config = makeHTTPConfig(requestTimeout: .seconds(5)) let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let url = server.url @@ -307,7 +307,7 @@ struct HTTPConcurrencyTests { } @Test func httpConcurrentRequestsShareSession() async throws { - var config = makeHTTPConfig(requestTimeout: 5) + var config = makeHTTPConfig(requestTimeout: .seconds(5)) config.prewarmToolsList = false let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) @@ -354,7 +354,7 @@ struct HTTPConcurrencyTests { } @Test func httpConcurrentRequestsCanOverlapAcrossSessions() async throws { - var config = makeHTTPConfig(requestTimeout: 5) + var config = makeHTTPConfig(requestTimeout: .seconds(5)) config.prewarmToolsList = false let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) @@ -403,7 +403,7 @@ struct HTTPConcurrencyTests { } @Test func httpRequestTimeoutDoesNotCancelAnotherRequestOnTheSameNativeConnection() async throws { - let config = makeHTTPConfig(requestTimeout: 10) + let config = makeHTTPConfig(requestTimeout: .seconds(10)) let clock = TestClock() let runtime = try HTTPTestRuntime(config: config, clock: makeHTTPTestClock(clock)) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) @@ -453,7 +453,7 @@ struct HTTPConcurrencyTests { } @Test func httpNotificationIsAcceptedWithoutWaitingForAnotherRequestResult() async throws { - let config = makeHTTPConfig(requestTimeout: 10) + let config = makeHTTPConfig(requestTimeout: .seconds(10)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let url = server.url @@ -491,7 +491,7 @@ struct HTTPConcurrencyTests { } @Test func httpToolCallNotificationIsAcceptedWithoutReachingTheHost() async throws { - let config = makeHTTPConfig(requestTimeout: 5) + let config = makeHTTPConfig(requestTimeout: .seconds(5)) let runtime = try HTTPTestRuntime(config: config) let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let url = server.url @@ -521,7 +521,7 @@ struct HTTPConcurrencyTests { /// Host notifications reach the session's GET stream; progress reaches only its request's response. @Test func httpServerNotificationsReachActiveSSESessions() async throws { - let config = makeHTTPConfig(requestTimeout: 10) + let config = makeHTTPConfig(requestTimeout: .seconds(10)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let url = server.url diff --git a/Tests/ProxyIntegrationTests/HTTPHandlerTestSupport.swift b/Tests/ProxyIntegrationTests/HTTPHandlerTestSupport.swift index c241ed67..d5cd2117 100644 --- a/Tests/ProxyIntegrationTests/HTTPHandlerTestSupport.swift +++ b/Tests/ProxyIntegrationTests/HTTPHandlerTestSupport.swift @@ -23,7 +23,7 @@ struct HTTPTestConfiguration: Sendable { var maxBodyBytes: Int var enablesDebugEndpoints = false - var requestTimeout: TimeInterval { + var requestTimeout: Duration? { get { runtime.requestTimeout } set { runtime.requestTimeout = newValue } } @@ -126,7 +126,7 @@ final class HTTPTestRuntime: Sendable { func makeHTTPConfig( maxBodyBytes: Int = 1024, - requestTimeout: TimeInterval = 1 + requestTimeout: Duration? = .seconds(1) ) -> HTTPTestConfiguration { HTTPTestConfiguration( runtime: ProxyRuntimeConfiguration( diff --git a/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift b/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift index c7f262b2..d1235f8e 100644 --- a/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift +++ b/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift @@ -405,7 +405,7 @@ struct HTTPHandlerTests { /// A client that disconnects gives up its request: the host learns of it, and the session can expire. @Test func aClientDisconnectCancelsItsRequestAndReleasesTheSession() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } try await addHTTPHandler(to: channel, config: config, runtime: runtime) @@ -431,7 +431,7 @@ struct HTTPHandlerTests { /// The server keeps reading a connection whose response has not started, so it notices a /// client that leaves a running request. @Test func aClientThatLeavesARunningRequestIsNoticedOverTheNetwork() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime) let clientGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) @@ -466,7 +466,7 @@ struct HTTPHandlerTests { /// A reply slower than clients wait for a response to start comes on an event stream that /// opens early and carries keepalives until the reply. @Test func aSlowReplyComesOnAnEventStreamThatOpensEarly() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } try await addHTTPHandler(to: channel, config: config, runtime: runtime) @@ -503,7 +503,7 @@ struct HTTPHandlerTests { /// Responses go out in request order, so a request sent before the previous response ended /// closes the connection instead of being answered out of order. @Test func aRequestBeforeThePreviousResponseEndsClosesTheConnection() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } try await addHTTPHandler(to: channel, config: config, runtime: runtime) @@ -524,7 +524,7 @@ struct HTTPHandlerTests { /// A cancellation sent right after a request, on another connection, finds that request. @Test func aCancellationFindsTheRequestSentBeforeIt() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let requestChannel = makeHTTPTestChannel() let cancelChannel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } @@ -546,7 +546,7 @@ struct HTTPHandlerTests { /// A client that stops reading skips later progress but still gets the reply. @Test func progressIsSkippedWhileTheClientFallsBehind() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } try await addHTTPHandler(to: channel, config: config, runtime: runtime) @@ -590,7 +590,7 @@ struct HTTPHandlerTests { /// A request that started is answered when its session is deleted; only later requests get a 404. @Test func deletingASessionAnswersItsRunningRequestAndRefusesLaterOnes() async throws { - let config = makeHTTPConfig(requestTimeout: 60) + let config = makeHTTPConfig(requestTimeout: .seconds(60)) let requestChannel = makeHTTPTestChannel() let deleteChannel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold } @@ -1082,7 +1082,7 @@ struct HTTPHandlerTests { } @Test func httpInitializedSessionSurvivesHostProcessLoss() async throws { - let config = makeHTTPConfig(requestTimeout: 5) + let config = makeHTTPConfig(requestTimeout: .seconds(5)) let channel = makeHTTPTestChannel() let toolCalls = NIOLockedValueBox(0) let runtime = try HTTPTestRuntime(config: config) { _, _ in @@ -1316,7 +1316,7 @@ struct HTTPHandlerTests { } @Test func httpTimeoutReturnsMCPErrorAndCancelsTheHostRequest() async throws { - let config = makeHTTPConfig(requestTimeout: 1) + let config = makeHTTPConfig(requestTimeout: .seconds(1)) let clock = TestClock() let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config, clock: makeHTTPTestClock(clock)) { _, _ in .hold } @@ -1638,7 +1638,7 @@ struct HTTPHandlerTests { @Test(arguments: HostFailureCase.allCases) func httpToolCallFailuresKeepTheirClassification(failure: HostFailureCase) async throws { - let config = makeHTTPConfig(requestTimeout: 1) + let config = makeHTTPConfig(requestTimeout: .seconds(1)) let clock = TestClock() let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config, clock: makeHTTPTestClock(clock)) { _, _ in diff --git a/Tests/ProxyStressTests/DocumentationSearchStressTests.swift b/Tests/ProxyStressTests/DocumentationSearchStressTests.swift index e0546461..4af0c99e 100644 --- a/Tests/ProxyStressTests/DocumentationSearchStressTests.swift +++ b/Tests/ProxyStressTests/DocumentationSearchStressTests.swift @@ -151,7 +151,7 @@ private struct StressHTTPServer { let maxBodyBytes = 1_048_576 let config = ProxyRuntimeConfiguration( maxMessageBytes: maxBodyBytes, - requestTimeout: 60, + requestTimeout: .seconds(60), prewarmToolsList: false ) let installation = XcodeHostInstallation(developerDirectory: URL(filePath: "/Fixture/Default.app")) diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift index 6b79c85f..6165c0ef 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift @@ -299,12 +299,12 @@ struct NativeHostBrokerTests { try await waitWithTimeout("shutdown finished", timeout: .seconds(5)) { await fixture.broker.shutdown() } } - /// A disabled request timeout (0) still bounds the cleanup close. - @Test(arguments: [5, 0] as [TimeInterval]) - func anUnansweredCleanupCloseExpiresSoTheModelCanBeReopened(requestTimeout: TimeInterval) async throws { + /// A disabled request timeout still bounds the cleanup close. + @Test(arguments: [.seconds(5), nil] as [Duration?]) + func anUnansweredCleanupCloseExpiresSoTheModelCanBeReopened(requestTimeout: Duration?) async throws { let clocks = makeDeterministicClocks() let fixture = try BrokerFixture(clock: clocks.clock, requestTimeout: requestTimeout) - let bound = Duration.seconds(requestTimeout > 0 ? requestTimeout : NativeHostBroker.cleanupFallbackTimeout) + let bound = requestTimeout ?? NativeHostBroker.cleanupFallbackTimeout let first = try await fixture.initialize("expiring-cleanup") _ = try await fixture.open(first) let native = try #require(fixture.factory.transports.withLockedValue { $0.first }) @@ -1170,7 +1170,7 @@ private final class BrokerFixture: Sendable { let notifications = NIOLockedValueBox<[(session: ProxySessionID, data: Data)]>([]) let defaultInstallation = XcodeHostInstallation(developerDirectory: URL(fileURLWithPath: "/Fixture/Default.app")) - init(clock: ClockClient = .liveValue, requestTimeout: TimeInterval = 5, holdsInitialization: Bool = false, + init(clock: ClockClient = .liveValue, requestTimeout: Duration? = .seconds(5), holdsInitialization: Bool = false, prewarmToolsList: Bool = false, logger: Logger = ProxyLogging.make("broker")) throws { let factory = factory diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift index b678a59e..4fe74e0a 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift @@ -35,7 +35,7 @@ struct NativeHostRuntimeTests { @Test func nativeHostIgnoresInheritedGUIRoutingConfiguration() throws { let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( - config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: 5)), + config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: .seconds(5))), baseEnvironment: ["MCP_XCODE_PID": "9876", "MCP_XCODE_SESSION_ID": "parent-session", "XCODE_PID": "legacy", "DEVELOPER_DIR": "/Parent/Developer", "PATH": "/usr/bin"]) #expect(configuration.command.hasSuffix("/xcode-mcp-native-host")) @@ -50,7 +50,7 @@ struct NativeHostRuntimeTests { @Test(arguments: [false, true]) func compilationCacheSharingReachesTheOwnedHost(sharesCompilationCache: Bool) throws { - var config = makeConfig(requestTimeout: 5) + var config = makeConfig(requestTimeout: .seconds(5)) config.sharesCompilationCache = sharesCompilationCache let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( config: makeBridgeRuntimeConfig(config), baseEnvironment: [:]) @@ -70,7 +70,7 @@ struct NativeHostRuntimeTests { baseEnvironment: ["PATH": "/usr/bin", "MCP_XCODE_PID": "9876"], processRunner: runner) let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( - config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: 5)), + config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: .seconds(5))), baseEnvironment: environment) #expect(configuration.environment["XCBBUILDSERVICE_PATH"] == path) @@ -181,7 +181,7 @@ struct NativeHostRuntimeTests { @Test func nativeHostSessionUsesConfiguredHelper() throws { let factory = try NativeHostSessionFactory( - configuration: makeBridgeRuntimeConfig(makeConfig(requestTimeout: 0)), environment: [:]) + configuration: makeBridgeRuntimeConfig(makeConfig(requestTimeout: nil)), environment: [:]) #expect(try upstreamCommand(from: factory).hasSuffix("/xcode-mcp-native-host")) } diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostTestSupport.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostTestSupport.swift index c97900e3..253396e0 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostTestSupport.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostTestSupport.swift @@ -4,7 +4,7 @@ import XcodeMCPCore import XcodeMCPProxyTestSupport @testable import XcodeMCPProxyRuntime -func makeConfig(requestTimeout: TimeInterval) -> ProxyRuntimeConfiguration { +func makeConfig(requestTimeout: Duration?) -> ProxyRuntimeConfiguration { ProxyRuntimeConfiguration( maxMessageBytes: 1024, requestTimeout: requestTimeout,