RetryPolicy.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. //
  2. // RetryPolicy.swift
  3. //
  4. // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes
  26. /// as well as certain types of networking errors.
  27. open class RetryPolicy: RequestInterceptor {
  28. /// The default retry limit for retry policies.
  29. public static let defaultRetryLimit: UInt = 2
  30. /// The default exponential backoff base for retry policies (must be a minimum of 2).
  31. public static let defaultExponentialBackoffBase: UInt = 2
  32. /// The default exponential backoff scale for retry policies.
  33. public static let defaultExponentialBackoffScale: Double = 0.5
  34. /// The default HTTP methods to retry.
  35. /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information.
  36. public static let defaultRetryableHTTPMethods: Set<HTTPMethod> = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent
  37. .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent
  38. .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent
  39. .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent
  40. .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent
  41. .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent
  42. ]
  43. /// The default HTTP status codes to retry.
  44. /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information.
  45. public static let defaultRetryableHTTPStatusCodes: Set<Int> = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9)
  46. 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1)
  47. 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3)
  48. 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4)
  49. 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5)
  50. ]
  51. /// The default URL error codes to retry.
  52. public static let defaultRetryableURLErrorCodes: Set<URLError.Code> = [// [Security] App Transport Security disallowed a connection because there is no secure network connection.
  53. // - [Disabled] ATS settings do not change at runtime.
  54. // .appTransportSecurityRequiresSecureConnection,
  55. // [System] An app or app extension attempted to connect to a background session that is already connected to a
  56. // process.
  57. // - [Enabled] The other process could release the background session.
  58. .backgroundSessionInUseByAnotherProcess,
  59. // [System] The shared container identifier of the URL session configuration is needed but has not been set.
  60. // - [Disabled] Cannot change at runtime.
  61. // .backgroundSessionRequiresSharedContainer,
  62. // [System] The app is suspended or exits while a background data task is processing.
  63. // - [Enabled] App can be foregrounded or launched to recover.
  64. .backgroundSessionWasDisconnected,
  65. // [Network] The URL Loading system received bad data from the server.
  66. // - [Enabled] Server could return valid data when retrying.
  67. .badServerResponse,
  68. // [Resource] A malformed URL prevented a URL request from being initiated.
  69. // - [Disabled] URL was most likely constructed incorrectly.
  70. // .badURL,
  71. // [System] A connection was attempted while a phone call is active on a network that does not support
  72. // simultaneous phone and data communication (EDGE or GPRS).
  73. // - [Enabled] Phone call could be ended to allow request to recover.
  74. .callIsActive,
  75. // [Client] An asynchronous load has been canceled.
  76. // - [Disabled] Request was cancelled by the client.
  77. // .cancelled,
  78. // [File System] A download task couldn’t close the downloaded file on disk.
  79. // - [Disabled] File system error is unlikely to recover with retry.
  80. // .cannotCloseFile,
  81. // [Network] An attempt to connect to a host failed.
  82. // - [Enabled] Server or DNS lookup could recover during retry.
  83. .cannotConnectToHost,
  84. // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure.
  85. // - [Disabled] File system error is unlikely to recover with retry.
  86. // .cannotCreateFile,
  87. // [Data] Content data received during a connection request had an unknown content encoding.
  88. // - [Disabled] Server is unlikely to modify the content encoding during a retry.
  89. // .cannotDecodeContentData,
  90. // [Data] Content data received during a connection request could not be decoded for a known content encoding.
  91. // - [Disabled] Server is unlikely to modify the content encoding during a retry.
  92. // .cannotDecodeRawData,
  93. // [Network] The host name for a URL could not be resolved.
  94. // - [Enabled] Server or DNS lookup could recover during retry.
  95. .cannotFindHost,
  96. // [Network] A request to load an item only from the cache could not be satisfied.
  97. // - [Enabled] Cache could be populated during a retry.
  98. .cannotLoadFromNetwork,
  99. // [File System] A download task was unable to move a downloaded file on disk.
  100. // - [Disabled] File system error is unlikely to recover with retry.
  101. // .cannotMoveFile,
  102. // [File System] A download task was unable to open the downloaded file on disk.
  103. // - [Disabled] File system error is unlikely to recover with retry.
  104. // .cannotOpenFile,
  105. // [Data] A task could not parse a response.
  106. // - [Disabled] Invalid response is unlikely to recover with retry.
  107. // .cannotParseResponse,
  108. // [File System] A download task was unable to remove a downloaded file from disk.
  109. // - [Disabled] File system error is unlikely to recover with retry.
  110. // .cannotRemoveFile,
  111. // [File System] A download task was unable to write to the downloaded file on disk.
  112. // - [Disabled] File system error is unlikely to recover with retry.
  113. // .cannotWriteToFile,
  114. // [Security] A client certificate was rejected.
  115. // - [Disabled] Client certificate is unlikely to change with retry.
  116. // .clientCertificateRejected,
  117. // [Security] A client certificate was required to authenticate an SSL connection during a request.
  118. // - [Disabled] Client certificate is unlikely to be provided with retry.
  119. // .clientCertificateRequired,
  120. // [Data] The length of the resource data exceeds the maximum allowed.
  121. // - [Disabled] Resource will likely still exceed the length maximum on retry.
  122. // .dataLengthExceedsMaximum,
  123. // [System] The cellular network disallowed a connection.
  124. // - [Enabled] WiFi connection could be established during retry.
  125. .dataNotAllowed,
  126. // [Network] The host address could not be found via DNS lookup.
  127. // - [Enabled] DNS lookup could succeed during retry.
  128. .dnsLookupFailed,
  129. // [Data] A download task failed to decode an encoded file during the download.
  130. // - [Enabled] Server could correct the decoding issue with retry.
  131. .downloadDecodingFailedMidStream,
  132. // [Data] A download task failed to decode an encoded file after downloading.
  133. // - [Enabled] Server could correct the decoding issue with retry.
  134. .downloadDecodingFailedToComplete,
  135. // [File System] A file does not exist.
  136. // - [Disabled] File system error is unlikely to recover with retry.
  137. // .fileDoesNotExist,
  138. // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file,
  139. // but a directory.
  140. // - [Disabled] FTP directory is not likely to change to a file during a retry.
  141. // .fileIsDirectory,
  142. // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been
  143. // exceeded (currently 16).
  144. // - [Disabled] The redirect loop is unlikely to be resolved within the retry window.
  145. // .httpTooManyRedirects,
  146. // [System] The attempted connection required activating a data context while roaming, but international roaming
  147. // is disabled.
  148. // - [Enabled] WiFi connection could be established during retry.
  149. .internationalRoamingOff,
  150. // [Connectivity] A client or server connection was severed in the middle of an in-progress load.
  151. // - [Enabled] A network connection could be established during retry.
  152. .networkConnectionLost,
  153. // [File System] A resource couldn’t be read because of insufficient permissions.
  154. // - [Disabled] Permissions are unlikely to be granted during retry.
  155. // .noPermissionsToReadFile,
  156. // [Connectivity] A network resource was requested, but an internet connection has not been established and
  157. // cannot be established automatically.
  158. // - [Enabled] A network connection could be established during retry.
  159. .notConnectedToInternet,
  160. // [Resource] A redirect was specified by way of server response code, but the server did not accompany this
  161. // code with a redirect URL.
  162. // - [Disabled] The redirect URL is unlikely to be supplied during a retry.
  163. // .redirectToNonExistentLocation,
  164. // [Client] A body stream is needed but the client did not provide one.
  165. // - [Disabled] The client will be unlikely to supply a body stream during retry.
  166. // .requestBodyStreamExhausted,
  167. // [Resource] A requested resource couldn’t be retrieved.
  168. // - [Disabled] The resource is unlikely to become available during the retry window.
  169. // .resourceUnavailable,
  170. // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more
  171. // specifically.
  172. // - [Enabled] The secure connection could be established during a retry given the lack of specificity
  173. // provided by the error.
  174. .secureConnectionFailed,
  175. // [Security] A server certificate had a date which indicates it has expired, or is not yet valid.
  176. // - [Enabled] The server certificate could become valid within the retry window.
  177. .serverCertificateHasBadDate,
  178. // [Security] A server certificate was not signed by any root server.
  179. // - [Disabled] The server certificate is unlikely to change during the retry window.
  180. // .serverCertificateHasUnknownRoot,
  181. // [Security] A server certificate is not yet valid.
  182. // - [Enabled] The server certificate could become valid within the retry window.
  183. .serverCertificateNotYetValid,
  184. // [Security] A server certificate was signed by a root server that isn’t trusted.
  185. // - [Disabled] The server certificate is unlikely to become trusted within the retry window.
  186. // .serverCertificateUntrusted,
  187. // [Network] An asynchronous operation timed out.
  188. // - [Enabled] The request timed out for an unknown reason and should be retried.
  189. .timedOut
  190. // [System] The URL Loading System encountered an error that it can’t interpret.
  191. // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry.
  192. // .unknown,
  193. // [Resource] A properly formed URL couldn’t be handled by the framework.
  194. // - [Disabled] The URL is unlikely to change during a retry.
  195. // .unsupportedURL,
  196. // [Client] Authentication is required to access a resource.
  197. // - [Disabled] The user authentication is unlikely to be provided by retrying.
  198. // .userAuthenticationRequired,
  199. // [Client] An asynchronous request for authentication has been canceled by the user.
  200. // - [Disabled] The user cancelled authentication and explicitly took action to not retry.
  201. // .userCancelledAuthentication,
  202. // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection
  203. // gracefully without sending any data.
  204. // - [Disabled] The server is unlikely to provide data during the retry window.
  205. // .zeroByteResource,
  206. ]
  207. /// The total number of times the request is allowed to be retried.
  208. public let retryLimit: UInt
  209. /// The base of the exponential backoff policy (should always be greater than or equal to 2).
  210. public let exponentialBackoffBase: UInt
  211. /// The scale of the exponential backoff.
  212. public let exponentialBackoffScale: Double
  213. /// The HTTP methods that are allowed to be retried.
  214. public let retryableHTTPMethods: Set<HTTPMethod>
  215. /// The HTTP status codes that are automatically retried by the policy.
  216. public let retryableHTTPStatusCodes: Set<Int>
  217. /// The URL error codes that are automatically retried by the policy.
  218. public let retryableURLErrorCodes: Set<URLError.Code>
  219. /// Creates an `ExponentialBackoffRetryPolicy` from the specified parameters.
  220. ///
  221. /// - Parameters:
  222. /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default.
  223. /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default.
  224. /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default.
  225. /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried.
  226. /// `RetryPolicy.defaultRetryableHTTPMethods` by default.
  227. /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy.
  228. /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default.
  229. /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy.
  230. /// `RetryPolicy.defaultRetryableURLErrorCodes` by default.
  231. public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
  232. exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
  233. exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
  234. retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
  235. retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
  236. retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes) {
  237. precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.")
  238. self.retryLimit = retryLimit
  239. self.exponentialBackoffBase = exponentialBackoffBase
  240. self.exponentialBackoffScale = exponentialBackoffScale
  241. self.retryableHTTPMethods = retryableHTTPMethods
  242. self.retryableHTTPStatusCodes = retryableHTTPStatusCodes
  243. self.retryableURLErrorCodes = retryableURLErrorCodes
  244. }
  245. open func retry(_ request: Request,
  246. for session: Session,
  247. dueTo error: Error,
  248. completion: @escaping (RetryResult) -> Void) {
  249. if
  250. request.retryCount < retryLimit,
  251. let httpMethod = request.request?.method,
  252. retryableHTTPMethods.contains(httpMethod),
  253. shouldRetry(response: request.response, error: error) {
  254. let timeDelay = pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale
  255. completion(.retryWithDelay(timeDelay))
  256. } else {
  257. completion(.doNotRetry)
  258. }
  259. }
  260. private func shouldRetry(response: HTTPURLResponse?, error: Error) -> Bool {
  261. if let statusCode = response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) {
  262. return true
  263. } else if let errorCode = (error as? URLError)?.code, retryableURLErrorCodes.contains(errorCode) {
  264. return true
  265. }
  266. return false
  267. }
  268. }
  269. // MARK: -
  270. /// A retry policy that automatically retries idempotent requests for network connection lost errors. For more
  271. /// information about retrying network connection lost errors, please refer to Apple's
  272. /// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html).
  273. open class ConnectionLostRetryPolicy: RetryPolicy {
  274. /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters.
  275. ///
  276. /// - Parameters:
  277. /// - retryLimit: The total number of times the request is allowed to be retried.
  278. /// `RetryPolicy.defaultRetryLimit` by default.
  279. /// - exponentialBackoffBase: The base of the exponential backoff policy.
  280. /// `RetryPolicy.defaultExponentialBackoffBase` by default.
  281. /// - exponentialBackoffScale: The scale of the exponential backoff.
  282. /// `RetryPolicy.defaultExponentialBackoffScale` by default.
  283. /// - retryableHTTPMethods: The idempotent http methods to retry.
  284. /// `RetryPolicy.defaultRetryableHTTPMethods` by default.
  285. public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
  286. exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
  287. exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
  288. retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods) {
  289. super.init(retryLimit: retryLimit,
  290. exponentialBackoffBase: exponentialBackoffBase,
  291. exponentialBackoffScale: exponentialBackoffScale,
  292. retryableHTTPMethods: retryableHTTPMethods,
  293. retryableHTTPStatusCodes: [],
  294. retryableURLErrorCodes: [.networkConnectionLost])
  295. }
  296. }