ClientResponse.swift 15 KB

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