2
0

OperationGroup.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*
  2. * Copyright 2016, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #if SWIFT_PACKAGE
  17. import CgRPC
  18. #endif
  19. /// A collection of gRPC operations
  20. class OperationGroup {
  21. /// A mutex for synchronizing tag generation
  22. static let tagMutex = Mutex()
  23. /// Used to generate unique tags for OperationGroups
  24. private static var nextTag: Int = 1
  25. /// Automatically-assigned tag that is used by the completion queue that watches this group.
  26. let tag: Int
  27. /// The call associated with the operation group. Retained while the operations are running.
  28. // FIXME(danielalm): Is this property needed?
  29. private let call: Call
  30. /// An array of operation objects that are passed into the initializer.
  31. let operations: [Operation]
  32. /// An array of observers used to watch the operation
  33. private var underlyingObservers: [UnsafeMutableRawPointer] = []
  34. /// Pointer to underlying C representation
  35. let underlyingOperations: UnsafeMutableRawPointer?
  36. /// Completion handler that is called when the group completes
  37. let completion: ((OperationGroup) -> Void)?
  38. /// Indicates that the OperationGroup completed successfully
  39. var success = false
  40. fileprivate var cachedInitialMetadata: Metadata?
  41. fileprivate var cachedTrailingMetadata: Metadata?
  42. /// Creates the underlying observer needed to run an operation
  43. ///
  44. /// - Parameter: operation: the operation to observe
  45. /// - Returns: the observer
  46. private func underlyingObserverForOperation(operation: Operation) throws -> UnsafeMutableRawPointer {
  47. let underlyingObserver: UnsafeMutableRawPointer
  48. switch operation {
  49. case .sendInitialMetadata(let metadata):
  50. underlyingObserver = cgrpc_observer_create_send_initial_metadata(try metadata.getUnderlyingArrayAndTransferFieldOwnership())!
  51. case .sendMessage(let message):
  52. underlyingObserver = cgrpc_observer_create_send_message()!
  53. cgrpc_observer_send_message_set_message(underlyingObserver, message.underlyingByteBuffer)
  54. case .sendCloseFromClient:
  55. underlyingObserver = cgrpc_observer_create_send_close_from_client()!
  56. case .sendStatusFromServer(let statusCode, let statusMessage, let metadata):
  57. underlyingObserver = cgrpc_observer_create_send_status_from_server(try metadata.getUnderlyingArrayAndTransferFieldOwnership())!
  58. cgrpc_observer_send_status_from_server_set_status(underlyingObserver, Int32(statusCode.rawValue))
  59. cgrpc_observer_send_status_from_server_set_status_details(underlyingObserver, statusMessage)
  60. case .receiveInitialMetadata:
  61. underlyingObserver = cgrpc_observer_create_recv_initial_metadata()!
  62. case .receiveMessage:
  63. underlyingObserver = cgrpc_observer_create_recv_message()!
  64. case .receiveStatusOnClient:
  65. underlyingObserver = cgrpc_observer_create_recv_status_on_client()!
  66. case .receiveCloseOnServer:
  67. underlyingObserver = cgrpc_observer_create_recv_close_on_server()!
  68. }
  69. return underlyingObserver
  70. }
  71. /// Initializes an OperationGroup representation
  72. ///
  73. /// - Parameter operations: an array of operations
  74. init(call: Call,
  75. operations: [Operation],
  76. completion: ((OperationGroup) -> Void)? = nil) throws {
  77. self.call = call
  78. self.operations = operations
  79. self.completion = completion
  80. // set tag to a unique value (per execution)
  81. OperationGroup.tagMutex.lock()
  82. tag = OperationGroup.nextTag
  83. OperationGroup.nextTag += 1
  84. OperationGroup.tagMutex.unlock()
  85. // create underlying observers and operations
  86. underlyingOperations = cgrpc_operations_create()
  87. cgrpc_operations_reserve_space_for_operations(underlyingOperations, Int32(operations.count))
  88. for operation in operations {
  89. let underlyingObserver = try underlyingObserverForOperation(operation: operation)
  90. underlyingObservers.append(underlyingObserver)
  91. cgrpc_operations_add_operation(underlyingOperations, underlyingObserver)
  92. }
  93. }
  94. deinit {
  95. for underlyingObserver in underlyingObservers {
  96. cgrpc_observer_destroy(underlyingObserver)
  97. }
  98. cgrpc_operations_destroy(underlyingOperations)
  99. }
  100. /// WARNING: The following assumes that at most one operation of each type is in the group,
  101. /// and these methods must ONLY be called after the operation has been returned to a completion queue.
  102. /// Gets the message that was received
  103. ///
  104. /// - Returns: message
  105. func receivedMessage() -> ByteBuffer? {
  106. for (i, operation) in operations.enumerated() {
  107. switch operation {
  108. case .receiveMessage:
  109. if let b = cgrpc_observer_recv_message_get_message(underlyingObservers[i]) {
  110. return ByteBuffer(underlyingByteBuffer: b)
  111. } else {
  112. return nil
  113. }
  114. default: continue
  115. }
  116. }
  117. return nil
  118. }
  119. /// Gets initial metadata that was received
  120. ///
  121. /// - Returns: metadata
  122. func receivedInitialMetadata() -> Metadata? {
  123. if let cachedInitialMetadata = self.cachedInitialMetadata {
  124. return cachedInitialMetadata
  125. }
  126. for (i, operation) in operations.enumerated() {
  127. switch operation {
  128. case .receiveInitialMetadata:
  129. cachedInitialMetadata = Metadata(
  130. underlyingArray: cgrpc_observer_recv_initial_metadata_get_metadata(underlyingObservers[i]),
  131. ownsFields: false)
  132. return cachedInitialMetadata!
  133. default:
  134. continue
  135. }
  136. }
  137. return nil
  138. }
  139. /// Gets a status code that was received
  140. ///
  141. /// - Returns: status code
  142. func receivedStatusCode() -> Int? {
  143. for (i, operation) in operations.enumerated() {
  144. switch operation {
  145. case .receiveStatusOnClient:
  146. return cgrpc_observer_recv_status_on_client_get_status(underlyingObservers[i])
  147. default:
  148. continue
  149. }
  150. }
  151. return nil
  152. }
  153. /// Gets a status message that was received
  154. ///
  155. /// - Returns: status message
  156. func receivedStatusMessage() -> String? {
  157. for (i, operation) in operations.enumerated() {
  158. switch operation {
  159. case .receiveStatusOnClient:
  160. // We actually know that this method will never return nil, so we can forcibly unwrap the result. (Also below.)
  161. let string = cgrpc_observer_recv_status_on_client_copy_status_details(underlyingObservers[i])!
  162. defer { cgrpc_free_copied_string(string) }
  163. return String(cString: string, encoding: String.Encoding.utf8)
  164. default:
  165. continue
  166. }
  167. }
  168. return nil
  169. }
  170. /// Gets trailing metadata that was received
  171. ///
  172. /// - Returns: metadata
  173. func receivedTrailingMetadata() -> Metadata? {
  174. if let cachedTrailingMetadata = self.cachedTrailingMetadata {
  175. return cachedTrailingMetadata
  176. }
  177. for (i, operation) in operations.enumerated() {
  178. switch operation {
  179. case .receiveStatusOnClient:
  180. cachedTrailingMetadata = Metadata(
  181. underlyingArray: cgrpc_observer_recv_status_on_client_get_metadata(underlyingObservers[i]),
  182. ownsFields: false)
  183. return cachedTrailingMetadata!
  184. default:
  185. continue
  186. }
  187. }
  188. return nil
  189. }
  190. }