RetryStrategy.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. //
  2. // RetryStrategy.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/05/04.
  6. //
  7. // Copyright (c) 2020 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// Represents a retry context which could be used to determine the current retry status.
  28. public class RetryContext {
  29. /// The source from which the target image should be retrieved.
  30. public let source: Source
  31. /// The last error which caused current retry behavior.
  32. public let error: KingfisherError
  33. /// The retried count before current retry happens. This value is `0` if the current retry is for the first time.
  34. public var retriedCount: Int
  35. /// A user set value for passing any other information during the retry. If you choose to use `RetryDecision.retry`
  36. /// as the retry decision for `RetryStrategy.retry(context:retryHandler:)`, the associated value of
  37. /// `RetryDecision.retry` will be delivered to you in the next retry.
  38. public internal(set) var userInfo: Any? = nil
  39. init(source: Source, error: KingfisherError) {
  40. self.source = source
  41. self.error = error
  42. self.retriedCount = 0
  43. }
  44. @discardableResult
  45. func increaseRetryCount() -> RetryContext {
  46. retriedCount += 1
  47. return self
  48. }
  49. }
  50. /// Represents decision of behavior on the current retry.
  51. public enum RetryDecision {
  52. /// A retry should happen. The associated `userInfo` will be pass to the next retry in the `RetryContext` parameter.
  53. case retry(userInfo: Any?)
  54. /// There should be no more retry attempt. The image retrieving process will fail with an error.
  55. case stop
  56. }
  57. /// Defines a retry strategy can be applied to a `.retryStrategy` option.
  58. public protocol RetryStrategy {
  59. /// Kingfisher calls this method if an error happens during the image retrieving process from a `KingfisherManager`.
  60. /// You implement this method to provide necessary logic based on the `context` parameter. Then you need to call
  61. /// `retryHandler` to pass the retry decision back to Kingfisher.
  62. ///
  63. /// - Parameters:
  64. /// - context: The retry context containing information of current retry attempt.
  65. /// - retryHandler: A block you need to call with a decision of whether the retry should happen or not.
  66. func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void)
  67. }
  68. /// A retry strategy that guides Kingfisher to retry when a `.responseError` happens, with a specified max retry count
  69. /// and a certain interval mechanism.
  70. public struct DelayRetryStrategy: RetryStrategy {
  71. /// Represents the interval mechanism which used in a `DelayRetryStrategy`.
  72. public enum Interval {
  73. /// The next retry attempt should happen in fixed seconds. For example, if the associated value is 3, the
  74. /// attempts happens after 3 seconds after the previous decision is made.
  75. case seconds(TimeInterval)
  76. /// The next retry attempt should happen in an accumulated duration. For example, if the associated value is 3,
  77. /// the attempts happens with interval of 3, 6, 9, 12, ... seconds.
  78. case accumulated(TimeInterval)
  79. /// Uses a block to determine the next interval. The current retry count is given as a parameter.
  80. case custom(block: (_ retriedCount: Int) -> TimeInterval)
  81. func timeInterval(for retriedCount: Int) -> TimeInterval {
  82. let retryAfter: TimeInterval
  83. switch self {
  84. case .seconds(let interval):
  85. retryAfter = interval
  86. case .accumulated(let interval):
  87. retryAfter = Double(retriedCount + 1) * interval
  88. case .custom(let block):
  89. retryAfter = block(retriedCount)
  90. }
  91. return retryAfter
  92. }
  93. }
  94. /// The max retry count defined for the retry strategy
  95. public let maxRetryCount: Int
  96. /// The retry interval mechanism defined for the retry strategy.
  97. public let retryInterval: Interval
  98. /// Creates a delay retry strategy.
  99. /// - Parameters:
  100. /// - maxRetryCount: The max retry count.
  101. /// - retryInterval: The retry interval mechanism. By default, `.seconds(3)` is used to provide a constant retry
  102. /// interval.
  103. public init(maxRetryCount: Int, retryInterval: Interval = .seconds(3)) {
  104. self.maxRetryCount = maxRetryCount
  105. self.retryInterval = retryInterval
  106. }
  107. public func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
  108. // Retry count exceeded.
  109. guard context.retriedCount < maxRetryCount else {
  110. retryHandler(.stop)
  111. return
  112. }
  113. // User cancel the task. No retry.
  114. guard !context.error.isTaskCancelled else {
  115. retryHandler(.stop)
  116. return
  117. }
  118. // Only retry for a response error.
  119. guard case KingfisherError.responseError = context.error else {
  120. retryHandler(.stop)
  121. return
  122. }
  123. let interval = retryInterval.timeInterval(for: context.retriedCount)
  124. if interval == 0 {
  125. retryHandler(.retry(userInfo: nil))
  126. } else {
  127. DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
  128. retryHandler(.retry(userInfo: nil))
  129. }
  130. }
  131. }
  132. }