Skip to content
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

use retry after instead of calculating delay #166

Merged
merged 4 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Sources/KlaviyoSwift/APIRequestErrorHandling.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@ enum InvalidField: Equatable {
}
}

private func getDelaySeconds(for count: Int) -> Int {
let delay = Int(pow(2.0, Double(count)))
private func addJitter(to value: Int) -> Int {
let jitter = environment.randomInt()
return min(delay + jitter, ErrorHandlingConstants.maxBackoff)
return value + jitter
}

private func parseError(_ data: Data) -> [InvalidField]? {
Expand Down Expand Up @@ -100,7 +99,7 @@ func handleRequestError(
environment.emitDeveloperWarning("Invalid data supplied for request. Skipping.")
return .deQueueCompletedResults(request)

case .rateLimitError:
case let .rateLimitError(retryAfter):
var requestRetryCount = 0
var totalRetryCount = 0
var nextBackoff = 0
Expand All @@ -112,7 +111,9 @@ func handleRequestError(
case let .retryWithBackoff(requestCount, totalCount, _):
requestRetryCount = requestCount + 1
totalRetryCount = totalCount + 1
nextBackoff = getDelaySeconds(for: totalRetryCount)
let exponentialBackOff = Int(pow(2.0, Double(totalRetryCount)))

nextBackoff = addJitter(to: retryAfter ?? exponentialBackOff)
}
return .requestFailed(
request, .retryWithBackoff(
Expand Down
5 changes: 3 additions & 2 deletions Sources/KlaviyoSwift/KlaviyoAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ struct KlaviyoAPI {

enum KlaviyoAPIError: Error {
case httpError(Int, Data)
case rateLimitError
case rateLimitError(Int?)
case missingOrInvalidResponse(URLResponse?)
case networkError(Error)
case internalError(String)
Expand Down Expand Up @@ -70,7 +70,8 @@ struct KlaviyoAPI {

if httpResponse.statusCode == 429 {
requestRateLimited(request)
return .failure(KlaviyoAPIError.rateLimitError)
let retryAfter = Int(httpResponse.value(forHTTPHeaderField: "Retry-After") ?? "0")
return .failure(KlaviyoAPIError.rateLimitError(retryAfter))
}

guard 200..<300 ~= httpResponse.statusCode else {
Expand Down
23 changes: 21 additions & 2 deletions Tests/KlaviyoSwiftTests/APIRequestErrorHandlingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ class APIRequestErrorHandlingTests: XCTestCase {
initialState.requestsInFlight = [request]
let store = TestStore(initialState: initialState, reducer: KlaviyoReducer())

environment.analytics.klaviyoAPI.send = { _ in .failure(.rateLimitError) }
environment.analytics.klaviyoAPI.send = { _ in .failure(.rateLimitError(nil)) }

_ = await store.send(.sendRequest)

Expand All @@ -273,7 +273,7 @@ class APIRequestErrorHandlingTests: XCTestCase {
initialState.requestsInFlight = [request]
let store = TestStore(initialState: initialState, reducer: KlaviyoReducer())

environment.analytics.klaviyoAPI.send = { _ in .failure(.rateLimitError) }
environment.analytics.klaviyoAPI.send = { _ in .failure(.rateLimitError(nil)) }

_ = await store.send(.sendRequest)

Expand All @@ -285,6 +285,25 @@ class APIRequestErrorHandlingTests: XCTestCase {
}
}

func testRetryWithRetryAfter() async throws {
var initialState = INITIALIZED_TEST_STATE()
initialState.retryInfo = .retryWithBackoff(requestCount: 3, totalRetryCount: 3, currentBackoff: 4)
let request = initialState.buildProfileRequest(apiKey: initialState.apiKey!, anonymousId: initialState.anonymousId!)
initialState.requestsInFlight = [request]
let store = TestStore(initialState: initialState, reducer: KlaviyoReducer())

environment.analytics.klaviyoAPI.send = { _ in .failure(.rateLimitError(20)) }

_ = await store.send(.sendRequest)

await store.receive(.requestFailed(request, .retryWithBackoff(requestCount: 4, totalRetryCount: 4, currentBackoff: 20)), timeout: TIMEOUT_NANOSECONDS) {
$0.flushing = false
$0.queue = [request]
$0.requestsInFlight = []
$0.retryInfo = .retryWithBackoff(requestCount: 4, totalRetryCount: 4, currentBackoff: 20)
}
}

// MARK: - Missing or invalid response

func testMissingOrInvalidResponse() async throws {
Expand Down
Loading