Repository navigation
fix: collect response bodies without appending a byte at a time #422
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: rel/1.0.0
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 } | ||
|
Comment on lines
+20
to
+26
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: |
||
| 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) }) | ||
| } | ||
|
Comment on lines
+32
to
+34
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: |
||
|
|
||
| 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<T>( | ||
| _ 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]), | ||
| ] | ||
|
Comment on lines
+74
to
+81
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: Consider adding a case with an empty chunk between non-empty ones (e.g. |
||
| 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 | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: Clearing
chunkindeferreleases the consumed chunk's backing storage immediately instead of retaining it across the nextfill()suspension: