Skip to content

Commit

Permalink
1.8.1
Browse files Browse the repository at this point in the history
  • Loading branch information
dankinsoid committed May 5, 2024
1 parent d5f8245 commit 3ed7acf
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 104 deletions.
32 changes: 16 additions & 16 deletions Sources/SwiftAPIClient/APIClientCaller.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,25 +187,25 @@ public extension APIClient {
let message = configs.loggingComponents.requestMessage(for: request, uuid: uuid, fileIDLine: fileIDLine)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if let mock = try configs.getMockIfNeeded(for: Value.self, serializer: serializer) {
return try caller.mockResult(for: mock)
}
if configs.reportMetrics {
updateTotalRequestsMetrics(for: request)
}
if let mock = try configs.getMockIfNeeded(for: Value.self, serializer: serializer) {
return try caller.mockResult(for: mock)
}
if configs.reportMetrics {
updateTotalRequestsMetrics(for: request)
}

return try caller.call(uuid: uuid, request: request, configs: configs) { response, validate in
do {
try validate()
let result = try serializer.serialize(response, configs)
if configs.reportMetrics {
updateTotalResponseMetrics(for: request, successful: true)
}
return result
if configs.reportMetrics {
updateTotalResponseMetrics(for: request, successful: true)
}
return result
} catch {
if configs.reportMetrics {
updateTotalResponseMetrics(for: request, successful: false)
}
if configs.reportMetrics {
updateTotalResponseMetrics(for: request, successful: false)
}
if let data = response as? Data, let failure = configs.errorDecoder.decodeError(data, configs) {
try configs.errorHandler(failure, configs)
throw failure
Expand All @@ -226,9 +226,9 @@ public extension APIClient {
)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if configs.reportMetrics {
updateTotalErrorsMetrics(for: nil)
}
if configs.reportMetrics {
updateTotalErrorsMetrics(for: nil)
}
try configs.errorHandler(error, configs)
}
throw error
Expand Down
38 changes: 19 additions & 19 deletions Sources/SwiftAPIClient/Clients/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,19 @@ extension APIClientCaller where Result == AsyncThrowingValue<Value> {
let start = Date()
do {
(value, response) = try await configs.httpClientMiddleware.execute(request: request, configs: configs, next: task)
} catch {
let duration = Date().timeIntervalSince(start)
if !configs.loggingComponents.isEmpty {
let message = configs.loggingComponents.errorMessage(
uuid: uuid,
error: error,
duration: duration
)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: nil, duration: duration, successful: false)
}
} catch {
let duration = Date().timeIntervalSince(start)
if !configs.loggingComponents.isEmpty {
let message = configs.loggingComponents.errorMessage(
uuid: uuid,
error: error,
duration: duration
)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: nil, duration: duration, successful: false)
}
throw error
}
let duration = Date().timeIntervalSince(start)
Expand All @@ -127,9 +127,9 @@ extension APIClientCaller where Result == AsyncThrowingValue<Value> {
)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: response.status, duration: duration, successful: true)
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: response.status, duration: duration, successful: true)
}
return result
} catch {
if !configs.loggingComponents.isEmpty {
Expand All @@ -142,9 +142,9 @@ extension APIClientCaller where Result == AsyncThrowingValue<Value> {
)
configs.logger.log(level: configs.logLevel, "\(message)")
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: response.status, duration: duration, successful: false)
}
if configs.reportMetrics {
updateHTTPMetrics(for: request, status: response.status, duration: duration, successful: false)
}
throw error
}
}
Expand Down
22 changes: 11 additions & 11 deletions Sources/SwiftAPIClient/Modifiers/MetricsModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import Foundation

public extension APIClient {

/// Whether to report metrics.
/// - Parameter reportMetrics: A boolean value indicating whether to report metrics.
/// - Returns: An instance of `APIClient` configured with the specified metrics reporting setting.
func reportMetrics(_ reportMetrics: Bool) -> APIClient {
configs(\.reportMetrics, reportMetrics)
}
/// Whether to report metrics.
/// - Parameter reportMetrics: A boolean value indicating whether to report metrics.
/// - Returns: An instance of `APIClient` configured with the specified metrics reporting setting.
func reportMetrics(_ reportMetrics: Bool) -> APIClient {
configs(\.reportMetrics, reportMetrics)
}
}

public extension APIClient.Configs {

/// Whether to report metrics.
var reportMetrics: Bool {
get { self[\.reportMetrics] ?? true }
set { self[\.reportMetrics] = newValue }
}
/// Whether to report metrics.
var reportMetrics: Bool {
get { self[\.reportMetrics] ?? true }
set { self[\.reportMetrics] = newValue }
}
}
10 changes: 5 additions & 5 deletions Sources/SwiftAPIClient/Modifiers/RequestModifiers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -300,15 +300,15 @@ public extension RequestBuilder where Request == HTTPRequestComponents {
if let host = newBaseURL.host(percentEncoded: false) {
$0.urlComponents.host = host
}
let path = newBaseURL.path(percentEncoded: false)
if !path.isEmpty, path != "/" {
$0.prependPath(path)
}
let path = newBaseURL.path(percentEncoded: false)
if !path.isEmpty, path != "/" {
$0.prependPath(path)
}
} else {
if let host = newBaseURL.host {
$0.urlComponents.percentEncodedHost = host
}
if !newBaseURL.path.isEmpty, newBaseURL.path != "/" {
if !newBaseURL.path.isEmpty, newBaseURL.path != "/" {
$0.prependPath(newBaseURL.path, percentEncoded: true)
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftAPIClient/Modifiers/RetryModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private struct RetryMiddleware: HTTPClientMiddleware {
}
throw error
}
if response.status.kind.isError, needRetry() {
if response.status.kind.isError, needRetry() {
return try await retry()
}
return (data, response)
Expand Down
20 changes: 10 additions & 10 deletions Sources/SwiftAPIClient/Types/LoggingComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,16 @@ public extension LoggingComponents {
if contains(.uuid) {
message = "[\(uuid.uuidString)]\n" + message
}
switch (statusCode?.kind, error) {
case (_, .some), (.serverError, _), (.clientError, _), (.invalid, _):
message.append("🛑")
case (.successful, _), (nil, nil):
message.append("")
case (.informational, _):
message.append("ℹ️")
case (.redirection, _):
message.append("🔀")
}
switch (statusCode?.kind, error) {
case (_, .some), (.serverError, _), (.clientError, _), (.invalid, _):
message.append("🛑")
case (.successful, _), (nil, nil):
message.append("")
case (.informational, _):
message.append("ℹ️")
case (.redirection, _):
message.append("🔀")
}
var isMultiline = false
if let statusCode, contains(.statusCode) {
message += " \(statusCode.code) \(statusCode.reasonPhrase)"
Expand Down
6 changes: 3 additions & 3 deletions Sources/SwiftAPIClient/Utils/Status+Ext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import HTTPTypes

extension HTTPResponse.Status.Kind {

var isError: Bool {
self == .clientError || self == .serverError || self == .invalid
}
var isError: Bool {
self == .clientError || self == .serverError || self == .invalid
}
}
78 changes: 39 additions & 39 deletions Sources/SwiftAPIClient/Utils/UpdateMetrics.swift
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
import Metrics
import HTTPTypes
import Foundation
import HTTPTypes
import Metrics

func updateTotalRequestsMetrics(
for request: HTTPRequestComponents
for request: HTTPRequestComponents
) {
Counter(
label: "api_client_requests_total",
dimensions: dimensions(for: request)
).increment()
Counter(
label: "api_client_requests_total",
dimensions: dimensions(for: request)
).increment()
}

func updateTotalResponseMetrics(
for request: HTTPRequestComponents,
successful: Bool
for request: HTTPRequestComponents,
successful: Bool
) {
Counter(
label: "api_client_responses_total",
dimensions: dimensions(for: request) + [("successful", successful.description)]
).increment()
if !successful {
updateTotalErrorsMetrics(for: request)
}
Counter(
label: "api_client_responses_total",
dimensions: dimensions(for: request) + [("successful", successful.description)]
).increment()
if !successful {
updateTotalErrorsMetrics(for: request)
}
}

func updateTotalErrorsMetrics(
for request: HTTPRequestComponents?
for request: HTTPRequestComponents?
) {
Counter(
label: "api_client_errors_total",
dimensions: dimensions(for: request)
).increment()
Counter(
label: "api_client_errors_total",
dimensions: dimensions(for: request)
).increment()
}

func updateHTTPMetrics(
for request: HTTPRequestComponents?,
status: HTTPResponse.Status?,
duration: Double,
successful: Bool
for request: HTTPRequestComponents?,
status: HTTPResponse.Status?,
duration: Double,
successful: Bool
) {
var dimensions = dimensions(for: request)
dimensions.append(("status", status?.code.description ?? "undefined"))
dimensions.append(("successful", successful.description))
Timer(
label: "http_client_request_duration_seconds",
dimensions: dimensions,
preferredDisplayUnit: .seconds
)
.recordSeconds(duration)
var dimensions = dimensions(for: request)
dimensions.append(("status", status?.code.description ?? "undefined"))
dimensions.append(("successful", successful.description))
Timer(
label: "http_client_request_duration_seconds",
dimensions: dimensions,
preferredDisplayUnit: .seconds
)
.recordSeconds(duration)
}

private func dimensions(
for request: HTTPRequestComponents?
for request: HTTPRequestComponents?
) -> [(String, String)] {
[
("method", request?.method.rawValue ?? "undefined"),
("path", request?.urlComponents.path ?? "undefined")
]
[
("method", request?.method.rawValue ?? "undefined"),
("path", request?.urlComponents.path ?? "undefined"),
]
}

0 comments on commit 3ed7acf

Please sign in to comment.