RequestTaskMap.swift 6.1 KB

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