GRPCClientStateMachine.swift 31 KB

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