Skip to content

Commit 60e1e52

Browse files
authored
refactor: share the AI provider transport and the core driver scaffolding (#4317)
1 parent a7299b3 commit 60e1e52

58 files changed

Lines changed: 1649 additions & 1844 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
//
2+
// AIProviderTransport.swift
3+
// TablePro
4+
//
5+
6+
import Foundation
7+
import TableProHTTP
8+
9+
struct AIHTTPReply {
10+
let data: Data
11+
let response: HTTPURLResponse
12+
13+
var statusCode: Int { response.statusCode }
14+
}
15+
16+
enum AIModelListReply {
17+
case unreachable(any Error)
18+
case notHTTP
19+
case rejected(AIHTTPReply)
20+
// Nil when the body is not JSON or has no array under the key.
21+
case entries([[String: Any]]?)
22+
}
23+
24+
// The HTTP side every provider shares. A provider configures it and keeps only its wire format.
25+
struct AIProviderTransport: Sendable {
26+
let configuredEndpoint: String
27+
let endpoint: AIEndpoint?
28+
let headers: [String: String]
29+
let forbiddenIsAuthFailure: Bool
30+
let session: URLSession
31+
32+
init(
33+
endpoint: String,
34+
style: AIEndpointStyle,
35+
headers: [String: String],
36+
forbiddenIsAuthFailure: Bool = false,
37+
session: URLSession
38+
) {
39+
self.configuredEndpoint = endpoint.trimmingCharacters(in: .whitespacesAndNewlines)
40+
self.endpoint = AIEndpoint(endpoint, style: style)
41+
self.headers = headers
42+
self.forbiddenIsAuthFailure = forbiddenIsAuthFailure
43+
self.session = session
44+
}
45+
46+
static func bearer(_ apiKey: String?) -> [String: String] {
47+
guard let apiKey, !apiKey.isEmpty else { return [:] }
48+
return ["Authorization": "Bearer \(apiKey)"]
49+
}
50+
51+
func url(_ resource: String, query: [URLQueryItem] = []) throws -> URL {
52+
guard let url = endpoint?.url(appending: resource, query: query) else {
53+
throw AIProviderError.invalidEndpoint(configuredEndpoint)
54+
}
55+
return url
56+
}
57+
58+
func get(_ url: URL, timeout: TimeInterval? = AIProvider.modelListTimeout, authenticated: Bool = true) -> URLRequest {
59+
var request = URLRequest(url: url)
60+
request.httpMethod = "GET"
61+
if let timeout {
62+
request.timeoutInterval = timeout
63+
}
64+
if authenticated {
65+
applyHeaders(to: &request)
66+
}
67+
return request
68+
}
69+
70+
func post(_ url: URL, body: [String: Any]) throws -> URLRequest {
71+
var request = URLRequest(url: url)
72+
request.httpMethod = "POST"
73+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
74+
applyHeaders(to: &request)
75+
request.httpBody = try JSONSerialization.data(withJSONObject: body)
76+
return request
77+
}
78+
79+
func stream<Wire: ChatStreamWire>(
80+
_ wire: Wire,
81+
request: @escaping @Sendable () async throws -> URLRequest
82+
) -> AsyncThrowingStream<ChatStreamEvent, Error> {
83+
SSEEventStream.make(
84+
session: session,
85+
treatForbiddenAsAuthFailure: forbiddenIsAuthFailure,
86+
wire: wire,
87+
buildRequest: request
88+
)
89+
}
90+
91+
func modelList(at url: URL, key: String, authenticated: Bool = true) async -> AIModelListReply {
92+
let data: Data
93+
let response: URLResponse
94+
do {
95+
(data, response) = try await session.data(
96+
for: get(url, authenticated: authenticated),
97+
delegate: SameOriginRedirects.shared
98+
)
99+
} catch {
100+
return .unreachable(error)
101+
}
102+
guard let httpResponse = response as? HTTPURLResponse else { return .notHTTP }
103+
guard httpResponse.statusCode == 200 else {
104+
return .rejected(AIHTTPReply(data: data, response: httpResponse))
105+
}
106+
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
107+
return .entries(json?[key] as? [[String: Any]])
108+
}
109+
110+
// A rejected key throws; any other answer is the provider's to judge.
111+
func connectionReply(to request: URLRequest) async throws -> AIHTTPReply? {
112+
let (data, response) = try await session.data(for: request, delegate: SameOriginRedirects.shared)
113+
guard let httpResponse = response as? HTTPURLResponse else { return nil }
114+
if httpResponse.statusCode == 401 || (httpResponse.statusCode == 403 && forbiddenIsAuthFailure) {
115+
throw AIProviderError.authenticationFailed("")
116+
}
117+
return AIHTTPReply(data: data, response: httpResponse)
118+
}
119+
120+
func httpError(_ reply: AIHTTPReply, url: URL?) -> AIProviderError {
121+
AIProviderError.mapHTTPError(
122+
statusCode: reply.statusCode,
123+
body: String(data: reply.data, encoding: .utf8) ?? "",
124+
treatForbiddenAsAuthFailure: forbiddenIsAuthFailure,
125+
requestURL: url
126+
)
127+
}
128+
129+
private func applyHeaders(to request: inout URLRequest) {
130+
for (field, value) in headers {
131+
request.setValue(value, forHTTPHeaderField: field)
132+
}
133+
}
134+
}

0 commit comments

Comments
 (0)