2
0

CompletionQueue.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. #endif
  36. import Foundation
  37. /// A type indicating the kind of event returned by the completion queue
  38. internal enum CompletionType {
  39. case queueShutdown
  40. case queueTimeout
  41. case complete
  42. case unknown
  43. fileprivate static func completionType(_ value: grpc_completion_type) -> CompletionType {
  44. switch(value) {
  45. case GRPC_QUEUE_SHUTDOWN:
  46. return .queueShutdown
  47. case GRPC_QUEUE_TIMEOUT:
  48. return .queueTimeout
  49. case GRPC_OP_COMPLETE:
  50. return .complete
  51. default:
  52. return .unknown
  53. }
  54. }
  55. }
  56. /// An event that is returned by the completion queue
  57. internal struct CompletionQueueEvent {
  58. internal var type: CompletionType
  59. internal var success: Int32
  60. internal var tag: Int64
  61. internal init(_ event: grpc_event) {
  62. type = CompletionType.completionType(event.type)
  63. success = event.success
  64. tag = cgrpc_event_tag(event)
  65. }
  66. }
  67. /// A gRPC Completion Queue
  68. internal class CompletionQueue {
  69. /// Optional user-provided name for the queue
  70. internal var name : String?
  71. /// Pointer to underlying C representation
  72. private var underlyingCompletionQueue : UnsafeMutableRawPointer
  73. /// Operation groups that are awaiting completion, keyed by tag
  74. private var operationGroups : [Int64 : OperationGroup] = [:]
  75. /// Mutex for synchronizing access to operationGroups
  76. private var operationGroupsMutex : Mutex = Mutex()
  77. /// Initializes a CompletionQueue
  78. ///
  79. /// - Parameter cq: the underlying C representation
  80. init(underlyingCompletionQueue: UnsafeMutableRawPointer) {
  81. // The underlying completion queue is NOT OWNED by this class, so we don't dealloc it in a deinit
  82. self.underlyingCompletionQueue = underlyingCompletionQueue
  83. }
  84. /// Waits for an operation group to complete
  85. ///
  86. /// - Parameter timeout: a timeout value in seconds
  87. /// - Returns: a grpc_completion_type code indicating the result of waiting
  88. internal func wait(timeout: TimeInterval) -> CompletionQueueEvent {
  89. let event = cgrpc_completion_queue_get_next_event(underlyingCompletionQueue, timeout);
  90. return CompletionQueueEvent(event)
  91. }
  92. /// Register an operation group for handling upon completion
  93. ///
  94. /// - Parameter operationGroup: the operation group to handle
  95. internal func register(_ operationGroup:OperationGroup) -> Void {
  96. operationGroupsMutex.lock()
  97. operationGroups[operationGroup.tag] = operationGroup
  98. operationGroupsMutex.unlock()
  99. }
  100. /// Runs a completion queue and call a completion handler when finished
  101. ///
  102. /// - Parameter callbackQueue: a DispatchQueue to use to call the completion handler
  103. /// - Parameter completion: a completion handler that is called when the queue stops running
  104. internal func runToCompletion(callbackQueue:DispatchQueue? = DispatchQueue.main,
  105. _ completion:@escaping () -> Void) {
  106. // run the completion queue on a new background thread
  107. DispatchQueue.global().async {
  108. var running = true
  109. while (running) {
  110. let event = cgrpc_completion_queue_get_next_event(self.underlyingCompletionQueue, -1.0)
  111. switch (event.type) {
  112. case GRPC_OP_COMPLETE:
  113. let tag = 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. do {
  120. operationGroup.success = (event.success == 1)
  121. try operationGroup.completion(operationGroup)
  122. } catch (let callError) {
  123. print("grpc error: \(callError)")
  124. }
  125. self.operationGroupsMutex.lock()
  126. self.operationGroups[tag] = nil
  127. self.operationGroupsMutex.unlock()
  128. }
  129. break
  130. case GRPC_QUEUE_SHUTDOWN:
  131. running = false
  132. break
  133. case GRPC_QUEUE_TIMEOUT:
  134. break
  135. default:
  136. break
  137. }
  138. }
  139. if let callbackQueue = callbackQueue {
  140. callbackQueue.async {
  141. // when the queue stops running, call the queue completion handler
  142. completion()
  143. }
  144. }
  145. }
  146. }
  147. /// Runs a completion queue
  148. internal func run() -> Void {
  149. self.runToCompletion(callbackQueue:nil) {}
  150. }
  151. /// Shuts down a completion queue
  152. internal func shutdown() -> Void {
  153. cgrpc_completion_queue_shutdown(underlyingCompletionQueue)
  154. }
  155. }