RequestTaskMap.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. //
  2. // RequestTaskMap.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. /// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s.
  26. struct RequestTaskMap {
  27. private typealias Events = (completed: Bool, metricsGathered: Bool)
  28. private var tasksToRequests: [URLSessionTask: Request]
  29. private var requestsToTasks: [Request: URLSessionTask]
  30. private var taskEvents: [URLSessionTask: Events]
  31. var requests: [Request] {
  32. Array(tasksToRequests.values)
  33. }
  34. init(tasksToRequests: [URLSessionTask: Request] = [:],
  35. requestsToTasks: [Request: URLSessionTask] = [:],
  36. taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:])
  37. {
  38. self.tasksToRequests = tasksToRequests
  39. self.requestsToTasks = requestsToTasks
  40. self.taskEvents = taskEvents
  41. }
  42. subscript(_ request: Request) -> URLSessionTask? {
  43. get { requestsToTasks[request] }
  44. set {
  45. guard let newValue = newValue else {
  46. guard let task = requestsToTasks[request] else {
  47. fatalError("RequestTaskMap consistency error: no task corresponding to request found.")
  48. }
  49. requestsToTasks.removeValue(forKey: request)
  50. tasksToRequests.removeValue(forKey: task)
  51. taskEvents.removeValue(forKey: task)
  52. return
  53. }
  54. requestsToTasks[request] = newValue
  55. tasksToRequests[newValue] = request
  56. taskEvents[newValue] = (completed: false, metricsGathered: false)
  57. }
  58. }
  59. subscript(_ task: URLSessionTask) -> Request? {
  60. get { tasksToRequests[task] }
  61. set {
  62. guard let newValue = newValue else {
  63. guard let request = tasksToRequests[task] else {
  64. fatalError("RequestTaskMap consistency error: no request corresponding to task found.")
  65. }
  66. tasksToRequests.removeValue(forKey: task)
  67. requestsToTasks.removeValue(forKey: request)
  68. taskEvents.removeValue(forKey: task)
  69. return
  70. }
  71. tasksToRequests[task] = newValue
  72. requestsToTasks[newValue] = task
  73. taskEvents[task] = (completed: false, metricsGathered: false)
  74. }
  75. }
  76. var count: Int {
  77. precondition(tasksToRequests.count == requestsToTasks.count,
  78. "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)")
  79. return tasksToRequests.count
  80. }
  81. var eventCount: Int {
  82. precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)")
  83. return taskEvents.count
  84. }
  85. var isEmpty: Bool {
  86. precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty,
  87. "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)")
  88. return tasksToRequests.isEmpty
  89. }
  90. var isEventsEmpty: Bool {
  91. precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)")
  92. return taskEvents.isEmpty
  93. }
  94. mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool {
  95. guard let events = taskEvents[task] else {
  96. fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
  97. }
  98. switch (events.completed, events.metricsGathered) {
  99. case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.")
  100. case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false
  101. case (true, false): self[task] = nil; return true
  102. }
  103. }
  104. mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool {
  105. guard let events = taskEvents[task] else {
  106. fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
  107. }
  108. switch (events.completed, events.metricsGathered) {
  109. case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.")
  110. #if os(Linux) // Linux doesn't gather metrics, so unconditionally remove the reference and return true.
  111. default: self[task] = nil; return true
  112. #else
  113. case (false, false):
  114. if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) {
  115. taskEvents[task] = (completed: true, metricsGathered: false); return false
  116. } else {
  117. // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true.
  118. self[task] = nil; return true
  119. }
  120. case (false, true):
  121. self[task] = nil; return true
  122. #endif
  123. }
  124. }
  125. }