diff --git a/Sources/MCP/Base/Transports/ResponseBody.swift b/Sources/MCP/Base/Transports/ResponseBody.swift index 5d41c05f..b357a695 100644 --- a/Sources/MCP/Base/Transports/ResponseBody.swift +++ b/Sources/MCP/Base/Transports/ResponseBody.swift @@ -41,6 +41,25 @@ struct ResponseBody: AsyncSequence, Sendable { var index = 0 mutating func next() async throws -> UInt8? { + // `fill()` only once the chunk is used up, so reading a byte + // costs one comparison. + if index >= chunk.endIndex { + guard try await fill() else { return nil } + } + defer { index += 1 } + return chunk[index] + } + + /// The bytes of the current chunk not read yet, or of the next one. + mutating func nextChunk() async throws -> Data? { + guard try await fill() else { return nil } + defer { index = chunk.endIndex } + return chunk[index...] + } + + /// Makes `chunk` hold a byte not read yet. Returns `false` at the + /// end of the body. + private mutating func fill() async throws -> Bool { while index >= chunk.endIndex { let next: Data? do { @@ -55,13 +74,12 @@ struct ResponseBody: AsyncSequence, Sendable { // A cut body must not pass for a whole one; this // throws where `URLSession.AsyncBytes` would. if cancellation.isCancelled { throw CancellationError() } - return nil + return false } chunk = next index = chunk.startIndex } - defer { index += 1 } - return chunk[index] + return true } } @@ -84,12 +102,26 @@ struct ResponseBody: AsyncSequence, Sendable { /// The whole body, up to `limit` bytes. func collect(limit: Int = .max) async throws -> Data { - var body = Data() - for try await byte in self { - body.append(byte) - if body.count >= limit { break } - } - return body + // Appending a byte at a time to `Data` costs about 9 ns a byte, so a + // 16 MiB body took about 150 ms. + #if canImport(FoundationNetworking) + // A chunk at a time. + var body = Data() + var iterator = makeAsyncIterator() + while body.count < limit, let chunk = try await iterator.nextChunk() { + body.append(chunk.prefix(limit - body.count)) + } + return body + #else + // `URLSession.AsyncBytes` has no chunks to hand out, so into + // `[UInt8]` first. + var bytes: [UInt8] = [] + var iterator = makeAsyncIterator() + while bytes.count < limit, let byte = try await iterator.next() { + bytes.append(byte) + } + return Data(bytes) + #endif } } diff --git a/Tests/MCPTests/ResponseBodyTests.swift b/Tests/MCPTests/ResponseBodyTests.swift new file mode 100644 index 00000000..c6abde8d --- /dev/null +++ b/Tests/MCPTests/ResponseBodyTests.swift @@ -0,0 +1,150 @@ +import Foundation +import Testing + +@testable import MCP + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +@Suite("Response body") +struct ResponseBodyTests { + /// Serves a 200 body in the chunks its script lists, then ends it or + /// fails it. + private final class ChunkScriptURLProtocol: URLProtocol { + struct Script: Sendable { + var chunks: [Int] + var failAtEnd = false + } + + private static let lock = NSLock() + /// `nonisolated(unsafe)`: `lock` guards it. + nonisolated(unsafe) private static var scripts: [String: Script] = [:] + + static func url(_ script: Script) -> URL { + let key = UUID().uuidString + lock.withLock { scripts[key] = script } + return URL(string: "http://localhost/\(key)")! + } + + /// The bytes of the body from `offset`: a pattern, so a byte read + /// twice or out of order shows. + static func bytes(_ offset: Int, _ count: Int) -> Data { + Data((offset..<(offset + count)).map { UInt8(truncatingIfNeeded: $0 % 251) }) + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let url = request.url! + let script = Self.lock.withLock { Self.scripts[url.lastPathComponent] }! + let response = HTTPURLResponse( + url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + var offset = 0 + for count in script.chunks { + client?.urlProtocol(self, didLoad: Self.bytes(offset, count)) + offset += count + } + if script.failAtEnd { + client?.urlProtocol(self, didFailWithError: URLError(.networkConnectionLost)) + } else { + client?.urlProtocolDidFinishLoading(self) + } + } + override func stopLoading() {} + } + + private func withScriptedBody( + _ script: ChunkScriptURLProtocol.Script, _ body: (ResponseBody) async throws -> T + ) async throws -> T { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [ChunkScriptURLProtocol.self] + let session = URLSession(configuration: configuration) + let streaming = StreamingSession(configuration: configuration) + defer { streaming.invalidate(along: session) } + let (responseBody, _) = try await session.responseBody( + for: URLRequest(url: ChunkScriptURLProtocol.url(script)), streaming: streaming) + return try await body(responseBody) + } + + @Test("collect(limit:) returns the first min(length, limit) bytes in order") + func collectLimits() async throws { + let mib = 1 << 20 + let cases: [([Int], [Int])] = [ + ([5, 5, 5], Array(0...16) + [.max]), + ([mib], [1, 10, mib - 1, mib, mib + 1, .max]), + ([mib, 3], [mib - 1, mib, mib + 1, mib + 2, mib + 3, mib + 4]), + ([], [0, 1, .max]), + ([1, 1, 1, 1], [1, 2, 3, 4, 5]), + ] + for (chunks, limits) in cases { + let length = chunks.reduce(0, +) + for limit in limits { + let data = try await withScriptedBody(.init(chunks: chunks)) { try await $0.collect(limit: limit) } + let expected = ChunkScriptURLProtocol.bytes(0, min(length, limit)) + #expect( + data == expected, + "chunks \(chunks) limit \(limit): got \(data.count) bytes, want \(expected.count)") + } + } + } + + @Test("collect(limit:) throws when the body fails before the limit") + func collectFailure() async throws { + await #expect(throws: (any Error).self) { + _ = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) { try await $0.collect() } + } + await #expect(throws: (any Error).self) { + _ = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) { + try await $0.collect(limit: 11) + } + } + #if canImport(FoundationNetworking) + // `URLSession.AsyncBytes` can throw the task's error before it + // hands out bytes that arrived ahead of it, so only here does a + // limit reached first return. + for limit in [7, 10] { + let data = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) { + try await $0.collect(limit: limit) + } + #expect(data == ChunkScriptURLProtocol.bytes(0, limit)) + } + #endif + } + + @Test("Bytes read one at a time match the body") + func byteIteration() async throws { + let data = try await withScriptedBody(.init(chunks: [3, 4, 1])) { body in + var out = Data() + for try await byte in body { out.append(byte) } + return out + } + #expect(data == ChunkScriptURLProtocol.bytes(0, 8)) + } + + #if canImport(FoundationNetworking) + @Test("next() and nextChunk() mixed read every byte once, in order") + func mixedReads() async throws { + let reads: [Data?] = try await withScriptedBody(.init(chunks: [5, 5, 5])) { body in + var iterator = body.makeAsyncIterator() + var reads: [Data?] = [] + reads.append(try await iterator.next().map { Data([$0]) }) + reads.append(try await iterator.nextChunk().map { Data($0) }) + reads.append(try await iterator.next().map { Data([$0]) }) + reads.append(try await iterator.next().map { Data([$0]) }) + reads.append(try await iterator.nextChunk().map { Data($0) }) + reads.append(try await iterator.nextChunk().map { Data($0) }) + reads.append(try await iterator.nextChunk().map { Data($0) }) + reads.append(try await iterator.next().map { Data([$0]) }) + return reads + } + let bytes = { ChunkScriptURLProtocol.bytes($0, $1) } + let expected: [Data?] = [ + bytes(0, 1), bytes(1, 4), bytes(5, 1), bytes(6, 1), bytes(7, 3), bytes(10, 5), nil, nil, + ] + #expect(reads == expected) + } + #endif +}