Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / HTTPClientProtocol / URLSession+HTTP.swift

URLSession+HTTP.swift134 lines · 4.2 KiBRaw
1//
2// URLSession+HTTPClientProtocol.swift
3//
4//
5// Created by Kabir Oberai on 05/05/21.
6//
7
8#if !os(Linux)
9import Foundation
10import ConcurrencyExtras
11import OpenAPIRuntime
12import OpenAPIURLSession
13import Dependencies
14
15public struct UnknownHTTPError: Error {}
16
17extension HTTPClientDependencyKey: DependencyKey {
18 public static let liveValue: HTTPClientProtocol = Client()
19}
20
21private struct Client: HTTPClientProtocol {
22 final class ClientDelegate: NSObject, URLSessionWebSocketDelegate {
23 let webSocketCallbacks = LockIsolated<[
24 URLSessionWebSocketTask: @Sendable (URLSessionWebSocketTask.CloseCode?) -> Void
25 ]>([:])
26
27 func urlSession(
28 _ session: URLSession,
29 webSocketTask: URLSessionWebSocketTask,
30 didOpenWithProtocol protocol: String?
31 ) {
32 webSocketCallbacks.withValue { $0.removeValue(forKey: webSocketTask) }?(nil)
33 }
34
35 func urlSession(
36 _ session: URLSession,
37 webSocketTask: URLSessionWebSocketTask,
38 didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
39 reason: Data?
40 ) {
41 webSocketCallbacks.withValue { $0.removeValue(forKey: webSocketTask) }?(closeCode)
42 }
43
44 func urlSession(
45 _ session: URLSession,
46 didReceive challenge: URLAuthenticationChallenge
47 ) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {
48 if ProcessInfo.processInfo.environment["XTL_DISABLE_TLS_VALIDATION"] == "1",
49 let trust = challenge.protectionSpace.serverTrust {
50 return (.useCredential, URLCredential(trust: trust))
51 } else {
52 return (.performDefaultHandling, nil)
53 }
54 }
55 }
56
57 private let clientDelegate = ClientDelegate()
58 private let session: URLSession
59
60 init() {
61 // no need for cert handling since the Apple Root CA is already
62 // installed on any devices which support the Security APIs which
63 // would have been required to add the custom root anyway
64 self.session = URLSession(configuration: .ephemeral, delegate: clientDelegate, delegateQueue: .main)
65 }
66
67 var asOpenAPITransport: any ClientTransport {
68 URLSessionTransport(configuration: .init(session: session))
69 }
70
71 func withEphemeralClient<T>(
72 perform: (any HTTPClientProtocol) async throws -> T
73 ) async throws -> T {
74 let ephemeralClient = Client()
75 let result = await Result { try await perform(ephemeralClient) }
76 ephemeralClient.session.finishTasksAndInvalidate()
77 return try result.get()
78 }
79
80 public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
81 let task = session.webSocketTask(with: url)
82 let (event, eventContinuation) = AsyncStream<URLSessionWebSocketTask.CloseCode?>.makeStream()
83 clientDelegate.webSocketCallbacks.withValue {
84 $0[task] = {
85 eventContinuation.yield($0)
86 eventContinuation.finish()
87 }
88 }
89 task.resume()
90 let code = await event.first { _ in true } ?? nil
91 if let code { throw Errors.webSocketClosed(code) }
92 return WebSocketSessionWrapper(task: task)
93 }
94
95 enum Errors: Error {
96 case webSocketClosed(URLSessionWebSocketTask.CloseCode)
97 }
98}
99
100private final class WebSocketSessionWrapper: WebSocketSession {
101 let task: URLSessionWebSocketTask
102
103 init(task: URLSessionWebSocketTask) {
104 self.task = task
105 }
106
107 func receive() async throws -> WebSocketMessage {
108 switch try await task.receive() {
109 case .data(let data): .data(data)
110 case .string(let text): .text(text)
111 @unknown default: .data(Data())
112 }
113 }
114
115 func send(_ message: WebSocketMessage) async throws {
116 let message: URLSessionWebSocketTask.Message = switch message {
117 case .data(let data): .data(data)
118 case .text(let text): .string(text)
119 }
120 try await task.send(message)
121 }
122
123 func close() {
124 task.cancel(with: .normalClosure, reason: nil)
125 }
126}
127
128extension Optional {
129 fileprivate mutating func inoutMap<E>(_ transform: (inout Wrapped) throws(E) -> Void) throws(E) {
130 if self != nil { try transform(&self!) }
131 }
132}
133
134#endif