HTTP2ToRawGRPCStateMachine.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /*
  2. * Copyright 2020, 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 Logging
  17. import NIO
  18. import NIOHPACK
  19. import NIOHTTP2
  20. struct HTTP2ToRawGRPCStateMachine {
  21. /// The current state.
  22. private var state: State
  23. /// Temporarily sets `self.state` to `._modifying` before calling the provided block and setting
  24. /// `self.state` to the `State` modified by the block.
  25. ///
  26. /// Since we hold state as associated data on our `State` enum, any modification to that state
  27. /// will trigger a copy on write for its heap allocated data. Temporarily setting the `self.state`
  28. /// to `._modifying` allows us to avoid an extra reference to any heap allocated data and
  29. /// therefore avoid a copy on write.
  30. private mutating func withStateAvoidingCoWs(_ body: (inout State) -> Action) -> Action {
  31. var state: State = ._modifying
  32. swap(&self.state, &state)
  33. defer {
  34. swap(&self.state, &state)
  35. }
  36. return body(&state)
  37. }
  38. internal init(
  39. services: [Substring: CallHandlerProvider],
  40. encoding: ServerMessageEncoding,
  41. normalizeHeaders: Bool = true
  42. ) {
  43. let state = RequestIdleResponseIdleState(
  44. services: services,
  45. encoding: encoding,
  46. normalizeHeaders: normalizeHeaders
  47. )
  48. self.state = .requestIdleResponseIdle(state)
  49. }
  50. }
  51. extension HTTP2ToRawGRPCStateMachine {
  52. enum State {
  53. // Both peers are idle. Nothing has happened to the stream.
  54. case requestIdleResponseIdle(RequestIdleResponseIdleState)
  55. // Received valid headers. Nothing has been sent in response.
  56. case requestOpenResponseIdle(RequestOpenResponseIdleState)
  57. // Received valid headers and request(s). Response headers have been sent.
  58. case requestOpenResponseOpen(RequestOpenResponseOpenState)
  59. // The request stream is closed. Nothing has been sent in response.
  60. case requestClosedResponseIdle(RequestClosedResponseIdleState)
  61. // The request stream is closed. Response headers have been sent.
  62. case requestClosedResponseOpen(RequestClosedResponseOpenState)
  63. // Both streams are closed. This state is terminal.
  64. case requestClosedResponseClosed
  65. // Not a real state. See 'withStateAvoidingCoWs'.
  66. case _modifying
  67. }
  68. struct RequestIdleResponseIdleState {
  69. /// The service providers, keyed by service name.
  70. var services: [Substring: CallHandlerProvider]
  71. /// The encoding configuration for this server.
  72. var encoding: ServerMessageEncoding
  73. /// Whether to normalize user-provided metadata.
  74. var normalizeHeaders: Bool
  75. }
  76. struct RequestOpenResponseIdleState {
  77. /// A length prefixed message reader for request messages.
  78. var reader: LengthPrefixedMessageReader
  79. /// A length prefixed message writer for response messages.
  80. var writer: LengthPrefixedMessageWriter
  81. /// The content type of the RPC.
  82. var contentType: ContentType
  83. /// An accept encoding header to send in the response headers indicating the message encoding
  84. /// that the server supports.
  85. var acceptEncoding: String?
  86. /// A message encoding header to send in the response headers indicating the encoding which will
  87. /// be used for responses.
  88. var responseEncoding: String?
  89. /// Whether to normalize user-provided metadata.
  90. var normalizeHeaders: Bool
  91. /// The pipeline configuration state.
  92. var configurationState: ConfigurationState
  93. }
  94. struct RequestClosedResponseIdleState {
  95. /// A length prefixed message reader for request messages.
  96. var reader: LengthPrefixedMessageReader
  97. /// A length prefixed message writer for response messages.
  98. var writer: LengthPrefixedMessageWriter
  99. /// The content type of the RPC.
  100. var contentType: ContentType
  101. /// An accept encoding header to send in the response headers indicating the message encoding
  102. /// that the server supports.
  103. var acceptEncoding: String?
  104. /// A message encoding header to send in the response headers indicating the encoding which will
  105. /// be used for responses.
  106. var responseEncoding: String?
  107. /// Whether to normalize user-provided metadata.
  108. var normalizeHeaders: Bool
  109. /// The pipeline configuration state.
  110. var configurationState: ConfigurationState
  111. init(from state: RequestOpenResponseIdleState) {
  112. self.reader = state.reader
  113. self.writer = state.writer
  114. self.contentType = state.contentType
  115. self.acceptEncoding = state.acceptEncoding
  116. self.responseEncoding = state.responseEncoding
  117. self.normalizeHeaders = state.normalizeHeaders
  118. self.configurationState = state.configurationState
  119. }
  120. }
  121. struct RequestOpenResponseOpenState {
  122. /// A length prefixed message reader for request messages.
  123. var reader: LengthPrefixedMessageReader
  124. /// A length prefixed message writer for response messages.
  125. var writer: LengthPrefixedMessageWriter
  126. /// Whether to normalize user-provided metadata.
  127. var normalizeHeaders: Bool
  128. init(from state: RequestOpenResponseIdleState) {
  129. self.reader = state.reader
  130. self.writer = state.writer
  131. self.normalizeHeaders = state.normalizeHeaders
  132. }
  133. }
  134. struct RequestClosedResponseOpenState {
  135. /// A length prefixed message reader for request messages.
  136. var reader: LengthPrefixedMessageReader
  137. /// A length prefixed message writer for response messages.
  138. var writer: LengthPrefixedMessageWriter
  139. /// Whether to normalize user-provided metadata.
  140. var normalizeHeaders: Bool
  141. init(from state: RequestOpenResponseOpenState) {
  142. self.reader = state.reader
  143. self.writer = state.writer
  144. self.normalizeHeaders = state.normalizeHeaders
  145. }
  146. init(from state: RequestClosedResponseIdleState) {
  147. self.reader = state.reader
  148. self.writer = state.writer
  149. self.normalizeHeaders = state.normalizeHeaders
  150. }
  151. }
  152. /// The pipeline configuration state.
  153. enum ConfigurationState {
  154. /// The pipeline is being configured. Any message data will be buffered into an appropriate
  155. /// message reader.
  156. case configuring(HPACKHeaders)
  157. /// The pipeline is configured.
  158. case configured
  159. /// Returns true if the configuration is in the `.configured` state.
  160. var isConfigured: Bool {
  161. switch self {
  162. case .configuring:
  163. return false
  164. case .configured:
  165. return true
  166. }
  167. }
  168. /// Configuration has completed.
  169. mutating func configured() -> HPACKHeaders {
  170. switch self {
  171. case .configured:
  172. preconditionFailure("Invalid state: already configured")
  173. case let .configuring(headers):
  174. self = .configured
  175. return headers
  176. }
  177. }
  178. }
  179. }
  180. extension HTTP2ToRawGRPCStateMachine {
  181. /// Actions to take as a result of interacting with the state machine.
  182. enum Action {
  183. /// No action is required.
  184. case none
  185. /// Configure the pipeline using the provided call handler.
  186. case configure(GRPCCallHandler)
  187. /// An error was caught, fire it down the pipeline.
  188. case errorCaught(Error)
  189. /// Forward the request headers to the next handler.
  190. case forwardHeaders(HPACKHeaders)
  191. /// Forward the buffer to the next handler.
  192. case forwardMessage(ByteBuffer)
  193. /// Forward the buffer to the next handler and then send end stream.
  194. case forwardMessageAndEnd(ByteBuffer)
  195. /// Forward the request headers to the next handler then try reading request messages.
  196. case forwardHeadersThenReadNextMessage(HPACKHeaders)
  197. /// Forward the buffer to the next handler then try reading request messages.
  198. case forwardMessageThenReadNextMessage(ByteBuffer)
  199. /// Forward end of stream to the next handler.
  200. case forwardEnd
  201. /// Try to read a request message.
  202. case readNextRequest
  203. /// Write the frame to the channel, optionally insert an extra flush (i.e. if the state machine
  204. /// is turning a request around rather than processing a response part).
  205. case write(HTTP2Frame.FramePayload, EventLoopPromise<Void>?, flush: Bool)
  206. /// Complete the promise with the given result.
  207. case completePromise(EventLoopPromise<Void>?, Result<Void, Error>)
  208. }
  209. struct StateAndAction {
  210. /// The next state.
  211. var state: State
  212. /// The action to take.
  213. var action: Action
  214. }
  215. }
  216. // MARK: Receive Headers
  217. // This is the only state in which we can receive headers.
  218. extension HTTP2ToRawGRPCStateMachine.RequestIdleResponseIdleState {
  219. func receive(
  220. headers: HPACKHeaders,
  221. eventLoop: EventLoop,
  222. errorDelegate: ServerErrorDelegate?,
  223. remoteAddress: SocketAddress?,
  224. logger: Logger
  225. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  226. // Extract and validate the content type. If it's nil we need to close.
  227. guard let contentType = self.extractContentType(from: headers) else {
  228. return self.unsupportedContentType()
  229. }
  230. // Now extract the request message encoding and setup an appropriate message reader.
  231. // We may send back a list of acceptable request message encodings as well.
  232. let reader: LengthPrefixedMessageReader
  233. let acceptableRequestEncoding: String?
  234. switch self.extractRequestEncoding(from: headers) {
  235. case let .valid(messageReader, acceptEncodingHeader):
  236. reader = messageReader
  237. acceptableRequestEncoding = acceptEncodingHeader
  238. case let .invalid(status, acceptableRequestEncoding):
  239. return self.invalidRequestEncoding(
  240. status: status,
  241. acceptableRequestEncoding: acceptableRequestEncoding,
  242. contentType: contentType
  243. )
  244. }
  245. // Figure out which encoding we should use for responses.
  246. let (writer, responseEncoding) = self.extractResponseEncoding(from: headers)
  247. // Parse the path, and create a call handler.
  248. guard let path = headers.first(name: ":path") else {
  249. return self.methodNotImplemented("", contentType: contentType)
  250. }
  251. guard let callPath = CallPath(requestURI: path),
  252. let service = self.services[Substring(callPath.service)] else {
  253. return self.methodNotImplemented(path, contentType: contentType)
  254. }
  255. // Create a call handler context, i.e. a bunch of 'stuff' we need to create the handler with,
  256. // some of which is exposed to service providers.
  257. let context = CallHandlerContext(
  258. errorDelegate: errorDelegate,
  259. logger: logger,
  260. encoding: self.encoding,
  261. eventLoop: eventLoop,
  262. path: path,
  263. remoteAddress: remoteAddress
  264. )
  265. // We have a matching service, hopefully we have a provider for the method too.
  266. let method = Substring(callPath.method)
  267. guard let handler = service.handleMethod(method, callHandlerContext: context) else {
  268. return self.methodNotImplemented(path, contentType: contentType)
  269. }
  270. // Finally, on to the next state!
  271. let requestOpenResponseIdle = HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState(
  272. reader: reader,
  273. writer: writer,
  274. contentType: contentType,
  275. acceptEncoding: acceptableRequestEncoding,
  276. responseEncoding: responseEncoding,
  277. normalizeHeaders: self.normalizeHeaders,
  278. configurationState: .configuring(headers)
  279. )
  280. return .init(
  281. state: .requestOpenResponseIdle(requestOpenResponseIdle),
  282. action: .configure(handler)
  283. )
  284. }
  285. /// The 'content-type' is not supported; close with status code 415.
  286. private func unsupportedContentType() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  287. // From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  288. //
  289. // If 'content-type' does not begin with "application/grpc", gRPC servers SHOULD respond
  290. // with HTTP status of 415 (Unsupported Media Type). This will prevent other HTTP/2
  291. // clients from interpreting a gRPC error response, which uses status 200 (OK), as
  292. // successful.
  293. let trailers = HPACKHeaders([(":status", "415")])
  294. return .init(
  295. state: .requestClosedResponseClosed,
  296. action: .write(.headers(.init(headers: trailers, endStream: true)), nil, flush: true)
  297. )
  298. }
  299. /// The RPC method is not implemented. Close with an appropriate status.
  300. private func methodNotImplemented(
  301. _ path: String,
  302. contentType: ContentType
  303. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  304. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
  305. for: GRPCStatus(code: .unimplemented, message: "'\(path)' is not implemented"),
  306. contentType: contentType,
  307. acceptableRequestEncoding: nil,
  308. userProvidedHeaders: nil,
  309. normalizeUserProvidedHeaders: self.normalizeHeaders
  310. )
  311. return .init(
  312. state: .requestClosedResponseClosed,
  313. action: .write(.headers(.init(headers: trailers, endStream: true)), nil, flush: true)
  314. )
  315. }
  316. /// The request encoding specified by the client is not supported. Close with an appropriate
  317. /// status.
  318. private func invalidRequestEncoding(
  319. status: GRPCStatus,
  320. acceptableRequestEncoding: String?,
  321. contentType: ContentType
  322. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  323. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
  324. for: status,
  325. contentType: contentType,
  326. acceptableRequestEncoding: acceptableRequestEncoding,
  327. userProvidedHeaders: nil,
  328. normalizeUserProvidedHeaders: self.normalizeHeaders
  329. )
  330. return .init(
  331. state: .requestClosedResponseClosed,
  332. action: .write(.headers(.init(headers: trailers, endStream: true)), nil, flush: true)
  333. )
  334. }
  335. /// Makes a 'GRPCStatus' and response trailers suitable for returning to the client when the
  336. /// request message encoding is not supported.
  337. ///
  338. /// - Parameters:
  339. /// - encoding: The unsupported request message encoding sent by the client.
  340. /// - acceptable: The list if acceptable request message encoding the client may use.
  341. /// - Returns: The status and trailers to return to the client.
  342. private func makeStatusAndTrailersForUnsupportedEncoding(
  343. _ encoding: String,
  344. advertisedEncoding: [String]
  345. ) -> (GRPCStatus, acceptEncoding: String?) {
  346. let status: GRPCStatus
  347. let acceptEncoding: String?
  348. if advertisedEncoding.isEmpty {
  349. // No compression is supported; there's nothing to tell the client about.
  350. status = GRPCStatus(code: .unimplemented, message: "compression is not supported")
  351. acceptEncoding = nil
  352. } else {
  353. // Return a list of supported encodings which we advertise. (The list we advertise may be a
  354. // subset of the encodings we support.)
  355. acceptEncoding = advertisedEncoding.joined(separator: ",")
  356. status = GRPCStatus(
  357. code: .unimplemented,
  358. message: "\(encoding) compression is not supported, supported algorithms are " +
  359. "listed in '\(GRPCHeaderName.acceptEncoding)'"
  360. )
  361. }
  362. return (status, acceptEncoding)
  363. }
  364. /// Extract and validate the 'content-type' sent by the client.
  365. /// - Parameter headers: The headers to extract the 'content-type' from
  366. private func extractContentType(from headers: HPACKHeaders) -> ContentType? {
  367. return headers.first(name: GRPCHeaderName.contentType).flatMap(ContentType.init)
  368. }
  369. /// The result of validating the request encoding header.
  370. private enum RequestEncodingValidation {
  371. /// The encoding was valid.
  372. case valid(messageReader: LengthPrefixedMessageReader, acceptEncoding: String?)
  373. /// The encoding was invalid, the RPC should be terminated with this status.
  374. case invalid(status: GRPCStatus, acceptEncoding: String?)
  375. }
  376. /// Extract and validate the request message encoding header.
  377. /// - Parameters:
  378. /// - headers: The headers to extract the message encoding header from.
  379. /// - Returns: `RequestEncodingValidation`, either a message reader suitable for decoding requests
  380. /// and an accept encoding response header if the request encoding was valid, or a pair of
  381. /// `GRPCStatus` and trailers to close the RPC with.
  382. private func extractRequestEncoding(from headers: HPACKHeaders) -> RequestEncodingValidation {
  383. let encodings = headers[canonicalForm: GRPCHeaderName.encoding]
  384. // Fail if there's more than one encoding header.
  385. if encodings.count > 1 {
  386. let status = GRPCStatus(
  387. code: .invalidArgument,
  388. message: "'\(GRPCHeaderName.encoding)' must contain no more than one value but was '\(encodings.joined(separator: ", "))'"
  389. )
  390. return .invalid(status: status, acceptEncoding: nil)
  391. }
  392. let encodingHeader = encodings.first
  393. let result: RequestEncodingValidation
  394. let validator = MessageEncodingHeaderValidator(encoding: self.encoding)
  395. switch validator.validate(requestEncoding: encodingHeader) {
  396. case let .supported(algorithm, decompressionLimit, acceptEncoding):
  397. // Request message encoding is valid and supported.
  398. result = .valid(
  399. messageReader: LengthPrefixedMessageReader(
  400. compression: algorithm,
  401. decompressionLimit: decompressionLimit
  402. ),
  403. acceptEncoding: acceptEncoding.isEmpty ? nil : acceptEncoding.joined(separator: ",")
  404. )
  405. case .noCompression:
  406. // No message encoding header was present. This means no compression is being used.
  407. result = .valid(
  408. messageReader: LengthPrefixedMessageReader(),
  409. acceptEncoding: nil
  410. )
  411. case let .unsupported(encoding, acceptable):
  412. // Request encoding is not supported.
  413. let (status, acceptEncoding) = self.makeStatusAndTrailersForUnsupportedEncoding(
  414. encoding,
  415. advertisedEncoding: acceptable
  416. )
  417. result = .invalid(status: status, acceptEncoding: acceptEncoding)
  418. }
  419. return result
  420. }
  421. /// Extract a suitable message encoding for responses.
  422. /// - Parameters:
  423. /// - headers: The headers to extract the acceptable response message encoding from.
  424. /// - configuration: The encoding configuration for the server.
  425. /// - Returns: A message writer and the response encoding header to send back to the client.
  426. private func extractResponseEncoding(
  427. from headers: HPACKHeaders
  428. ) -> (LengthPrefixedMessageWriter, String?) {
  429. let writer: LengthPrefixedMessageWriter
  430. let responseEncoding: String?
  431. switch self.encoding {
  432. case let .enabled(configuration):
  433. // Extract the encodings acceptable to the client for response messages.
  434. let acceptableResponseEncoding = headers[canonicalForm: GRPCHeaderName.acceptEncoding]
  435. // Select the first algorithm that we support and have enabled. If we don't find one then we
  436. // won't compress response messages.
  437. let algorithm = acceptableResponseEncoding.lazy.compactMap { value in
  438. CompressionAlgorithm(rawValue: value)
  439. }.first {
  440. configuration.enabledAlgorithms.contains($0)
  441. }
  442. writer = LengthPrefixedMessageWriter(compression: algorithm)
  443. responseEncoding = algorithm?.name
  444. case .disabled:
  445. // The server doesn't have compression enabled.
  446. writer = LengthPrefixedMessageWriter(compression: .none)
  447. responseEncoding = nil
  448. }
  449. return (writer, responseEncoding)
  450. }
  451. }
  452. // MARK: - Receive Data
  453. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
  454. mutating func receive(
  455. buffer: inout ByteBuffer,
  456. endStream: Bool
  457. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  458. // Append the bytes to the reader.
  459. self.reader.append(buffer: &buffer)
  460. let state: HTTP2ToRawGRPCStateMachine.State
  461. let action: HTTP2ToRawGRPCStateMachine.Action
  462. switch (self.configurationState.isConfigured, endStream) {
  463. case (true, true):
  464. /// Configured and end stream: read from the buffer, end will be sent as a result of draining
  465. /// the reader in the next state.
  466. state = .requestClosedResponseIdle(.init(from: self))
  467. action = .readNextRequest
  468. case (true, false):
  469. /// Configured but not end stream, just read from the buffer.
  470. state = .requestOpenResponseIdle(self)
  471. action = .readNextRequest
  472. case (false, true):
  473. // Not configured yet, but end of stream. Request stream is now closed but there's no point
  474. // reading yet.
  475. state = .requestClosedResponseIdle(.init(from: self))
  476. action = .none
  477. case (false, false):
  478. // Not configured yet, not end stream. No point reading a message yet since we don't have
  479. // anywhere to deliver it.
  480. state = .requestOpenResponseIdle(self)
  481. action = .none
  482. }
  483. return .init(state: state, action: action)
  484. }
  485. }
  486. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
  487. mutating func receive(
  488. buffer: inout ByteBuffer,
  489. endStream: Bool
  490. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  491. self.reader.append(buffer: &buffer)
  492. let state: HTTP2ToRawGRPCStateMachine.State
  493. if endStream {
  494. // End stream, so move to the closed state. Any end of request stream events events will
  495. // happen as a result of reading from the closed state.
  496. state = .requestClosedResponseOpen(.init(from: self))
  497. } else {
  498. state = .requestOpenResponseOpen(self)
  499. }
  500. return .init(state: state, action: .readNextRequest)
  501. }
  502. }
  503. // MARK: - Send Headers
  504. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
  505. func send(
  506. headers userProvidedHeaders: HPACKHeaders,
  507. promise: EventLoopPromise<Void>?
  508. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  509. let headers = HTTP2ToRawGRPCStateMachine.makeResponseHeaders(
  510. contentType: self.contentType,
  511. responseEncoding: self.responseEncoding,
  512. acceptableRequestEncoding: self.acceptEncoding,
  513. userProvidedHeaders: userProvidedHeaders,
  514. normalizeUserProvidedHeaders: self.normalizeHeaders
  515. )
  516. return .init(
  517. state: .requestOpenResponseOpen(.init(from: self)),
  518. action: .write(.headers(.init(headers: headers)), promise, flush: false)
  519. )
  520. }
  521. }
  522. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
  523. func send(
  524. headers userProvidedHeaders: HPACKHeaders,
  525. promise: EventLoopPromise<Void>?
  526. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  527. let headers = HTTP2ToRawGRPCStateMachine.makeResponseHeaders(
  528. contentType: self.contentType,
  529. responseEncoding: self.responseEncoding,
  530. acceptableRequestEncoding: self.acceptEncoding,
  531. userProvidedHeaders: userProvidedHeaders,
  532. normalizeUserProvidedHeaders: self.normalizeHeaders
  533. )
  534. return .init(
  535. state: .requestClosedResponseOpen(.init(from: self)),
  536. action: .write(.headers(.init(headers: headers)), promise, flush: false)
  537. )
  538. }
  539. }
  540. // MARK: - Send Data
  541. extension HTTP2ToRawGRPCStateMachine {
  542. static func writeGRPCFramedMessage(
  543. _ buffer: ByteBuffer,
  544. compress: Bool,
  545. allocator: ByteBufferAllocator,
  546. promise: EventLoopPromise<Void>?,
  547. writer: LengthPrefixedMessageWriter
  548. ) -> Action {
  549. do {
  550. let prefixed = try writer.write(buffer: buffer, allocator: allocator, compressed: compress)
  551. return .write(.data(.init(data: .byteBuffer(prefixed))), promise, flush: false)
  552. } catch {
  553. return .completePromise(promise, .failure(error))
  554. }
  555. }
  556. }
  557. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
  558. func send(
  559. buffer: ByteBuffer,
  560. allocator: ByteBufferAllocator,
  561. compress: Bool,
  562. promise: EventLoopPromise<Void>?
  563. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  564. let action = HTTP2ToRawGRPCStateMachine.writeGRPCFramedMessage(
  565. buffer,
  566. compress: compress,
  567. allocator: allocator,
  568. promise: promise,
  569. writer: self.writer
  570. )
  571. return .init(state: .requestOpenResponseOpen(self), action: action)
  572. }
  573. }
  574. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
  575. func send(
  576. buffer: ByteBuffer,
  577. allocator: ByteBufferAllocator,
  578. compress: Bool,
  579. promise: EventLoopPromise<Void>?
  580. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  581. let action = HTTP2ToRawGRPCStateMachine.writeGRPCFramedMessage(
  582. buffer,
  583. compress: compress,
  584. allocator: allocator,
  585. promise: promise,
  586. writer: self.writer
  587. )
  588. return .init(state: .requestClosedResponseOpen(self), action: action)
  589. }
  590. }
  591. // MARK: - Send End
  592. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
  593. func send(
  594. status: GRPCStatus,
  595. trailers userProvidedTrailers: HPACKHeaders,
  596. promise: EventLoopPromise<Void>?
  597. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  598. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
  599. for: status,
  600. contentType: self.contentType,
  601. acceptableRequestEncoding: self.acceptEncoding,
  602. userProvidedHeaders: userProvidedTrailers,
  603. normalizeUserProvidedHeaders: self.normalizeHeaders
  604. )
  605. return .init(
  606. state: .requestClosedResponseClosed,
  607. action: .write(.headers(.init(headers: trailers, endStream: true)), promise, flush: false)
  608. )
  609. }
  610. }
  611. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
  612. func send(
  613. status: GRPCStatus,
  614. trailers userProvidedTrailers: HPACKHeaders,
  615. promise: EventLoopPromise<Void>?
  616. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  617. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
  618. for: status,
  619. contentType: self.contentType,
  620. acceptableRequestEncoding: self.acceptEncoding,
  621. userProvidedHeaders: userProvidedTrailers,
  622. normalizeUserProvidedHeaders: self.normalizeHeaders
  623. )
  624. return .init(
  625. state: .requestClosedResponseClosed,
  626. action: .write(.headers(.init(headers: trailers, endStream: true)), promise, flush: false)
  627. )
  628. }
  629. }
  630. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
  631. func send(
  632. status: GRPCStatus,
  633. trailers userProvidedTrailers: HPACKHeaders,
  634. promise: EventLoopPromise<Void>?
  635. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  636. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailers(
  637. for: status,
  638. userProvidedHeaders: userProvidedTrailers,
  639. normalizeUserProvidedHeaders: true
  640. )
  641. return .init(
  642. state: .requestClosedResponseClosed,
  643. action: .write(.headers(.init(headers: trailers, endStream: true)), promise, flush: false)
  644. )
  645. }
  646. }
  647. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
  648. func send(
  649. status: GRPCStatus,
  650. trailers userProvidedTrailers: HPACKHeaders,
  651. promise: EventLoopPromise<Void>?
  652. ) -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  653. let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailers(
  654. for: status,
  655. userProvidedHeaders: userProvidedTrailers,
  656. normalizeUserProvidedHeaders: true
  657. )
  658. return .init(
  659. state: .requestClosedResponseClosed,
  660. action: .write(.headers(.init(headers: trailers, endStream: true)), promise, flush: false)
  661. )
  662. }
  663. }
  664. // MARK: - Pipeline Configured
  665. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
  666. mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  667. let headers = self.configurationState.configured()
  668. let action: HTTP2ToRawGRPCStateMachine.Action
  669. // If there are unprocessed bytes then we need to read messages as well.
  670. let hasUnprocessedBytes = self.reader.unprocessedBytes != 0
  671. if hasUnprocessedBytes {
  672. // If there are unprocessed bytes, we need to try to read after sending the metadata.
  673. action = .forwardHeadersThenReadNextMessage(headers)
  674. } else {
  675. // No unprocessed bytes; the reader is empty. Just send the metadata.
  676. action = .forwardHeaders(headers)
  677. }
  678. return .init(state: .requestOpenResponseIdle(self), action: action)
  679. }
  680. }
  681. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
  682. mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  683. let headers = self.configurationState.configured()
  684. return .init(
  685. state: .requestClosedResponseIdle(self),
  686. // Since we're already closed, we need to forward the headers and start reading.
  687. action: .forwardHeadersThenReadNextMessage(headers)
  688. )
  689. }
  690. }
  691. // MARK: - Read Next Request
  692. extension HTTP2ToRawGRPCStateMachine {
  693. static func read(
  694. from reader: inout LengthPrefixedMessageReader,
  695. requestStreamClosed: Bool
  696. ) -> HTTP2ToRawGRPCStateMachine.Action {
  697. do {
  698. // Try to read a message.
  699. guard let buffer = try reader.nextMessage() else {
  700. // We didn't read a message: if we're closed then there's no chance of receiving more bytes,
  701. // just forward the end of stream. If we're not closed then we could receive more bytes so
  702. // there's no need to take any action at this point.
  703. return requestStreamClosed ? .forwardEnd : .none
  704. }
  705. guard reader.unprocessedBytes == 0 else {
  706. // There are still unprocessed bytes, continue reading.
  707. return .forwardMessageThenReadNextMessage(buffer)
  708. }
  709. // If we're closed and there's nothing left to read, then we're done, forward the message and
  710. // end of stream. If we're closed we could still receive more bytes (or end stream) so just
  711. // forward the message.
  712. return requestStreamClosed ? .forwardMessageAndEnd(buffer) : .forwardMessage(buffer)
  713. } catch {
  714. return .errorCaught(error)
  715. }
  716. }
  717. }
  718. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
  719. mutating func readNextRequest() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  720. let action = HTTP2ToRawGRPCStateMachine.read(from: &self.reader, requestStreamClosed: false)
  721. return .init(state: .requestOpenResponseIdle(self), action: action)
  722. }
  723. }
  724. extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
  725. mutating func readNextRequest() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  726. let action = HTTP2ToRawGRPCStateMachine.read(from: &self.reader, requestStreamClosed: false)
  727. return .init(state: .requestOpenResponseOpen(self), action: action)
  728. }
  729. }
  730. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
  731. mutating func readNextRequest() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  732. let action = HTTP2ToRawGRPCStateMachine.read(from: &self.reader, requestStreamClosed: true)
  733. return .init(state: .requestClosedResponseIdle(self), action: action)
  734. }
  735. }
  736. extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
  737. mutating func readNextRequest() -> HTTP2ToRawGRPCStateMachine.StateAndAction {
  738. let action = HTTP2ToRawGRPCStateMachine.read(from: &self.reader, requestStreamClosed: true)
  739. return .init(state: .requestClosedResponseOpen(self), action: action)
  740. }
  741. }
  742. // MARK: - Top Level State Changes
  743. extension HTTP2ToRawGRPCStateMachine {
  744. /// Receive request headers.
  745. mutating func receive(
  746. headers: HPACKHeaders,
  747. eventLoop: EventLoop,
  748. errorDelegate: ServerErrorDelegate?,
  749. remoteAddress: SocketAddress?,
  750. logger: Logger
  751. ) -> Action {
  752. return self.withStateAvoidingCoWs { state in
  753. state.receive(
  754. headers: headers,
  755. eventLoop: eventLoop,
  756. errorDelegate: errorDelegate,
  757. remoteAddress: remoteAddress,
  758. logger: logger
  759. )
  760. }
  761. }
  762. /// Receive request buffer.
  763. mutating func receive(buffer: inout ByteBuffer, endStream: Bool) -> Action {
  764. return self.withStateAvoidingCoWs { state in
  765. state.receive(buffer: &buffer, endStream: endStream)
  766. }
  767. }
  768. /// Send response headers.
  769. mutating func send(headers: HPACKHeaders, promise: EventLoopPromise<Void>?) -> Action {
  770. return self.withStateAvoidingCoWs { state in
  771. state.send(headers: headers, promise: promise)
  772. }
  773. }
  774. /// Send a response buffer.
  775. mutating func send(
  776. buffer: ByteBuffer,
  777. allocator: ByteBufferAllocator,
  778. compress: Bool,
  779. promise: EventLoopPromise<Void>?
  780. ) -> Action {
  781. return self.withStateAvoidingCoWs { state in
  782. state.send(buffer: buffer, allocator: allocator, compress: compress, promise: promise)
  783. }
  784. }
  785. /// Send status and trailers.
  786. mutating func send(
  787. status: GRPCStatus,
  788. trailers: HPACKHeaders,
  789. promise: EventLoopPromise<Void>?
  790. ) -> Action {
  791. return self.withStateAvoidingCoWs { state in
  792. state.send(status: status, trailers: trailers, promise: promise)
  793. }
  794. }
  795. /// The pipeline has been configured with a service provider.
  796. mutating func pipelineConfigured() -> Action {
  797. return self.withStateAvoidingCoWs { state in
  798. state.pipelineConfigured()
  799. }
  800. }
  801. /// Try to read a request message.
  802. mutating func readNextRequest() -> Action {
  803. return self.withStateAvoidingCoWs { state in
  804. state.readNextRequest()
  805. }
  806. }
  807. }
  808. extension HTTP2ToRawGRPCStateMachine.State {
  809. mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.Action {
  810. switch self {
  811. case .requestIdleResponseIdle:
  812. preconditionFailure("Invalid state: pipeline configured before receiving request headers")
  813. case var .requestOpenResponseIdle(state):
  814. let stateAndAction = state.pipelineConfigured()
  815. self = stateAndAction.state
  816. return stateAndAction.action
  817. case var .requestClosedResponseIdle(state):
  818. let stateAndAction = state.pipelineConfigured()
  819. self = stateAndAction.state
  820. return stateAndAction.action
  821. case .requestOpenResponseOpen,
  822. .requestClosedResponseOpen,
  823. .requestClosedResponseClosed:
  824. preconditionFailure("Invalid state: response stream opened before pipeline was configured")
  825. case ._modifying:
  826. preconditionFailure("Left in modifying state")
  827. }
  828. }
  829. mutating func receive(
  830. headers: HPACKHeaders,
  831. eventLoop: EventLoop,
  832. errorDelegate: ServerErrorDelegate?,
  833. remoteAddress: SocketAddress?,
  834. logger: Logger
  835. ) -> HTTP2ToRawGRPCStateMachine.Action {
  836. switch self {
  837. // This is the only state in which we can receive headers. Everything else is invalid.
  838. case let .requestIdleResponseIdle(state):
  839. let stateAndAction = state.receive(
  840. headers: headers,
  841. eventLoop: eventLoop,
  842. errorDelegate: errorDelegate,
  843. remoteAddress: remoteAddress,
  844. logger: logger
  845. )
  846. self = stateAndAction.state
  847. return stateAndAction.action
  848. // We can't receive headers in any of these states.
  849. case .requestOpenResponseIdle,
  850. .requestOpenResponseOpen,
  851. .requestClosedResponseIdle,
  852. .requestClosedResponseOpen,
  853. .requestClosedResponseClosed:
  854. preconditionFailure("Invalid state")
  855. case ._modifying:
  856. preconditionFailure("Left in modifying state")
  857. }
  858. }
  859. /// Receive a buffer from the client.
  860. mutating func receive(buffer: inout ByteBuffer, endStream: Bool) -> HTTP2ToRawGRPCStateMachine
  861. .Action {
  862. switch self {
  863. case .requestIdleResponseIdle:
  864. /// This isn't allowed: we must receive the request headers first.
  865. preconditionFailure("Invalid state")
  866. case var .requestOpenResponseIdle(state):
  867. let stateAndAction = state.receive(buffer: &buffer, endStream: endStream)
  868. self = stateAndAction.state
  869. return stateAndAction.action
  870. case var .requestOpenResponseOpen(state):
  871. let stateAndAction = state.receive(buffer: &buffer, endStream: endStream)
  872. self = stateAndAction.state
  873. return stateAndAction.action
  874. case .requestClosedResponseIdle,
  875. .requestClosedResponseOpen:
  876. preconditionFailure("Invalid state: the request stream is already closed")
  877. case .requestClosedResponseClosed:
  878. // This is okay: we could have closed before receiving end.
  879. return .none
  880. case ._modifying:
  881. preconditionFailure("Left in modifying state")
  882. }
  883. }
  884. mutating func readNextRequest() -> HTTP2ToRawGRPCStateMachine.Action {
  885. switch self {
  886. case .requestIdleResponseIdle:
  887. preconditionFailure("Invalid state")
  888. case var .requestOpenResponseIdle(state):
  889. let stateAndAction = state.readNextRequest()
  890. self = stateAndAction.state
  891. return stateAndAction.action
  892. case var .requestOpenResponseOpen(state):
  893. let stateAndAction = state.readNextRequest()
  894. self = stateAndAction.state
  895. return stateAndAction.action
  896. case var .requestClosedResponseIdle(state):
  897. let stateAndAction = state.readNextRequest()
  898. self = stateAndAction.state
  899. return stateAndAction.action
  900. case var .requestClosedResponseOpen(state):
  901. let stateAndAction = state.readNextRequest()
  902. self = stateAndAction.state
  903. return stateAndAction.action
  904. case .requestClosedResponseClosed:
  905. return .none
  906. case ._modifying:
  907. preconditionFailure("Left in modifying state")
  908. }
  909. }
  910. mutating func send(
  911. headers: HPACKHeaders,
  912. promise: EventLoopPromise<Void>?
  913. ) -> HTTP2ToRawGRPCStateMachine.Action {
  914. switch self {
  915. case .requestIdleResponseIdle:
  916. preconditionFailure("Invalid state: the request stream isn't open")
  917. case let .requestOpenResponseIdle(state):
  918. let stateAndAction = state.send(headers: headers, promise: promise)
  919. self = stateAndAction.state
  920. return stateAndAction.action
  921. case let .requestClosedResponseIdle(state):
  922. let stateAndAction = state.send(headers: headers, promise: promise)
  923. self = stateAndAction.state
  924. return stateAndAction.action
  925. case .requestOpenResponseOpen,
  926. .requestClosedResponseOpen,
  927. .requestClosedResponseClosed:
  928. return .completePromise(promise, .failure(GRPCError.AlreadyComplete()))
  929. case ._modifying:
  930. preconditionFailure("Left in modifying state")
  931. }
  932. }
  933. mutating func send(
  934. buffer: ByteBuffer,
  935. allocator: ByteBufferAllocator,
  936. compress: Bool,
  937. promise: EventLoopPromise<Void>?
  938. ) -> HTTP2ToRawGRPCStateMachine.Action {
  939. switch self {
  940. case .requestIdleResponseIdle:
  941. preconditionFailure("Invalid state: the request stream is still closed")
  942. case .requestOpenResponseIdle,
  943. .requestClosedResponseIdle:
  944. let error = GRPCError.InvalidState("Response headers must be sent before response message")
  945. return .completePromise(promise, .failure(error))
  946. case let .requestOpenResponseOpen(state):
  947. let stateAndAction = state.send(
  948. buffer: buffer,
  949. allocator: allocator,
  950. compress: compress,
  951. promise: promise
  952. )
  953. self = stateAndAction.state
  954. return stateAndAction.action
  955. case let .requestClosedResponseOpen(state):
  956. let stateAndAction = state.send(
  957. buffer: buffer,
  958. allocator: allocator,
  959. compress: compress,
  960. promise: promise
  961. )
  962. self = stateAndAction.state
  963. return stateAndAction.action
  964. case .requestClosedResponseClosed:
  965. return .completePromise(promise, .failure(GRPCError.AlreadyComplete()))
  966. case ._modifying:
  967. preconditionFailure("Left in modifying state")
  968. }
  969. }
  970. mutating func send(
  971. status: GRPCStatus,
  972. trailers: HPACKHeaders,
  973. promise: EventLoopPromise<Void>?
  974. ) -> HTTP2ToRawGRPCStateMachine.Action {
  975. switch self {
  976. case .requestIdleResponseIdle:
  977. preconditionFailure("Invalid state: the request stream is still closed")
  978. case let .requestOpenResponseIdle(state):
  979. let stateAndAction = state.send(status: status, trailers: trailers, promise: promise)
  980. self = stateAndAction.state
  981. return stateAndAction.action
  982. case let .requestClosedResponseIdle(state):
  983. let stateAndAction = state.send(status: status, trailers: trailers, promise: promise)
  984. self = stateAndAction.state
  985. return stateAndAction.action
  986. case let .requestOpenResponseOpen(state):
  987. let stateAndAction = state.send(status: status, trailers: trailers, promise: promise)
  988. self = stateAndAction.state
  989. return stateAndAction.action
  990. case let .requestClosedResponseOpen(state):
  991. let stateAndAction = state.send(status: status, trailers: trailers, promise: promise)
  992. self = stateAndAction.state
  993. return stateAndAction.action
  994. case .requestClosedResponseClosed:
  995. return .completePromise(promise, .failure(GRPCError.AlreadyComplete()))
  996. case ._modifying:
  997. preconditionFailure("Left in modifying state")
  998. }
  999. }
  1000. }
  1001. // MARK: - Helpers
  1002. extension HTTP2ToRawGRPCStateMachine {
  1003. static func makeResponseHeaders(
  1004. contentType: ContentType,
  1005. responseEncoding: String?,
  1006. acceptableRequestEncoding: String?,
  1007. userProvidedHeaders: HPACKHeaders,
  1008. normalizeUserProvidedHeaders: Bool
  1009. ) -> HPACKHeaders {
  1010. // 4 because ':status' and 'content-type' are required. We may send back 'grpc-encoding' and
  1011. // 'grpc-accept-encoding' as well.
  1012. let capacity = 4 + userProvidedHeaders.count
  1013. var headers = HPACKHeaders()
  1014. headers.reserveCapacity(capacity)
  1015. headers.add(name: ":status", value: "200")
  1016. headers.add(name: GRPCHeaderName.contentType, value: contentType.canonicalValue)
  1017. if let responseEncoding = responseEncoding {
  1018. headers.add(name: GRPCHeaderName.encoding, value: responseEncoding)
  1019. }
  1020. if let acceptEncoding = acceptableRequestEncoding {
  1021. headers.add(name: GRPCHeaderName.acceptEncoding, value: acceptEncoding)
  1022. }
  1023. // Add user provided headers, normalizing if required.
  1024. headers.add(contentsOf: userProvidedHeaders, normalize: normalizeUserProvidedHeaders)
  1025. return headers
  1026. }
  1027. static func makeResponseTrailersOnly(
  1028. for status: GRPCStatus,
  1029. contentType: ContentType,
  1030. acceptableRequestEncoding: String?,
  1031. userProvidedHeaders: HPACKHeaders?,
  1032. normalizeUserProvidedHeaders: Bool
  1033. ) -> HPACKHeaders {
  1034. // 5 because ':status', 'content-type', 'grpc-status' are required. We may also send back
  1035. // 'grpc-message' and 'grpc-accept-encoding'.
  1036. let capacity = 5 + (userProvidedHeaders.map { $0.count } ?? 0)
  1037. var headers = HPACKHeaders()
  1038. headers.reserveCapacity(capacity)
  1039. // Add the required trailers.
  1040. headers.add(name: ":status", value: "200")
  1041. headers.add(name: GRPCHeaderName.contentType, value: contentType.canonicalValue)
  1042. headers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  1043. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  1044. headers.add(name: GRPCHeaderName.statusMessage, value: message)
  1045. }
  1046. // We may include this if the requested encoding was not valid.
  1047. if let acceptEncoding = acceptableRequestEncoding {
  1048. headers.add(name: GRPCHeaderName.acceptEncoding, value: acceptEncoding)
  1049. }
  1050. if let userProvided = userProvidedHeaders {
  1051. headers.add(contentsOf: userProvided, normalize: normalizeUserProvidedHeaders)
  1052. }
  1053. return headers
  1054. }
  1055. static func makeResponseTrailers(
  1056. for status: GRPCStatus,
  1057. userProvidedHeaders: HPACKHeaders,
  1058. normalizeUserProvidedHeaders: Bool
  1059. ) -> HPACKHeaders {
  1060. // 2 because 'grpc-status' is required, we may also send back 'grpc-message'.
  1061. let capacity = 2 + userProvidedHeaders.count
  1062. var trailers = HPACKHeaders()
  1063. trailers.reserveCapacity(capacity)
  1064. // status code.
  1065. trailers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  1066. // status message, if present.
  1067. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  1068. trailers.add(name: GRPCHeaderName.statusMessage, value: message)
  1069. }
  1070. // user provided trailers.
  1071. trailers.add(contentsOf: userProvidedHeaders, normalize: normalizeUserProvidedHeaders)
  1072. return trailers
  1073. }
  1074. }
  1075. private extension HPACKHeaders {
  1076. mutating func add(contentsOf other: HPACKHeaders, normalize: Bool) {
  1077. if normalize {
  1078. self.add(contentsOf: other.lazy.map { name, value, indexable in
  1079. (name: name.lowercased(), value: value, indexable: indexable)
  1080. })
  1081. } else {
  1082. self.add(contentsOf: other)
  1083. }
  1084. }
  1085. }