LengthPrefixedMessageReader.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import Logging
  18. import NIOCore
  19. import NIOHTTP1
  20. /// This class reads and decodes length-prefixed gRPC messages.
  21. ///
  22. /// Messages are expected to be in the following format:
  23. /// - compression flag: 0/1 as a 1-byte unsigned integer,
  24. /// - message length: length of the message as a 4-byte unsigned integer,
  25. /// - message: `message_length` bytes.
  26. ///
  27. /// Messages may span multiple `ByteBuffer`s, and `ByteBuffer`s may contain multiple
  28. /// length-prefixed messages.
  29. ///
  30. /// - SeeAlso:
  31. /// [gRPC Protocol](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md)
  32. internal struct LengthPrefixedMessageReader {
  33. let compression: CompressionAlgorithm?
  34. private let decompressor: Zlib.Inflate?
  35. init() {
  36. self.compression = nil
  37. self.decompressor = nil
  38. }
  39. init(compression: CompressionAlgorithm, decompressionLimit: DecompressionLimit) {
  40. self.compression = compression
  41. switch compression.algorithm {
  42. case .identity:
  43. self.decompressor = nil
  44. case .deflate:
  45. self.decompressor = Zlib.Inflate(format: .deflate, limit: decompressionLimit)
  46. case .gzip:
  47. self.decompressor = Zlib.Inflate(format: .gzip, limit: decompressionLimit)
  48. }
  49. }
  50. /// The result of trying to parse a message with the bytes we currently have.
  51. ///
  52. /// - needMoreData: More data is required to continue reading a message.
  53. /// - continue: Continue reading a message.
  54. /// - message: A message was read.
  55. internal enum ParseResult {
  56. case needMoreData
  57. case `continue`
  58. case message(ByteBuffer)
  59. }
  60. /// The parsing state; what we expect to be reading next.
  61. internal enum ParseState {
  62. case expectingCompressedFlag
  63. case expectingMessageLength(compressed: Bool)
  64. case expectingMessage(Int, compressed: Bool)
  65. }
  66. private var buffer: ByteBuffer!
  67. private var state: ParseState = .expectingCompressedFlag
  68. /// Returns the number of unprocessed bytes.
  69. internal var unprocessedBytes: Int {
  70. return self.buffer.map { $0.readableBytes } ?? 0
  71. }
  72. /// Returns the number of bytes that have been consumed and not discarded.
  73. internal var _consumedNonDiscardedBytes: Int {
  74. return self.buffer.map { $0.readerIndex } ?? 0
  75. }
  76. /// Whether the reader is mid-way through reading a message.
  77. internal var isReading: Bool {
  78. switch self.state {
  79. case .expectingCompressedFlag:
  80. return false
  81. case .expectingMessageLength, .expectingMessage:
  82. return true
  83. }
  84. }
  85. /// Appends data to the buffer from which messages will be read.
  86. internal mutating func append(buffer: inout ByteBuffer) {
  87. guard buffer.readableBytes > 0 else {
  88. return
  89. }
  90. if self.buffer == nil {
  91. self.buffer = buffer.slice()
  92. // mark the bytes as "read"
  93. buffer.moveReaderIndex(forwardBy: buffer.readableBytes)
  94. } else {
  95. switch self.state {
  96. case let .expectingMessage(length, _):
  97. // We need to reserve enough space for the message or the incoming buffer, whichever
  98. // is larger.
  99. let remainingMessageBytes = Int(length) - self.buffer.readableBytes
  100. self.buffer
  101. .reserveCapacity(minimumWritableBytes: max(remainingMessageBytes, buffer.readableBytes))
  102. case .expectingCompressedFlag,
  103. .expectingMessageLength:
  104. // Just append the buffer; these parts are too small to make a meaningful difference.
  105. ()
  106. }
  107. self.buffer.writeBuffer(&buffer)
  108. }
  109. }
  110. /// Reads bytes from the buffer until it is exhausted or a message has been read.
  111. ///
  112. /// - Returns: A buffer containing a message if one has been read, or `nil` if not enough
  113. /// bytes have been consumed to return a message.
  114. /// - Throws: Throws an error if the compression algorithm is not supported.
  115. internal mutating func nextMessage(maxLength: Int) throws -> ByteBuffer? {
  116. switch try self.processNextState(maxLength: maxLength) {
  117. case .needMoreData:
  118. self.nilBufferIfPossible()
  119. return nil
  120. case .continue:
  121. return try self.nextMessage(maxLength: maxLength)
  122. case let .message(message):
  123. self.nilBufferIfPossible()
  124. return message
  125. }
  126. }
  127. /// `nil`s out `buffer` if it exists and has no readable bytes.
  128. ///
  129. /// This allows the next call to `append` to avoid writing the contents of the appended buffer.
  130. private mutating func nilBufferIfPossible() {
  131. let readableBytes = self.buffer?.readableBytes ?? 0
  132. let readerIndex = self.buffer?.readerIndex ?? 0
  133. let capacity = self.buffer?.capacity ?? 0
  134. if readableBytes == 0 {
  135. self.buffer = nil
  136. } else if readerIndex > 1024, readerIndex > (capacity / 2) {
  137. // A rough-heuristic: if there is a kilobyte of read data, and there is more data that
  138. // has been read than there is space in the rest of the buffer, we'll try to discard some
  139. // read bytes here. We're trying to avoid doing this if there is loads of writable bytes that
  140. // we'll have to shift.
  141. self.buffer?.discardReadBytes()
  142. }
  143. }
  144. private mutating func processNextState(maxLength: Int) throws -> ParseResult {
  145. guard self.buffer != nil else {
  146. return .needMoreData
  147. }
  148. switch self.state {
  149. case .expectingCompressedFlag:
  150. guard let compressionFlag: UInt8 = self.buffer.readInteger() else {
  151. return .needMoreData
  152. }
  153. let isCompressionEnabled = compressionFlag != 0
  154. // Compression is enabled, but not expected.
  155. if isCompressionEnabled, self.compression == nil {
  156. throw GRPCError.CompressionUnsupported().captureContext()
  157. }
  158. self.state = .expectingMessageLength(compressed: isCompressionEnabled)
  159. case let .expectingMessageLength(compressed):
  160. guard let messageLength = self.buffer.readInteger(as: UInt32.self).map(Int.init) else {
  161. return .needMoreData
  162. }
  163. if messageLength > maxLength {
  164. throw GRPCError.PayloadLengthLimitExceeded(
  165. actualLength: messageLength,
  166. limit: maxLength
  167. ).captureContext()
  168. }
  169. self.state = .expectingMessage(messageLength, compressed: compressed)
  170. case let .expectingMessage(length, compressed):
  171. guard var message = self.buffer.readSlice(length: length) else {
  172. return .needMoreData
  173. }
  174. let result: ParseResult
  175. // TODO: If compression is enabled and we store the buffer slices then we can feed the slices
  176. // into the decompressor. This should eliminate one buffer allocation (i.e. the buffer into
  177. // which we currently accumulate the slices before decompressing it into a new buffer).
  178. // If compression is set but the algorithm is 'identity' then we will not get a decompressor
  179. // here.
  180. if compressed, let decompressor = self.decompressor {
  181. var decompressed = ByteBufferAllocator().buffer(capacity: 0)
  182. try decompressor.inflate(&message, into: &decompressed)
  183. // Compression contexts should be reset between messages.
  184. decompressor.reset()
  185. result = .message(decompressed)
  186. } else {
  187. result = .message(message)
  188. }
  189. self.state = .expectingCompressedFlag
  190. return result
  191. }
  192. return .continue
  193. }
  194. }