CompletionQueue.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #if SWIFT_PACKAGE
  34. import CgRPC
  35. import Dispatch
  36. #endif
  37. import Foundation
  38. /// A type indicating the kind of event returned by the completion queue
  39. internal enum CompletionType {
  40. case queueShutdown
  41. case queueTimeout
  42. case complete
  43. case unknown
  44. fileprivate static func completionType(_ value: grpc_completion_type) -> CompletionType {
  45. switch(value) {
  46. case GRPC_QUEUE_SHUTDOWN:
  47. return .queueShutdown
  48. case GRPC_QUEUE_TIMEOUT:
  49. return .queueTimeout
  50. case GRPC_OP_COMPLETE:
  51. return .complete
  52. default:
  53. return .unknown
  54. }
  55. }
  56. }
  57. /// An event that is returned by the completion queue
  58. internal struct CompletionQueueEvent {
  59. internal var type: CompletionType
  60. internal var success: Int32
  61. internal var tag: Int64
  62. internal init(_ event: grpc_event) {
  63. type = CompletionType.completionType(event.type)
  64. success = event.success
  65. tag = cgrpc_event_tag(event)
  66. }
  67. }
  68. /// A gRPC Completion Queue
  69. internal class CompletionQueue {
  70. /// Optional user-provided name for the queue
  71. internal var name : String?
  72. /// Pointer to underlying C representation
  73. private var underlyingCompletionQueue : UnsafeMutableRawPointer
  74. /// Operation groups that are awaiting completion, keyed by tag
  75. private var operationGroups : [Int64 : OperationGroup] = [:]
  76. /// Mutex for synchronizing access to operationGroups
  77. private var operationGroupsMutex : Mutex = Mutex()
  78. /// Initializes a CompletionQueue
  79. ///
  80. /// - Parameter cq: the underlying C representation
  81. init(underlyingCompletionQueue: UnsafeMutableRawPointer) {
  82. // The underlying completion queue is NOT OWNED by this class, so we don't dealloc it in a deinit
  83. self.underlyingCompletionQueue = underlyingCompletionQueue
  84. }
  85. /// Waits for an operation group to complete
  86. ///
  87. /// - Parameter timeout: a timeout value in seconds
  88. /// - Returns: a grpc_completion_type code indicating the result of waiting
  89. internal func wait(timeout: TimeInterval) -> CompletionQueueEvent {
  90. let event = cgrpc_completion_queue_get_next_event(underlyingCompletionQueue, timeout);
  91. return CompletionQueueEvent(event)
  92. }
  93. /// Register an operation group for handling upon completion
  94. ///
  95. /// - Parameter operationGroup: the operation group to handle
  96. internal func register(_ operationGroup:OperationGroup) -> Void {
  97. operationGroupsMutex.lock()
  98. operationGroups[operationGroup.tag] = operationGroup
  99. operationGroupsMutex.unlock()
  100. }
  101. /// Runs a completion queue and call a completion handler when finished
  102. ///
  103. /// - Parameter callbackQueue: a DispatchQueue to use to call the completion handler
  104. /// - Parameter completion: a completion handler that is called when the queue stops running
  105. internal func runToCompletion(callbackQueue:DispatchQueue? = DispatchQueue.main,
  106. _ completion:@escaping () -> Void) {
  107. // run the completion queue on a new background thread
  108. DispatchQueue.global().async {
  109. var running = true
  110. while (running) {
  111. let event = cgrpc_completion_queue_get_next_event(self.underlyingCompletionQueue, -1.0)
  112. switch (event.type) {
  113. case GRPC_OP_COMPLETE:
  114. let tag = cgrpc_event_tag(event)
  115. self.operationGroupsMutex.lock()
  116. let operationGroup = self.operationGroups[tag]
  117. self.operationGroupsMutex.unlock()
  118. if let operationGroup = operationGroup {
  119. // call the operation group completion handler
  120. do {
  121. operationGroup.success = (event.success == 1)
  122. try operationGroup.completion(operationGroup)
  123. } catch (let callError) {
  124. print("CompletionQueue runToCompletion: grpc error \(callError)")
  125. }
  126. self.operationGroupsMutex.lock()
  127. self.operationGroups[tag] = nil
  128. self.operationGroupsMutex.unlock()
  129. }
  130. break
  131. case GRPC_QUEUE_SHUTDOWN:
  132. running = false
  133. break
  134. case GRPC_QUEUE_TIMEOUT:
  135. break
  136. default:
  137. break
  138. }
  139. }
  140. if let callbackQueue = callbackQueue {
  141. callbackQueue.async {
  142. // when the queue stops running, call the queue completion handler
  143. completion()
  144. }
  145. }
  146. }
  147. }
  148. /// Runs a completion queue
  149. internal func run() -> Void {
  150. self.runToCompletion(callbackQueue:nil) {}
  151. }
  152. /// Shuts down a completion queue
  153. internal func shutdown() -> Void {
  154. cgrpc_completion_queue_shutdown(underlyingCompletionQueue)
  155. }
  156. }