RetryStrategy.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 that could be used to determine the current retry status.
  28. ///
  29. /// The instance of this type can be shared between different retry attempts.
  30. public class RetryContext {
  31. /// The source from which the target image should be retrieved.
  32. public let source: Source
  33. /// The source from which the target image should be retrieved.
  34. public let error: KingfisherError
  35. /// The number of retries attempted before the current retry happens.
  36. ///
  37. /// This value is `0` if the current retry is for the first time.
  38. public var retriedCount: Int
  39. /// A user-set value for passing any other information during the retry.
  40. ///
  41. /// If you choose to use ``RetryDecision/retry(userInfo:)`` as the retry decision for
  42. /// ``RetryStrategy/retry(context:retryHandler:)``, the associated value of ``RetryDecision/retry(userInfo:)`` will
  43. /// be delivered to you in the next retry.
  44. public internal(set) var userInfo: Any? = nil
  45. init(source: Source, error: KingfisherError) {
  46. self.source = source
  47. self.error = error
  48. self.retriedCount = 0
  49. }
  50. @discardableResult
  51. func increaseRetryCount() -> RetryContext {
  52. retriedCount += 1
  53. return self
  54. }
  55. }
  56. /// Represents the decision on the behavior for the current retry.
  57. public enum RetryDecision {
  58. /// A retry should happen. The associated `userInfo` value will be passed to the next retry in the
  59. /// ``RetryContext`` parameter.
  60. case retry(userInfo: Any?)
  61. /// There should be no more retry attempts. The image retrieving process will fail with an error.
  62. case stop
  63. }
  64. /// Defines a retry strategy that can be applied to the ``KingfisherOptionsInfoItem/retryStrategy(_:)`` option.
  65. public protocol RetryStrategy: Sendable {
  66. /// Kingfisher calls this method if an error occurs during the image retrieving process from ``KingfisherManager``.
  67. ///
  68. /// You implement this method to provide the necessary logic based on the `context` parameter. Then you need to call
  69. /// `retryHandler` to pass the retry decision back to Kingfisher.
  70. ///
  71. /// - Parameters:
  72. /// - context: The retry context containing information of the current retry attempt.
  73. /// - retryHandler: A block you need to call with a decision on whether the retry should happen or not.
  74. func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void)
  75. }
  76. /// A retry strategy that guides Kingfisher to perform retry operation with some delay.
  77. ///
  78. /// When an error of ``KingfisherError/ResponseErrorReason`` happens, Kingfisher uses the retry strategy in its option
  79. /// to retry. This strategy defines a specified maximum retry count and a certain interval mechanism.
  80. public struct DelayRetryStrategy: RetryStrategy {
  81. /// Represents the interval mechanism used in a ``DelayRetryStrategy``.
  82. public enum Interval : Sendable{
  83. /// The next retry attempt should happen in a fixed number of seconds.
  84. ///
  85. /// For example, if the associated value is 3, the attempt happens 3 seconds after the previous decision is
  86. /// made.
  87. case seconds(TimeInterval)
  88. /// The next retry attempt should happen in an accumulated duration.
  89. ///
  90. /// For example, if the associated value is 3, the attempts happen with intervals of 3, 6, 9, 12, ... seconds.
  91. case accumulated(TimeInterval)
  92. /// Uses a block to determine the next interval.
  93. ///
  94. /// The current retry count is given as a parameter.
  95. case custom(block: @Sendable (_ retriedCount: Int) -> TimeInterval)
  96. func timeInterval(for retriedCount: Int) -> TimeInterval {
  97. let retryAfter: TimeInterval
  98. switch self {
  99. case .seconds(let interval):
  100. retryAfter = interval
  101. case .accumulated(let interval):
  102. retryAfter = Double(retriedCount + 1) * interval
  103. case .custom(let block):
  104. retryAfter = block(retriedCount)
  105. }
  106. return retryAfter
  107. }
  108. }
  109. /// The maximum number of retries allowed by the retry strategy.
  110. public let maxRetryCount: Int
  111. /// The interval between retry attempts in the retry strategy.
  112. public let retryInterval: Interval
  113. /// Creates a delayed retry strategy.
  114. ///
  115. /// - Parameters:
  116. /// - maxRetryCount: The maximum number of retries allowed.
  117. /// - retryInterval: The mechanism defining the interval between retry attempts.
  118. ///
  119. /// By default, ``Interval/seconds(_:)`` with an associated value `3` is used to establish a constant retry
  120. /// interval.
  121. public init(maxRetryCount: Int, retryInterval: Interval = .seconds(3)) {
  122. self.maxRetryCount = maxRetryCount
  123. self.retryInterval = retryInterval
  124. }
  125. public func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
  126. // Retry count exceeded.
  127. guard context.retriedCount < maxRetryCount else {
  128. retryHandler(.stop)
  129. return
  130. }
  131. // User cancel the task. No retry.
  132. guard !context.error.isTaskCancelled else {
  133. retryHandler(.stop)
  134. return
  135. }
  136. // Only retry for a response error.
  137. guard case KingfisherError.responseError = context.error else {
  138. retryHandler(.stop)
  139. return
  140. }
  141. let interval = retryInterval.timeInterval(for: context.retriedCount)
  142. if interval == 0 {
  143. retryHandler(.retry(userInfo: nil))
  144. } else {
  145. DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
  146. retryHandler(.retry(userInfo: nil))
  147. }
  148. }
  149. }
  150. }