EventMonitor.swift 40 KB

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