HTTP1ToGRPCServerCodec.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import Logging
  18. import NIO
  19. import NIOFoundationCompat
  20. import NIOHPACK
  21. import NIOHTTP1
  22. import SwiftProtobuf
  23. /// Incoming gRPC package with a fixed message type.
  24. ///
  25. /// - Important: This is **NOT** part of the public API.
  26. public enum _GRPCServerRequestPart<Request> {
  27. case headers(HPACKHeaders)
  28. case message(Request)
  29. case end
  30. }
  31. public typealias _RawGRPCServerRequestPart = _GRPCServerRequestPart<ByteBuffer>
  32. /// Outgoing gRPC package with a fixed message type.
  33. ///
  34. /// - Important: This is **NOT** part of the public API.
  35. public enum _GRPCServerResponsePart<Response> {
  36. case headers(HPACKHeaders)
  37. case message(_MessageContext<Response>)
  38. case statusAndTrailers(GRPCStatus, HPACKHeaders)
  39. }
  40. public typealias _RawGRPCServerResponsePart = _GRPCServerResponsePart<ByteBuffer>
  41. /// A simple channel handler that translates HTTP1 data types into gRPC packets, and vice versa.
  42. ///
  43. /// We use HTTP1 (instead of HTTP2) primitives, as these are easier to work with than raw HTTP2
  44. /// primitives while providing all the functionality we need. In addition, it allows us to support
  45. /// gRPC-Web (gRPC over HTTP1).
  46. ///
  47. /// The translation from HTTP2 to HTTP1 is done by `HTTP2ToHTTP1ServerCodec`.
  48. public final class HTTP1ToGRPCServerCodec {
  49. public init(encoding: ServerMessageEncoding, logger: Logger) {
  50. self.encoding = encoding
  51. self.encodingHeaderValidator = MessageEncodingHeaderValidator(encoding: encoding)
  52. self.logger = logger
  53. self.messageReader = LengthPrefixedMessageReader()
  54. self.messageWriter = LengthPrefixedMessageWriter()
  55. }
  56. private var contentType: ContentType?
  57. private let encoding: ServerMessageEncoding
  58. private let encodingHeaderValidator: MessageEncodingHeaderValidator
  59. private var acceptEncodingHeader: String?
  60. private var responseEncodingHeader: String?
  61. private let logger: Logger
  62. private var stopwatch: Stopwatch?
  63. // The following buffers use force unwrapping explicitly. With optionals, developers
  64. // are encouraged to unwrap them using guard-else statements. These don't work cleanly
  65. // with structs, since the guard-else would create a new copy of the struct, which
  66. // would then have to be re-assigned into the class variable for the changes to take effect.
  67. // By force unwrapping, we avoid those reassignments, and the code is a bit cleaner.
  68. // Buffer to store binary encoded protos as they're being received if the proto is split across
  69. // multiple buffers.
  70. private var binaryRequestBuffer: NIO.ByteBuffer!
  71. // Buffers to store text encoded protos. Only used when content-type is application/grpc-web-text.
  72. // TODO(kaipi): Extract all gRPC Web processing logic into an independent handler only added on
  73. // the HTTP1.1 pipeline, as it's starting to get in the way of readability.
  74. private var requestTextBuffer: NIO.ByteBuffer!
  75. private var responseTextBuffers: CircularBuffer<ByteBuffer>?
  76. var inboundState = InboundState.expectingHeaders {
  77. willSet {
  78. guard newValue != self.inboundState else { return }
  79. self.logger.debug(
  80. "inbound state changed",
  81. metadata: ["old_state": "\(self.inboundState)", "new_state": "\(newValue)"]
  82. )
  83. }
  84. }
  85. var outboundState = OutboundState.expectingHeaders {
  86. willSet {
  87. guard newValue != self.outboundState else { return }
  88. self.logger.debug(
  89. "outbound state changed",
  90. metadata: ["old_state": "\(self.outboundState)", "new_state": "\(newValue)"]
  91. )
  92. }
  93. }
  94. var messageReader: LengthPrefixedMessageReader
  95. var messageWriter: LengthPrefixedMessageWriter
  96. }
  97. extension HTTP1ToGRPCServerCodec {
  98. enum InboundState {
  99. case expectingHeaders
  100. case expectingBody
  101. // ignore any additional messages; e.g. we've seen .end or we've sent an error and are waiting for the stream to close.
  102. case ignore
  103. }
  104. enum OutboundState {
  105. case expectingHeaders
  106. case expectingBodyOrStatus
  107. case ignore
  108. }
  109. }
  110. extension HTTP1ToGRPCServerCodec: ChannelInboundHandler {
  111. public typealias InboundIn = HTTPServerRequestPart
  112. public typealias InboundOut = _RawGRPCServerRequestPart
  113. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  114. if case .ignore = self.inboundState {
  115. self.logger.notice("ignoring read data", metadata: ["data": "\(data)"])
  116. return
  117. }
  118. do {
  119. switch self.unwrapInboundIn(data) {
  120. case let .head(requestHead):
  121. self.inboundState = try self.processHead(context: context, requestHead: requestHead)
  122. case var .body(body):
  123. self.inboundState = try self.processBody(context: context, body: &body)
  124. case let .end(trailers):
  125. self.inboundState = try self.processEnd(context: context, trailers: trailers)
  126. }
  127. } catch {
  128. context.fireErrorCaught(error)
  129. self.inboundState = .ignore
  130. }
  131. }
  132. func processHead(context: ChannelHandlerContext,
  133. requestHead: HTTPRequestHead) throws -> InboundState {
  134. self.logger.debug("processing request head", metadata: ["head": "\(requestHead)"])
  135. guard case .expectingHeaders = self.inboundState else {
  136. self.logger.error(
  137. "invalid state while processing request head",
  138. metadata: ["state": "\(self.inboundState)", "head": "\(requestHead)"]
  139. )
  140. throw GRPCError.InvalidState("expected state .expectingHeaders, got \(self.inboundState)")
  141. .captureContext()
  142. }
  143. self.stopwatch = .start()
  144. self.logger.debug("rpc call started", metadata: [
  145. "path": "\(requestHead.uri)",
  146. "method": "\(requestHead.method)",
  147. "version": "\(requestHead.version)",
  148. ])
  149. if let contentType = requestHead.headers.first(name: GRPCHeaderName.contentType)
  150. .flatMap(ContentType.init) {
  151. self.contentType = contentType
  152. } else {
  153. self.logger.debug("no 'content-type' header, assuming content type is 'application/grpc'")
  154. // If the Content-Type is not present, assume the request is binary encoded gRPC.
  155. self.contentType = .protobuf
  156. }
  157. if self.contentType == .webTextProtobuf {
  158. self.requestTextBuffer = context.channel.allocator.buffer(capacity: 0)
  159. }
  160. // What compression was used for sending requests?
  161. let encodingHeader = requestHead.headers.first(name: GRPCHeaderName.encoding)
  162. switch self.encodingHeaderValidator.validate(requestEncoding: encodingHeader) {
  163. case let .supported(algorithm, limit, acceptableEncoding):
  164. self.messageReader = LengthPrefixedMessageReader(
  165. compression: algorithm,
  166. decompressionLimit: limit
  167. )
  168. if acceptableEncoding.isEmpty {
  169. self.acceptEncodingHeader = nil
  170. } else {
  171. self.acceptEncodingHeader = acceptableEncoding.joined(separator: ",")
  172. }
  173. case .noCompression:
  174. self.messageReader = LengthPrefixedMessageReader()
  175. self.acceptEncodingHeader = nil
  176. case let .unsupported(header, acceptableEncoding):
  177. let message: String
  178. let headers: HPACKHeaders
  179. if acceptableEncoding.isEmpty {
  180. message = "compression is not supported"
  181. headers = .init()
  182. } else {
  183. let advertised = acceptableEncoding.joined(separator: ",")
  184. message = "'\(header)' compression is not supported, supported: \(advertised)"
  185. headers = [GRPCHeaderName.acceptEncoding: advertised]
  186. }
  187. let status = GRPCStatus(code: .unimplemented, message: message)
  188. defer {
  189. self.write(
  190. context: context,
  191. data: NIOAny(OutboundIn.statusAndTrailers(status, headers)),
  192. promise: nil
  193. )
  194. self.flush(context: context)
  195. }
  196. // We're about to fast-fail, so ignore any following inbound messages.
  197. return .ignore
  198. }
  199. // What compression should we use for writing responses?
  200. let clientAcceptableEncoding = requestHead.headers[canonicalForm: GRPCHeaderName.acceptEncoding]
  201. if let responseEncoding = self.selectResponseEncoding(from: clientAcceptableEncoding) {
  202. self.messageWriter = LengthPrefixedMessageWriter(compression: responseEncoding)
  203. self.responseEncodingHeader = responseEncoding.name
  204. } else {
  205. self.messageWriter = LengthPrefixedMessageWriter(compression: .none)
  206. self.responseEncodingHeader = nil
  207. }
  208. // We normalize in the 2-to-1 handler.
  209. let headers = HPACKHeaders(httpHeaders: requestHead.headers, normalizeHTTPHeaders: false)
  210. context.fireChannelRead(self.wrapInboundOut(.headers(headers)))
  211. return .expectingBody
  212. }
  213. func processBody(context: ChannelHandlerContext, body: inout ByteBuffer) throws -> InboundState {
  214. self.logger.debug("processing body: \(body)")
  215. guard case .expectingBody = self.inboundState else {
  216. self.logger.error(
  217. "invalid state while processing body",
  218. metadata: ["state": "\(self.inboundState)", "body": "\(body)"]
  219. )
  220. throw GRPCError.InvalidState("expected state .expectingBody, got \(self.inboundState)")
  221. .captureContext()
  222. }
  223. // If the contentType is text, then decode the incoming bytes as base64 encoded, and append
  224. // it to the binary buffer. If the request is chunked, this section will process the text
  225. // in the biggest chunk that is multiple of 4, leaving the unread bytes in the textBuffer
  226. // where it will expect a new incoming chunk.
  227. if self.contentType == .webTextProtobuf {
  228. precondition(self.requestTextBuffer != nil)
  229. self.requestTextBuffer.writeBuffer(&body)
  230. // Read in chunks of 4 bytes as base64 encoded strings will always be multiples of 4.
  231. let readyBytes = self.requestTextBuffer
  232. .readableBytes - (self.requestTextBuffer.readableBytes % 4)
  233. guard let base64Encoded = requestTextBuffer.readString(length: readyBytes),
  234. let decodedData = Data(base64Encoded: base64Encoded) else {
  235. throw GRPCError.Base64DecodeError().captureContext()
  236. }
  237. body.writeContiguousBytes(decodedData)
  238. }
  239. self.messageReader.append(buffer: &body)
  240. do {
  241. // We may be re-entrantly called, and that re-entrant call may error. If the state changed for any reason,
  242. // stop looping.
  243. while self.inboundState == .expectingBody,
  244. let buffer = try self.messageReader.nextMessage() {
  245. context.fireChannelRead(self.wrapInboundOut(.message(buffer)))
  246. }
  247. } catch let grpcError as GRPCError.WithContext {
  248. context.fireErrorCaught(grpcError)
  249. return .ignore
  250. } catch {
  251. context.fireErrorCaught(GRPCError.DeserializationFailure().captureContext())
  252. return .ignore
  253. }
  254. // We may have been called re-entrantly and transitioned out of the state we were in (e.g. because of an
  255. // error). In all cases, if we get here we want to persist the current state.
  256. return self.inboundState
  257. }
  258. private func processEnd(context: ChannelHandlerContext,
  259. trailers: HTTPHeaders?) throws -> InboundState {
  260. self.logger.debug("processing end")
  261. if let trailers = trailers {
  262. self.logger.error(
  263. "unexpected trailers when processing stream end",
  264. metadata: ["trailers": "\(trailers)"]
  265. )
  266. throw GRPCError.InvalidState("unexpected trailers received").captureContext()
  267. }
  268. context.fireChannelRead(self.wrapInboundOut(.end))
  269. return .ignore
  270. }
  271. }
  272. extension HTTP1ToGRPCServerCodec: ChannelOutboundHandler {
  273. public typealias OutboundIn = _RawGRPCServerResponsePart
  274. public typealias OutboundOut = HTTPServerResponsePart
  275. public func write(context: ChannelHandlerContext, data: NIOAny,
  276. promise: EventLoopPromise<Void>?) {
  277. if case .ignore = self.outboundState {
  278. self.logger.notice("ignoring written data: \(data)")
  279. promise?.fail(GRPCError.InvalidState("rpc has already finished").captureContext())
  280. return
  281. }
  282. switch self.unwrapOutboundIn(data) {
  283. case var .headers(headers):
  284. guard case .expectingHeaders = self.outboundState else {
  285. self.logger.error(
  286. "invalid state while writing headers",
  287. metadata: ["state": "\(self.outboundState)", "headers": "\(headers)"]
  288. )
  289. return
  290. }
  291. var version = HTTPVersion(major: 2, minor: 0)
  292. if let contentType = self.contentType {
  293. headers.add(name: GRPCHeaderName.contentType, value: contentType.canonicalValue)
  294. if contentType != .protobuf {
  295. version = .init(major: 1, minor: 1)
  296. }
  297. }
  298. // Are we compressing responses?
  299. if let responseEncoding = self.responseEncodingHeader {
  300. headers.add(name: GRPCHeaderName.encoding, value: responseEncoding)
  301. }
  302. // The client may have sent us a message using an encoding we didn't advertise; we'll send
  303. // an accept-encoding header back if that's the case.
  304. if let acceptEncoding = self.acceptEncodingHeader {
  305. headers.add(name: GRPCHeaderName.acceptEncoding, value: acceptEncoding)
  306. }
  307. context.write(
  308. self
  309. .wrapOutboundOut(.head(HTTPResponseHead(
  310. version: version,
  311. status: .ok,
  312. headers: HTTPHeaders(headers.map { ($0.name, $0.value) })
  313. ))),
  314. promise: promise
  315. )
  316. self.outboundState = .expectingBodyOrStatus
  317. case let .message(messageContext):
  318. guard case .expectingBodyOrStatus = self.outboundState else {
  319. self.logger.error(
  320. "invalid state while writing message",
  321. metadata: ["state": "\(self.outboundState)"]
  322. )
  323. return
  324. }
  325. do {
  326. if self.contentType == .webTextProtobuf {
  327. // Store the response into an independent buffer. We can't return the message directly as
  328. // it needs to be aggregated with all the responses plus the trailers, in order to have
  329. // the base64 response properly encoded in a single byte stream.
  330. let buffer = try self.messageWriter.write(
  331. buffer: messageContext.message,
  332. allocator: context.channel.allocator,
  333. compressed: messageContext.compressed
  334. )
  335. self.appendResponseText(buffer)
  336. // Since we stored the written data, mark the write promise as successful so that the
  337. // ServerStreaming provider continues sending the data.
  338. promise?.succeed(())
  339. } else {
  340. let messageBuffer = try self.messageWriter.write(
  341. buffer: messageContext.message,
  342. allocator: context.channel.allocator,
  343. compressed: messageContext.compressed
  344. )
  345. context.write(self.wrapOutboundOut(.body(.byteBuffer(messageBuffer))), promise: promise)
  346. }
  347. } catch {
  348. let error = GRPCError.SerializationFailure().captureContext()
  349. promise?.fail(error)
  350. context.fireErrorCaught(error)
  351. self.outboundState = .ignore
  352. return
  353. }
  354. self.outboundState = .expectingBodyOrStatus
  355. case let .statusAndTrailers(status, trailers):
  356. // If we error before sending the initial headers then we won't have sent the request head.
  357. // NIOHTTP2 doesn't support sending a single frame as a "Trailers-Only" response so we still
  358. // need to loop back and send the request head first.
  359. if case .expectingHeaders = self.outboundState {
  360. self.write(context: context, data: NIOAny(OutboundIn.headers([:])), promise: nil)
  361. }
  362. var trailers = trailers
  363. trailers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  364. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  365. trailers.add(name: GRPCHeaderName.statusMessage, value: message)
  366. }
  367. if self.contentType == .webTextProtobuf {
  368. // Encode the trailers into the response byte stream as a length delimited message, as per
  369. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
  370. let textTrailers = trailers.map { name, value, _ in "\(name): \(value)" }
  371. .joined(separator: "\r\n")
  372. var trailersBuffer = context.channel.allocator.buffer(capacity: 5 + textTrailers.utf8.count)
  373. trailersBuffer.writeInteger(UInt8(0x80))
  374. trailersBuffer.writeInteger(UInt32(textTrailers.utf8.count))
  375. trailersBuffer.writeString(textTrailers)
  376. self.appendResponseText(trailersBuffer)
  377. // This code can only be called on the grpc-web path, so we know the response text buffers must be non-nil
  378. // and must contain at least one element.
  379. guard var buffers = self.responseTextBuffers else {
  380. preconditionFailure("Building web response text but responseTextBuffers are nil")
  381. }
  382. // Avoid a CoW
  383. self.responseTextBuffers = nil
  384. var responseTextBuffer = buffers.popFirst()!
  385. // Read the data from the first buffer.
  386. var accumulatedData = responseTextBuffer.readData(length: responseTextBuffer.readableBytes)!
  387. // Reserve enough capacity and append the remaining buffers.
  388. let requiredExtraCapacity = buffers.lazy.map { $0.readableBytes }.reduce(0, +)
  389. accumulatedData.reserveCapacity(accumulatedData.count + requiredExtraCapacity)
  390. while let buffer = buffers.popFirst() {
  391. accumulatedData.append(contentsOf: buffer.readableBytesView)
  392. }
  393. // Restore the buffers.
  394. self.responseTextBuffers = buffers
  395. // TODO: Binary responses that are non multiples of 3 will end = or == when encoded in
  396. // base64. Investigate whether this might have any effect on the transport mechanism and
  397. // client decoding. Initial results say that they are innocuous, but we might have to keep
  398. // an eye on this in case something trips up.
  399. let encodedData = accumulatedData.base64EncodedString()
  400. // Reuse our first buffer.
  401. responseTextBuffer.clear(minimumCapacity: Int(encodedData.utf8.count))
  402. responseTextBuffer.writeString(encodedData)
  403. // After collecting all response for gRPC Web connections, send one final aggregated
  404. // response.
  405. context.write(
  406. self.wrapOutboundOut(.body(.byteBuffer(responseTextBuffer))),
  407. promise: promise
  408. )
  409. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  410. } else {
  411. let httpTrailers = HTTPHeaders(trailers.map { ($0.name, $0.value) })
  412. context.write(self.wrapOutboundOut(.end(httpTrailers)), promise: promise)
  413. }
  414. // Log the call duration and status
  415. if let stopwatch = self.stopwatch {
  416. self.stopwatch = nil
  417. let millis = stopwatch.elapsedMillis()
  418. self.logger.debug("rpc call finished", metadata: [
  419. "duration_ms": "\(millis)",
  420. "status_code": "\(status.code.rawValue)",
  421. ])
  422. }
  423. self.outboundState = .ignore
  424. self.inboundState = .ignore
  425. }
  426. }
  427. private func appendResponseText(_ buffer: ByteBuffer) {
  428. if self.responseTextBuffers == nil {
  429. self.responseTextBuffers = CircularBuffer()
  430. }
  431. self.responseTextBuffers!.append(buffer)
  432. }
  433. }
  434. private extension HTTP1ToGRPCServerCodec {
  435. /// Selects an appropriate response encoding from the list of encodings sent to us by the client.
  436. /// Returns `nil` if there were no appropriate algorithms, in which case the server will send
  437. /// messages uncompressed.
  438. func selectResponseEncoding(from acceptableEncoding: [Substring]) -> CompressionAlgorithm? {
  439. guard case let .enabled(configuration) = self.encoding else {
  440. return nil
  441. }
  442. return acceptableEncoding.compactMap {
  443. CompressionAlgorithm(rawValue: String($0))
  444. }.first {
  445. configuration.enabledAlgorithms.contains($0)
  446. }
  447. }
  448. }
  449. struct MessageEncodingHeaderValidator {
  450. var encoding: ServerMessageEncoding
  451. enum ValidationResult {
  452. /// The requested compression is supported.
  453. case supported(
  454. algorithm: CompressionAlgorithm,
  455. decompressionLimit: DecompressionLimit,
  456. acceptEncoding: [String]
  457. )
  458. /// The `requestEncoding` is not supported; `acceptEncoding` contains all algorithms we do
  459. /// support.
  460. case unsupported(requestEncoding: String, acceptEncoding: [String])
  461. /// No compression was requested.
  462. case noCompression
  463. }
  464. /// Validates the value of the 'grpc-encoding' header against compression algorithms supported and
  465. /// advertised by this peer.
  466. ///
  467. /// - Parameter requestEncoding: The value of the 'grpc-encoding' header.
  468. func validate(requestEncoding: String?) -> ValidationResult {
  469. switch (self.encoding, requestEncoding) {
  470. // Compression is enabled and the client sent a message encoding header. Do we support it?
  471. case let (.enabled(configuration), .some(header)):
  472. guard let algorithm = CompressionAlgorithm(rawValue: header) else {
  473. return .unsupported(
  474. requestEncoding: header,
  475. acceptEncoding: configuration.enabledAlgorithms.map { $0.name }
  476. )
  477. }
  478. if configuration.enabledAlgorithms.contains(algorithm) {
  479. return .supported(
  480. algorithm: algorithm,
  481. decompressionLimit: configuration.decompressionLimit,
  482. acceptEncoding: []
  483. )
  484. } else {
  485. // From: https://github.com/grpc/grpc/blob/master/doc/compression.md
  486. //
  487. // Note that a peer MAY choose to not disclose all the encodings it supports. However, if
  488. // it receives a message compressed in an undisclosed but supported encoding, it MUST
  489. // include said encoding in the response's grpc-accept-encoding header.
  490. return .supported(
  491. algorithm: algorithm,
  492. decompressionLimit: configuration.decompressionLimit,
  493. acceptEncoding: configuration.enabledAlgorithms.map { $0.name } + CollectionOfOne(header)
  494. )
  495. }
  496. // Compression is disabled and the client sent a message encoding header. We don't support this
  497. // unless the header is "identity", which is no compression. Note this is different to the
  498. // supported but not advertised case since we have explicitly not enabled compression.
  499. case let (.disabled, .some(header)):
  500. guard let algorithm = CompressionAlgorithm(rawValue: header) else {
  501. return .unsupported(
  502. requestEncoding: header,
  503. acceptEncoding: []
  504. )
  505. }
  506. if algorithm == .identity {
  507. return .noCompression
  508. } else {
  509. return .unsupported(requestEncoding: header, acceptEncoding: [])
  510. }
  511. // The client didn't send a message encoding header.
  512. case (_, .none):
  513. return .noCompression
  514. }
  515. }
  516. }