HTTP2ToRawGRPCStateMachine.swift 40 KB

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