ClientResponse.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 received by a client.
  17. ///
  18. /// Single responses are used for unary and client-streaming RPCs. For streaming responses
  19. /// see ``StreamingClientResponse``.
  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, or the client failed to execute the request. The failure case contains
  28. /// an ``RPCError`` describing why the RPC failed, including an error code, error message and any
  29. /// metadata sent by the server.
  30. ///
  31. /// ### Using responses
  32. ///
  33. /// Each response has a ``accepted`` property which contains all RPC information. You can create
  34. /// one by calling ``init(accepted:)`` or one of the two convenience initializers:
  35. /// - ``init(message:metadata:trailingMetadata:)`` to create a successful response, or
  36. /// - ``init(of:error:)`` to create a failed response.
  37. ///
  38. /// You can interrogate a response by inspecting the ``accepted`` property directly or by using
  39. /// its convenience properties:
  40. /// - ``metadata`` extracts the initial metadata,
  41. /// - ``message`` extracts the message, or throws if the response failed, and
  42. /// - ``trailingMetadata`` extracts the trailing metadata.
  43. ///
  44. /// The following example demonstrates how you can use the API:
  45. ///
  46. /// ```swift
  47. /// // Create a successful response
  48. /// let response = ClientResponse<String>(
  49. /// message: "Hello, World!",
  50. /// metadata: ["hello": "initial metadata"],
  51. /// trailingMetadata: ["goodbye": "trailing metadata"]
  52. /// )
  53. ///
  54. /// // The explicit API:
  55. /// switch response {
  56. /// case .success(let contents):
  57. /// print("Received response with message '\(try contents.message.get())'")
  58. /// case .failure(let error):
  59. /// print("RPC failed with code '\(error.code)'")
  60. /// }
  61. ///
  62. /// // The convenience API:
  63. /// do {
  64. /// print("Received response with message '\(try response.message)'")
  65. /// } catch let error as RPCError {
  66. /// print("RPC failed with code '\(error.code)'")
  67. /// }
  68. /// ```
  69. public struct ClientResponse<Message: Sendable>: Sendable {
  70. /// The contents of an accepted response with a single message.
  71. public struct Contents: Sendable {
  72. /// Metadata received from the server at the beginning of the response.
  73. ///
  74. /// The metadata may contain transport-specific information in addition to any application
  75. /// level metadata provided by the service.
  76. public var metadata: Metadata
  77. /// The response message received from the server, or an error of the RPC failed with a
  78. /// non-ok status.
  79. public var message: Result<Message, RPCError>
  80. /// Metadata received from the server at the end of the response.
  81. ///
  82. /// The metadata may contain transport-specific information in addition to any application
  83. /// level metadata provided by the service.
  84. public var trailingMetadata: Metadata
  85. /// Creates a `Contents`.
  86. ///
  87. /// - Parameters:
  88. /// - metadata: Metadata received from the server at the beginning of the response.
  89. /// - message: The response message received from the server.
  90. /// - trailingMetadata: Metadata received from the server at the end of the response.
  91. public init(
  92. metadata: Metadata,
  93. message: Message,
  94. trailingMetadata: Metadata
  95. ) {
  96. self.metadata = metadata
  97. self.message = .success(message)
  98. self.trailingMetadata = trailingMetadata
  99. }
  100. /// Creates a `Contents`.
  101. ///
  102. /// - Parameters:
  103. /// - metadata: Metadata received from the server at the beginning of the response.
  104. /// - error: Error received from the server.
  105. public init(
  106. metadata: Metadata,
  107. error: RPCError
  108. ) {
  109. self.metadata = metadata
  110. self.message = .failure(error)
  111. self.trailingMetadata = error.metadata
  112. }
  113. }
  114. /// Whether the RPC was accepted or rejected.
  115. ///
  116. /// The `success` case indicates the RPC completed successfully with an
  117. /// ``Status/Code-swift.struct/ok`` status code. The `failure` case indicates that the RPC was
  118. /// rejected by the server and wasn't processed or couldn't be processed successfully.
  119. public var accepted: Result<Contents, RPCError>
  120. /// Creates a new response.
  121. ///
  122. /// - Parameter accepted: The result of the RPC.
  123. public init(accepted: Result<Contents, RPCError>) {
  124. self.accepted = accepted
  125. }
  126. }
  127. /// A response for a stream of messages received by a client.
  128. ///
  129. /// Stream responses are used for server-streaming and bidirectional-streaming RPCs. For single
  130. /// responses see ``ClientResponse``.
  131. ///
  132. /// A stream response captures every part of the response stream over time and distinguishes
  133. /// accepted and rejected requests via the ``accepted`` property. An "accepted" request is one
  134. /// where the the server responds with initial metadata and attempts to process the request. A
  135. /// "rejected" request is one where the server responds with a status as the first and only
  136. /// response part and doesn't process the request body.
  137. ///
  138. /// The value for the `success` case contains the initial metadata and a ``RPCAsyncSequence`` of
  139. /// message parts (messages followed by a single status). If the sequence completes without
  140. /// throwing then the response implicitly has an ``Status/Code-swift.struct/ok`` status code.
  141. /// However, the response sequence may also throw an ``RPCError`` if the server fails to complete
  142. /// processing the request.
  143. ///
  144. /// The `failure` case indicates that the server chose not to process the RPC or the client failed
  145. /// to execute the request. The failure case contains an ``RPCError`` describing why the RPC
  146. /// failed, including an error code, error message and any metadata sent by the server.
  147. ///
  148. /// ### Using streaming responses
  149. ///
  150. /// Each response has a ``accepted`` property which contains RPC information. You can create
  151. /// one by calling ``init(accepted:)`` or one of the two convenience initializers:
  152. /// - ``init(of:metadata:bodyParts:)`` to create an accepted response, or
  153. /// - ``init(of:error:)`` to create a failed response.
  154. ///
  155. /// You can interrogate a response by inspecting the ``accepted`` property directly or by using
  156. /// its convenience properties:
  157. /// - ``metadata`` extracts the initial metadata,
  158. /// - ``messages`` extracts the sequence of response message, or throws if the response failed.
  159. ///
  160. /// The following example demonstrates how you can use the API:
  161. ///
  162. /// ```swift
  163. /// // Create a failed response
  164. /// let response = StreamingClientResponse(
  165. /// of: String.self,
  166. /// error: RPCError(code: .notFound, message: "The requested resource couldn't be located")
  167. /// )
  168. ///
  169. /// // The explicit API:
  170. /// switch response {
  171. /// case .success(let contents):
  172. /// for try await part in contents.bodyParts {
  173. /// switch part {
  174. /// case .message(let message):
  175. /// print("Received message '\(message)'")
  176. /// case .trailingMetadata(let metadata):
  177. /// print("Received trailing metadata '\(metadata)'")
  178. /// }
  179. /// }
  180. /// case .failure(let error):
  181. /// print("RPC failed with code '\(error.code)'")
  182. /// }
  183. ///
  184. /// // The convenience API:
  185. /// do {
  186. /// for try await message in response.messages {
  187. /// print("Received message '\(message)'")
  188. /// }
  189. /// } catch let error as RPCError {
  190. /// print("RPC failed with code '\(error.code)'")
  191. /// }
  192. /// ```
  193. public struct StreamingClientResponse<Message: Sendable>: Sendable {
  194. public struct Contents: Sendable {
  195. /// Metadata received from the server at the beginning of the response.
  196. ///
  197. /// The metadata may contain transport-specific information in addition to any application
  198. /// level metadata provided by the service.
  199. public var metadata: Metadata
  200. /// A sequence of stream parts received from the server ending with metadata if the RPC
  201. /// succeeded.
  202. ///
  203. /// If the RPC fails then the sequence will throw an ``RPCError``.
  204. ///
  205. /// The sequence may only be iterated once.
  206. public var bodyParts: RPCAsyncSequence<BodyPart, any Error>
  207. /// Parts received from the server.
  208. public enum BodyPart: Sendable {
  209. /// A response message.
  210. case message(Message)
  211. /// Metadata. Must be the final value of the sequence unless the stream throws an error.
  212. case trailingMetadata(Metadata)
  213. }
  214. /// Creates a ``Contents``.
  215. ///
  216. /// - Parameters:
  217. /// - metadata: Metadata received from the server at the beginning of the response.
  218. /// - bodyParts: An `AsyncSequence` of parts received from the server.
  219. public init(
  220. metadata: Metadata,
  221. bodyParts: RPCAsyncSequence<BodyPart, any Error>
  222. ) {
  223. self.metadata = metadata
  224. self.bodyParts = bodyParts
  225. }
  226. }
  227. /// Whether the RPC was accepted or rejected.
  228. ///
  229. /// The `success` case indicates the RPC was accepted by the server for
  230. /// processing, however, the RPC may still fail by throwing an error from its
  231. /// `messages` sequence. The `failure` case indicates that the RPC was
  232. /// rejected by the server.
  233. public var accepted: Result<Contents, RPCError>
  234. /// Creates a new response.
  235. ///
  236. /// - Parameter accepted: The result of the RPC.
  237. public init(accepted: Result<Contents, RPCError>) {
  238. self.accepted = accepted
  239. }
  240. }
  241. // MARK: - Convenience API
  242. extension ClientResponse {
  243. /// Creates a new accepted response.
  244. ///
  245. /// - Parameters:
  246. /// - metadata: Metadata received from the server at the beginning of the response.
  247. /// - message: The response message received from the server.
  248. /// - trailingMetadata: Metadata received from the server at the end of the response.
  249. public init(message: Message, metadata: Metadata = [:], trailingMetadata: Metadata = [:]) {
  250. let contents = Contents(
  251. metadata: metadata,
  252. message: message,
  253. trailingMetadata: trailingMetadata
  254. )
  255. self.accepted = .success(contents)
  256. }
  257. /// Creates a new accepted response with a failed outcome.
  258. ///
  259. /// - Parameters:
  260. /// - messageType: The type of message.
  261. /// - metadata: Metadata received from the server at the beginning of the response.
  262. /// - error: An error describing why the RPC failed.
  263. public init(of messageType: Message.Type = Message.self, metadata: Metadata, error: RPCError) {
  264. let contents = Contents(metadata: metadata, error: error)
  265. self.accepted = .success(contents)
  266. }
  267. /// Creates a new failed response.
  268. ///
  269. /// - Parameters:
  270. /// - messageType: The type of message.
  271. /// - error: An error describing why the RPC failed.
  272. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  273. self.accepted = .failure(error)
  274. }
  275. /// Returns metadata received from the server at the start of the response.
  276. ///
  277. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  278. public var metadata: Metadata {
  279. switch self.accepted {
  280. case let .success(contents):
  281. return contents.metadata
  282. case .failure:
  283. return [:]
  284. }
  285. }
  286. /// Returns the message received from the server.
  287. ///
  288. /// - Throws: ``RPCError`` if the request failed.
  289. public var message: Message {
  290. get throws {
  291. try self.accepted.flatMap { $0.message }.get()
  292. }
  293. }
  294. /// Returns metadata received from the server at the end of the response.
  295. ///
  296. /// Unlike ``metadata``, for rejected RPCs the metadata returned may contain values.
  297. public var trailingMetadata: Metadata {
  298. switch self.accepted {
  299. case let .success(contents):
  300. return contents.trailingMetadata
  301. case let .failure(error):
  302. return error.metadata
  303. }
  304. }
  305. }
  306. extension StreamingClientResponse {
  307. /// Creates a new accepted response.
  308. ///
  309. /// - Parameters:
  310. /// - messageType: The type of message.
  311. /// - metadata: Metadata received from the server at the beginning of the response.
  312. /// - bodyParts: An ``RPCAsyncSequence`` of response parts received from the server.
  313. public init(
  314. of messageType: Message.Type = Message.self,
  315. metadata: Metadata,
  316. bodyParts: RPCAsyncSequence<Contents.BodyPart, any Error>
  317. ) {
  318. let contents = Contents(metadata: metadata, bodyParts: bodyParts)
  319. self.accepted = .success(contents)
  320. }
  321. /// Creates a new failed response.
  322. ///
  323. /// - Parameters:
  324. /// - messageType: The type of message.
  325. /// - error: An error describing why the RPC failed.
  326. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  327. self.accepted = .failure(error)
  328. }
  329. /// Returns metadata received from the server at the start of the response.
  330. ///
  331. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  332. public var metadata: Metadata {
  333. switch self.accepted {
  334. case let .success(contents):
  335. return contents.metadata
  336. case .failure:
  337. return [:]
  338. }
  339. }
  340. /// Returns the messages received from the server.
  341. ///
  342. /// For rejected RPCs the `RPCAsyncSequence` throws a `RPCError``.
  343. public var messages: RPCAsyncSequence<Message, any Error> {
  344. switch self.accepted {
  345. case let .success(contents):
  346. let filtered = contents.bodyParts.compactMap {
  347. switch $0 {
  348. case let .message(message):
  349. return message
  350. case .trailingMetadata:
  351. return nil
  352. }
  353. }
  354. return RPCAsyncSequence(wrapping: filtered)
  355. case let .failure(error):
  356. return RPCAsyncSequence.throwing(error)
  357. }
  358. }
  359. }