Skip to content

Commit

Permalink
Add assertion when using gRPC with URLSession (#138)
Browse files Browse the repository at this point in the history
Add a debug assertion failure that will trigger when the
`URLSessionHTTPClient` is used with gRPC to make it more apparent as to
why some "successful" responses are still invalid.

For context, URLSession does not support trailers and is thus
incompatible with gRPC.
  • Loading branch information
rebello95 committed Jun 26, 2023
1 parent 1c9599b commit 6d6df4f
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Libraries/Connect/Implementation/URLSessionHTTPClient.swift
Expand Up @@ -45,6 +45,7 @@ open class URLSessionHTTPClient: NSObject, HTTPClientInterface {
onMetrics: @Sendable @escaping (HTTPMetrics) -> Void,
onResponse: @Sendable @escaping (HTTPResponse) -> Void
) -> Cancelable {
assert(!request.isGRPC, "URLSessionHTTPClient does not support gRPC, use NIOHTTPClient")
let urlRequest = URLRequest(httpRequest: request)
let task = self.session.dataTask(with: urlRequest) { data, urlResponse, error in
if let httpURLResponse = urlResponse as? HTTPURLResponse {
Expand Down Expand Up @@ -93,6 +94,7 @@ open class URLSessionHTTPClient: NSObject, HTTPClientInterface {
open func stream(
request: HTTPRequest, responseCallbacks: ResponseCallbacks
) -> RequestCallbacks {
assert(!request.isGRPC, "URLSessionHTTPClient does not support gRPC, use NIOHTTPClient")
let urlSessionStream = URLSessionStream(
request: URLRequest(httpRequest: request),
session: self.session,
Expand Down Expand Up @@ -196,6 +198,15 @@ extension Code {
}
}

private extension HTTPRequest {
var isGRPC: Bool {
return self.headers[HeaderConstants.contentType]?.first.map { contentType in
return contentType.hasPrefix("application/grpc")
&& !contentType.hasPrefix("application/grpc-web")
} ?? false
}
}

private extension URLRequest {
init(httpRequest: HTTPRequest) {
self.init(url: httpRequest.url)
Expand Down

0 comments on commit 6d6df4f

Please sign in to comment.