HTTP2ToRawGRPCStateMachine.swift 43 KB

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