Skip to content
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

Two handy extensions to work with HTTPClientResponse body #736

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Sources/AsyncHTTPClient/AsyncAwait/HTTPClientResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,17 @@ extension HTTPClientResponse {
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension HTTPClientResponse {
/// Response body as `ByteBuffer`.
/// - Parameter maxBytes: The maximum number of bytes this method is allowed to accumulate.
/// - Returns: Bytes collected over time
public func bytes(upTo maxBytes: Int) async throws -> ByteBuffer {
let expectedBytes = self.headers.first(name: "content-length").flatMap(Int.init) ?? maxBytes
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't just blindly trust the content-length: it should reject values of the content length above the upTo value.

return try await self.body.collect(upTo: expectedBytes)
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@usableFromInline
typealias TransactionBody = NIOThrowingAsyncSequenceProducer<
Expand Down
11 changes: 11 additions & 0 deletions Sources/AsyncHTTPClient/FoundationExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,14 @@ extension HTTPClient.Body {
return self.bytes(data)
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension HTTPClientResponse {
/// Response body as `Data`.
/// - Parameter maxBytes: The maximum number of bytes this method is allowed to accumulate.
/// - Returns: Bytes collected over time
public func data(upTo maxBytes: Int) async throws -> Data? {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same note here.

var bytes = try await self.bytes(upTo: maxBytes)
return bytes.readData(length: bytes.readableBytes)
}
}
53 changes: 53 additions & 0 deletions Tests/AsyncHTTPClientTests/AsyncAwaitEndToEndTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,59 @@ final class AsyncAwaitEndToEndTests: XCTestCase {
}
}
}

func testResponseBytesHelper() {
XCTAsyncTest {
let bin = HTTPBin(.http2(compress: false)) { _ in HTTPEchoHandler() }
defer { XCTAssertNoThrow(try bin.shutdown()) }
let client = makeDefaultHTTPClient()
defer { XCTAssertNoThrow(try client.syncShutdown()) }
let logger = Logger(label: "HTTPClient", factory: StreamLogHandler.standardOutput(label:))
var request = HTTPClientRequest(url: "https://localhost:\(bin.port)/")
request.method = .POST
request.body = .bytes(ByteBuffer(string: "1234"))

guard let response = await XCTAssertNoThrowWithResult(
try await client.execute(request, deadline: .now() + .seconds(10), logger: logger)
) else { return }
XCTAssertEqual(response.headers["content-length"], ["4"])
guard let body = await XCTAssertNoThrowWithResult(
try await response.bytes(upTo: 3)
) else { return }
XCTAssertEqual(body, ByteBuffer(string: "1234"))

guard var responseNoContentLength = await XCTAssertNoThrowWithResult(
try await client.execute(request, deadline: .now() + .seconds(10), logger: logger)
) else { return }
responseNoContentLength.headers.remove(name: "content-length")
guard let body2 = await XCTAssertNoThrowWithResult(
try await responseNoContentLength.bytes(upTo: 4)
) else { return }
XCTAssertEqual(body2, ByteBuffer(string: "1234"))
}
}

func testResponseBodyDataHelper() {
XCTAsyncTest {
let bin = HTTPBin(.http2(compress: false)) { _ in HTTPEchoHandler() }
defer { XCTAssertNoThrow(try bin.shutdown()) }
let client = makeDefaultHTTPClient()
defer { XCTAssertNoThrow(try client.syncShutdown()) }
let logger = Logger(label: "HTTPClient", factory: StreamLogHandler.standardOutput(label:))
var request = HTTPClientRequest(url: "https://localhost:\(bin.port)/")
request.method = .POST
request.body = .bytes(ByteBuffer(string: "1234"))

guard let response = await XCTAssertNoThrowWithResult(
try await client.execute(request, deadline: .now() + .seconds(10), logger: logger)
) else { return }
XCTAssertEqual(response.headers["content-length"], ["4"])
guard let bodyData = await XCTAssertNoThrowWithResult(
try await response.data(upTo: 4)
) else { return }
XCTAssertEqual(bodyData, "1234".data(using: .utf8))
}
}
}

struct AnySendableSequence<Element>: @unchecked Sendable {
Expand Down