-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathHttpClient.swift
More file actions
196 lines (159 loc) · 6.68 KB
/
Copy pathHttpClient.swift
File metadata and controls
196 lines (159 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import Foundation
/// An internal protocol for HTTP clients.
///
/// Outside of tests, this is implemented by ``PlatformHttpClient`` as a thin wrapper around
/// ``URLSession``. In tests, we can use a mock implementation to test the sync client instead.
///
/// This is an internal protocol and tailored towards what the sync client actually needs. It is not
/// a general-purpose HTTP client.
protocol HttpClient: Sendable {
/// Start streaming a `/sync/stream` response body, emitting individual lines.
///
/// Throws an ``UnexpectedResponseError`` if the response can't be interpreted as sync lines.
func receiveSyncLines(request: URLRequest) async throws -> (HTTPURLResponse, any SyncLineResponse)
/// Read a full response body.
func readFully(request: URLRequest) async throws -> (HTTPURLResponse, Data)
}
struct UnexpectedResponseError: Error, CustomDebugStringConvertible {
let response: HTTPURLResponse
let message: String
var debugDescription: String {
message
}
}
protocol SyncLineResponse: Sendable, AsyncSequence where AsyncIterator: SyncLineResponseIterator {}
protocol SyncLineResponseIterator: AsyncIteratorProtocol {
mutating func next() async throws -> SyncLine?
}
enum SyncLine {
case text(contents: String)
// In the future, we might also want to support splitting BSON objects. Currently, we stream JSON only.
//case binary(contents: Data)
}
struct PlatformHttpClient: HttpClient {
let session: URLSession
func receiveSyncLines(request: URLRequest) async throws -> (HTTPURLResponse, any SyncLineResponse) {
let (bytes, originalResponse) = try await session.bytes(for: request)
let response = originalResponse as! HTTPURLResponse
let jsonStreamMimeType = "application/x-ndjson"
if response.mimeType != jsonStreamMimeType {
throw UnexpectedResponseError(
response: response,
message: "Invalid sync lines response, (expected \(jsonStreamMimeType), got \(response.mimeType, default: "")"
)
}
struct PlatformSyncLineResponse<Base>: SyncLineResponse where Base : AsyncSequence, Base.Element == UInt8, Base: Sendable {
let lines: AsyncLineSequence<Base>
func makeAsyncIterator() -> some SyncLineResponseIterator {
return PlatformSyncLineResponseIterator<Base>(inner: lines.makeAsyncIterator())
}
}
struct PlatformSyncLineResponseIterator<Base>: SyncLineResponseIterator where Base : AsyncSequence, Base.Element == UInt8, Base: Sendable {
typealias Element = SyncLine
var inner: AsyncLineSequence<Base>.AsyncIterator
mutating func next() async throws -> SyncLine? {
let line = try await inner.next()
return line.map { SyncLine.text(contents: $0) }
}
}
return (response, PlatformSyncLineResponse(lines: bytes.lines))
}
func readFully(request: URLRequest) async throws -> (HTTPURLResponse, Data) {
let (data, response) = try await session.data(for: request)
return (response as! HTTPURLResponse, data)
}
}
/// A wrapper around a ``HttpClient`` emitting log events for responses and sync lines.
struct LoggingClient: HttpClient {
let inner: HttpClient
let logger: SyncRequestLoggerConfiguration
fileprivate var shouldLogInfo: Bool {
logger.requestLevel != .none
}
fileprivate var shouldLogHeaders: Bool {
logger.requestLevel == .all || logger.requestLevel == .headers
}
fileprivate var shouldLogBody: Bool {
logger.requestLevel == .all || logger.requestLevel == .body
}
func receiveSyncLines(request: URLRequest) async throws -> (HTTPURLResponse, any SyncLineResponse) {
logRequest(request: request)
do {
let (response, lines) = try await inner.receiveSyncLines(request: request)
logResponse(response: response)
return (response, LogSyncLines(logger: self, inner: lines))
} catch {
logError(error: error)
throw error
}
}
func readFully(request: URLRequest) async throws -> (HTTPURLResponse, Data) {
logRequest(request: request)
do {
let (response, data) = try await inner.readFully(request: request)
logResponse(response: response)
if shouldLogBody, let content = String(data: data, encoding: .utf8) {
logger.log(" Response: \(content)")
}
return (response, data)
} catch {
logError(error: error)
throw error
}
}
private func logRequest(request: URLRequest) {
if shouldLogInfo, let method = request.httpMethod, let url = request.url {
logger.log("Starting request to \(method) \(url)")
}
if shouldLogHeaders, let headers = request.allHTTPHeaderFields {
for (key, value) in headers {
logger.log("with header \(key): \(value)")
}
}
if shouldLogBody, let rawBody = request.httpBody, let body = String(data: rawBody, encoding: .utf8) {
logger.log("with body: \(body)")
}
if shouldLogInfo {
logger.log("sending request")
}
}
private func logResponse(response: HTTPURLResponse) {
if shouldLogInfo, let url = response.url {
logger.log("Got response code \(response.statusCode) on \(url)")
}
if shouldLogHeaders {
for (key, value) in response.allHeaderFields {
logger.log("with header \(key): \(value)")
}
}
}
private func logError(error: any Error) {
if shouldLogInfo {
logger.log("Error: \(error)")
}
}
}
private struct LogSyncLines: SyncLineResponse, Sendable {
typealias AsyncIterator = LogSyncLinesIterator
let logger: LoggingClient
let inner: any SyncLineResponse
func makeAsyncIterator() -> LogSyncLinesIterator {
LogSyncLinesIterator(logger: logger, inner: inner.makeAsyncIterator())
}
}
private struct LogSyncLinesIterator: SyncLineResponseIterator {
let logger: LoggingClient
var inner: any SyncLineResponseIterator
mutating func next() async throws -> SyncLine? {
let line = try await self.inner.next()
if logger.shouldLogBody {
switch line {
case .none:
logger.logger.log("End of response")
case .some(.text(contents: let contents)):
logger.logger.log("Response line: \(contents)")
}
}
return line
}
}