-
Notifications
You must be signed in to change notification settings - Fork 32
/
Contents.swift
387 lines (294 loc) · 9.97 KB
/
Contents.swift
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//: [Previous](@previous)
import Alicerce
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
// MARK: Certificate Pinning
// for now, use the expiration date from the certificate itself
let gitHubRootExpirationDate = ISO8601DateFormatter().date(from: "2031-11-10T00:00:00Z")!
let gitHubPolicy = try ServerTrustEvaluator.PinningPolicy(
domainName: "github.com",
includeSubdomains: true,
expirationDate: gitHubRootExpirationDate,
pinnedHashes: ["WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="], // DigiCertHighAssuranceEVRootCA
enforceBackupPin: false // we should ideally have a backup pin that's not in the chain to avoid bricking clients
)
let configuration = try ServerTrustEvaluator.Configuration(
pinningPolicies: [gitHubPolicy],
certificateCheckingOrder: .rootToLeaf,
allowNotPinnedDomains: false,
allowExpiredDomainPolicies: false
)
let serverTrustEvaluator = try ServerTrustEvaluator(configuration: configuration)
// MARK: - Network Stack
let network = Network.URLSessionNetworkStack(
authenticationChallengeHandler: serverTrustEvaluator,
retryQueue: DispatchQueue(label: "com.alicerce.network.retry-queue")
)
network.session = URLSession(
configuration: .default,
delegate: network,
delegateQueue: nil
)
// MARK: - Endpoint
enum GitHubEndpoint: HTTPResourceEndpoint {
case repo(owner: String, name: String)
case repoCollaborators(owner: String, name: String, affiliation: RepoAffiliation = .all)
case nonExistent
enum RepoAffiliation: String {
case outside
case direct
case all
}
var method: HTTP.Method {
switch self {
case .repo, .repoCollaborators, .nonExistent:
return .GET
}
}
var baseURL: URL { URL(string: "https://api.github.com")! }
var path: String? {
switch self {
case .repo(let owner, let name):
return "/repos/\(owner)/\(name)"
case .repoCollaborators(let owner, let name, _):
return "/repos/\(owner)/\(name)/collaborators"
case .nonExistent:
return "/non/existent"
}
}
var queryItems: [URLQueryItem]? {
switch self {
case .repo, .nonExistent:
return nil
case .repoCollaborators(_, _, let affiliation):
return [URLQueryItem(name: "affiliation", value: affiliation.rawValue)]
}
}
var headers: HTTP.Headers? { ["Accept": "application/vnd.github.v3+json"] }
}
// MARK: Resource helpers
extension Network.URLSessionResource {
static func github(
endpoint: GitHubEndpoint,
interceptors: [URLSessionResourceInterceptor] = [],
retryActionPriority: @escaping Retry.Action.CompareClosure = Retry.Action.mostPrioritary
) -> Self {
.init(
baseRequestMaking: .endpoint(endpoint),
errorDecoding: .json(GitHubAPIError.self),
interceptors: interceptors
)
}
}
// MARK: API Error
enum GitHubAPIError: Error, Decodable {
case generic(message: String)
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let message = try container.decode(String.self, forKey: .message)
self = .generic(message: message)
}
private enum CodingKeys: String, CodingKey {
case message
}
}
// MARK: - Models
struct GitHubRepo: Decodable {
var name: String
var fullName: String
var stars: Int
private enum CodingKeys: String, CodingKey {
case name
case fullName = "full_name"
case stars = "stargazers_count"
}
}
struct GitHubRepoCollaborator: Decodable {
var login: String
var avatarURL: String
private enum CodingKeys: String, CodingKey {
case login
case avatarURL = "avatar_url"
}
}
// MARK: basic request
network.fetch(resource: .github(endpoint: .repo(owner: "Mindera", name: "Alicerce"))) { result in
switch result {
case .success(let value):
String(decoding: value.value, as: UTF8.self)
value.response
case .failure(.http(let statusCode, let apiError as GitHubAPIError, let response)):
apiError
statusCode
response
case .failure(let error):
error
}
}
network.fetchAndDecode(
resource: .github(endpoint: .repo(owner: "Mindera", name: "Alicerce")),
decoding: .json(GitHubRepo.self)
) { result in
switch result {
case .success(let value):
value
case .failure(.fetch(Network.URLSessionError.http(let statusCode, let apiError as GitHubAPIError, let response))):
apiError
statusCode
response
case .failure(let error):
error
}
}
// MARK: failing request (404 - resource not found)
network.fetch(resource: .github(endpoint: .nonExistent)) { result in
switch result {
case .success(let value):
value
case .failure(.http(let statusCode, let apiError as GitHubAPIError, let response)):
apiError
statusCode
response
case .failure(let error):
error
}
}
// MARK: failing request (retries)
let retryInterceptors: [URLSessionResourceInterceptor] = [
Network.URLSessionRetryPolicy.backoff(
.exponential(
baseDelay: 0.1,
scale: { delay, retry in delay * Double(retry) },
until: .maxDelay(0.4)
)
),
Network.URLSessionRetryPolicy.maxRetries(3) // try setting to higher retries (e.g. 4) to trigger different retryError
]
network.fetch(resource: .github(endpoint: .nonExistent, interceptors: retryInterceptors)) { result in
switch result {
case .success(let value):
value
case .failure(.retry(let retryError, let state)):
retryError
state
case .failure(let error):
error
}
}
// MARK: failing request (401 - requires authentication)
network.fetch(resource: .github(endpoint: .repoCollaborators(owner: "Mindera", name: "Alicerce"))) { result in
switch result {
case .success(let value):
value
case .failure(.retry(let retryError, let state)):
retryError
state
case .failure(let error):
error
}
}
// MARK: authenticated request
final class GitHubAuthenticator: URLRequestAuthenticator {
let personalAccessToken: String
init(personalAccessToken: String) {
self.personalAccessToken = personalAccessToken
}
@discardableResult
func authenticateRequest(_ request: URLRequest, handler: @escaping AuthenticationHandler) -> Cancelable {
// this is a basic example to show how to use an authenticator, using a hardcoded token
// on a real app this would be a "proper" authenticator for the GitHub API (e.g. using OAuth)
var request = request
var headers = request.allHTTPHeaderFields ?? [:]
headers["Authorization"] = "token \(personalAccessToken)"
request.allHTTPHeaderFields = headers
return handler(.success(request))
}
func evaluateFailedRequest(
_ request: URLRequest,
data: Data?,
response: URLResponse?,
error: Error,
retryState: Retry.State
) -> Retry.Action {
// here we could intercept authentication errors (e.g. 401 Unauthorized) and trigger a reauthentication, while
// instructing the resource to be retried accordingly (e.g. after a certain amount of time), or not (e.g. user
// is logged out)
return .none
}
}
extension GitHubAuthenticator: URLSessionResourceInterceptor {}
// https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line
let authenticator = GitHubAuthenticator(personalAccessToken: "<#personalAccessToken#>")
network.fetchAndDecode(
resource: .github(
endpoint: .repoCollaborators(owner: "Mindera", name: "Alicerce", affiliation: .all),
interceptors: [authenticator] + retryInterceptors
),
decoding: .json([GitHubRepoCollaborator].self)
) { result in
switch result {
case .success(let value):
value
case .failure(.fetch(Network.URLSessionError.retry(let retryError, let state))):
retryError
state
case .failure(let error):
error
}
}
// MARK: logged request
final class URLSessionResourceLogger: URLSessionResourceInterceptor {
func interceptScheduledTask(withIdentifier identifier: Int, request: URLRequest, retryState: Retry.State) {
print("🚀 Task #\(identifier) with URL: '\(request.url!)' (attempt #\(retryState.attemptCount)) scheduled...")
}
func interceptSuccessfulTask(
withIdentifier identifier: Int,
request: URLRequest,
data: Data,
response: URLResponse,
retryState: Retry.State
) {
print(
"""
🎉 Task #\(identifier) with URL: '\(request.url!)' (attempt #\(retryState.attemptCount)) \
completed successfully!
"""
)
}
func interceptFailedTask(
withIdentifier identifier: Int,
request: URLRequest,
data: Data?,
response: URLResponse?,
error: Network.URLSessionError,
retryState: Retry.State
) -> Retry.Action {
print(
"""
💥 Task #\(identifier) with URL: '\(request.url!)' (attempt #\(retryState.attemptCount)) \
failed with error: \(error.localizedDescription)!
"""
)
return .none
}
}
let resourceLogger = URLSessionResourceLogger()
network.fetchAndDecode(
resource: .github(
endpoint: .repoCollaborators(owner: "Mindera", name: "Alicerce", affiliation: .all),
interceptors: [resourceLogger, authenticator] + retryInterceptors
),
decoding: .json([GitHubRepoCollaborator].self)
) { result in
switch result {
case .success(let value):
value
case .failure(.fetch(Network.URLSessionError.retry(let retryError, let state))):
retryError
state
case .failure(let error):
error
}
}
//: [Next](@next)