OperationGroup.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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: Int64 = 1
  25. /// Automatically-assigned tag that is used by the completion queue that watches this group.
  26. let tag: Int64
  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) -> UnsafeMutableRawPointer {
  47. let underlyingObserver: UnsafeMutableRawPointer
  48. switch operation {
  49. case .sendInitialMetadata(let metadata):
  50. underlyingObserver = cgrpc_observer_create_send_initial_metadata(metadata.underlyingArray)!
  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(metadata.underlyingArray)!
  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) {
  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 = 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. return cachedInitialMetadata!
  132. default:
  133. continue
  134. }
  135. }
  136. return nil
  137. }
  138. /// Gets a status code that was received
  139. ///
  140. /// - Returns: status code
  141. func receivedStatusCode() -> Int? {
  142. for (i, operation) in operations.enumerated() {
  143. switch operation {
  144. case .receiveStatusOnClient:
  145. return cgrpc_observer_recv_status_on_client_get_status(underlyingObservers[i])
  146. default:
  147. continue
  148. }
  149. }
  150. return nil
  151. }
  152. /// Gets a status message that was received
  153. ///
  154. /// - Returns: status message
  155. func receivedStatusMessage() -> String? {
  156. for (i, operation) in operations.enumerated() {
  157. switch operation {
  158. case .receiveStatusOnClient:
  159. // We actually know that this method will never return nil, so we can forcibly unwrap the result. (Also below.)
  160. let string = cgrpc_observer_recv_status_on_client_copy_status_details(underlyingObservers[i])!
  161. defer { cgrpc_free_copied_string(string) }
  162. return String(cString: string, encoding: String.Encoding.utf8)
  163. default:
  164. continue
  165. }
  166. }
  167. return nil
  168. }
  169. /// Gets trailing metadata that was received
  170. ///
  171. /// - Returns: metadata
  172. func receivedTrailingMetadata() -> Metadata? {
  173. if let cachedTrailingMetadata = self.cachedTrailingMetadata {
  174. return cachedTrailingMetadata
  175. }
  176. for (i, operation) in operations.enumerated() {
  177. switch operation {
  178. case .receiveStatusOnClient:
  179. cachedTrailingMetadata = Metadata(
  180. underlyingArray: cgrpc_observer_recv_status_on_client_get_metadata(underlyingObservers[i]))
  181. return cachedTrailingMetadata!
  182. default:
  183. continue
  184. }
  185. }
  186. return nil
  187. }
  188. }