Skip to content

Commit

Permalink
issue #721 Refactor usages of URLSession.call (#982)
Browse files Browse the repository at this point in the history
* Refactor usages of URLSession.call

* URLSession extension updated
  • Loading branch information
ivan-ushakov authored Nov 10, 2021
1 parent 5c62780 commit 9ba1f40
Show file tree
Hide file tree
Showing 6 changed files with 14 additions and 80 deletions.
36 changes: 3 additions & 33 deletions FlowCrypt/Extensions/URLSessionExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import FlowCryptCommon
import Foundation
import Promises

struct HttpRes {
let status: Int
Expand All @@ -17,8 +16,6 @@ struct HttpErr: Error {
let error: Error?
}

private let logger = Logger.nested("URLSession")

private func toString(_ trace: Trace) -> String {
let result = trace.result()
if result < 1.0 {
Expand All @@ -28,35 +25,8 @@ private func toString(_ trace: Trace) -> String {
}

extension URLSession {
func call(_ urlRequest: URLRequest, tolerateStatus: [Int]? = nil) -> Promise<HttpRes> {
Promise { resolve, reject in
let trace = Trace(id: "call")
self.dataTask(with: urlRequest) { data, response, error in
let res = response as? HTTPURLResponse
let status = res?.statusCode ?? GeneralConstants.Global.generalError
let urlMethod = urlRequest.httpMethod ?? "GET"
let urlString = urlRequest.url?.stringWithFilteredTokens ?? "??"
let headers = urlRequest.headersWithFilteredTokens
let message = "URLSession.call status:\(status) \(toString(trace)) \(urlMethod) \(urlString), headers: \(headers)"
Logger.nested("URLSession").logInfo(message)

let validStatusCode = 200 ... 299
let isInToleranceStatusCodes = (tolerateStatus?.contains(status) ?? false)
let isCodeValid = validStatusCode ~= status || isInToleranceStatusCodes
let isValidResponse = error == nil && isCodeValid
if let data = data, isValidResponse {
resolve(HttpRes(status: status, data: data))
} else {
reject(HttpErr(status: status, data: data, error: error))
}
}.resume()
}
}
}

extension URLSession {
func asyncCall(_ urlRequest: URLRequest, tolerateStatus: [Int]? = nil) async throws -> HttpRes {
let trace = Trace(id: "asyncCall")
func call(_ urlRequest: URLRequest, tolerateStatus: [Int]? = nil) async throws -> HttpRes {
let trace = Trace(id: "call")

var data: Data?
var response: URLResponse?
Expand All @@ -72,7 +42,7 @@ extension URLSession {
let urlMethod = urlRequest.httpMethod ?? "GET"
let urlString = urlRequest.url?.stringWithFilteredTokens ?? "??"
let headers = urlRequest.headersWithFilteredTokens
let message = "URLSession.asyncCall status:\(status) \(toString(trace)) \(urlMethod) \(urlString), headers: \(headers)"
let message = "URLSession.call status:\(status) \(toString(trace)) \(urlMethod) \(urlString), headers: \(headers)"
Logger.nested("URLSession").logInfo(message)

let validStatusCode = 200 ... 299
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class EnterpriseServerApi: EnterpriseServerApiType {
timeout: Constants.getActiveFesTimeout,
tolerateStatus: Constants.getToleratedHTTPStatuses
)
let response = try await ApiCall.asyncCall(request)
let response = try await ApiCall.call(request)

if Constants.getToleratedHTTPStatuses.contains(response.status) {
return nil
Expand Down Expand Up @@ -114,7 +114,7 @@ class EnterpriseServerApi: EnterpriseServerApiType {
apiName: Constants.apiName,
url: "https://fes.\(userDomain)/api/v1/client-configuration?domain=\(userDomain)"
)
let safeReponse = try await ApiCall.asyncCall(request)
let safeReponse = try await ApiCall.call(request)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
Expand Down
40 changes: 2 additions & 38 deletions FlowCrypt/Functionality/Services/ApiCall.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
//

import Foundation
import Promises

enum ApiCall {}

Expand All @@ -24,42 +23,7 @@ extension ApiCall {
}

extension ApiCall {
static func call(_ request: Request) -> Promise<HttpRes> {
Promise { () -> HttpRes in
guard let url = URL(string: request.url) else {
throw HttpErr(
status: -2,
data: Data(),
error: AppErr.unexpected("Invalid url: \(request.url)")
)
}

var urlRequest = URLRequest.urlRequest(
with: url,
method: request.method,
body: request.body,
headers: request.headers
)
urlRequest.timeoutInterval = request.timeout

do {
let result = try awaitPromise(URLSession.shared.call(
urlRequest,
tolerateStatus: request.tolerateStatus)
)
return result
} catch {
guard let httpError = error as? HttpErr else {
throw error
}
throw ApiError.create(from: httpError, request: request)
}
}
}
}

extension ApiCall {
static func asyncCall(_ request: Request) async throws -> HttpRes {
static func call(_ request: Request) async throws -> HttpRes {
guard let url = URL(string: request.url) else {
throw HttpErr(
status: -2,
Expand All @@ -77,7 +41,7 @@ extension ApiCall {
urlRequest.timeoutInterval = request.timeout

do {
let result = try await URLSession.shared.asyncCall(
let result = try await URLSession.shared.call(
urlRequest,
tolerateStatus: request.tolerateStatus
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ actor EmailKeyManagerApi: EmailKeyManagerApiType {
body: nil,
headers: headers
)
let response = try await ApiCall.asyncCall(request)
let response = try await ApiCall.call(request)
let decryptedPrivateKeysResponse = try JSONDecoder().decode(DecryptedPrivateKeysResponse.self, from: response.data)

if decryptedPrivateKeysResponse.privateKeys.isEmpty {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ extension AttesterApi {
timeout: Constants.lookupEmailRequestTimeout,
tolerateStatus: [404]
)
let res = try await ApiCall.asyncCall(request)
let res = try await ApiCall.call(request)

if res.status >= 200, res.status <= 299 {
return try await core.parseKeys(armoredOrBinary: res.data).keyDetails
Expand Down Expand Up @@ -93,7 +93,7 @@ extension AttesterApi {
body: pubkey.data(),
headers: headers
)
let res = try await ApiCall.asyncCall(request)
let res = try await ApiCall.call(request)
return res.data.toStr()
}

Expand All @@ -105,7 +105,7 @@ extension AttesterApi {
method: .post,
body: pubkey.data()
)
let res = try await ApiCall.asyncCall(request)
let res = try await ApiCall.call(request)
return res.data.toStr()
}

Expand All @@ -117,6 +117,6 @@ extension AttesterApi {
body: try? JSONSerialization.data(withJSONObject: ["email": email, "pubkey": pubkey]),
headers: [URLHeader(value: "application/json", httpHeaderField: "Content-Type")]
)
_ = try await ApiCall.asyncCall(request) // will throw on non-200
_ = try await ApiCall.call(request) // will throw on non-200
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ extension WkdApi {
url: urls.policy,
timeout: Constants.lookupEmailRequestTimeout
)
_ = try await ApiCall.asyncCall(request)
_ = try await ApiCall.call(request)
} catch {
Logger.nested("WkdApi").logInfo("Failed to load \(urls.policy) with error \(error)")
return (hasPolicy: false, key: nil)
Expand All @@ -86,7 +86,7 @@ extension WkdApi {
timeout: Constants.lookupEmailRequestTimeout,
tolerateStatus: [404]
)
let pubKeyResponse = try await ApiCall.asyncCall(request)
let pubKeyResponse = try await ApiCall.call(request)
if !pubKeyResponse.data.toStr().isEmpty {
Logger.nested("WKDURLsService").logInfo("Loaded WKD url \(urls.pubKeys) and will try to extract Public Keys")
}
Expand Down

0 comments on commit 9ba1f40

Please sign in to comment.