OperationGroup.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. /// Singleton class that provides a mutex for synchronizing tag generation
  37. private class OperationGroupTagLock {
  38. var mutex : Mutex
  39. private init() {
  40. mutex = Mutex()
  41. }
  42. static let sharedInstance = OperationGroupTagLock()
  43. }
  44. /// A collection of gRPC operations
  45. internal class OperationGroup {
  46. /// Used to generate unique tags for OperationGroups
  47. private static var nextTag : Int64 = 1
  48. /// Automatically-assigned tag that is used by the completion queue that watches this group.
  49. internal var tag : Int64
  50. /// The call associated with the operation group. Retained while the operations are running.
  51. private var call : Call
  52. /// An array of operation objects that are passed into the initializer.
  53. private var operations : [Operation]
  54. /// An array of observers used to watch the operation
  55. private var underlyingObservers : [UnsafeMutableRawPointer] = []
  56. /// Pointer to underlying C representation
  57. internal var underlyingOperations : UnsafeMutableRawPointer?
  58. /// Completion handler that is called when the group completes
  59. internal var completion : ((OperationGroup) throws -> Void)
  60. /// Indicates that the OperationGroup completed successfully
  61. internal var success : Bool = false
  62. /// Creates the underlying observer needed to run an operation
  63. ///
  64. /// - Parameter: operation: the operation to observe
  65. /// - Returns: the observer
  66. private func underlyingObserverForOperation(operation: Operation) -> UnsafeMutableRawPointer {
  67. var underlyingObserver : UnsafeMutableRawPointer
  68. switch operation {
  69. case .sendInitialMetadata(let metadata):
  70. underlyingObserver = cgrpc_observer_create_send_initial_metadata(metadata.underlyingArray)!
  71. case .sendMessage(let message):
  72. underlyingObserver = cgrpc_observer_create_send_message()!
  73. cgrpc_observer_send_message_set_message(underlyingObserver, message.underlyingByteBuffer)
  74. case .sendCloseFromClient:
  75. underlyingObserver = cgrpc_observer_create_send_close_from_client()!
  76. case .sendStatusFromServer(let statusCode, let statusMessage, let metadata):
  77. underlyingObserver = cgrpc_observer_create_send_status_from_server(metadata.underlyingArray)!
  78. cgrpc_observer_send_status_from_server_set_status(underlyingObserver, Int32(statusCode))
  79. cgrpc_observer_send_status_from_server_set_status_details(underlyingObserver, statusMessage)
  80. case .receiveInitialMetadata:
  81. underlyingObserver = cgrpc_observer_create_recv_initial_metadata()!
  82. case .receiveMessage:
  83. underlyingObserver = cgrpc_observer_create_recv_message()!
  84. case .receiveStatusOnClient:
  85. underlyingObserver = cgrpc_observer_create_recv_status_on_client()!
  86. case .receiveCloseOnServer:
  87. underlyingObserver = cgrpc_observer_create_recv_close_on_server()!
  88. }
  89. return underlyingObserver
  90. }
  91. /// Initializes an OperationGroup representation
  92. ///
  93. /// - Parameter operations: an array of operations
  94. init(call: Call,
  95. operations: [Operation],
  96. completion: @escaping ((OperationGroup) throws -> Void)) {
  97. self.call = call
  98. self.operations = operations
  99. self.completion = completion
  100. // set tag
  101. let mutex = OperationGroupTagLock.sharedInstance.mutex
  102. mutex.lock()
  103. self.tag = OperationGroup.nextTag
  104. OperationGroup.nextTag += 1
  105. mutex.unlock()
  106. // create observers
  107. for operation in operations {
  108. self.underlyingObservers.append(self.underlyingObserverForOperation(operation: operation))
  109. }
  110. // create operations
  111. self.underlyingOperations = cgrpc_operations_create()
  112. cgrpc_operations_reserve_space_for_operations(self.underlyingOperations, Int32(operations.count))
  113. for underlyingObserver in underlyingObservers {
  114. cgrpc_operations_add_operation(self.underlyingOperations, underlyingObserver)
  115. }
  116. }
  117. deinit {
  118. for underlyingObserver in underlyingObservers {
  119. cgrpc_observer_destroy(underlyingObserver);
  120. }
  121. cgrpc_operations_destroy(underlyingOperations);
  122. }
  123. /// WARNING: The following assumes that at most one operation of each type is in the group.
  124. /// Gets the message that was received
  125. ///
  126. /// - Returns: message
  127. internal func receivedMessage() -> ByteBuffer? {
  128. for (i, operation) in operations.enumerated() {
  129. switch (operation) {
  130. case .receiveMessage:
  131. if let b = cgrpc_observer_recv_message_get_message(underlyingObservers[i]) {
  132. return ByteBuffer(underlyingByteBuffer:b)
  133. } else {
  134. return nil
  135. }
  136. default: continue
  137. }
  138. }
  139. return nil
  140. }
  141. /// Gets the initial metadata that was received
  142. ///
  143. /// - Returns: metadata
  144. internal func receivedInitialMetadata() -> Metadata? {
  145. for (i, operation) in operations.enumerated() {
  146. switch (operation) {
  147. case .receiveInitialMetadata:
  148. return Metadata(underlyingArray:cgrpc_observer_recv_initial_metadata_get_metadata(underlyingObservers[i]));
  149. default:
  150. continue
  151. }
  152. }
  153. return nil
  154. }
  155. /// Gets the status code that was received
  156. ///
  157. /// - Returns: status code
  158. internal func receivedStatusCode() -> Int? {
  159. for (i, operation) in operations.enumerated() {
  160. switch (operation) {
  161. case .receiveStatusOnClient:
  162. return cgrpc_observer_recv_status_on_client_get_status(underlyingObservers[i])
  163. default:
  164. continue
  165. }
  166. }
  167. return nil
  168. }
  169. /// Gets the status message that was received
  170. ///
  171. /// - Returns: status message
  172. internal func receivedStatusMessage() -> String? {
  173. for (i, operation) in operations.enumerated() {
  174. switch (operation) {
  175. case .receiveStatusOnClient:
  176. return String(cString:cgrpc_observer_recv_status_on_client_get_status_details(underlyingObservers[i]),
  177. encoding:String.Encoding.utf8)!
  178. default:
  179. continue
  180. }
  181. }
  182. return nil
  183. }
  184. /// Gets the trailing metadata that was received
  185. ///
  186. /// - Returns: metadata
  187. internal func receivedTrailingMetadata() -> Metadata? {
  188. for (i, operation) in operations.enumerated() {
  189. switch (operation) {
  190. case .receiveStatusOnClient:
  191. return Metadata(underlyingArray:cgrpc_observer_recv_status_on_client_get_metadata(underlyingObservers[i]));
  192. default:
  193. continue
  194. }
  195. }
  196. return nil
  197. }
  198. }