Skip to content

fix(functions): fix streamed responses #525

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

Merged
merged 1 commit into from
Sep 7, 2024
Merged
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
38 changes: 20 additions & 18 deletions Sources/Functions/FunctionsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,24 +198,7 @@ public final class FunctionsClient: Sendable {

let urlRequest = buildRequest(functionName: functionName, options: invokeOptions).urlRequest

let task = session.dataTask(with: urlRequest) { data, response, _ in
guard let httpResponse = response as? HTTPURLResponse else {
continuation.finish(throwing: URLError(.badServerResponse))
return
}

guard 200 ..< 300 ~= httpResponse.statusCode else {
let error = FunctionsError.httpError(code: httpResponse.statusCode, data: data ?? Data())
continuation.finish(throwing: error)
return
}

let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true"
if isRelayError {
continuation.finish(throwing: FunctionsError.relayError)
}
}

let task = session.dataTask(with: urlRequest)
task.resume()

continuation.onTermination = { _ in
Expand Down Expand Up @@ -259,4 +242,23 @@ final class StreamResponseDelegate: NSObject, URLSessionDataDelegate, Sendable {
func urlSession(_: URLSession, task _: URLSessionTask, didCompleteWithError error: (any Error)?) {
continuation.finish(throwing: error)
}

func urlSession(_: URLSession, dataTask _: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let httpResponse = response as? HTTPURLResponse else {
continuation.finish(throwing: URLError(.badServerResponse))
return
}

guard 200 ..< 300 ~= httpResponse.statusCode else {
let error = FunctionsError.httpError(code: httpResponse.statusCode, data: Data())
continuation.finish(throwing: error)
return
}

let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true"
if isRelayError {
continuation.finish(throwing: FunctionsError.relayError)
}
completionHandler(.allow)
}
}
Loading