Skip to content

Commit

Permalink
♻️ Retry downloads upon network failure up to three times
Browse files Browse the repository at this point in the history
  • Loading branch information
chris-araman committed May 9, 2021
1 parent c3ef7b4 commit 4dee61d
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion Sources/MasKit/AppStore/Downloader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import StoreFoundation
func downloadAll(_ appIDs: [UInt64], purchase: Bool = false) -> Promise<Void> {
var firstError: Error?
return appIDs.reduce(Guarantee<Void>.value(())) { previous, appID in
previous.then { download(appID, purchase: purchase).recover { error in
previous.then { downloadWithRetries(appID, purchase: purchase).recover { error in
if firstError == nil {
firstError = error
}
Expand All @@ -32,6 +32,27 @@ func downloadAll(_ appIDs: [UInt64], purchase: Bool = false) -> Promise<Void> {
}
}

private func downloadWithRetries(
_ appID: UInt64, purchase: Bool = false, attempts: Int = 3
) -> Promise<Void> {
download(appID, purchase: purchase).recover { error -> Promise<Void> in
guard attempts > 1 else {
throw error
}

// If the download failed due to network issues, try again. Otherwise, fail immediately.
guard case MASError.downloadFailed(let downloadError) = error,
case NSURLErrorDomain = downloadError?.domain else {
throw error
}

let attempts = attempts - 1
printWarning((downloadError ?? error).localizedDescription)
print("Trying again up to \(attempts) more \(attempts == 1 ? "time" : "times").")
return downloadWithRetries(appID, purchase: purchase, attempts: attempts)
}
}

/// Downloads an app, printing progress to the console.
///
/// - Parameter appID: The ID of the app to be downloaded
Expand Down

0 comments on commit 4dee61d

Please sign in to comment.