LengthPrefixedMessageReader.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 NIO
  18. import NIOHTTP1
  19. import Logging
  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(UInt32, 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 .expectingMessage(let 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.reserveCapacity(minimumWritableBytes: max(remainingMessageBytes, buffer.readableBytes))
  101. case .expectingCompressedFlag,
  102. .expectingMessageLength:
  103. // Just append the buffer; these parts are too small to make a meaningful difference.
  104. ()
  105. }
  106. self.buffer.writeBuffer(&buffer)
  107. }
  108. }
  109. /// Reads bytes from the buffer until it is exhausted or a message has been read.
  110. ///
  111. /// - Returns: A buffer containing a message if one has been read, or `nil` if not enough
  112. /// bytes have been consumed to return a message.
  113. /// - Throws: Throws an error if the compression algorithm is not supported.
  114. internal mutating func nextMessage() throws -> ByteBuffer? {
  115. switch try self.processNextState() {
  116. case .needMoreData:
  117. self.nilBufferIfPossible()
  118. return nil
  119. case .continue:
  120. return try nextMessage()
  121. case .message(let message):
  122. self.nilBufferIfPossible()
  123. return message
  124. }
  125. }
  126. /// `nil`s out `buffer` if it exists and has no readable bytes.
  127. ///
  128. /// This allows the next call to `append` to avoid writing the contents of the appended buffer.
  129. private mutating func nilBufferIfPossible() {
  130. let readableBytes = self.buffer?.readableBytes ?? 0
  131. let readerIndex = self.buffer?.readerIndex ?? 0
  132. let capacity = self.buffer?.capacity ?? 0
  133. if readableBytes == 0 {
  134. self.buffer = nil
  135. } else if readerIndex > 1024 && readerIndex > (capacity / 2) {
  136. // A rough-heuristic: if there is a kilobyte of read data, and there is more data that
  137. // has been read than there is space in the rest of the buffer, we'll try to discard some
  138. // read bytes here. We're trying to avoid doing this if there is loads of writable bytes that
  139. // we'll have to shift.
  140. self.buffer?.discardReadBytes()
  141. }
  142. }
  143. private mutating func processNextState() throws -> ParseResult {
  144. guard self.buffer != nil else {
  145. return .needMoreData
  146. }
  147. switch self.state {
  148. case .expectingCompressedFlag:
  149. guard let compressionFlag: UInt8 = self.buffer.readInteger() else {
  150. return .needMoreData
  151. }
  152. let isCompressionEnabled = compressionFlag != 0
  153. // Compression is enabled, but not expected.
  154. if isCompressionEnabled && self.compression == nil {
  155. throw GRPCError.CompressionUnsupported().captureContext()
  156. }
  157. self.state = .expectingMessageLength(compressed: isCompressionEnabled)
  158. case .expectingMessageLength(let compressed):
  159. guard let messageLength: UInt32 = self.buffer.readInteger() else {
  160. return .needMoreData
  161. }
  162. self.state = .expectingMessage(messageLength, compressed: compressed)
  163. case .expectingMessage(let length, let compressed):
  164. let signedLength: Int = numericCast(length)
  165. guard var message = self.buffer.readSlice(length: signedLength) else {
  166. return .needMoreData
  167. }
  168. let result: ParseResult
  169. // TODO: If compression is enabled and we store the buffer slices then we can feed the slices
  170. // into the decompressor. This should eliminate one buffer allocation (i.e. the buffer into
  171. // which we currently accumulate the slices before decompressing it into a new buffer).
  172. // If compression is set but the algorithm is 'identity' then we will not get a decompressor
  173. // here.
  174. if compressed, let decompressor = self.decompressor {
  175. var decompressed = ByteBufferAllocator().buffer(capacity: 0)
  176. try decompressor.inflate(&message, into: &decompressed)
  177. // Compression contexts should be reset between messages.
  178. decompressor.reset()
  179. result = .message(decompressed)
  180. } else {
  181. result = .message(message)
  182. }
  183. self.state = .expectingCompressedFlag
  184. return result
  185. }
  186. return .continue
  187. }
  188. }