-
Notifications
You must be signed in to change notification settings - Fork 33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unify Configuration Management #241
Merged
Merged
Changes from 26 commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
156dd1d
Configuration PoC
jaceklyp 0b0e725
More tests, and cleaner API
jaceklyp 3dae118
Add more tests
jaceklyp 5f3e07c
Add payload validation
jaceklyp 4be949c
Get rid of ConfigurationTasks and add possibility to override urls in…
jaceklyp a1a13dd
Move code around
jaceklyp bf766e7
Move onDidStore to fetch method
jaceklyp 0bb3ea5
Merge branch 'main' into jacek/unify-configuration
jaceklyp e240c13
APIRequest refactor part1
jaceklyp 2261fe2
Continue refactoring
jaceklyp 147a030
Use OptionSet instead of array of options
jaceklyp b78d5e2
Fix tests
jaceklyp 2b4d58f
Add more tests
jaceklyp cf88a48
Create ConfigurationURLProvider to customize urls for Configuration
jaceklyp 25006d4
Fix typo
jaceklyp 2ebbd14
Provide setUserAgent method
jaceklyp c8242f9
Merge branch 'main' into jacek/unify-configuration
jaceklyp 156654d
Fix deployment target
jaceklyp 35c33d7
Fix compilation errors
jaceklyp 0ccd2ff
Fix tests failing on broken locale
jaceklyp f3650bc
Error messages + handling 304
jaceklyp dfe4307
Fix for 304 handling logic
jaceklyp 6bfae72
Update tests
jaceklyp a493f4c
Fix tests
jaceklyp 4a37765
Fix naming
jaceklyp d379db2
Fix test
jaceklyp c971ba9
Address PR comments
jaceklyp e3ba7d9
Address PR comments #2
jaceklyp 74333ef
Remove prints
jaceklyp 219280d
Fix warnings and add logger option
jaceklyp c2a4ff1
Make Error public
jaceklyp 54010a3
Add single configuration fetch method
jaceklyp 2f3dee2
Get rid of fetch(any:) method
jaceklyp 2f3bd90
Merge branch 'main' into jacek/unify-configuration
jaceklyp 351d4d9
Fix compilation errors
jaceklyp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
// | ||
// APIHeaders.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2023 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
|
||
public typealias HTTPHeaders = [String: String] | ||
|
||
public struct APIHeaders { | ||
|
||
public typealias UserAgent = String | ||
private static var userAgent: UserAgent? | ||
public static func setUserAgent(_ userAgent: UserAgent) { | ||
self.userAgent = userAgent | ||
} | ||
|
||
public init() { } | ||
|
||
public var defaultHeaders: HTTPHeaders { | ||
guard let userAgent = APIHeaders.userAgent else { | ||
fatalError("Please set the userAgent before accessing defaultHeaders.") | ||
} | ||
|
||
let acceptEncoding = "gzip;q=1.0, compress;q=0.5" | ||
let languages = Locale.preferredLanguages.prefix(6) | ||
let acceptLanguage = languages.enumerated().map { index, language in | ||
let q = 1.0 - (Double(index) * 0.1) | ||
return "\(language);q=\(q)" | ||
}.joined(separator: ", ") | ||
|
||
return [ | ||
HTTPHeaderField.acceptEncoding: acceptEncoding, | ||
HTTPHeaderField.acceptLanguage: acceptLanguage, | ||
HTTPHeaderField.userAgent: userAgent | ||
] | ||
} | ||
|
||
public func defaultHeaders(with etag: String?) -> HTTPHeaders { | ||
guard let etag = etag else { | ||
return defaultHeaders | ||
} | ||
return defaultHeaders.merging([HTTPHeaderField.ifNoneMatch: etag]) { (_, new) in new } | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
// | ||
// APIRequest.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2023 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
|
||
public typealias APIResponse = (data: Data?, response: HTTPURLResponse) | ||
public typealias APIRequestCompletion = (APIResponse?, APIRequest.Error?) -> Void | ||
|
||
public struct APIRequest { | ||
|
||
private let request: URLRequest | ||
private let urlSession: URLSession | ||
private let requirements: APIResponseRequirements | ||
|
||
public init<QueryParams: Collection>(configuration: APIRequest.Configuration<QueryParams>, | ||
requirements: APIResponseRequirements = [], | ||
urlSession: URLSession = .shared) { | ||
self.request = configuration.request | ||
self.requirements = requirements | ||
self.urlSession = urlSession | ||
} | ||
|
||
@available(*, deprecated, message: "This method is deprecated. Please use the 'fetch()' async method instead.") | ||
@discardableResult | ||
public func fetch(completion: @escaping APIRequestCompletion) -> URLSessionDataTask { | ||
let task = urlSession.dataTask(with: request) { (data, response, error) in | ||
if let error = error { | ||
completion(nil, .urlSession(error)) | ||
} else { | ||
do { | ||
let response = try self.validateAndUnwrap(data: data, response: response) | ||
completion(response, nil) | ||
} catch { | ||
completion(nil, error as? APIRequest.Error ?? .urlSession(error)) | ||
} | ||
} | ||
} | ||
task.resume() | ||
return task | ||
} | ||
|
||
private func validateAndUnwrap(data: Data?, response: URLResponse?) throws -> APIResponse { | ||
let httpResponse = try getHTTPResponse(from: response) | ||
|
||
var data = data | ||
if requirements.contains(.allow304), httpResponse.statusCode == HTTPURLResponse.Constants.notModifiedStatusCode { | ||
data = nil // Avoid returning empty data | ||
} else { | ||
try httpResponse.assertSuccessfulStatusCode() | ||
let data = data ?? Data() | ||
if requirements.contains(.nonEmptyData), data.isEmpty { | ||
throw APIRequest.Error.emptyData | ||
} | ||
} | ||
|
||
if requirements.contains(.etag), httpResponse.etag == nil { | ||
throw APIRequest.Error.missingEtagInResponse | ||
} | ||
|
||
return (data, httpResponse) | ||
} | ||
|
||
private func getHTTPResponse(from response: URLResponse?) throws -> HTTPURLResponse { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think you could remove this method and just define |
||
guard let httpResponse = response?.asHTTPURLResponse else { | ||
throw APIRequest.Error.invalidResponse | ||
} | ||
return httpResponse | ||
} | ||
|
||
public func fetch() async throws -> APIResponse { | ||
let (data, response) = try await fetch(for: request) | ||
return try validateAndUnwrap(data: data, response: response) | ||
} | ||
|
||
private func fetch(for request: URLRequest) async throws -> (Data, URLResponse) { | ||
do { | ||
return try await urlSession.data(for: request) | ||
} catch let error { | ||
throw Error.urlSession(error) | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// | ||
// APIRequestConfiguration.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2023 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
import Common | ||
|
||
extension APIRequest { | ||
|
||
public struct Configuration<QueryParams: Collection> where QueryParams.Element == (key: String, value: String) { | ||
|
||
let url: URL | ||
let method: HTTPMethod | ||
let queryParameters: QueryParams | ||
let allowedQueryReservedCharacters: CharacterSet? | ||
let headers: HTTPHeaders | ||
let body: Data? | ||
let timeoutInterval: TimeInterval | ||
let attribution: URLRequestAttribution? | ||
|
||
public init(url: URL, | ||
method: HTTPMethod = .get, | ||
queryParameters: QueryParams = [], | ||
allowedQueryReservedCharacters: CharacterSet? = nil, | ||
headers: HTTPHeaders = APIHeaders().defaultHeaders, | ||
body: Data? = nil, | ||
timeoutInterval: TimeInterval = 60.0, | ||
attribution: URLRequestAttribution? = nil) { | ||
self.url = url | ||
self.method = method | ||
self.queryParameters = queryParameters | ||
self.allowedQueryReservedCharacters = allowedQueryReservedCharacters | ||
self.headers = headers | ||
self.body = body | ||
self.timeoutInterval = timeoutInterval | ||
self.attribution = attribution | ||
} | ||
|
||
var request: URLRequest { | ||
let url = url.appendingParameters(queryParameters, allowedReservedCharacters: allowedQueryReservedCharacters) | ||
var request = URLRequest(url: url, timeoutInterval: timeoutInterval) | ||
request.allHTTPHeaderFields = headers | ||
request.httpMethod = method.rawValue | ||
request.httpBody = body | ||
if #available(iOS 15.0, macOS 12.0, *) { | ||
if let attribution = attribution?.urlRequestAttribution { | ||
request.attribution = attribution | ||
} | ||
} | ||
return request | ||
} | ||
|
||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// | ||
// APIRequestError.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2023 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
|
||
extension APIRequest { | ||
|
||
public enum Error: Swift.Error, LocalizedError { | ||
|
||
case urlSession(Swift.Error) | ||
case invalidResponse | ||
case missingEtagInResponse | ||
case emptyData | ||
case invalidStatusCode(Int) | ||
|
||
public var errorDescription: String? { | ||
switch self { | ||
case .urlSession(let error): | ||
return "URL session error: \(error.localizedDescription)" | ||
case .invalidResponse: | ||
return "Invalid response received." | ||
case .missingEtagInResponse: | ||
return "ETag header missing in response." | ||
case .emptyData: | ||
return "Empty data received in response." | ||
case .invalidStatusCode(let statusCode): | ||
return "Invalid status code received in response (\(statusCode))." | ||
} | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is time-sensitive, based on when
setUserAgent
is called, right? Shouldn't it rather be an assertion, to not crash the app on production?