EventMonitor.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. //
  2. // EventMonitor.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various
  26. /// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses.
  27. public protocol EventMonitor {
  28. /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. Defaults to `.main`.
  29. var queue: DispatchQueue { get }
  30. // MARK: - URLSession Events
  31. // MARK: URLSessionDelegate Events
  32. /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method.
  33. func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
  34. // MARK: URLSessionTaskDelegate Events
  35. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method.
  36. func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
  37. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method.
  38. func urlSession(_ session: URLSession,
  39. task: URLSessionTask,
  40. didSendBodyData bytesSent: Int64,
  41. totalBytesSent: Int64,
  42. totalBytesExpectedToSend: Int64)
  43. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method.
  44. func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
  45. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method.
  46. func urlSession(_ session: URLSession,
  47. task: URLSessionTask,
  48. willPerformHTTPRedirection response: HTTPURLResponse,
  49. newRequest request: URLRequest)
  50. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method.
  51. func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
  52. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method.
  53. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
  54. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method.
  55. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  56. func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
  57. // MARK: URLSessionDataDelegate Events
  58. /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method.
  59. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
  60. /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method.
  61. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
  62. // MARK: URLSessionDownloadDelegate Events
  63. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method.
  64. func urlSession(_ session: URLSession,
  65. downloadTask: URLSessionDownloadTask,
  66. didResumeAtOffset fileOffset: Int64,
  67. expectedTotalBytes: Int64)
  68. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method.
  69. func urlSession(_ session: URLSession,
  70. downloadTask: URLSessionDownloadTask,
  71. didWriteData bytesWritten: Int64,
  72. totalBytesWritten: Int64,
  73. totalBytesExpectedToWrite: Int64)
  74. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method.
  75. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
  76. // MARK: - Request Events
  77. /// Event called when a `URLRequest` is first created for a `Request`.
  78. func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
  79. /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails.
  80. func request(_ request: Request, didFailToCreateURLRequestWithError error: Error)
  81. /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`.
  82. func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
  83. /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`.
  84. func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: Error)
  85. /// Event called when a `URLSessionTask` subclass instance is created for a `Request`.
  86. func request(_ request: Request, didCreateTask task: URLSessionTask)
  87. /// Event called when a `Request` receives a `URLSessionTaskMetrics` value.
  88. func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
  89. /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificat pinning fails.
  90. func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: Error)
  91. /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may recieve this event
  92. /// multiple times if it is retried.
  93. func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: Error?)
  94. /// Event called when a `Request` is about to be retried.
  95. func requestIsRetrying(_ request: Request)
  96. /// Event called when a `Request` finishes and response serializers are being called.
  97. func requestDidFinish(_ request: Request)
  98. /// Event called when a `Request` receives a `resume` call.
  99. func requestDidResume(_ request: Request)
  100. /// Event called when a `Request`'s associated `URLSessionTask` is resumed.
  101. func request(_ request: Request, didResumeTask task: URLSessionTask)
  102. /// Event called when a `Request` receives a `suspend` call.
  103. func requestDidSuspend(_ request: Request)
  104. /// Event called when a `Request`'s associated `URLSessionTask` is suspended.
  105. func request(_ request: Request, didSuspendTask task: URLSessionTask)
  106. /// Event called when a `Request` receives a `cancel` call.
  107. func requestDidCancel(_ request: Request)
  108. /// Event called when a `Request`'s associated `URLSessionTask` is cancelled.
  109. func request(_ request: Request, didCancelTask task: URLSessionTask)
  110. // MARK: DataRequest Events
  111. /// Event called when a `DataRequest` calls a `Validation`.
  112. func request(_ request: DataRequest,
  113. didValidateRequest urlRequest: URLRequest?,
  114. response: HTTPURLResponse,
  115. data: Data?,
  116. withResult result: Request.ValidationResult)
  117. /// Event called when a `DataRequest` creates a `DataResponse<Data?>` value without calling a `ResponseSerializer`.
  118. func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?>)
  119. /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse<Value>`.
  120. func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value>)
  121. // MARK: UploadRequest Events
  122. /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents.
  123. func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
  124. /// Event called when an `UploadRequest` failes to create its `Uploadable` value due to an error.
  125. func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: Error)
  126. /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if
  127. /// the `InputStream` does not wrap a `Data` value or file `URL`.
  128. func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
  129. // MARK: DownloadRequest Events
  130. /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved.
  131. func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: AFResult<URL>)
  132. /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the
  133. /// downloaded file will be moved to.
  134. func request(_ request: DownloadRequest, didCreateDestinationURL url: URL)
  135. /// Event called when a `DownloadRequest` calls a `Validation`.
  136. func request(_ request: DownloadRequest,
  137. didValidateRequest urlRequest: URLRequest?,
  138. response: HTTPURLResponse,
  139. fileURL: URL?,
  140. withResult result: Request.ValidationResult)
  141. /// Event called when a `DownloadRequest` creates a `DownloadResponse<URL?>` without calling a `ResponseSerializer`.
  142. func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?>)
  143. /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse<Value>`
  144. func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value>)
  145. }
  146. extension EventMonitor {
  147. /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. Defaults to `.main`.
  148. public var queue: DispatchQueue { return .main }
  149. // MARK: Default Implementations
  150. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { }
  151. public func urlSession(_ session: URLSession,
  152. task: URLSessionTask,
  153. didReceive challenge: URLAuthenticationChallenge) { }
  154. public func urlSession(_ session: URLSession,
  155. task: URLSessionTask,
  156. didSendBodyData bytesSent: Int64,
  157. totalBytesSent: Int64,
  158. totalBytesExpectedToSend: Int64) { }
  159. public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { }
  160. public func urlSession(_ session: URLSession,
  161. task: URLSessionTask,
  162. willPerformHTTPRedirection response: HTTPURLResponse,
  163. newRequest request: URLRequest) { }
  164. public func urlSession(_ session: URLSession,
  165. task: URLSessionTask,
  166. didFinishCollecting metrics: URLSessionTaskMetrics) { }
  167. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { }
  168. public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { }
  169. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { }
  170. public func urlSession(_ session: URLSession,
  171. dataTask: URLSessionDataTask,
  172. willCacheResponse proposedResponse: CachedURLResponse) { }
  173. public func urlSession(_ session: URLSession,
  174. downloadTask: URLSessionDownloadTask,
  175. didResumeAtOffset fileOffset: Int64,
  176. expectedTotalBytes: Int64) { }
  177. public func urlSession(_ session: URLSession,
  178. downloadTask: URLSessionDownloadTask,
  179. didWriteData bytesWritten: Int64,
  180. totalBytesWritten: Int64,
  181. totalBytesExpectedToWrite: Int64) { }
  182. public func urlSession(_ session: URLSession,
  183. downloadTask: URLSessionDownloadTask,
  184. didFinishDownloadingTo location: URL) { }
  185. public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { }
  186. public func request(_ request: Request, didFailToCreateURLRequestWithError error: Error) { }
  187. public func request(_ request: Request,
  188. didAdaptInitialRequest initialRequest: URLRequest,
  189. to adaptedRequest: URLRequest) { }
  190. public func request(_ request: Request,
  191. didFailToAdaptURLRequest initialRequest: URLRequest,
  192. withError error: Error) { }
  193. public func request(_ request: Request, didCreateTask task: URLSessionTask) { }
  194. public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { }
  195. public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: Error) { }
  196. public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: Error?) { }
  197. public func requestIsRetrying(_ request: Request) { }
  198. public func requestDidFinish(_ request: Request) { }
  199. public func requestDidResume(_ request: Request) { }
  200. public func request(_ request: Request, didResumeTask task: URLSessionTask) { }
  201. public func requestDidSuspend(_ request: Request) { }
  202. public func request(_ request: Request, didSuspendTask task: URLSessionTask) { }
  203. public func requestDidCancel(_ request: Request) { }
  204. public func request(_ request: Request, didCancelTask task: URLSessionTask) { }
  205. public func request(_ request: DataRequest,
  206. didValidateRequest urlRequest: URLRequest?,
  207. response: HTTPURLResponse,
  208. data: Data?,
  209. withResult result: Request.ValidationResult) { }
  210. public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?>) { }
  211. public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value>) { }
  212. public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { }
  213. public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: Error) { }
  214. public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { }
  215. public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: AFResult<URL>) { }
  216. public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { }
  217. public func request(_ request: DownloadRequest,
  218. didValidateRequest urlRequest: URLRequest?,
  219. response: HTTPURLResponse,
  220. fileURL: URL?,
  221. withResult result: Request.ValidationResult) { }
  222. public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?>) { }
  223. public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value>) { }
  224. }
  225. /// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues.
  226. public final class CompositeEventMonitor: EventMonitor {
  227. public let queue = DispatchQueue(label: "org.alamofire.componsiteEventMonitor", qos: .background)
  228. let monitors: [EventMonitor]
  229. init(monitors: [EventMonitor]) {
  230. self.monitors = monitors
  231. }
  232. func performEvent(_ event: @escaping (EventMonitor) -> Void) {
  233. queue.async {
  234. for monitor in self.monitors {
  235. monitor.queue.async { event(monitor) }
  236. }
  237. }
  238. }
  239. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  240. performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) }
  241. }
  242. public func urlSession(_ session: URLSession,
  243. task: URLSessionTask,
  244. didReceive challenge: URLAuthenticationChallenge) {
  245. performEvent { $0.urlSession(session, task: task, didReceive: challenge) }
  246. }
  247. public func urlSession(_ session: URLSession,
  248. task: URLSessionTask,
  249. didSendBodyData bytesSent: Int64,
  250. totalBytesSent: Int64,
  251. totalBytesExpectedToSend: Int64) {
  252. performEvent {
  253. $0.urlSession(session,
  254. task: task,
  255. didSendBodyData: bytesSent,
  256. totalBytesSent: totalBytesSent,
  257. totalBytesExpectedToSend: totalBytesExpectedToSend)
  258. }
  259. }
  260. public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
  261. performEvent {
  262. $0.urlSession(session, taskNeedsNewBodyStream: task)
  263. }
  264. }
  265. public func urlSession(_ session: URLSession,
  266. task: URLSessionTask,
  267. willPerformHTTPRedirection response: HTTPURLResponse,
  268. newRequest request: URLRequest) {
  269. performEvent {
  270. $0.urlSession(session,
  271. task: task,
  272. willPerformHTTPRedirection: response,
  273. newRequest: request)
  274. }
  275. }
  276. public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  277. performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) }
  278. }
  279. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  280. performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) }
  281. }
  282. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  283. public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  284. performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) }
  285. }
  286. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  287. performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) }
  288. }
  289. public func urlSession(_ session: URLSession,
  290. dataTask: URLSessionDataTask,
  291. willCacheResponse proposedResponse: CachedURLResponse) {
  292. performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) }
  293. }
  294. public func urlSession(_ session: URLSession,
  295. downloadTask: URLSessionDownloadTask,
  296. didResumeAtOffset fileOffset: Int64,
  297. expectedTotalBytes: Int64) {
  298. performEvent {
  299. $0.urlSession(session,
  300. downloadTask: downloadTask,
  301. didResumeAtOffset: fileOffset,
  302. expectedTotalBytes: expectedTotalBytes)
  303. }
  304. }
  305. public func urlSession(_ session: URLSession,
  306. downloadTask: URLSessionDownloadTask,
  307. didWriteData bytesWritten: Int64,
  308. totalBytesWritten: Int64,
  309. totalBytesExpectedToWrite: Int64) {
  310. performEvent {
  311. $0.urlSession(session,
  312. downloadTask: downloadTask,
  313. didWriteData: bytesWritten,
  314. totalBytesWritten: totalBytesWritten,
  315. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  316. }
  317. }
  318. public func urlSession(_ session: URLSession,
  319. downloadTask: URLSessionDownloadTask,
  320. didFinishDownloadingTo location: URL) {
  321. performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) }
  322. }
  323. public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
  324. performEvent { $0.request(request, didCreateURLRequest: urlRequest) }
  325. }
  326. public func request(_ request: Request, didFailToCreateURLRequestWithError error: Error) {
  327. performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) }
  328. }
  329. public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  330. performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) }
  331. }
  332. public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: Error) {
  333. performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) }
  334. }
  335. public func request(_ request: Request, didCreateTask task: URLSessionTask) {
  336. performEvent { $0.request(request, didCreateTask: task) }
  337. }
  338. public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
  339. performEvent { $0.request(request, didGatherMetrics: metrics) }
  340. }
  341. public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: Error) {
  342. performEvent { $0.request(request, didFailTask: task, earlyWithError: error) }
  343. }
  344. public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: Error?) {
  345. performEvent { $0.request(request, didCompleteTask: task, with: error) }
  346. }
  347. public func requestIsRetrying(_ request: Request) {
  348. performEvent { $0.requestIsRetrying(request) }
  349. }
  350. public func requestDidFinish(_ request: Request) {
  351. performEvent { $0.requestDidFinish(request) }
  352. }
  353. public func requestDidResume(_ request: Request) {
  354. performEvent { $0.requestDidResume(request) }
  355. }
  356. public func request(_ request: Request, didResumeTask task: URLSessionTask) {
  357. performEvent { $0.request(request, didResumeTask: task) }
  358. }
  359. public func requestDidSuspend(_ request: Request) {
  360. performEvent { $0.requestDidSuspend(request) }
  361. }
  362. public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
  363. performEvent { $0.request(request, didSuspendTask: task) }
  364. }
  365. public func requestDidCancel(_ request: Request) {
  366. performEvent { $0.requestDidCancel(request) }
  367. }
  368. public func request(_ request: Request, didCancelTask task: URLSessionTask) {
  369. performEvent { $0.request(request, didCancelTask: task) }
  370. }
  371. public func request(_ request: DataRequest,
  372. didValidateRequest urlRequest: URLRequest?,
  373. response: HTTPURLResponse,
  374. data: Data?,
  375. withResult result: Request.ValidationResult) {
  376. performEvent { $0.request(request,
  377. didValidateRequest: urlRequest,
  378. response: response,
  379. data: data,
  380. withResult: result)
  381. }
  382. }
  383. public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?>) {
  384. performEvent { $0.request(request, didParseResponse: response) }
  385. }
  386. public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value>) {
  387. performEvent { $0.request(request, didParseResponse: response) }
  388. }
  389. public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
  390. performEvent { $0.request(request, didCreateUploadable: uploadable) }
  391. }
  392. public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: Error) {
  393. performEvent { $0.request(request, didFailToCreateUploadableWithError: error) }
  394. }
  395. public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
  396. performEvent { $0.request(request, didProvideInputStream: stream) }
  397. }
  398. public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: AFResult<URL>) {
  399. performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) }
  400. }
  401. public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
  402. performEvent { $0.request(request, didCreateDestinationURL: url) }
  403. }
  404. public func request(_ request: DownloadRequest,
  405. didValidateRequest urlRequest: URLRequest?,
  406. response: HTTPURLResponse,
  407. fileURL: URL?,
  408. withResult result: Request.ValidationResult) {
  409. performEvent { $0.request(request,
  410. didValidateRequest: urlRequest,
  411. response: response,
  412. fileURL: fileURL,
  413. withResult: result) }
  414. }
  415. public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?>) {
  416. performEvent { $0.request(request, didParseResponse: response) }
  417. }
  418. public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value>) {
  419. performEvent { $0.request(request, didParseResponse: response) }
  420. }
  421. }
  422. /// `EventMonitor` that allows optional closures to be set to receive events.
  423. open class ClosureEventMonitor: EventMonitor {
  424. /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event.
  425. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
  426. /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`.
  427. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)?
  428. /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event.
  429. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
  430. /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event.
  431. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)?
  432. /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event.
  433. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)?
  434. /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event.
  435. open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)?
  436. /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event.
  437. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
  438. /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event.
  439. open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)?
  440. /// Closure that recieves the `urlSession(_:dataTask:didReceive:)` event.
  441. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
  442. /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event.
  443. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)?
  444. /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event.
  445. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
  446. /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`
  447. /// event.
  448. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  449. /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event.
  450. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
  451. // MARK: - Request Events
  452. /// Closure called on the `request(_:didCreateURLRequest:)` event.
  453. open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)?
  454. /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event.
  455. open var requestDidFailToCreateURLRequestWithError: ((Request, Error) -> Void)?
  456. /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event.
  457. open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)?
  458. /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event.
  459. open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, Error) -> Void)?
  460. /// Closure called on the `request(_:didCreateTask:)` event.
  461. open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)?
  462. /// Closure called on the `request(_:didGatherMetrics:)` event.
  463. open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)?
  464. /// Closure called on the `request(_:didFailTask:earlyWithError:)` event.
  465. open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, Error) -> Void)?
  466. /// Closure called on the `request(_:didCompleteTask:with:)` event.
  467. open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, Error?) -> Void)?
  468. /// Closure called on the `requestIsRetrying(_:)` event.
  469. open var requestIsRetrying: ((Request) -> Void)?
  470. /// Closure called on the `requestDidFinish(_:)` event.
  471. open var requestDidFinish: ((Request) -> Void)?
  472. /// Closure called on the `requestDidResume(_:)` event.
  473. open var requestDidResume: ((Request) -> Void)?
  474. /// Closure called on the `request(_:didResumeTask:)` event.
  475. open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)?
  476. /// Closure called on the `requestDidSuspend(_:)` event.
  477. open var requestDidSuspend: ((Request) -> Void)?
  478. /// Closure called on the `request(_:didSuspendTask:)` event.
  479. open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)?
  480. /// Closure called on the `requestDidCancel(_:)` event.
  481. open var requestDidCancel: ((Request) -> Void)?
  482. /// Closure called on the `request(_:didCancelTask:)` event.
  483. open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)?
  484. /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event.
  485. open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)?
  486. /// Closure called on the `request(_:didParseResponse:)` event.
  487. open var requestDidParseResponse: ((DataRequest, DataResponse<Data?>) -> Void)?
  488. /// Closure called on the `request(_:didCreateUploadable:)` event.
  489. open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)?
  490. /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event.
  491. open var requestDidFailToCreateUploadableWithError: ((UploadRequest, Error) -> Void)?
  492. /// Closure called on the `request(_:didProvideInputStream:)` event.
  493. open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)?
  494. /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event.
  495. open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, AFResult<URL>) -> Void)?
  496. /// Closure called on the `request(_:didCreateDestinationURL:)` event.
  497. open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)?
  498. /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event.
  499. open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)?
  500. /// Closure called on the `request(_:didParseResponse:)` event.
  501. open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse<URL?>) -> Void)?
  502. public let queue: DispatchQueue
  503. public init(queue: DispatchQueue = .main) {
  504. self.queue = queue
  505. }
  506. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  507. sessionDidBecomeInvalidWithError?(session, error)
  508. }
  509. open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) {
  510. taskDidReceiveChallenge?(session, task, challenge)
  511. }
  512. open func urlSession(_ session: URLSession,
  513. task: URLSessionTask,
  514. didSendBodyData bytesSent: Int64,
  515. totalBytesSent: Int64,
  516. totalBytesExpectedToSend: Int64) {
  517. taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  518. }
  519. open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
  520. taskNeedNewBodyStream?(session, task)
  521. }
  522. open func urlSession(_ session: URLSession,
  523. task: URLSessionTask,
  524. willPerformHTTPRedirection response: HTTPURLResponse,
  525. newRequest request: URLRequest) {
  526. taskWillPerformHTTPRedirection?(session, task, response, request)
  527. }
  528. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  529. taskDidFinishCollectingMetrics?(session, task, metrics)
  530. }
  531. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  532. taskDidComplete?(session, task, error)
  533. }
  534. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  535. taskIsWaitingForConnectivity?(session, task)
  536. }
  537. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  538. dataTaskDidReceiveData?(session, dataTask, data)
  539. }
  540. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) {
  541. dataTaskWillCacheResponse?(session, dataTask, proposedResponse)
  542. }
  543. open func urlSession(_ session: URLSession,
  544. downloadTask: URLSessionDownloadTask,
  545. didResumeAtOffset fileOffset: Int64,
  546. expectedTotalBytes: Int64) {
  547. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  548. }
  549. open func urlSession(_ session: URLSession,
  550. downloadTask: URLSessionDownloadTask,
  551. didWriteData bytesWritten: Int64,
  552. totalBytesWritten: Int64,
  553. totalBytesExpectedToWrite: Int64) {
  554. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  555. }
  556. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  557. downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
  558. }
  559. // MARK: Request Events
  560. open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
  561. requestDidCreateURLRequest?(request, urlRequest)
  562. }
  563. open func request(_ request: Request, didFailToCreateURLRequestWithError error: Error) {
  564. requestDidFailToCreateURLRequestWithError?(request, error)
  565. }
  566. open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  567. requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest)
  568. }
  569. open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: Error) {
  570. requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error)
  571. }
  572. open func request(_ request: Request, didCreateTask task: URLSessionTask) {
  573. requestDidCreateTask?(request, task)
  574. }
  575. open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
  576. requestDidGatherMetrics?(request, metrics)
  577. }
  578. open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: Error) {
  579. requestDidFailTaskEarlyWithError?(request, task, error)
  580. }
  581. open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: Error?) {
  582. requestDidCompleteTaskWithError?(request, task, error)
  583. }
  584. open func requestIsRetrying(_ request: Request) {
  585. requestIsRetrying?(request)
  586. }
  587. open func requestDidFinish(_ request: Request) {
  588. requestDidFinish?(request)
  589. }
  590. open func requestDidResume(_ request: Request) {
  591. requestDidResume?(request)
  592. }
  593. public func request(_ request: Request, didResumeTask task: URLSessionTask) {
  594. requestDidResumeTask?(request, task)
  595. }
  596. open func requestDidSuspend(_ request: Request) {
  597. requestDidSuspend?(request)
  598. }
  599. public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
  600. requestDidSuspendTask?(request, task)
  601. }
  602. open func requestDidCancel(_ request: Request) {
  603. requestDidCancel?(request)
  604. }
  605. public func request(_ request: Request, didCancelTask task: URLSessionTask) {
  606. requestDidCancelTask?(request, task)
  607. }
  608. open func request(_ request: DataRequest,
  609. didValidateRequest urlRequest: URLRequest?,
  610. response: HTTPURLResponse,
  611. data: Data?,
  612. withResult result: Request.ValidationResult) {
  613. requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result)
  614. }
  615. open func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?>) {
  616. requestDidParseResponse?(request, response)
  617. }
  618. open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
  619. requestDidCreateUploadable?(request, uploadable)
  620. }
  621. open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: Error) {
  622. requestDidFailToCreateUploadableWithError?(request, error)
  623. }
  624. open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
  625. requestDidProvideInputStream?(request, stream)
  626. }
  627. open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: AFResult<URL>) {
  628. requestDidFinishDownloadingUsingTaskWithResult?(request, task, result)
  629. }
  630. open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
  631. requestDidCreateDestinationURL?(request, url)
  632. }
  633. open func request(_ request: DownloadRequest,
  634. didValidateRequest urlRequest: URLRequest?,
  635. response: HTTPURLResponse,
  636. fileURL: URL?,
  637. withResult result: Request.ValidationResult) {
  638. requestDidValidateRequestResponseFileURLWithResult?(request,
  639. urlRequest,
  640. response,
  641. fileURL,
  642. result)
  643. }
  644. open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?>) {
  645. requestDidParseDownloadResponse?(request, response)
  646. }
  647. }