RetryStrategy.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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: @unchecked Sendable {
  31. private let propertyQueue = DispatchQueue(label: "com.onevcat.Kingfisher.RetryContextPropertyQueue")
  32. /// The source from which the target image should be retrieved.
  33. public let source: Source
  34. /// The source from which the target image should be retrieved.
  35. public let error: KingfisherError
  36. private var _retriedCount: Int
  37. /// The number of retries attempted before the current retry happens.
  38. ///
  39. /// This value is `0` if the current retry is for the first time.
  40. public var retriedCount: Int {
  41. get { propertyQueue.sync { _retriedCount } }
  42. set { propertyQueue.sync { _retriedCount = newValue } }
  43. }
  44. private var _userInfo: Any? = nil
  45. /// A user-set value for passing any other information during the retry.
  46. ///
  47. /// If you choose to use ``RetryDecision/retry(userInfo:)`` as the retry decision for
  48. /// ``RetryStrategy/retry(context:retryHandler:)``, the associated value of ``RetryDecision/retry(userInfo:)`` will
  49. /// be delivered to you in the next retry.
  50. public internal(set) var userInfo: Any? {
  51. get { propertyQueue.sync { _userInfo } }
  52. set { propertyQueue.sync { _userInfo = newValue } }
  53. }
  54. init(source: Source, error: KingfisherError) {
  55. self.source = source
  56. self.error = error
  57. _retriedCount = 0
  58. }
  59. @discardableResult
  60. func increaseRetryCount() -> RetryContext {
  61. retriedCount += 1
  62. return self
  63. }
  64. }
  65. /// Represents the decision on the behavior for the current retry.
  66. public enum RetryDecision {
  67. /// A retry should happen. The associated `userInfo` value will be passed to the next retry in the
  68. /// ``RetryContext`` parameter.
  69. case retry(userInfo: Any?)
  70. /// There should be no more retry attempts. The image retrieving process will fail with an error.
  71. case stop
  72. }
  73. /// Defines a retry strategy that can be applied to the ``KingfisherOptionsInfoItem/retryStrategy(_:)`` option.
  74. public protocol RetryStrategy: Sendable {
  75. /// Kingfisher calls this method if an error occurs during the image retrieving process from ``KingfisherManager``.
  76. ///
  77. /// You implement this method to provide the necessary logic based on the `context` parameter. Then you need to call
  78. /// `retryHandler` to pass the retry decision back to Kingfisher.
  79. ///
  80. /// - Parameters:
  81. /// - context: The retry context containing information of the current retry attempt.
  82. /// - retryHandler: A block you need to call with a decision on whether the retry should happen or not.
  83. func retry(context: RetryContext, retryHandler: @escaping @Sendable (RetryDecision) -> Void)
  84. }
  85. /// A retry strategy that guides Kingfisher to perform retry operation with some delay.
  86. ///
  87. /// When an error of ``KingfisherError/ResponseErrorReason`` happens, Kingfisher uses the retry strategy in its option
  88. /// to retry. This strategy defines a specified maximum retry count and a certain interval mechanism.
  89. public struct DelayRetryStrategy: RetryStrategy {
  90. /// Represents the interval mechanism used in a ``DelayRetryStrategy``.
  91. public enum Interval : Sendable{
  92. /// The next retry attempt should happen in a fixed number of seconds.
  93. ///
  94. /// For example, if the associated value is 3, the attempt happens 3 seconds after the previous decision is
  95. /// made.
  96. case seconds(TimeInterval)
  97. /// The next retry attempt should happen in an accumulated duration.
  98. ///
  99. /// For example, if the associated value is 3, the attempts happen with intervals of 3, 6, 9, 12, ... seconds.
  100. case accumulated(TimeInterval)
  101. /// Uses a block to determine the next interval.
  102. ///
  103. /// The current retry count is given as a parameter.
  104. case custom(block: @Sendable (_ retriedCount: Int) -> TimeInterval)
  105. func timeInterval(for retriedCount: Int) -> TimeInterval {
  106. let retryAfter: TimeInterval
  107. switch self {
  108. case .seconds(let interval):
  109. retryAfter = interval
  110. case .accumulated(let interval):
  111. retryAfter = Double(retriedCount + 1) * interval
  112. case .custom(let block):
  113. retryAfter = block(retriedCount)
  114. }
  115. return retryAfter
  116. }
  117. }
  118. /// The maximum number of retries allowed by the retry strategy.
  119. public let maxRetryCount: Int
  120. /// The interval between retry attempts in the retry strategy.
  121. public let retryInterval: Interval
  122. /// Creates a delayed retry strategy.
  123. ///
  124. /// - Parameters:
  125. /// - maxRetryCount: The maximum number of retries allowed.
  126. /// - retryInterval: The mechanism defining the interval between retry attempts.
  127. ///
  128. /// By default, ``Interval/seconds(_:)`` with an associated value `3` is used to establish a constant retry
  129. /// interval.
  130. public init(maxRetryCount: Int, retryInterval: Interval = .seconds(3)) {
  131. self.maxRetryCount = maxRetryCount
  132. self.retryInterval = retryInterval
  133. }
  134. public func retry(context: RetryContext, retryHandler: @escaping @Sendable (RetryDecision) -> Void) {
  135. // Retry count exceeded.
  136. guard context.retriedCount < maxRetryCount else {
  137. retryHandler(.stop)
  138. return
  139. }
  140. // User cancel the task. No retry.
  141. guard !context.error.isTaskCancelled else {
  142. retryHandler(.stop)
  143. return
  144. }
  145. // Only retry for a response error.
  146. guard case KingfisherError.responseError = context.error else {
  147. retryHandler(.stop)
  148. return
  149. }
  150. let interval = retryInterval.timeInterval(for: context.retriedCount)
  151. if interval == 0 {
  152. retryHandler(.retry(userInfo: nil))
  153. } else {
  154. DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
  155. retryHandler(.retry(userInfo: nil))
  156. }
  157. }
  158. }
  159. }
  160. /// A retry strategy that observes network state and retries on reconnect.
  161. ///
  162. /// This strategy only retries when network becomes available after a disconnection.
  163. /// It does not use any delay mechanisms - it retries immediately when network is restored.
  164. ///
  165. /// The network monitor is created lazily only when this strategy is first used,
  166. /// ensuring no unnecessary resource usage when the strategy is not in use.
  167. public struct NetworkRetryStrategy: RetryStrategy {
  168. /// The timeout for waiting for network reconnection (in seconds).
  169. private let timeoutInterval: TimeInterval?
  170. /// The network monitoring service used to observe connectivity changes.
  171. private let networkMonitor: NetworkMonitoring
  172. /// Creates a network-aware retry strategy.
  173. ///
  174. /// - Parameters:
  175. /// - timeoutInterval: The timeout for waiting for network reconnection. If nil, no timeout is applied. Defaults to 30 seconds.
  176. public init(timeoutInterval: TimeInterval? = 30) {
  177. self.init(
  178. timeoutInterval: timeoutInterval,
  179. networkMonitor: NetworkMonitor.default
  180. )
  181. }
  182. internal init(
  183. timeoutInterval: TimeInterval?,
  184. networkMonitor: NetworkMonitoring
  185. ) {
  186. self.timeoutInterval = timeoutInterval
  187. self.networkMonitor = networkMonitor
  188. }
  189. public func retry(context: RetryContext, retryHandler: @escaping @Sendable (RetryDecision) -> Void) {
  190. // Dispose of any previous disposable from userInfo
  191. if let previousObserver = context.userInfo as? NetworkObserver {
  192. previousObserver.cancel()
  193. }
  194. // User cancel the task. No retry.
  195. guard !context.error.isTaskCancelled else {
  196. retryHandler(.stop)
  197. return
  198. }
  199. // Only retry for a response error.
  200. guard case KingfisherError.responseError = context.error else {
  201. retryHandler(.stop)
  202. return
  203. }
  204. // Check if we have network connectivity
  205. if networkMonitor.isConnected {
  206. // Network is available, retry immediately
  207. retryHandler(.retry(userInfo: nil))
  208. } else {
  209. // Network is not available, wait for reconnection
  210. waitForReconnection(context: context, retryHandler: retryHandler)
  211. }
  212. }
  213. // MARK: - Private helpers
  214. private func waitForReconnection(
  215. context: RetryContext,
  216. retryHandler: @escaping @Sendable (RetryDecision) -> Void
  217. ) {
  218. let observer = networkMonitor.observeConnectivity(timeoutInterval: timeoutInterval) { [weak context] isConnected in
  219. if isConnected {
  220. // Connection is restored, retry immediately
  221. retryHandler(.retry(userInfo: context?.userInfo))
  222. } else {
  223. // Timeout reached or cancelled
  224. retryHandler(.stop)
  225. }
  226. }
  227. // Store the observer in userInfo so it can be cancelled if needed
  228. context.userInfo = observer
  229. }
  230. }