GRPCClientStateMachine.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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 Logging
  18. import NIOCore
  19. import NIOHPACK
  20. import NIOHTTP1
  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(String?)
  25. /// The HTTP response status from the server was not 200 OK.
  26. case invalidHTTPStatus(String?)
  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, Equatable {
  33. /// The 'content-type' header was missing or the value is not supported by this implementation.
  34. case invalidContentType(String?)
  35. /// The HTTP response status from the server was not 200 OK.
  36. case invalidHTTPStatus(String?)
  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 {
  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, pendingReadState: PendingReadState)
  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(pendingReadState: PendingReadState)
  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. /// This isn't a real state. See `withStateAvoidingCoWs`.
  112. case modifying
  113. }
  114. /// The current state of the state machine.
  115. internal private(set) var state: State
  116. /// The default user-agent string.
  117. private static let userAgent = "grpc-swift-nio/\(Version.versionString)"
  118. /// Creates a state machine representing a gRPC client's request and response stream state.
  119. ///
  120. /// - Parameter requestArity: The expected number of messages on the request stream.
  121. /// - Parameter responseArity: The expected number of messages on the response stream.
  122. init(requestArity: MessageArity, responseArity: MessageArity) {
  123. self.state = .clientIdleServerIdle(
  124. pendingWriteState: .init(arity: requestArity, contentType: .protobuf),
  125. readArity: responseArity
  126. )
  127. }
  128. /// Creates a state machine representing a gRPC client's request and response stream state.
  129. ///
  130. /// - Parameter state: The initial state of the state machine.
  131. init(state: State) {
  132. self.state = state
  133. }
  134. /// Initiates an RPC.
  135. ///
  136. /// The only valid state transition is:
  137. /// - `.clientIdleServerIdle` → `.clientActiveServerIdle`
  138. ///
  139. /// All other states will result in an `.invalidState` error.
  140. ///
  141. /// On success the state will transition to `.clientActiveServerIdle`.
  142. ///
  143. /// - Parameter requestHead: The client request head for the RPC.
  144. mutating func sendRequestHeaders(
  145. requestHead: _GRPCRequestHead,
  146. allocator: ByteBufferAllocator
  147. ) -> Result<HPACKHeaders, SendRequestHeadersError> {
  148. return self.withStateAvoidingCoWs { state in
  149. state.sendRequestHeaders(requestHead: requestHead, allocator: allocator)
  150. }
  151. }
  152. /// Formats a request to send to the server.
  153. ///
  154. /// The client must be streaming in order for this to return successfully. Therefore the valid
  155. /// state transitions are:
  156. /// - `.clientActiveServerIdle` → `.clientActiveServerIdle`
  157. /// - `.clientActiveServerActive` → `.clientActiveServerActive`
  158. ///
  159. /// The client should not attempt to send requests once the request stream is closed, that is
  160. /// from one of the following states:
  161. /// - `.clientClosedServerIdle`
  162. /// - `.clientClosedServerActive`
  163. /// - `.clientClosedServerClosed`
  164. /// Doing so will result in a `.cardinalityViolation`.
  165. ///
  166. /// Sending a message when both peers are idle (in the `.clientIdleServerIdle` state) will result
  167. /// in a `.invalidState` error.
  168. ///
  169. /// - Parameter message: The serialized request to send to the server.
  170. /// - Parameter compressed: Whether the request should be compressed.
  171. /// - Parameter allocator: A `ByteBufferAllocator` to allocate the buffer into which the encoded
  172. /// request will be written.
  173. mutating func sendRequest(
  174. _ message: ByteBuffer,
  175. compressed: Bool
  176. ) -> Result<(ByteBuffer, ByteBuffer?), MessageWriteError> {
  177. return self.withStateAvoidingCoWs { state in
  178. state.sendRequest(message, compressed: compressed)
  179. }
  180. }
  181. /// Closes the request stream.
  182. ///
  183. /// The client must be streaming requests in order to terminate the request stream. Valid
  184. /// states transitions are:
  185. /// - `.clientActiveServerIdle` → `.clientClosedServerIdle`
  186. /// - `.clientActiveServerActive` → `.clientClosedServerActive`
  187. ///
  188. /// The client should not attempt to close the request stream if it is already closed, that is
  189. /// from one of the following states:
  190. /// - `.clientClosedServerIdle`
  191. /// - `.clientClosedServerActive`
  192. /// - `.clientClosedServerClosed`
  193. /// Doing so will result in an `.alreadyClosed` error.
  194. ///
  195. /// Closing the request stream when both peers are idle (in the `.clientIdleServerIdle` state)
  196. /// will result in a `.invalidState` error.
  197. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> {
  198. return self.withStateAvoidingCoWs { state in
  199. state.sendEndOfRequestStream()
  200. }
  201. }
  202. /// Receive an acknowledgement of the RPC from the server. This **must not** be a "Trailers-Only"
  203. /// response.
  204. ///
  205. /// The server must be idle in order to receive response headers. The valid state transitions are:
  206. /// - `.clientActiveServerIdle` → `.clientActiveServerActive`
  207. /// - `.clientClosedServerIdle` → `.clientClosedServerActive`
  208. ///
  209. /// The response head will be parsed and validated against the gRPC specification. The following
  210. /// errors may be returned:
  211. /// - `.invalidHTTPStatus` if the status was not "200",
  212. /// - `.invalidContentType` if the "content-type" header does not start with "application/grpc",
  213. /// - `.unsupportedMessageEncoding` if the "grpc-encoding" header is not supported.
  214. ///
  215. /// It is not possible to receive response headers from the following states:
  216. /// - `.clientIdleServerIdle`
  217. /// - `.clientActiveServerActive`
  218. /// - `.clientClosedServerActive`
  219. /// - `.clientClosedServerClosed`
  220. /// Doing so will result in a `.invalidState` error.
  221. ///
  222. /// - Parameter headers: The headers received from the server.
  223. mutating func receiveResponseHeaders(
  224. _ headers: HPACKHeaders
  225. ) -> Result<Void, ReceiveResponseHeadError> {
  226. return self.withStateAvoidingCoWs { state in
  227. state.receiveResponseHeaders(headers)
  228. }
  229. }
  230. /// Read a response buffer from the server and return any decoded messages.
  231. ///
  232. /// If the response stream has an expected count of `.one` then this function is guaranteed to
  233. /// produce *at most* one `Response` in the `Result`.
  234. ///
  235. /// To receive a response buffer the server must be streaming. Valid states are:
  236. /// - `.clientClosedServerActive` → `.clientClosedServerActive`
  237. /// - `.clientActiveServerActive` → `.clientActiveServerActive`
  238. ///
  239. /// This function will read all of the bytes in the `buffer` and attempt to produce as many
  240. /// messages as possible. This may lead to a number of errors:
  241. /// - `.cardinalityViolation` if more than one message is received when the state reader is
  242. /// expects at most one.
  243. /// - `.leftOverBytes` if bytes remain in the buffer after reading one message when at most one
  244. /// message is expected.
  245. /// - `.deserializationFailed` if the message could not be deserialized.
  246. ///
  247. /// It is not possible to receive response headers from the following states:
  248. /// - `.clientIdleServerIdle`
  249. /// - `.clientClosedServerActive`
  250. /// - `.clientActiveServerActive`
  251. /// - `.clientClosedServerClosed`
  252. /// Doing so will result in a `.invalidState` error.
  253. ///
  254. /// - Parameter buffer: A buffer of bytes received from the server.
  255. mutating func receiveResponseBuffer(
  256. _ buffer: inout ByteBuffer,
  257. maxMessageLength: Int
  258. ) -> Result<[ByteBuffer], MessageReadError> {
  259. return self.withStateAvoidingCoWs { state in
  260. state.receiveResponseBuffer(&buffer, maxMessageLength: maxMessageLength)
  261. }
  262. }
  263. /// Receive the end of the response stream from the server and parse the results into
  264. /// a `GRPCStatus`.
  265. ///
  266. /// To close the response stream the server must be streaming or idle (since the server may choose
  267. /// to 'fast fail' the RPC). Valid states are:
  268. /// - `.clientActiveServerIdle` → `.clientClosedServerClosed`
  269. /// - `.clientActiveServerActive` → `.clientClosedServerClosed`
  270. /// - `.clientClosedServerIdle` → `.clientClosedServerClosed`
  271. /// - `.clientClosedServerActive` → `.clientClosedServerClosed`
  272. ///
  273. /// It is not possible to receive an end-of-stream if the RPC has not been initiated or has
  274. /// already been terminated. That is, in one of the following states:
  275. /// - `.clientIdleServerIdle`
  276. /// - `.clientClosedServerClosed`
  277. /// Doing so will result in a `.invalidState` error.
  278. ///
  279. /// - Parameter trailers: The trailers to parse.
  280. mutating func receiveEndOfResponseStream(
  281. _ trailers: HPACKHeaders
  282. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  283. return self.withStateAvoidingCoWs { state in
  284. state.receiveEndOfResponseStream(trailers)
  285. }
  286. }
  287. /// Receive a DATA frame with the end stream flag set. Determines whether it is safe for the
  288. /// caller to ignore the end stream flag or whether a synthesised status should be forwarded.
  289. ///
  290. /// Receiving a DATA frame with the end stream flag set is unexpected: the specification dictates
  291. /// that an RPC should be ended by the server sending the client a HEADERS frame with end stream
  292. /// set. However, we will tolerate end stream on a DATA frame if we believe the RPC has already
  293. /// completed (i.e. we are in the 'clientClosedServerClosed' state). In cases where we don't
  294. /// expect end of stream on a DATA frame we will emit a status with a message explaining
  295. /// the protocol violation.
  296. mutating func receiveEndOfResponseStream() -> GRPCStatus? {
  297. return self.withStateAvoidingCoWs { state in
  298. state.receiveEndOfResponseStream()
  299. }
  300. }
  301. /// Temporarily sets `self.state` to `.modifying` before calling the provided block and setting
  302. /// `self.state` to the `State` modified by the block.
  303. ///
  304. /// Since we hold state as associated data on our `State` enum, any modification to that state
  305. /// will trigger a copy on write for its heap allocated data. Temporarily setting the `self.state`
  306. /// to `.modifying` allows us to avoid an extra reference to any heap allocated data and therefore
  307. /// avoid a copy on write.
  308. @inline(__always)
  309. private mutating func withStateAvoidingCoWs<ResultType>(
  310. _ body: (inout State) -> ResultType
  311. ) -> ResultType {
  312. var state = State.modifying
  313. swap(&self.state, &state)
  314. defer {
  315. swap(&self.state, &state)
  316. }
  317. return body(&state)
  318. }
  319. }
  320. extension GRPCClientStateMachine.State {
  321. /// See `GRPCClientStateMachine.sendRequestHeaders(requestHead:)`.
  322. mutating func sendRequestHeaders(
  323. requestHead: _GRPCRequestHead,
  324. allocator: ByteBufferAllocator
  325. ) -> Result<HPACKHeaders, SendRequestHeadersError> {
  326. let result: Result<HPACKHeaders, SendRequestHeadersError>
  327. switch self {
  328. case let .clientIdleServerIdle(pendingWriteState, responseArity):
  329. let headers = self.makeRequestHeaders(
  330. method: requestHead.method,
  331. scheme: requestHead.scheme,
  332. host: requestHead.host,
  333. path: requestHead.path,
  334. timeout: GRPCTimeout(deadline: requestHead.deadline),
  335. customMetadata: requestHead.customMetadata,
  336. compression: requestHead.encoding
  337. )
  338. result = .success(headers)
  339. self = .clientActiveServerIdle(
  340. writeState: pendingWriteState.makeWriteState(
  341. messageEncoding: requestHead.encoding,
  342. allocator: allocator
  343. ),
  344. pendingReadState: .init(arity: responseArity, messageEncoding: requestHead.encoding)
  345. )
  346. case .clientActiveServerIdle,
  347. .clientClosedServerIdle,
  348. .clientClosedServerActive,
  349. .clientActiveServerActive,
  350. .clientClosedServerClosed:
  351. result = .failure(.invalidState)
  352. case .modifying:
  353. preconditionFailure("State left as 'modifying'")
  354. }
  355. return result
  356. }
  357. /// See `GRPCClientStateMachine.sendRequest(_:allocator:)`.
  358. mutating func sendRequest(
  359. _ message: ByteBuffer,
  360. compressed: Bool
  361. ) -> Result<(ByteBuffer, ByteBuffer?), MessageWriteError> {
  362. let result: Result<(ByteBuffer, ByteBuffer?), MessageWriteError>
  363. switch self {
  364. case .clientActiveServerIdle(var writeState, let pendingReadState):
  365. result = writeState.write(message, compressed: compressed)
  366. self = .clientActiveServerIdle(writeState: writeState, pendingReadState: pendingReadState)
  367. case .clientActiveServerActive(var writeState, let readState):
  368. result = writeState.write(message, compressed: compressed)
  369. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  370. case .clientClosedServerIdle,
  371. .clientClosedServerActive,
  372. .clientClosedServerClosed:
  373. result = .failure(.cardinalityViolation)
  374. case .clientIdleServerIdle:
  375. result = .failure(.invalidState)
  376. case .modifying:
  377. preconditionFailure("State left as 'modifying'")
  378. }
  379. return result
  380. }
  381. /// See `GRPCClientStateMachine.sendEndOfRequestStream()`.
  382. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> {
  383. let result: Result<Void, SendEndOfRequestStreamError>
  384. switch self {
  385. case let .clientActiveServerIdle(_, pendingReadState):
  386. result = .success(())
  387. self = .clientClosedServerIdle(pendingReadState: pendingReadState)
  388. case let .clientActiveServerActive(_, readState):
  389. result = .success(())
  390. self = .clientClosedServerActive(readState: readState)
  391. case .clientClosedServerIdle,
  392. .clientClosedServerActive,
  393. .clientClosedServerClosed:
  394. result = .failure(.alreadyClosed)
  395. case .clientIdleServerIdle:
  396. result = .failure(.invalidState)
  397. case .modifying:
  398. preconditionFailure("State left as 'modifying'")
  399. }
  400. return result
  401. }
  402. /// See `GRPCClientStateMachine.receiveResponseHeaders(_:)`.
  403. mutating func receiveResponseHeaders(
  404. _ headers: HPACKHeaders
  405. ) -> Result<Void, ReceiveResponseHeadError> {
  406. let result: Result<Void, ReceiveResponseHeadError>
  407. switch self {
  408. case let .clientActiveServerIdle(writeState, pendingReadState):
  409. result = self.parseResponseHeaders(headers, pendingReadState: pendingReadState)
  410. .map { readState in
  411. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  412. }
  413. case let .clientClosedServerIdle(pendingReadState):
  414. result = self.parseResponseHeaders(headers, pendingReadState: pendingReadState)
  415. .map { readState in
  416. self = .clientClosedServerActive(readState: readState)
  417. }
  418. case .clientIdleServerIdle,
  419. .clientClosedServerActive,
  420. .clientActiveServerActive,
  421. .clientClosedServerClosed:
  422. result = .failure(.invalidState)
  423. case .modifying:
  424. preconditionFailure("State left as 'modifying'")
  425. }
  426. return result
  427. }
  428. /// See `GRPCClientStateMachine.receiveResponseBuffer(_:)`.
  429. mutating func receiveResponseBuffer(
  430. _ buffer: inout ByteBuffer,
  431. maxMessageLength: Int
  432. ) -> Result<[ByteBuffer], MessageReadError> {
  433. let result: Result<[ByteBuffer], MessageReadError>
  434. switch self {
  435. case var .clientClosedServerActive(readState):
  436. result = readState.readMessages(&buffer, maxLength: maxMessageLength)
  437. self = .clientClosedServerActive(readState: readState)
  438. case .clientActiveServerActive(let writeState, var readState):
  439. result = readState.readMessages(&buffer, maxLength: maxMessageLength)
  440. self = .clientActiveServerActive(writeState: writeState, readState: readState)
  441. case .clientIdleServerIdle,
  442. .clientActiveServerIdle,
  443. .clientClosedServerIdle,
  444. .clientClosedServerClosed:
  445. result = .failure(.invalidState)
  446. case .modifying:
  447. preconditionFailure("State left as 'modifying'")
  448. }
  449. return result
  450. }
  451. /// See `GRPCClientStateMachine.receiveEndOfResponseStream(_:)`.
  452. mutating func receiveEndOfResponseStream(
  453. _ trailers: HPACKHeaders
  454. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  455. let result: Result<GRPCStatus, ReceiveEndOfResponseStreamError>
  456. switch self {
  457. case .clientActiveServerIdle,
  458. .clientClosedServerIdle:
  459. result = self.parseTrailersOnly(trailers).map { status in
  460. self = .clientClosedServerClosed
  461. return status
  462. }
  463. case .clientActiveServerActive,
  464. .clientClosedServerActive:
  465. result = .success(self.parseTrailers(trailers))
  466. self = .clientClosedServerClosed
  467. case .clientIdleServerIdle,
  468. .clientClosedServerClosed:
  469. result = .failure(.invalidState)
  470. case .modifying:
  471. preconditionFailure("State left as 'modifying'")
  472. }
  473. return result
  474. }
  475. /// See `GRPCClientStateMachine.receiveEndOfResponseStream()`.
  476. mutating func receiveEndOfResponseStream() -> GRPCStatus? {
  477. let status: GRPCStatus?
  478. switch self {
  479. case .clientIdleServerIdle:
  480. // Can't see end stream before writing on it.
  481. preconditionFailure()
  482. case .clientActiveServerIdle,
  483. .clientActiveServerActive,
  484. .clientClosedServerIdle,
  485. .clientClosedServerActive:
  486. self = .clientClosedServerClosed
  487. status = .init(
  488. code: .internalError,
  489. message: "Protocol violation: received DATA frame with end stream set"
  490. )
  491. case .clientClosedServerClosed:
  492. // We've already closed. Ignore this.
  493. status = nil
  494. case .modifying:
  495. preconditionFailure("State left as 'modifying'")
  496. }
  497. return status
  498. }
  499. /// Makes the request headers (`Request-Headers` in the specification) used to initiate an RPC
  500. /// call.
  501. ///
  502. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  503. ///
  504. /// - Parameter host: The host serving the RPC.
  505. /// - Parameter options: Any options related to the call.
  506. /// - Parameter requestID: A request ID associated with the call. An additional header will be
  507. /// added using this value if `options.requestIDHeader` is specified.
  508. private func makeRequestHeaders(
  509. method: String,
  510. scheme: String,
  511. host: String,
  512. path: String,
  513. timeout: GRPCTimeout,
  514. customMetadata: HPACKHeaders,
  515. compression: ClientMessageEncoding
  516. ) -> HPACKHeaders {
  517. var headers = HPACKHeaders()
  518. // The 10 is:
  519. // - 6 which are required and added just below, and
  520. // - 4 which are possibly added, depending on conditions.
  521. headers.reserveCapacity(10 + customMetadata.count)
  522. // Add the required headers.
  523. headers.add(name: ":method", value: method)
  524. headers.add(name: ":path", value: path)
  525. headers.add(name: ":authority", value: host)
  526. headers.add(name: ":scheme", value: scheme)
  527. headers.add(name: "content-type", value: "application/grpc")
  528. // Used to detect incompatible proxies, part of the gRPC specification.
  529. headers.add(name: "te", value: "trailers")
  530. switch compression {
  531. case let .enabled(configuration):
  532. // Request encoding.
  533. if let outbound = configuration.outbound {
  534. headers.add(name: GRPCHeaderName.encoding, value: outbound.name)
  535. }
  536. // Response encoding.
  537. if !configuration.inbound.isEmpty {
  538. headers.add(name: GRPCHeaderName.acceptEncoding, value: configuration.acceptEncodingHeader)
  539. }
  540. case .disabled:
  541. ()
  542. }
  543. // Add the timeout header, if a timeout was specified.
  544. if timeout != .infinite {
  545. headers.add(name: GRPCHeaderName.timeout, value: String(describing: timeout))
  546. }
  547. // Add user-defined custom metadata: this should come after the call definition headers.
  548. // TODO: make header normalization user-configurable.
  549. headers.add(contentsOf: customMetadata.lazy.map { name, value, indexing in
  550. (name.lowercased(), value, indexing)
  551. })
  552. // Add default user-agent value, if `customMetadata` didn't contain user-agent
  553. if !customMetadata.contains(name: "user-agent") {
  554. headers.add(name: "user-agent", value: GRPCClientStateMachine.userAgent)
  555. }
  556. return headers
  557. }
  558. /// Parses the response headers ("Response-Headers" in the specification) from the server into
  559. /// a `ReadState`.
  560. ///
  561. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  562. ///
  563. /// - Parameter headers: The headers to parse.
  564. private func parseResponseHeaders(
  565. _ headers: HPACKHeaders,
  566. pendingReadState: PendingReadState
  567. ) -> Result<ReadState, ReceiveResponseHeadError> {
  568. // From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  569. //
  570. // "Implementations should expect broken deployments to send non-200 HTTP status codes in
  571. // responses as well as a variety of non-GRPC content-types and to omit Status & Status-Message.
  572. // Implementations must synthesize a Status & Status-Message to propagate to the application
  573. // layer when this occurs."
  574. let statusHeader = headers.first(name: ":status")
  575. let responseStatus = statusHeader
  576. .flatMap(Int.init)
  577. .map { code in
  578. HTTPResponseStatus(statusCode: code)
  579. } ?? .preconditionFailed
  580. guard responseStatus == .ok else {
  581. return .failure(.invalidHTTPStatus(statusHeader))
  582. }
  583. let contentTypeHeader = headers.first(name: "content-type")
  584. guard contentTypeHeader.flatMap(ContentType.init) != nil else {
  585. return .failure(.invalidContentType(contentTypeHeader))
  586. }
  587. let result: Result<ReadState, ReceiveResponseHeadError>
  588. // What compression mechanism is the server using, if any?
  589. if let encodingHeader = headers.first(name: GRPCHeaderName.encoding) {
  590. // Note: the server is allowed to encode messages using an algorithm which wasn't included in
  591. // the 'grpc-accept-encoding' header. If the client still supports that algorithm (despite not
  592. // permitting the server to use it) then it must still decode that message. Ideally we should
  593. // log a message here if that was the case but we don't hold that information.
  594. if let compression = CompressionAlgorithm(rawValue: encodingHeader) {
  595. result = .success(pendingReadState.makeReadState(compression: compression))
  596. } else {
  597. // The algorithm isn't one we support.
  598. result = .failure(.unsupportedMessageEncoding(encodingHeader))
  599. }
  600. } else {
  601. // No compression was specified, this is fine.
  602. result = .success(pendingReadState.makeReadState(compression: nil))
  603. }
  604. return result
  605. }
  606. /// Parses the response trailers ("Trailers" in the specification) from the server into
  607. /// a `GRPCStatus`.
  608. ///
  609. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  610. ///
  611. /// - Parameter trailers: Trailers to parse.
  612. private func parseTrailers(_ trailers: HPACKHeaders) -> GRPCStatus {
  613. // Extract the "Status" and "Status-Message"
  614. let code = self.readStatusCode(from: trailers) ?? .unknown
  615. let message = self.readStatusMessage(from: trailers)
  616. return .init(code: code, message: message)
  617. }
  618. private func readStatusCode(from trailers: HPACKHeaders) -> GRPCStatus.Code? {
  619. return trailers.first(name: GRPCHeaderName.statusCode)
  620. .flatMap(Int.init)
  621. .flatMap(GRPCStatus.Code.init)
  622. }
  623. private func readStatusMessage(from trailers: HPACKHeaders) -> String? {
  624. return trailers.first(name: GRPCHeaderName.statusMessage)
  625. .map(GRPCStatusMessageMarshaller.unmarshall)
  626. }
  627. /// Parses a "Trailers-Only" response from the server into a `GRPCStatus`.
  628. ///
  629. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  630. ///
  631. /// - Parameter trailers: Trailers to parse.
  632. private func parseTrailersOnly(
  633. _ trailers: HPACKHeaders
  634. ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> {
  635. // We need to check whether we have a valid HTTP status in the headers, if we don't then we also
  636. // need to check whether we have a gRPC status as it should take preference over a synthesising
  637. // one from the ":status".
  638. //
  639. // See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
  640. let statusHeader = trailers.first(name: ":status")
  641. guard let status = statusHeader.flatMap(Int.init).map({ HTTPResponseStatus(statusCode: $0) })
  642. else {
  643. return .failure(.invalidHTTPStatus(statusHeader))
  644. }
  645. guard status == .ok else {
  646. if let code = self.readStatusCode(from: trailers) {
  647. let message = self.readStatusMessage(from: trailers)
  648. return .failure(.invalidHTTPStatusWithGRPCStatus(.init(code: code, message: message)))
  649. } else {
  650. return .failure(.invalidHTTPStatus(statusHeader))
  651. }
  652. }
  653. // Only validate the content-type header if it's present. This is a small deviation from the
  654. // spec as the content-type is meant to be sent in "Trailers-Only" responses. However, if it's
  655. // missing then we should avoid the error and propagate the status code and message sent by
  656. // the server instead.
  657. if let contentTypeHeader = trailers.first(name: "content-type"),
  658. ContentType(value: contentTypeHeader) == nil {
  659. return .failure(.invalidContentType(contentTypeHeader))
  660. }
  661. // We've verified the status and content type are okay: parse the trailers.
  662. return .success(self.parseTrailers(trailers))
  663. }
  664. }