ServerResponse.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * Copyright 2023, 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. /// A namespace for response message types used by servers.
  17. public enum ServerResponse {}
  18. extension ServerResponse {
  19. /// A response for a single message sent by a server.
  20. ///
  21. /// Single responses are used for unary and client-streaming RPCs. For streaming responses
  22. /// see ``ServerResponse/Stream``.
  23. ///
  24. /// A single response captures every part of the response stream and distinguishes successful
  25. /// and unsuccessful responses via the ``accepted`` property. The value for the `success` case
  26. /// contains the initial metadata, response message, and the trailing metadata and implicitly
  27. /// has an ``Status/Code-swift.struct/ok`` status code.
  28. ///
  29. /// The `failure` case indicates that the server chose not to process the RPC, or the processing
  30. /// of the RPC failed. The failure case contains an ``RPCError`` describing why the RPC failed,
  31. /// including an error code, error message and any metadata sent by the server.
  32. ///
  33. /// ### Using ``Single`` responses
  34. ///
  35. /// Each response has an ``accepted`` property which contains all RPC information. You can create
  36. /// one by calling ``init(accepted:)`` or one of the two convenience initializers:
  37. /// - ``init(message:metadata:trailingMetadata:)`` to create a successful response, or
  38. /// - ``init(of:error:)`` to create a failed response.
  39. ///
  40. /// You can interrogate a response by inspecting the ``accepted`` property directly or by using
  41. /// its convenience properties:
  42. /// - ``metadata`` extracts the initial metadata,
  43. /// - ``message`` extracts the message, or throws if the response failed, and
  44. /// - ``trailingMetadata`` extracts the trailing metadata.
  45. ///
  46. /// The following example demonstrates how you can use the API:
  47. ///
  48. /// ```swift
  49. /// // Create a successful response
  50. /// let response = ServerResponse.Single<String>(
  51. /// message: "Hello, World!",
  52. /// metadata: ["hello": "initial metadata"],
  53. /// trailingMetadata: ["goodbye": "trailing metadata"]
  54. /// )
  55. ///
  56. /// // The explicit API:
  57. /// switch response {
  58. /// case .success(let contents):
  59. /// print("Received response with message '\(contents.message)'")
  60. /// case .failure(let error):
  61. /// print("RPC failed with code '\(error.code)'")
  62. /// }
  63. ///
  64. /// // The convenience API:
  65. /// do {
  66. /// print("Received response with message '\(try response.message)'")
  67. /// } catch let error as RPCError {
  68. /// print("RPC failed with code '\(error.code)'")
  69. /// }
  70. /// ```
  71. public struct Single<Message: Sendable>: Sendable {
  72. /// An accepted RPC with a successful outcome.
  73. public struct Contents: Sendable {
  74. /// Caller-specified metadata to send to the client at the start of the response.
  75. ///
  76. /// Both gRPC Swift and its transport layer may insert additional metadata. Keys prefixed with
  77. /// "grpc-" are prohibited and may result in undefined behaviour. Transports may also insert
  78. /// their own metadata, you should avoid using key names which may clash with transport
  79. /// specific metadata. Note that transports may also impose limits in the amount of metadata
  80. /// which may be sent.
  81. public var metadata: Metadata
  82. /// The message to send to the client.
  83. public var message: Message
  84. /// Caller-specified metadata to send to the client at the end of the response.
  85. ///
  86. /// Both gRPC Swift and its transport layer may insert additional metadata. Keys prefixed with
  87. /// "grpc-" are prohibited and may result in undefined behaviour. Transports may also insert
  88. /// their own metadata, you should avoid using key names which may clash with transport
  89. /// specific metadata. Note that transports may also impose limits in the amount of metadata
  90. /// which may be sent.
  91. public var trailingMetadata: Metadata
  92. /// Create a new single client request.
  93. ///
  94. /// - Parameters:
  95. /// - message: The message to send to the server.
  96. /// - metadata: Metadata to send to the client at the start of the response. Defaults to
  97. /// empty.
  98. /// - trailingMetadata: Metadata to send to the client at the end of the response. Defaults
  99. /// to empty.
  100. public init(
  101. message: Message,
  102. metadata: Metadata = [:],
  103. trailingMetadata: Metadata = [:]
  104. ) {
  105. self.metadata = metadata
  106. self.message = message
  107. self.trailingMetadata = trailingMetadata
  108. }
  109. }
  110. /// Whether the RPC was accepted or rejected.
  111. ///
  112. /// The `success` indicates the server accepted the RPC for processing and the RPC completed
  113. /// successfully and implies the RPC succeeded with the ``Status/Code-swift.struct/ok`` status
  114. /// code. The `failure` case indicates that the service rejected the RPC without processing it
  115. /// or could not process it successfully.
  116. public var accepted: Result<Contents, RPCError>
  117. /// Creates a response.
  118. ///
  119. /// - Parameter accepted: Whether the RPC was accepted or rejected.
  120. public init(accepted: Result<Contents, RPCError>) {
  121. self.accepted = accepted
  122. }
  123. }
  124. }
  125. extension ServerResponse {
  126. /// A response for a stream of messages sent by a server.
  127. ///
  128. /// Stream responses are used for server-streaming and bidirectional-streaming RPCs. For single
  129. /// responses see ``ServerResponse/Single``.
  130. ///
  131. /// A stream response captures every part of the response stream and distinguishes whether the
  132. /// request was processed by the server via the ``accepted`` property. The value for the `success`
  133. /// case contains the initial metadata and a closure which is provided with a message write and
  134. /// returns trailing metadata. If the closure returns without error then the response implicitly
  135. /// has an ``Status/Code-swift.struct/ok`` status code. You can throw an error from the producer
  136. /// to indicate that the request couldn't be handled successfully. If an ``RPCError`` is thrown
  137. /// then the client will receive an equivalent error populated with the same code and message. If
  138. /// an error of any other type is thrown then the client will receive an error with the
  139. /// ``Status/Code-swift.struct/unknown`` status code.
  140. ///
  141. /// The `failure` case indicates that the server chose not to process the RPC. The failure case
  142. /// contains an ``RPCError`` describing why the RPC failed, including an error code, error
  143. /// message and any metadata to send to the client.
  144. ///
  145. /// ### Using ``Stream`` responses
  146. ///
  147. /// Each response has an ``accepted`` property which contains all RPC information. You can create
  148. /// one by calling ``init(accepted:)`` or one of the two convenience initializers:
  149. /// - ``init(of:metadata:producer:)`` to create a successful response, or
  150. /// - ``init(of:error:)`` to create a failed response.
  151. ///
  152. /// You can interrogate a response by inspecting the ``accepted`` property directly. The following
  153. /// example demonstrates how you can use the API:
  154. ///
  155. /// ```swift
  156. /// // Create a successful response
  157. /// let response = ServerResponse.Stream(
  158. /// of: String.self,
  159. /// metadata: ["hello": "initial metadata"]
  160. /// ) { writer in
  161. /// // Write a few messages.
  162. /// try await writer.write("Hello")
  163. /// try await writer.write("World")
  164. ///
  165. /// // Send trailing metadata to the client.
  166. /// return ["goodbye": "trailing metadata"]
  167. /// }
  168. /// ```
  169. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  170. public struct Stream<Message: Sendable>: Sendable {
  171. /// The contents of a response to a request which has been accepted for processing.
  172. public struct Contents: Sendable {
  173. /// Metadata to send to the client at the beginning of the response stream.
  174. public var metadata: Metadata
  175. /// A closure which, when called, writes values into the provided writer and returns trailing
  176. /// metadata indicating the end of the response stream.
  177. ///
  178. /// Returning metadata indicates a successful response and gRPC will terminate the RPC with
  179. /// an ``Status/Code-swift.struct/ok`` status code. Throwing an error will terminate the RPC
  180. /// with an appropriate status code. You can control the status code, message and metadata
  181. /// returned to the client by throwing an ``RPCError``. If the error thrown is a type other
  182. /// than ``RPCError`` then a status with code ``Status/Code-swift.struct/unknown`` will
  183. /// be returned to the client.
  184. ///
  185. /// gRPC will invoke this function at most once therefore it isn't required to be idempotent.
  186. public var producer: @Sendable (RPCWriter<Message>) async throws -> Metadata
  187. /// Create a ``Contents``.
  188. ///
  189. /// - Parameters:
  190. /// - metadata: Metadata to send to the client at the start of the response.
  191. /// - producer: A function which produces values
  192. public init(
  193. metadata: Metadata,
  194. producer: @escaping @Sendable (RPCWriter<Message>) async throws -> Metadata
  195. ) {
  196. self.metadata = metadata
  197. self.producer = producer
  198. }
  199. }
  200. /// Whether the RPC was accepted or rejected.
  201. ///
  202. /// The `success` case indicates that the service accepted the RPC for processing and will
  203. /// send initial metadata back to the client before producing response messages. The RPC may
  204. /// still result in failure by later throwing an error.
  205. ///
  206. /// The `failure` case indicates that the server rejected the RPC and will not process it. Only
  207. /// the status and trailing metadata will be sent to the client.
  208. public var accepted: Result<Contents, RPCError>
  209. /// Creates a response.
  210. ///
  211. /// - Parameter accepted: Whether the RPC was accepted or rejected.
  212. public init(accepted: Result<Contents, RPCError>) {
  213. self.accepted = accepted
  214. }
  215. }
  216. }
  217. extension ServerResponse.Single {
  218. /// Creates a new accepted response.
  219. ///
  220. /// - Parameters:
  221. /// - metadata: Metadata to send to the client at the beginning of the response.
  222. /// - message: The response message to send to the client.
  223. /// - trailingMetadata: Metadata to send to the client at the end of the response.
  224. public init(message: Message, metadata: Metadata = [:], trailingMetadata: Metadata = [:]) {
  225. let contents = Contents(
  226. message: message,
  227. metadata: metadata,
  228. trailingMetadata: trailingMetadata
  229. )
  230. self.accepted = .success(contents)
  231. }
  232. /// Creates a new failed response.
  233. ///
  234. /// - Parameters:
  235. /// - messageType: The type of message.
  236. /// - error: An error describing why the RPC failed.
  237. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  238. self.accepted = .failure(error)
  239. }
  240. /// Returns the metadata to be sent to the client at the start of the response.
  241. ///
  242. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  243. public var metadata: Metadata {
  244. switch self.accepted {
  245. case let .success(contents):
  246. return contents.metadata
  247. case .failure:
  248. return [:]
  249. }
  250. }
  251. /// Returns the message to send to the client.
  252. ///
  253. /// - Throws: ``RPCError`` if the request failed.
  254. public var message: Message {
  255. get throws {
  256. try self.accepted.map { $0.message }.get()
  257. }
  258. }
  259. /// Returns metadata to be sent to the client at the end of the response.
  260. ///
  261. /// Unlike ``metadata``, for rejected RPCs the metadata returned may contain values.
  262. public var trailingMetadata: Metadata {
  263. switch self.accepted {
  264. case let .success(contents):
  265. return contents.trailingMetadata
  266. case let .failure(error):
  267. return error.metadata
  268. }
  269. }
  270. }
  271. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  272. extension ServerResponse.Stream {
  273. /// Creates a new accepted response.
  274. ///
  275. /// - Parameters:
  276. /// - messageType: The type of message.
  277. /// - metadata: Metadata to send to the client at the beginning of the response.
  278. /// - producer: A closure which, when called, writes messages to the client.
  279. public init(
  280. of messageType: Message.Type = Message.self,
  281. metadata: Metadata = [:],
  282. producer: @escaping @Sendable (RPCWriter<Message>) async throws -> Metadata
  283. ) {
  284. let contents = Contents(metadata: metadata, producer: producer)
  285. self.accepted = .success(contents)
  286. }
  287. /// Creates a new failed response.
  288. ///
  289. /// - Parameters:
  290. /// - messageType: The type of message.
  291. /// - error: An error describing why the RPC failed.
  292. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  293. self.accepted = .failure(error)
  294. }
  295. /// Returns metadata received from the server at the start of the response.
  296. ///
  297. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  298. public var metadata: Metadata {
  299. switch self.accepted {
  300. case let .success(contents):
  301. return contents.metadata
  302. case .failure:
  303. return [:]
  304. }
  305. }
  306. }
  307. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  308. extension ServerResponse.Stream {
  309. @_spi(Testing)
  310. public init(single response: ServerResponse.Single<Message>) {
  311. switch response.accepted {
  312. case .success(let contents):
  313. let contents = Contents(metadata: contents.metadata) {
  314. try await $0.write(contents.message)
  315. return contents.trailingMetadata
  316. }
  317. self.accepted = .success(contents)
  318. case .failure(let error):
  319. self.accepted = .failure(error)
  320. }
  321. }
  322. }