OperationGroup.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 to a unique value (per execution)
  101. let mutex = OperationGroupTagLock.sharedInstance.mutex
  102. mutex.lock()
  103. self.tag = OperationGroup.nextTag
  104. OperationGroup.nextTag += 1
  105. mutex.unlock()
  106. // create underlying observers and operations
  107. self.underlyingOperations = cgrpc_operations_create()
  108. cgrpc_operations_reserve_space_for_operations(self.underlyingOperations, Int32(operations.count))
  109. for operation in operations {
  110. let underlyingObserver = self.underlyingObserverForOperation(operation: operation)
  111. self.underlyingObservers.append(underlyingObserver)
  112. cgrpc_operations_add_operation(self.underlyingOperations, underlyingObserver)
  113. }
  114. }
  115. deinit {
  116. for underlyingObserver in underlyingObservers {
  117. cgrpc_observer_destroy(underlyingObserver);
  118. }
  119. cgrpc_operations_destroy(underlyingOperations);
  120. }
  121. /// WARNING: The following assumes that at most one operation of each type is in the group.
  122. /// Gets the message that was received
  123. ///
  124. /// - Returns: message
  125. internal func receivedMessage() -> ByteBuffer? {
  126. for (i, operation) in operations.enumerated() {
  127. switch (operation) {
  128. case .receiveMessage:
  129. if let b = cgrpc_observer_recv_message_get_message(underlyingObservers[i]) {
  130. return ByteBuffer(underlyingByteBuffer:b)
  131. } else {
  132. return nil
  133. }
  134. default: continue
  135. }
  136. }
  137. return nil
  138. }
  139. /// Gets initial metadata that was received
  140. ///
  141. /// - Returns: metadata
  142. internal func receivedInitialMetadata() -> Metadata? {
  143. for (i, operation) in operations.enumerated() {
  144. switch (operation) {
  145. case .receiveInitialMetadata:
  146. return Metadata(underlyingArray:cgrpc_observer_recv_initial_metadata_get_metadata(underlyingObservers[i]));
  147. default:
  148. continue
  149. }
  150. }
  151. return nil
  152. }
  153. /// Gets a status code that was received
  154. ///
  155. /// - Returns: status code
  156. internal func receivedStatusCode() -> Int? {
  157. for (i, operation) in operations.enumerated() {
  158. switch (operation) {
  159. case .receiveStatusOnClient:
  160. return cgrpc_observer_recv_status_on_client_get_status(underlyingObservers[i])
  161. default:
  162. continue
  163. }
  164. }
  165. return nil
  166. }
  167. /// Gets a status message that was received
  168. ///
  169. /// - Returns: status message
  170. internal func receivedStatusMessage() -> String? {
  171. for (i, operation) in operations.enumerated() {
  172. switch (operation) {
  173. case .receiveStatusOnClient:
  174. return String(cString:cgrpc_observer_recv_status_on_client_get_status_details(underlyingObservers[i]),
  175. encoding:String.Encoding.utf8)!
  176. default:
  177. continue
  178. }
  179. }
  180. return nil
  181. }
  182. /// Gets trailing metadata that was received
  183. ///
  184. /// - Returns: metadata
  185. internal func receivedTrailingMetadata() -> Metadata? {
  186. for (i, operation) in operations.enumerated() {
  187. switch (operation) {
  188. case .receiveStatusOnClient:
  189. return Metadata(underlyingArray:cgrpc_observer_recv_status_on_client_get_metadata(underlyingObservers[i]));
  190. default:
  191. continue
  192. }
  193. }
  194. return nil
  195. }
  196. }