CompletionQueue.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. /// Initializes a CompletionQueue
  76. ///
  77. /// - Parameter cq: the underlying C representation
  78. init(underlyingCompletionQueue: UnsafeMutableRawPointer) {
  79. // The underlying completion queue is NOT OWNED by this class, so we don't dealloc it in a deinit
  80. self.underlyingCompletionQueue = underlyingCompletionQueue
  81. }
  82. /// Waits for an operation group to complete
  83. ///
  84. /// - Parameter timeout: a timeout value in seconds
  85. /// - Returns: a grpc_completion_type code indicating the result of waiting
  86. internal func wait(timeout: TimeInterval) -> CompletionQueueEvent {
  87. let event = cgrpc_completion_queue_get_next_event(underlyingCompletionQueue, timeout);
  88. return CompletionQueueEvent(event)
  89. }
  90. /// Register an operation group for handling upon completion
  91. ///
  92. /// - Parameter operationGroup: the operation group to handle
  93. internal func register(_ operationGroup:OperationGroup) -> Void {
  94. operationGroups[operationGroup.tag] = operationGroup
  95. }
  96. /// Runs a completion queue and call a completion handler when finished
  97. ///
  98. /// - Parameter: a completion handler that is called when the queue stops running
  99. internal func runToCompletion(_ completion:@escaping () -> Void) {
  100. DispatchQueue.global().async {
  101. var running = true
  102. while (running) {
  103. let event = cgrpc_completion_queue_get_next_event(self.underlyingCompletionQueue, -1.0)
  104. switch (event.type) {
  105. case GRPC_OP_COMPLETE:
  106. let tag = cgrpc_event_tag(event)
  107. if let operationGroup = self.operationGroups[tag] {
  108. // call the operation group completion handler
  109. do {
  110. try operationGroup.completion(event.success == 1)
  111. } catch (let callError) {
  112. print("grpc error: \(callError)")
  113. }
  114. self.operationGroups[tag] = nil
  115. }
  116. break
  117. case GRPC_QUEUE_SHUTDOWN:
  118. running = false
  119. break
  120. case GRPC_QUEUE_TIMEOUT:
  121. break
  122. default:
  123. break
  124. }
  125. }
  126. DispatchQueue.main.async {
  127. // when the queue stops running, call the queue completion handler
  128. completion()
  129. }
  130. }
  131. }
  132. /// Runs a completion queue
  133. internal func run() -> Void {
  134. self.runToCompletion() {}
  135. }
  136. /// Shuts down a completion queue
  137. internal func shutdown() -> Void {
  138. cgrpc_completion_queue_shutdown(underlyingCompletionQueue)
  139. }
  140. }