CompletionQueue.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. * Copyright 2016, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #if SWIFT_PACKAGE
  17. import CgRPC
  18. import Dispatch
  19. #endif
  20. import Foundation
  21. /// A type indicating the kind of event returned by the completion queue
  22. enum CompletionType {
  23. case queueShutdown
  24. case queueTimeout
  25. case complete
  26. case unknown
  27. fileprivate static func completionType(_ value: grpc_completion_type) -> CompletionType {
  28. switch value {
  29. case GRPC_QUEUE_SHUTDOWN:
  30. return .queueShutdown
  31. case GRPC_QUEUE_TIMEOUT:
  32. return .queueTimeout
  33. case GRPC_OP_COMPLETE:
  34. return .complete
  35. default:
  36. return .unknown
  37. }
  38. }
  39. }
  40. /// An event that is returned by the completion queue
  41. struct CompletionQueueEvent {
  42. let type: CompletionType
  43. let success: Int32
  44. let tag: Int
  45. init(_ event: grpc_event) {
  46. type = CompletionType.completionType(event.type)
  47. success = event.success
  48. tag = Int(bitPattern: cgrpc_event_tag(event))
  49. }
  50. }
  51. /// A gRPC Completion Queue
  52. class CompletionQueue {
  53. /// Optional user-provided name for the queue
  54. let name: String?
  55. /// Pointer to underlying C representation
  56. private let underlyingCompletionQueue: UnsafeMutableRawPointer
  57. /// Operation groups that are awaiting completion, keyed by tag
  58. private var operationGroups: [Int: OperationGroup] = [:]
  59. /// Mutex for synchronizing access to operationGroups
  60. private let operationGroupsMutex: Mutex = Mutex()
  61. private var _hasBeenShutdown = false
  62. public var hasBeenShutdown: Bool { return operationGroupsMutex.synchronize { _hasBeenShutdown } }
  63. /// Initializes a CompletionQueue
  64. ///
  65. /// - Parameter cq: the underlying C representation
  66. init(underlyingCompletionQueue: UnsafeMutableRawPointer, name: String? = nil) {
  67. // The underlying completion queue is NOT OWNED by this class, so we don't dealloc it in a deinit
  68. self.underlyingCompletionQueue = underlyingCompletionQueue
  69. self.name = name
  70. }
  71. deinit {
  72. operationGroupsMutex.synchronize {
  73. _hasBeenShutdown = true
  74. }
  75. cgrpc_completion_queue_shutdown(underlyingCompletionQueue)
  76. cgrpc_completion_queue_drain(underlyingCompletionQueue)
  77. grpc_completion_queue_destroy(underlyingCompletionQueue)
  78. }
  79. /// Waits for an operation group to complete
  80. ///
  81. /// - Parameter timeout: a timeout value in seconds
  82. /// - Returns: a grpc_completion_type code indicating the result of waiting
  83. func wait(timeout: TimeInterval) -> CompletionQueueEvent {
  84. let event = cgrpc_completion_queue_get_next_event(underlyingCompletionQueue, timeout)
  85. return CompletionQueueEvent(event)
  86. }
  87. /// Register an operation group for handling upon completion. Will throw if the queue has been shutdown already.
  88. ///
  89. /// - Parameter operationGroup: the operation group to handle.
  90. func register(_ operationGroup: OperationGroup, onSuccess: () throws -> Void) throws {
  91. try operationGroupsMutex.synchronize {
  92. guard !_hasBeenShutdown
  93. else { throw CallError.completionQueueShutdown }
  94. operationGroups[operationGroup.tag] = operationGroup
  95. try onSuccess()
  96. }
  97. }
  98. /// Runs a completion queue and call a completion handler when finished
  99. ///
  100. /// - Parameter completion: a completion handler that is called when the queue stops running
  101. func runToCompletion(completion: (() -> Void)?) {
  102. // run the completion queue on a new background thread
  103. var threadLabel = "SwiftGRPC.CompletionQueue.runToCompletion.spinloopThread"
  104. if let name = self.name {
  105. threadLabel.append(" (\(name))")
  106. }
  107. let spinloopThreadQueue = DispatchQueue(label: threadLabel)
  108. spinloopThreadQueue.async {
  109. spinloop: while true {
  110. let event = cgrpc_completion_queue_get_next_event(self.underlyingCompletionQueue, 600)
  111. switch event.type {
  112. case GRPC_OP_COMPLETE:
  113. let tag = Int(bitPattern:cgrpc_event_tag(event))
  114. self.operationGroupsMutex.lock()
  115. let operationGroup = self.operationGroups[tag]
  116. self.operationGroupsMutex.unlock()
  117. if let operationGroup = operationGroup {
  118. // call the operation group completion handler
  119. operationGroup.success = (event.success == 1)
  120. operationGroup.completion?(operationGroup)
  121. self.operationGroupsMutex.synchronize {
  122. self.operationGroups[tag] = nil
  123. }
  124. } else {
  125. print("CompletionQueue.runToCompletion error: operation group with tag \(tag) not found")
  126. }
  127. case GRPC_QUEUE_SHUTDOWN:
  128. self.operationGroupsMutex.lock()
  129. let currentOperationGroups = self.operationGroups
  130. self.operationGroups = [:]
  131. self.operationGroupsMutex.unlock()
  132. for operationGroup in currentOperationGroups.values {
  133. operationGroup.success = false
  134. operationGroup.completion?(operationGroup)
  135. }
  136. break spinloop
  137. case GRPC_QUEUE_TIMEOUT:
  138. continue spinloop
  139. default:
  140. break spinloop
  141. }
  142. }
  143. // when the queue stops running, call the queue completion handler
  144. completion?()
  145. }
  146. }
  147. /// Runs a completion queue
  148. func run() {
  149. runToCompletion(completion: nil)
  150. }
  151. /// Shuts down a completion queue
  152. func shutdown() {
  153. var needsShutdown = false
  154. operationGroupsMutex.synchronize {
  155. if !_hasBeenShutdown {
  156. needsShutdown = true
  157. _hasBeenShutdown = true
  158. }
  159. }
  160. if needsShutdown {
  161. cgrpc_completion_queue_shutdown(underlyingCompletionQueue)
  162. }
  163. }
  164. }