ClientResponse.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 ``Single`` 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 ``Stream`` 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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  194. public struct StreamingClientResponse<Message: Sendable>: Sendable {
  195. public struct Contents: Sendable {
  196. /// Metadata received from the server at the beginning of the response.
  197. ///
  198. /// The metadata may contain transport-specific information in addition to any application
  199. /// level metadata provided by the service.
  200. public var metadata: Metadata
  201. /// A sequence of stream parts received from the server ending with metadata if the RPC
  202. /// succeeded.
  203. ///
  204. /// If the RPC fails then the sequence will throw an ``RPCError``.
  205. ///
  206. /// The sequence may only be iterated once.
  207. public var bodyParts: RPCAsyncSequence<BodyPart, any Error>
  208. /// Parts received from the server.
  209. public enum BodyPart: Sendable {
  210. /// A response message.
  211. case message(Message)
  212. /// Metadata. Must be the final value of the sequence unless the stream throws an error.
  213. case trailingMetadata(Metadata)
  214. }
  215. /// Creates a ``Contents``.
  216. ///
  217. /// - Parameters:
  218. /// - metadata: Metadata received from the server at the beginning of the response.
  219. /// - bodyParts: An `AsyncSequence` of parts received from the server.
  220. public init(
  221. metadata: Metadata,
  222. bodyParts: RPCAsyncSequence<BodyPart, any Error>
  223. ) {
  224. self.metadata = metadata
  225. self.bodyParts = bodyParts
  226. }
  227. }
  228. /// Whether the RPC was accepted or rejected.
  229. ///
  230. /// The `success` case indicates the RPC was accepted by the server for
  231. /// processing, however, the RPC may still fail by throwing an error from its
  232. /// `messages` sequence. The `failure` case indicates that the RPC was
  233. /// rejected by the server.
  234. public var accepted: Result<Contents, RPCError>
  235. /// Creates a new response.
  236. ///
  237. /// - Parameter accepted: The result of the RPC.
  238. public init(accepted: Result<Contents, RPCError>) {
  239. self.accepted = accepted
  240. }
  241. }
  242. // MARK: - Convenience API
  243. extension ClientResponse {
  244. /// Creates a new accepted response.
  245. ///
  246. /// - Parameters:
  247. /// - metadata: Metadata received from the server at the beginning of the response.
  248. /// - message: The response message received from the server.
  249. /// - trailingMetadata: Metadata received from the server at the end of the response.
  250. public init(message: Message, metadata: Metadata = [:], trailingMetadata: Metadata = [:]) {
  251. let contents = Contents(
  252. metadata: metadata,
  253. message: message,
  254. trailingMetadata: trailingMetadata
  255. )
  256. self.accepted = .success(contents)
  257. }
  258. /// Creates a new accepted response with a failed outcome.
  259. ///
  260. /// - Parameters:
  261. /// - messageType: The type of message.
  262. /// - metadata: Metadata received from the server at the beginning of the response.
  263. /// - error: An error describing why the RPC failed.
  264. public init(of messageType: Message.Type = Message.self, metadata: Metadata, error: RPCError) {
  265. let contents = Contents(metadata: metadata, error: error)
  266. self.accepted = .success(contents)
  267. }
  268. /// Creates a new failed response.
  269. ///
  270. /// - Parameters:
  271. /// - messageType: The type of message.
  272. /// - error: An error describing why the RPC failed.
  273. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  274. self.accepted = .failure(error)
  275. }
  276. /// Returns metadata received from the server at the start of the response.
  277. ///
  278. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  279. public var metadata: Metadata {
  280. switch self.accepted {
  281. case let .success(contents):
  282. return contents.metadata
  283. case .failure:
  284. return [:]
  285. }
  286. }
  287. /// Returns the message received from the server.
  288. ///
  289. /// - Throws: ``RPCError`` if the request failed.
  290. public var message: Message {
  291. get throws {
  292. try self.accepted.flatMap { $0.message }.get()
  293. }
  294. }
  295. /// Returns metadata received from the server at the end of the response.
  296. ///
  297. /// Unlike ``metadata``, for rejected RPCs the metadata returned may contain values.
  298. public var trailingMetadata: Metadata {
  299. switch self.accepted {
  300. case let .success(contents):
  301. return contents.trailingMetadata
  302. case let .failure(error):
  303. return error.metadata
  304. }
  305. }
  306. }
  307. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  308. extension StreamingClientResponse {
  309. /// Creates a new accepted response.
  310. ///
  311. /// - Parameters:
  312. /// - messageType: The type of message.
  313. /// - metadata: Metadata received from the server at the beginning of the response.
  314. /// - bodyParts: An ``RPCAsyncSequence`` of response parts received from the server.
  315. public init(
  316. of messageType: Message.Type = Message.self,
  317. metadata: Metadata,
  318. bodyParts: RPCAsyncSequence<Contents.BodyPart, any Error>
  319. ) {
  320. let contents = Contents(metadata: metadata, bodyParts: bodyParts)
  321. self.accepted = .success(contents)
  322. }
  323. /// Creates a new failed response.
  324. ///
  325. /// - Parameters:
  326. /// - messageType: The type of message.
  327. /// - error: An error describing why the RPC failed.
  328. public init(of messageType: Message.Type = Message.self, error: RPCError) {
  329. self.accepted = .failure(error)
  330. }
  331. /// Returns metadata received from the server at the start of the response.
  332. ///
  333. /// For rejected RPCs (in other words, where ``accepted`` is `failure`) the metadata is empty.
  334. public var metadata: Metadata {
  335. switch self.accepted {
  336. case let .success(contents):
  337. return contents.metadata
  338. case .failure:
  339. return [:]
  340. }
  341. }
  342. /// Returns the messages received from the server.
  343. ///
  344. /// For rejected RPCs the `RPCAsyncSequence` throws a `RPCError``.
  345. public var messages: RPCAsyncSequence<Message, any Error> {
  346. switch self.accepted {
  347. case let .success(contents):
  348. let filtered = contents.bodyParts.compactMap {
  349. switch $0 {
  350. case let .message(message):
  351. return message
  352. case .trailingMetadata:
  353. return nil
  354. }
  355. }
  356. return RPCAsyncSequence(wrapping: filtered)
  357. case let .failure(error):
  358. return RPCAsyncSequence.throwing(error)
  359. }
  360. }
  361. }