Skip to content

Commit

Permalink
improve withRetry utility
Browse files Browse the repository at this point in the history
  • Loading branch information
omochi committed May 22, 2024
1 parent b464865 commit 236774f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
13 changes: 10 additions & 3 deletions Tests/CartonCommandTests/CommandTestHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,17 +145,24 @@ func fetchWebContent(at url: URL, timeout: Duration) async throws -> (response:
return (response: response, body: body)
}

func withRetry<R>(maxAttempts: Int, delay: Duration, body: () async throws -> R) async throws -> R {
func withRetry<R>(
maxAttempts: Int,
initialDelay: Duration,
retryInterval: Duration,
body: () async throws -> R
) async throws -> R {
try await Task.sleep(for: initialDelay)

var attempt = 0
while true {
try await Task.sleep(for: delay)

attempt += 1
do {
return try await body()
} catch {
if attempt < maxAttempts {
print("attempt \(attempt) failed: \(error), retrying...")

try await Task.sleep(for: retryInterval)
continue
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/CartonCommandTests/DevCommandTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ final class DevCommandTests: XCTestCase {
let count = 5

do {
return try await withRetry(maxAttempts: count, delay: delay) {
return try await withRetry(maxAttempts: count, initialDelay: delay, retryInterval: delay) {
try await fetchWebContent(at: url, timeout: timeOut)
}
} catch {
Expand Down
8 changes: 6 additions & 2 deletions Tests/CartonCommandTests/FrontendDevServerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,16 @@ final class FrontendDevServerTests: XCTestCase {
defer {
devServer.signal(SIGINT)
}
try await Task.sleep(for: .seconds(3))

let host = try URL(string: "http://127.0.0.1:8080").unwrap("url")

do {
let indexHtml = try await fetchString(at: host)
let indexHtml = try await withRetry(
maxAttempts: 5, initialDelay: .seconds(3), retryInterval: .seconds(10)
) {
try await fetchString(at: host)
}

XCTAssertEqual(indexHtml, """
<!DOCTYPE html>
<html>
Expand Down

0 comments on commit 236774f

Please sign in to comment.