ControlService.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. * Copyright 2024, 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. import GRPCCore
  17. import struct Foundation.Data
  18. struct ControlService: ControlStreamingServiceProtocol {
  19. func unary(
  20. request: ServerRequest.Stream<Control.Method.Unary.Input>
  21. ) async throws -> ServerResponse.Stream<Control.Method.Unary.Output> {
  22. try await self.handle(request: request)
  23. }
  24. func serverStream(
  25. request: ServerRequest.Stream<Control.Method.ServerStream.Input>
  26. ) async throws -> ServerResponse.Stream<Control.Method.ServerStream.Output> {
  27. try await self.handle(request: request)
  28. }
  29. func clientStream(
  30. request: ServerRequest.Stream<Control.Method.ClientStream.Input>
  31. ) async throws -> ServerResponse.Stream<Control.Method.ClientStream.Output> {
  32. try await self.handle(request: request)
  33. }
  34. func bidiStream(
  35. request: ServerRequest.Stream<Control.Method.BidiStream.Input>
  36. ) async throws -> ServerResponse.Stream<Control.Method.BidiStream.Output> {
  37. try await self.handle(request: request)
  38. }
  39. }
  40. extension ControlService {
  41. private func handle(
  42. request: ServerRequest.Stream<ControlInput>
  43. ) async throws -> ServerResponse.Stream<ControlOutput> {
  44. var iterator = request.messages.makeAsyncIterator()
  45. guard let message = try await iterator.next() else {
  46. // Empty input stream, empty output stream.
  47. return ServerResponse.Stream { _ in [:] }
  48. }
  49. // Check if the request is for a trailers-only response.
  50. if message.hasStatus, message.isTrailersOnly {
  51. let trailers = message.echoMetadataInTrailers ? request.metadata.echo() : [:]
  52. let code = Status.Code(rawValue: message.status.code.rawValue).flatMap { RPCError.Code($0) }
  53. if let code = code {
  54. throw RPCError(code: code, message: message.status.message, metadata: trailers)
  55. } else {
  56. // Invalid code, the request is invalid, so throw an appropriate error.
  57. throw RPCError(
  58. code: .invalidArgument,
  59. message: "Trailers only response must use a non-OK status code"
  60. )
  61. }
  62. }
  63. // Not a trailers-only response. Should the metadata be echo'd back?
  64. let metadata = message.echoMetadataInHeaders ? request.metadata.echo() : [:]
  65. // The iterator needs to be transferred into the response. This is okay: we won't touch the
  66. // iterator again from the current concurrency domain.
  67. let transfer = UnsafeTransfer(iterator)
  68. return ServerResponse.Stream(metadata: metadata) { writer in
  69. // Finish dealing with the first message.
  70. switch try await self.processMessage(message, metadata: request.metadata, writer: writer) {
  71. case .return(let metadata):
  72. return metadata
  73. case .continue:
  74. ()
  75. }
  76. var iterator = transfer.wrappedValue
  77. // Process the rest of the messages.
  78. while let message = try await iterator.next() {
  79. switch try await self.processMessage(message, metadata: request.metadata, writer: writer) {
  80. case .return(let metadata):
  81. return metadata
  82. case .continue:
  83. ()
  84. }
  85. }
  86. // Input stream finished without explicitly setting a status; finish the RPC cleanly.
  87. return [:]
  88. }
  89. }
  90. private enum NextProcessingStep {
  91. case `return`(Metadata)
  92. case `continue`
  93. }
  94. private func processMessage(
  95. _ input: ControlInput,
  96. metadata: Metadata,
  97. writer: RPCWriter<ControlOutput>
  98. ) async throws -> NextProcessingStep {
  99. // If messages were requested, build a response and send them back.
  100. if input.numberOfMessages > 0 {
  101. let output = ControlOutput.with {
  102. $0.payload = Data(
  103. repeating: UInt8(truncatingIfNeeded: input.messageParams.content),
  104. count: Int(input.messageParams.size)
  105. )
  106. }
  107. for _ in 0 ..< input.numberOfMessages {
  108. try await writer.write(output)
  109. }
  110. }
  111. // Check whether the RPC should be finished (i.e. the input `hasStatus`).
  112. guard input.hasStatus else {
  113. if input.echoMetadataInTrailers {
  114. // There was no status in the input, but echo metadata in trailers was set. This is an
  115. // implicit 'ok' status.
  116. let trailers = input.echoMetadataInTrailers ? metadata.echo() : [:]
  117. return .return(trailers)
  118. } else {
  119. // No status, and not echoing back metadata. Continue consuming the input stream.
  120. return .continue
  121. }
  122. }
  123. // Build the trailers.
  124. let trailers = input.echoMetadataInTrailers ? metadata.echo() : [:]
  125. if input.status.code == .ok {
  126. return .return(trailers)
  127. }
  128. // Non-OK status code, throw an error.
  129. let code = Status.Code(rawValue: input.status.code.rawValue).flatMap { RPCError.Code($0) }
  130. if let code = code {
  131. // Valid error code, throw it.
  132. throw RPCError(code: code, message: input.status.message, metadata: trailers)
  133. } else {
  134. // Invalid error code, throw an appropriate error.
  135. throw RPCError(
  136. code: .invalidArgument,
  137. message: "Invalid error code '\(input.status.code)'"
  138. )
  139. }
  140. }
  141. }
  142. extension Metadata {
  143. fileprivate func echo() -> Self {
  144. var copy = Metadata()
  145. copy.reserveCapacity(self.count)
  146. for (key, value) in self {
  147. // Header field names mustn't contain ":".
  148. let key = "echo-" + key.replacingOccurrences(of: ":", with: "")
  149. switch value {
  150. case .string(let stringValue):
  151. copy.addString(stringValue, forKey: key)
  152. case .binary(let binaryValue):
  153. copy.addBinary(binaryValue, forKey: key)
  154. }
  155. }
  156. return copy
  157. }
  158. }
  159. private struct UnsafeTransfer<Wrapped> {
  160. var wrappedValue: Wrapped
  161. init(_ wrappedValue: Wrapped) {
  162. self.wrappedValue = wrappedValue
  163. }
  164. }
  165. extension UnsafeTransfer: @unchecked Sendable {}