ServerResponse.swift 14 KB

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