GRPCClientStateMachine.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import NIO
  18. import NIOHTTP1
  19. import NIOHPACK
  20. import Logging
  21. import SwiftProtobuf
  22. enum ReceiveResponseHeadError: Error, Equatable {
  23. /// The 'content-type' header was missing or the value is not supported by this implementation.
  24. case invalidContentType
  25. /// The HTTP response status from the server was not 200 OK.
  26. case invalidHTTPStatus(HTTPResponseStatus?)
  27. /// The encoding used by the server is not supported.
  28. case unsupportedMessageEncoding(String)
  29. /// An invalid state was encountered. This is a serious implementation error.
  30. case invalidState
  31. }
  32. enum ReceiveEndOfResponseStreamError: Error {
  33. /// The 'content-type' header was missing or the value is not supported by this implementation.
  34. case invalidContentType
  35. /// The HTTP response status from the server was not 200 OK.
  36. case invalidHTTPStatus(HTTPResponseStatus?)
  37. /// The HTTP response status from the server was not 200 OK but the "grpc-status" header contained
  38. /// a valid value.
  39. case invalidHTTPStatusWithGRPCStatus(GRPCStatus)
  40. /// An invalid state was encountered. This is a serious implementation error.
  41. case invalidState
  42. }
  43. enum SendRequestHeadersError: Error {
  44. /// An invalid state was encountered. This is a serious implementation error.
  45. case invalidState
  46. }
  47. enum SendEndOfRequestStreamError: Error {
  48. /// The request stream has already been closed. This may happen if the RPC was cancelled, timed
  49. /// out, the server terminated the RPC, or the user explicitly closed the stream multiple times.
  50. case alreadyClosed
  51. /// An invalid state was encountered. This is a serious implementation error.
  52. case invalidState
  53. }
  54. /// A state machine for a single gRPC call from the perspective of a client.
  55. ///
  56. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  57. struct GRPCClientStateMachine<Request: Message, Response: Message> {
  58. /// The combined state of the request (client) and response (server) streams for an RPC call.
  59. ///
  60. /// The following states are not possible:
  61. /// - `.clientIdleServerActive`: The client must initiate the call before the server moves
  62. /// from the idle state.
  63. /// - `.clientIdleServerClosed`: The client must initiate the call before the server moves from
  64. /// the idle state.
  65. /// - `.clientActiveServerClosed`: The client may not stream if the server is closed.
  66. ///
  67. /// Note: when a peer (client or server) state is "active" it means that messages _may_ be sent or
  68. /// received. That is, the headers for the stream have been processed by the state machine and
  69. /// end-of-stream has not yet been processed. A stream may expect any number of messages (i.e. up
  70. /// to one for a unary call and many for a streaming call).
  71. enum State {
  72. /// Initial state. Neither request stream nor response stream have been initiated. Holds the
  73. /// pending write state for the request stream and arity for the response stream, respectively.
  74. ///
  75. /// Valid transitions:
  76. /// - `clientActiveServerIdle`: if the client initiates the RPC,
  77. /// - `clientClosedServerClosed`: if the client terminates the RPC.
  78. case clientIdleServerIdle(pendingWriteState: PendingWriteState, readArity: MessageArity)
  79. /// The client has initiated an RPC and has not received initial metadata from the server. Holds
  80. /// the writing state for request stream and arity for the response stream.
  81. ///
  82. /// Valid transitions:
  83. /// - `clientActiveServerActive`: if the server acknowledges the RPC initiation,
  84. /// - `clientClosedServerIdle`: if the client closes the request stream,
  85. /// - `clientClosedServerClosed`: if the client terminates the RPC or the server terminates the
  86. /// RPC with a "trailers-only" response.
  87. case clientActiveServerIdle(writeState: WriteState, readArity: MessageArity)
  88. /// The client has indicated to the server that it has finished sending requests. The server
  89. /// has not yet sent response headers for the RPC. Holds the response stream arity.
  90. ///
  91. /// Valid transitions:
  92. /// - `clientClosedServerActive`: if the server acknowledges the RPC initiation,
  93. /// - `clientClosedServerClosed`: if the client terminates the RPC or the server terminates the
  94. /// RPC with a "trailers-only" response.
  95. case clientClosedServerIdle(readArity: MessageArity)
  96. /// The client has initiated the RPC and the server has acknowledged it. Messages may have been
  97. /// sent and/or received. Holds the request stream write state and response stream read state.
  98. ///
  99. /// Valid transitions:
  100. /// - `clientClosedServerActive`: if the client closes the request stream,
  101. /// - `clientClosedServerClosed`: if the client or server terminates the RPC.
  102. case clientActiveServerActive(writeState: WriteState, readState: ReadState)
  103. /// The client has indicated to the server that it has finished sending requests. The server
  104. /// has acknowledged the RPC. Holds the response stream read state.
  105. ///
  106. /// Valid transitions:
  107. /// - `clientClosedServerClosed`: if the client or server terminate the RPC.
  108. case clientClosedServerActive(readState: ReadState)
  109. /// The RPC has terminated. There are no valid transitions from this state.
  110. case clientClosedServerClosed
  111. }
  112. /// The current state of the state machine.
  113. internal private(set) var state: State {
  114. didSet {
  115. switch (oldValue, self.state) {
  116. // All valid transitions:
  117. case (.clientIdleServerIdle, .clientActiveServerIdle),
  118. (.clientIdleServerIdle, .clientClosedServerClosed),
  119. (.clientActiveServerIdle, .clientActiveServerActive),
  120. (.clientActiveServerIdle, .clientClosedServerIdle),
  121. (.clientActiveServerIdle, .clientClosedServerClosed),
  122. (.clientClosedServerIdle, .clientClosedServerActive),
  123. (.clientClosedServerIdle, .clientClosedServerClosed),
  124. (.clientActiveServerActive, .clientClosedServerActive),
  125. (.clientActiveServerActive, .clientClosedServerClosed),
  126. (.clientClosedServerActive, .clientClosedServerClosed):
  127. break
  128. // Self transitions, also valid:
  129. case (.clientIdleServerIdle, .clientIdleServerIdle),
  130. (.clientActiveServerIdle, .clientActiveServerIdle),
  131. (.clientClosedServerIdle, .clientClosedServerIdle),
  132. (.clientActiveServerActive, .clientActiveServerActive),
  133. (.clientClosedServerActive, .clientClosedServerActive),
  134. (.clientClosedServerClosed, .clientClosedServerClosed):
  135. break
  136. default:
  137. preconditionFailure("invalid state transition from '\(oldValue)' to '\(self.state)'")
  138. }
  139. }
  140. }
  141. /// Creates a state machine representing a gRPC client's request and response stream state.
  142. ///
  143. /// - Parameter requestArity: The expected number of messages on the request stream.
  144. /// - Parameter responseArity: The expected number of messages on the response stream.
  145. init(requestArity: MessageArity, responseArity: MessageArity) {
  146. self.state = .clientIdleServerIdle(
  147. pendingWriteState: .init(arity: requestArity, compression: .none, contentType: .protobuf),
  148. readArity: responseArity
  149. )
  150. }
  151. /// Creates a state machine representing a gRPC client's request and response stream state.
  152. ///
  153. /// - Parameter state: The initial state of the state machine.
  154. init(state: State) {
  155. self.state = state
  156. }
  157. /// Initiates an RPC.
  158. ///
  159. /// The only valid state transition is:
  160. /// - `.clientIdleServerIdle` → `.clientActiveServerIdle`
  161. ///
  162. /// All other states will result in an `.invalidState` error.
  163. ///
  164. /// On success the state will transition to `.clientActiveServerIdle`.
  165. ///
  166. /// - Parameter requestHead: The client request head for the RPC.
  167. mutating func sendRequestHeaders(
  168. requestHead: _GRPCRequestHead
  169. ) -> Result<HPACKHeaders, SendRequestHeadersError> {
  170. return self.state.sendRequestHeaders(requestHead: requestHead)
  171. }
  172. /// Formats a request to send to the server.
  173. ///
  174. /// The client must be streaming in order for this to return successfully. Therefore the valid
  175. /// state transitions are:
  176. /// - `.clientActiveServerIdle` → `.clientActiveServerIdle`
  177. /// - `.clientActiveServerActive` → `.clientActiveServerActive`
  178. ///
  179. /// The client should not attempt to send requests once the request stream is closed, that is
  180. /// from one of the following states:
  181. /// - `.clientClosedServerIdle`
  182. /// - `.clientClosedServerActive`
  183. /// - `.clientClosedServerClosed`
  184. /// Doing so will result in a `.cardinalityViolation`.
  185. ///
  186. /// Sending a message when both peers are idle (in the `.clientIdleServerIdle` state) will result
  187. /// in a `.invalidState` error.
  188. ///
  189. /// - Parameter message: The `Request` to send to the server.
  190. /// - Parameter allocator: A `ByteBufferAllocator` to allocate the buffer into which the encoded
  191. /// request will be written.
  192. mutating func sendRequest(
  193. _ message: Request,
  194. allocator: ByteBufferAllocator
  195. ) -> Result<ByteBuffer, MessageWriteError> {
  196. return self.state.sendRequest(message, allocator: allocator)
  197. }
  198. /// Closes the request stream.
  199. ///
  200. /// The client must be streaming requests in order to terminate the request stream. Valid
  201. /// states transitions are:
  202. /// - `.clientActiveServerIdle` → `.clientClosedServerIdle`
  203. /// - `.clientActiveServerActive` → `.clientClosedServerActive`
  204. ///
  205. /// The client should not attempt to close the request stream if it is already closed, that is
  206. /// from one of the following states:
  207. /// - `.clientClosedServerIdle`
  208. /// - `.clientClosedServerActive`
  209. /// - `.clientClosedServerClosed`
  210. /// Doing so will result in an `.alreadyClosed` error.
  211. ///
  212. /// Closing the request stream when both peers are idle (in the `.clientIdleServerIdle` state)
  213. /// will result in a `.invalidState` error.
  214. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> {
  215. return self.state.sendEndOfRequestStream()
  216. }
  217. /// Receive an acknowledgement of the RPC from the server. This **must not** be a "Trailers-Only"
  218. /// response.
  219. ///
  220. /// The server must be idle in order to receive response headers. The valid state transitions are:
  221. /// - `.clientActiveServerIdle` → `.clientActiveServerActive`
  222. /// - `.clientClosedServerIdle` → `.clientClosedServerActive`
  223. ///
  224. /// The response head will be parsed and validated against the gRPC specification. The following
  225. /// errors may be returned:
  226. /// - `.invalidHTTPStatus` if the status was not "200",
  227. /// - `.invalidContentType` if the "content-type" header does not start with "application/grpc",
  228. /// - `.unsupportedMessageEncoding` if the "grpc-encoding" header is not supported.
  229. ///
  230. /// It is not possible to receive response headers from the following states:
  231. /// - `.clientIdleServerIdle`
  232. /// - `.clientActiveServerActive`
  233. /// - `.clientClosedServerActive`
  234. /// - `.clientClosedServerClosed`
  235. /// Doing so will result in a `.invalidState` error.
  236. ///
  237. /// - Parameter headers: The headers received from the server.
  238. mutating func receiveResponseHeaders(
  239. _ headers: HPACKHeaders
  240. ) -> Result<Void, ReceiveResponseHeadError> {
  241. return self.state.receiveResponseHeaders(headers)
  242. }
  243. /// Read a response buffer from the server and return any decoded messages.
  244. ///
  245. /// If the response stream has an expected count of `.one` then this function is guaranteed to
  246. /// produce *at most* one `Response` in the `Result`.
  247. ///
  248. /// To receive a response buffer the server must be streaming. Valid states are:
  249. /// - `.clientClosedServerActive` → `.clientClosedServerActive`
  250. /// - `.clientActiveServerActive` → `.clientActiveServerActive`
  251. ///
  252. /// This function will read all of the bytes in the `buffer` and attempt to produce as many
  253. /// messages as possible. This may lead to a number of errors:
  254. /// - `.cardinalityViolation` if more than one message is received when the state reader is
  255. /// expects at most one.
  256. /// - `.leftOverBytes` if bytes remain in the buffer after reading one message when at most one
  257. /// message is expected.
  258. /// - `.deserializationFailed` if the message could not be deserialized.
  259. ///
  260. /// It is not possible to receive response headers from the following states:
  261. /// - `.clientIdleServerIdle`
  262. /// - `.clientClosedServerActive`
  263. /// - `.clientActiveServerActive`
  264. /// - `.clientClosedServerClosed`
  265. /// Doing so will result in a `.invalidState` error.
  266. ///
  267. /// - Parameter buffer: A buffer of bytes received from the server.
  268. mutating func receiveResponseBuffer(
  269. _ buffer: inout ByteBuffer
  270. ) -> Result<[Response], MessageReadError> {
  271. return self.state.receiveResponseBuffer(&buffer)
  272. }
  273. /// Receive the end of the response stream from the server and parse the results into
  274. /// a `GRPCStatus`.
  275. ///
  276. /// To close the response stream the server must be streaming or idle (since the server may choose
  277. /// to 'fast fail' the RPC). Valid states are:
  278. /// - `.clientActiveServerIdle` → `.clientClosedServerClosed`
  279. /// - `.clientActiveServerActive` → `.clientClosedServerClosed`
  280. /// - `.clientClosedServerIdle` → `.clientClosedServerClosed`
  281. /// - `.clientClosedServerActive` → `.clientClosedServerClosed`
  282. ///
  283. /// It is not possible to receive an end-of-stream if the RPC has not been initiated or has
  284. /// already been terminated. That is, in one of the following states:
  285. /// - `.clientIdleServerIdle`
  286. /// - `.clientClosedServerClosed`
  287. /// Doing so will result in a `.invalidState` error.
  288. ///
  289. /// - Parameter trailers: The trailers to parse.
  290. mutating func receiveEndOfResponseStream(
  291. _ trailers: HPACKHeaders
  292. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  293. return self.state.receiveEndOfResponseStream(trailers)
  294. }
  295. }
  296. extension GRPCClientStateMachine.State {
  297. /// See `GRPCClientStateMachine.sendRequestHeaders(requestHead:)`.
  298. mutating func sendRequestHeaders(
  299. requestHead: _GRPCRequestHead
  300. ) -> Result<HPACKHeaders, SendRequestHeadersError> {
  301. let result: Result<HPACKHeaders, SendRequestHeadersError>
  302. switch self {
  303. case let .clientIdleServerIdle(pendingWriteState, responseArity):
  304. let headers = self.makeRequestHeaders(
  305. method: requestHead.method,
  306. scheme: requestHead.scheme,
  307. host: requestHead.host,
  308. path: requestHead.path,
  309. timeout: requestHead.timeout,
  310. customMetadata: requestHead.customMetadata
  311. )
  312. result = .success(headers)
  313. self = .clientActiveServerIdle(
  314. writeState: pendingWriteState.makeWriteState(),
  315. readArity: responseArity
  316. )
  317. case .clientActiveServerIdle,
  318. .clientClosedServerIdle,
  319. .clientClosedServerActive,
  320. .clientActiveServerActive,
  321. .clientClosedServerClosed:
  322. result = .failure(.invalidState)
  323. }
  324. return result
  325. }
  326. /// See `GRPCClientStateMachine.sendRequest(_:allocator:)`.
  327. mutating func sendRequest(
  328. _ message: Request,
  329. allocator: ByteBufferAllocator
  330. ) -> Result<ByteBuffer, MessageWriteError> {
  331. let result: Result<ByteBuffer, MessageWriteError>
  332. switch self {
  333. case .clientActiveServerIdle(var writeState, let readArity):
  334. result = writeState.write(message, allocator: allocator)
  335. self = .clientActiveServerIdle(writeState: writeState, readArity: readArity)
  336. case .clientActiveServerActive(var writeState, let readState):
  337. result = writeState.write(message, allocator: allocator)
  338. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  339. case .clientClosedServerIdle,
  340. .clientClosedServerActive,
  341. .clientClosedServerClosed:
  342. result = .failure(.cardinalityViolation)
  343. case .clientIdleServerIdle:
  344. result = .failure(.invalidState)
  345. }
  346. return result
  347. }
  348. /// See `GRPCClientStateMachine.sendEndOfRequestStream()`.
  349. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> {
  350. let result: Result<Void, SendEndOfRequestStreamError>
  351. switch self {
  352. case .clientActiveServerIdle(_, let readArity):
  353. result = .success(())
  354. self = .clientClosedServerIdle(readArity: readArity)
  355. case .clientActiveServerActive(_, let readState):
  356. result = .success(())
  357. self = .clientClosedServerActive(readState: readState)
  358. case .clientClosedServerIdle,
  359. .clientClosedServerActive,
  360. .clientClosedServerClosed:
  361. result = .failure(.alreadyClosed)
  362. case .clientIdleServerIdle:
  363. result = .failure(.invalidState)
  364. }
  365. return result
  366. }
  367. /// See `GRPCClientStateMachine.receiveResponseHeaders(_:)`.
  368. mutating func receiveResponseHeaders(
  369. _ headers: HPACKHeaders
  370. ) -> Result<Void, ReceiveResponseHeadError> {
  371. let result: Result<Void, ReceiveResponseHeadError>
  372. switch self {
  373. case let .clientActiveServerIdle(writeState, readArity):
  374. result = self.parseResponseHeaders(headers, arity: readArity).map { readState in
  375. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  376. }
  377. case let .clientClosedServerIdle(readArity):
  378. result = self.parseResponseHeaders(headers, arity: readArity).map { readState in
  379. self = .clientClosedServerActive(readState: readState)
  380. }
  381. case .clientIdleServerIdle,
  382. .clientClosedServerActive,
  383. .clientActiveServerActive,
  384. .clientClosedServerClosed:
  385. result = .failure(.invalidState)
  386. }
  387. return result
  388. }
  389. /// See `GRPCClientStateMachine.receiveResponseBuffer(_:)`.
  390. mutating func receiveResponseBuffer(
  391. _ buffer: inout ByteBuffer
  392. ) -> Result<[Response], MessageReadError> {
  393. let result: Result<[Response], MessageReadError>
  394. switch self {
  395. case .clientClosedServerActive(var readState):
  396. result = readState.readMessages(&buffer)
  397. self = .clientClosedServerActive(readState: readState)
  398. case .clientActiveServerActive(let writeState, var readState):
  399. result = readState.readMessages(&buffer)
  400. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  401. case .clientIdleServerIdle,
  402. .clientActiveServerIdle,
  403. .clientClosedServerIdle,
  404. .clientClosedServerClosed:
  405. result = .failure(.invalidState)
  406. }
  407. return result
  408. }
  409. /// See `GRPCClientStateMachine.receiveEndOfResponseStream(_:)`.
  410. mutating func receiveEndOfResponseStream(
  411. _ trailers: HPACKHeaders
  412. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  413. let result: Result<GRPCStatus, ReceiveEndOfResponseStreamError>
  414. switch self {
  415. case .clientActiveServerIdle,
  416. .clientClosedServerIdle:
  417. result = self.parseTrailersOnly(trailers).map { status in
  418. self = .clientClosedServerClosed
  419. return status
  420. }
  421. case .clientActiveServerActive,
  422. .clientClosedServerActive:
  423. result = .success(self.parseTrailers(trailers))
  424. self = .clientClosedServerClosed
  425. case .clientIdleServerIdle,
  426. .clientClosedServerClosed:
  427. result = .failure(.invalidState)
  428. }
  429. return result
  430. }
  431. /// Makes the request headers (`Request-Headers` in the specification) used to initiate an RPC
  432. /// call.
  433. ///
  434. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  435. ///
  436. /// - Parameter host: The host serving the RPC.
  437. /// - Parameter options: Any options related to the call.
  438. /// - Parameter requestID: A request ID associated with the call. An additional header will be
  439. /// added using this value if `options.requestIDHeader` is specified.
  440. private func makeRequestHeaders(
  441. method: String,
  442. scheme: String,
  443. host: String,
  444. path: String,
  445. timeout: GRPCTimeout,
  446. customMetadata: HPACKHeaders
  447. ) -> HPACKHeaders {
  448. // Note: we don't currently set the 'grpc-encoding' header, if we do we will need to feed that
  449. // encoded into the message writer.
  450. var headers: HPACKHeaders = [
  451. ":method": method,
  452. ":path": path,
  453. ":authority": host,
  454. ":scheme": scheme,
  455. "content-type": "application/grpc",
  456. "te": "trailers", // Used to detect incompatible proxies, part of the gRPC specification.
  457. "user-agent": "grpc-swift-nio", // TODO: Add a more specific user-agent.
  458. ]
  459. // Add the timeout header, if a timeout was specified.
  460. if timeout != .infinite {
  461. headers.add(name: GRPCHeaderName.timeout, value: String(describing: timeout))
  462. }
  463. // Add user-defined custom metadata: this should come after the call definition headers.
  464. headers.add(contentsOf: customMetadata)
  465. return headers
  466. }
  467. /// Parses the response headers ("Response-Headers" in the specification) from the server into
  468. /// a `ReadState`.
  469. ///
  470. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  471. ///
  472. /// - Parameter headers: The headers to parse.
  473. private func parseResponseHeaders(
  474. _ headers: HPACKHeaders,
  475. arity: MessageArity
  476. ) -> Result<ReadState, ReceiveResponseHeadError> {
  477. // From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  478. //
  479. // "Implementations should expect broken deployments to send non-200 HTTP status codes in
  480. // responses as well as a variety of non-GRPC content-types and to omit Status & Status-Message.
  481. // Implementations must synthesize a Status & Status-Message to propagate to the application
  482. // layer when this occurs."
  483. let responseStatus = headers.first(name: ":status")
  484. .flatMap(Int.init)
  485. .map { code in
  486. HTTPResponseStatus(statusCode: code)
  487. } ?? .preconditionFailed
  488. guard responseStatus == .ok else {
  489. return .failure(.invalidHTTPStatus(responseStatus))
  490. }
  491. guard headers.first(name: "content-type").flatMap(ContentType.init) != nil else {
  492. return .failure(.invalidContentType)
  493. }
  494. // What compression mechanism is the server using, if any?
  495. let compression = CompressionMechanism(value: headers.first(name: GRPCHeaderName.encoding))
  496. // From: https://github.com/grpc/grpc/blob/master/doc/compression.md
  497. //
  498. // "If a server sent data which is compressed by an algorithm that is not supported by the
  499. // client, an INTERNAL error status will occur on the client side."
  500. guard compression.supported else {
  501. return .failure(.unsupportedMessageEncoding(compression.rawValue))
  502. }
  503. let reader = LengthPrefixedMessageReader(mode: .client, compressionMechanism: compression)
  504. return .success(.reading(arity, reader))
  505. }
  506. /// Parses the response trailers ("Trailers" in the specification) from the server into
  507. /// a `GRPCStatus`.
  508. ///
  509. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  510. ///
  511. /// - Parameter trailers: Trailers to parse.
  512. private func parseTrailers(_ trailers: HPACKHeaders) -> GRPCStatus {
  513. // Extract the "Status" and "Status-Message"
  514. let code = self.readStatusCode(from: trailers) ?? .unknown
  515. let message = self.readStatusMessage(from: trailers)
  516. return .init(code: code, message: message)
  517. }
  518. private func readStatusCode(from trailers: HPACKHeaders) -> GRPCStatus.Code? {
  519. return trailers.first(name: GRPCHeaderName.statusCode)
  520. .flatMap(Int.init)
  521. .flatMap(GRPCStatus.Code.init)
  522. }
  523. private func readStatusMessage(from trailers: HPACKHeaders) -> String? {
  524. return trailers.first(name: GRPCHeaderName.statusMessage)
  525. .map(GRPCStatusMessageMarshaller.unmarshall)
  526. }
  527. /// Parses a "Trailers-Only" response from the server into a `GRPCStatus`.
  528. ///
  529. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  530. ///
  531. /// - Parameter trailers: Trailers to parse.
  532. private func parseTrailersOnly(
  533. _ trailers: HPACKHeaders
  534. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  535. // We need to check whether we have a valid HTTP status in the headers, if we don't then we also
  536. // need to check whether we have a gRPC status as it should take preference over a synthesising
  537. // one from the ":status".
  538. //
  539. // See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
  540. guard let status = trailers.first(name: ":status").flatMap(Int.init).map({ HTTPResponseStatus(statusCode: $0) }) else {
  541. return .failure(.invalidHTTPStatus(nil))
  542. }
  543. guard status == .ok else {
  544. if let code = self.readStatusCode(from: trailers) {
  545. let message = self.readStatusMessage(from: trailers)
  546. return .failure(.invalidHTTPStatusWithGRPCStatus(.init(code: code, message: message)))
  547. } else {
  548. return .failure(.invalidHTTPStatus(status))
  549. }
  550. }
  551. guard trailers.first(name: "content-type").flatMap(ContentType.init) != nil else {
  552. return .failure(.invalidContentType)
  553. }
  554. // We've verified the status and content type are okay: parse the trailers.
  555. return .success(self.parseTrailers(trailers))
  556. }
  557. }