Skip to content

Commit

Permalink
fix Test
Browse files Browse the repository at this point in the history
  • Loading branch information
zunda-pixel committed Nov 30, 2024
1 parent 1b370ff commit 9322ce2
Show file tree
Hide file tree
Showing 92 changed files with 586 additions and 427 deletions.
8 changes: 5 additions & 3 deletions Sources/Auth/AuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1122,10 +1122,12 @@ public final class AuthClient: Sendable {

if let jwt {
request.headerFields[.authorization] = "Bearer \(jwt)"
let (data, _) = try await api.execute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
} else {
let (data, _) = try await api.authorizedExecute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
}

let (data, _) = try await api.authorizedExecute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
}

/// Updates user data, if there is a logged in user.
Expand Down
2 changes: 1 addition & 1 deletion Sources/Auth/AuthClientConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ extension AuthClient {
},
autoRefreshToken: Bool = AuthClient.Configuration.defaultAutoRefreshToken
) {
let headers = headers.merging(with: Configuration.defaultHeaders)
let headers = Configuration.defaultHeaders.merging(headers) { $1 }

self.url = url ?? defaultAuthURL
self.headers = headers
Expand Down
7 changes: 2 additions & 5 deletions Sources/Auth/Internal/APIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ struct APIClient: Sendable {
func execute(
for request: HTTPRequest,
from bodyData: Data?
) async throws -> (
Data,
HTTPResponse
) {
) async throws -> (Data, HTTPResponse) {
var request = request
request.headerFields = HTTPFields(configuration.headers).merging(with: request.headerFields)
request.headerFields = request.headerFields.merging(configuration.headers) { $1 }

if request.headerFields[.apiVersionHeaderName] == nil {
request.headerFields[.apiVersionHeaderName] = apiVersions[._20240101]!.name.rawValue
Expand Down
3 changes: 2 additions & 1 deletion Sources/Auth/Internal/SessionStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ extension StorageMigration {
let storedSession = try? AuthClient.Configuration.jsonDecoder.decode(
StoredSession.self,
from: data
) {
)
{
let session = try AuthClient.Configuration.jsonEncoder.encode(storedSession.session)
try storage.store(key: key, value: session)
}
Expand Down
6 changes: 5 additions & 1 deletion Sources/Functions/FunctionsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,13 @@ public final class FunctionsClient: Sendable {
url: url
.appendingPathComponent(functionName)
.appendingQueryItems(options.query),
headerFields: mutableState.headers.merging(with: options.headers)
headerFields: mutableState.headers.merging(options.headers) { $1 }
)

if options.body != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}

if let region = options.region ?? region {
request.headerFields[.xRegion] = region
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Functions/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public struct FunctionInvokeOptions: Sendable {
}

self.method = method
self.headers = defaultHeaders.merging(with: headers)
self.headers = defaultHeaders.merging(headers) { $1 }
self.region = region
self.query = query
}
Expand Down
7 changes: 6 additions & 1 deletion Sources/Helpers/HTTP/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ package actor HTTPClient: HTTPClientType {
_ bodyData: Data?
) async throws -> (Data, HTTPResponse) {
var next: @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse) = {
return try await self.fetch($0, $1)
request, bodyData in
var request = request
if bodyData != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}
return try await self.fetch(request, bodyData)
}

for interceptor in interceptors.reversed() {
Expand Down
16 changes: 10 additions & 6 deletions Sources/Helpers/HTTP/HTTPFields.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,21 @@ extension HTTPFields {
return .init(keyValues, uniquingKeysWith: { $1 })
}

package mutating func merge(with other: Self) {
for field in other {
self[field.name] = field.value
}
package mutating func merge(
_ other: Self,
uniquingKeysWith combine: (String, String) throws -> String
) rethrows {
self = try self.merging(other, uniquingKeysWith: combine)
}

package func merging(with other: Self) -> Self {
package func merging(
_ other: Self,
uniquingKeysWith combine: (String, String) throws -> String
) rethrows -> HTTPFields {
var copy = self

for field in other {
copy[field.name] = field.value
copy[field.name] = try combine(self[field.name] ?? "", field.value)
}

return copy
Expand Down
4 changes: 4 additions & 0 deletions Sources/Helpers/HTTP/LoggerInterceptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ package struct LoggerInterceptor: HTTPClientInterceptor {
)

do {
var request = request
if bodyData != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}
let (data, response) = try await next(request, bodyData)
logger.verbose(
"""
Expand Down
116 changes: 116 additions & 0 deletions Sources/Helpers/HTTP/URLSession+HTTPRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import Foundation
import HTTPTypes

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

#if !os(WASI)

extension URLSessionTask {
/// The original HTTP request this task was created with.
public var originalHTTPRequest: HTTPRequest? {
self.originalRequest?.httpRequest
}

/// The current HTTP request -- may differ from the `originalHTTPRequest` due to HTTP redirection.
public var currentHTTPRequest: HTTPRequest? {
self.currentRequest?.httpRequest
}

/// The HTTP response received from the server.
public var httpResponse: HTTPResponse? {
(self.response as? HTTPURLResponse)?.httpResponse
}
}

private enum HTTPTypeConversionError: Error {
case failedToConvertHTTPRequestToURLRequest
case failedToConvertURLResponseToHTTPResponse
}

#endif

#if canImport(FoundationNetworking) && compiler(<6)

@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension URLSession {
/// Convenience method to load data using an `HTTPRequest`; creates and resumes a `URLSessionDataTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to load data.
/// - Parameter delegate: Task-specific delegate.
/// - Returns: Data and response.
public func data(
for request: HTTPRequest,
delegate: (any URLSessionTaskDelegate)? = nil
) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.data(for: urlRequest, delegate: delegate)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}

/// Convenience method to upload data using an `HTTPRequest`, creates and resumes a `URLSessionUploadTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to upload data.
/// - Parameter bodyData: Data to upload.
/// - Parameter delegate: Task-specific delegate.
/// - Returns: Data and response.
public func upload(
for request: HTTPRequest,
from bodyData: Data,
delegate: (any URLSessionTaskDelegate)? = nil
) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.upload(
for: urlRequest, from: bodyData, delegate: delegate)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension URLSession {
/// Convenience method to load data using an `HTTPRequest`; creates and resumes a `URLSessionDataTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to load data.
/// - Returns: Data and response.
public func data(for request: HTTPRequest) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.data(for: urlRequest)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}

/// Convenience method to upload data using an `HTTPRequest`, creates and resumes a `URLSessionUploadTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to upload data.
/// - Parameter bodyData: Data to upload.
/// - Returns: Data and response.
public func upload(for request: HTTPRequest, from bodyData: Data) async throws -> (
Data, HTTPResponse
) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.upload(for: urlRequest, from: bodyData)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}
}

#endif
6 changes: 3 additions & 3 deletions Sources/PostgREST/PostgrestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public class PostgrestBuilder: @unchecked Sendable {
options: FetchOptions,
decode: (Data) throws -> T
) async throws -> PostgrestResponse<T> {
let request = mutableState.withValue {
let (request, bodyData) = mutableState.withValue {
$0.fetchOptions = options

if $0.fetchOptions.head {
Expand Down Expand Up @@ -130,10 +130,10 @@ public class PostgrestBuilder: @unchecked Sendable {
}
}

return $0.request
return ($0.request, $0.bodyData)
}

let (data, response) = try await http.send(request, nil)
let (data, response) = try await http.send(request, bodyData)

guard 200..<300 ~= response.status.code else {
if let error = try? configuration.decoder.decode(PostgrestError.self, from: data) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/PostgREST/PostgrestClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public final class PostgrestClient: Sendable {
public init(configuration: Configuration) {
_configuration = LockIsolated(configuration)
_configuration.withValue {
$0.headers.merge(with: Configuration.defaultHeaders)
$0.headers.merge(Configuration.defaultHeaders) { l, _ in l }
}
}

Expand Down
18 changes: 10 additions & 8 deletions Sources/Realtime/PhoenixTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
// THE SOFTWARE.

import Foundation
import HTTPTypes

#if canImport(FoundationNetworking)
import FoundationNetworking
Expand Down Expand Up @@ -46,7 +47,7 @@ public protocol PhoenixTransport {
- Parameters:
- headers: Headers to include in the URLRequests when opening the Websocket connection. Can be empty [:]
*/
func connect(with headers: [String: String])
func connect(with headers: HTTPFields)

/**
Disconnect from the server.
Expand Down Expand Up @@ -192,20 +193,21 @@ open class URLSessionTransport: NSObject, PhoenixTransport, URLSessionWebSocketD
public var readyState: PhoenixTransportReadyState = .closed
public var delegate: (any PhoenixTransportDelegate)? = nil

public func connect(with headers: [String: String]) {
public func connect(with headers: HTTPFields) {
// Set the transport state as connecting
readyState = .connecting

// Create the session and websocket task
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
var request = URLRequest(url: url)
let request = HTTPRequest(
method: .get,
url: url,
headerFields: headers
)

for (key, value) in headers {
guard let value = value as? String else { continue }
request.addValue(value, forHTTPHeaderField: key)
}
let urlRequest = URLRequest(httpRequest: request)!

task = session?.webSocketTask(with: request)
task = session?.webSocketTask(with: urlRequest)

// Start the task
task?.resume()
Expand Down
2 changes: 1 addition & 1 deletion Sources/Realtime/RealtimeClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ public class RealtimeClient: PhoenixTransportDelegate {
// self.connection?.enabledSSLCipherSuites = enabledSSLCipherSuites
// #endif

connection?.connect(with: headers.dictionary)
connection?.connect(with: headers)
}

/// Disconnects the socket
Expand Down
9 changes: 5 additions & 4 deletions Sources/Realtime/V2/RealtimeChannelV2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ struct Socket: Sendable {
var addChannel: @Sendable (_ channel: RealtimeChannelV2) -> Void
var removeChannel: @Sendable (_ channel: RealtimeChannelV2) async -> Void
var push: @Sendable (_ message: RealtimeMessageV2) async -> Void
var httpSend: @Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse)
var httpSend:
@Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse)
}

extension Socket {
Expand Down
21 changes: 13 additions & 8 deletions Sources/Realtime/V2/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ public struct RealtimeClientOptions: Sendable {
var timeoutInterval: TimeInterval
var disconnectOnSessionLoss: Bool
var connectOnSubscribe: Bool
var fetch: (@Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse))?
var fetch:
(
@Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse)
)?
package var logger: (any SupabaseLogger)?

public static let defaultHeartbeatInterval: TimeInterval = 15
Expand All @@ -40,10 +43,12 @@ public struct RealtimeClientOptions: Sendable {
timeoutInterval: TimeInterval = Self.defaultTimeoutInterval,
disconnectOnSessionLoss: Bool = Self.defaultDisconnectOnSessionLoss,
connectOnSubscribe: Bool = Self.defaultConnectOnSubscribe,
fetch: (@Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse))? = nil,
fetch: (
@Sendable (
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse)
)? = nil,
logger: (any SupabaseLogger)? = nil
) {
self.headers = headers
Expand Down
2 changes: 1 addition & 1 deletion Sources/Storage/StorageApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class StorageApi: @unchecked Sendable {
from bodyData: Data?
) async throws -> (Data, HTTPResponse) {
var request = request
request.headerFields = configuration.headers.merging(with: request.headerFields)
request.headerFields = configuration.headers.merging(request.headerFields) { $1 }

let (data, response) = try await http.send(request, bodyData)

Expand Down
Loading

0 comments on commit 9322ce2

Please sign in to comment.