LengthPrefixedMessageReader.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. var compression: CompressionAlgorithm?
  34. var decompressor: Zlib.Inflate?
  35. init(compression: CompressionAlgorithm? = nil) {
  36. self.compression = compression
  37. switch compression?.algorithm {
  38. case .none, .some(.identity):
  39. self.decompressor = nil
  40. case .some(.deflate):
  41. self.decompressor = Zlib.Inflate(format: .deflate)
  42. case .some(.gzip):
  43. self.decompressor = Zlib.Inflate(format: .gzip)
  44. }
  45. }
  46. /// The result of trying to parse a message with the bytes we currently have.
  47. ///
  48. /// - needMoreData: More data is required to continue reading a message.
  49. /// - continue: Continue reading a message.
  50. /// - message: A message was read.
  51. internal enum ParseResult {
  52. case needMoreData
  53. case `continue`
  54. case message(ByteBuffer)
  55. }
  56. /// The parsing state; what we expect to be reading next.
  57. internal enum ParseState {
  58. case expectingCompressedFlag
  59. case expectingMessageLength(compressed: Bool)
  60. case expectingMessage(UInt32, compressed: Bool)
  61. }
  62. private var buffer: ByteBuffer!
  63. private var state: ParseState = .expectingCompressedFlag
  64. /// Returns the number of unprocessed bytes.
  65. internal var unprocessedBytes: Int {
  66. return self.buffer.map { $0.readableBytes } ?? 0
  67. }
  68. /// Whether the reader is mid-way through reading a message.
  69. internal var isReading: Bool {
  70. switch self.state {
  71. case .expectingCompressedFlag:
  72. return false
  73. case .expectingMessageLength, .expectingMessage:
  74. return true
  75. }
  76. }
  77. /// Appends data to the buffer from which messages will be read.
  78. internal mutating func append(buffer: inout ByteBuffer) {
  79. guard buffer.readableBytes > 0 else {
  80. return
  81. }
  82. if self.buffer == nil {
  83. self.buffer = buffer.slice()
  84. // mark the bytes as "read"
  85. buffer.moveReaderIndex(forwardBy: buffer.readableBytes)
  86. } else {
  87. self.buffer.writeBuffer(&buffer)
  88. }
  89. }
  90. /// Reads bytes from the buffer until it is exhausted or a message has been read.
  91. ///
  92. /// - Returns: A buffer containing a message if one has been read, or `nil` if not enough
  93. /// bytes have been consumed to return a message.
  94. /// - Throws: Throws an error if the compression algorithm is not supported.
  95. internal mutating func nextMessage() throws -> ByteBuffer? {
  96. switch try self.processNextState() {
  97. case .needMoreData:
  98. self.nilBufferIfPossible()
  99. return nil
  100. case .continue:
  101. return try nextMessage()
  102. case .message(let message):
  103. self.nilBufferIfPossible()
  104. return message
  105. }
  106. }
  107. /// `nil`s out `buffer` if it exists and has no readable bytes.
  108. ///
  109. /// This allows the next call to `append` to avoid writing the contents of the appended buffer.
  110. private mutating func nilBufferIfPossible() {
  111. if self.buffer?.readableBytes == 0 {
  112. self.buffer = nil
  113. }
  114. }
  115. private mutating func processNextState() throws -> ParseResult {
  116. guard self.buffer != nil else {
  117. return .needMoreData
  118. }
  119. switch self.state {
  120. case .expectingCompressedFlag:
  121. guard let compressionFlag: UInt8 = self.buffer.readInteger() else {
  122. return .needMoreData
  123. }
  124. let isCompressionEnabled = compressionFlag != 0
  125. // Compression is enabled, but not expected.
  126. if isCompressionEnabled && self.compression == nil {
  127. throw GRPCError.CompressionUnsupported().captureContext()
  128. }
  129. self.state = .expectingMessageLength(compressed: isCompressionEnabled)
  130. case .expectingMessageLength(let compressed):
  131. guard let messageLength: UInt32 = self.buffer.readInteger() else {
  132. return .needMoreData
  133. }
  134. self.state = .expectingMessage(messageLength, compressed: compressed)
  135. case .expectingMessage(let length, let compressed):
  136. let signedLength: Int = numericCast(length)
  137. guard var message = self.buffer.readSlice(length: signedLength) else {
  138. return .needMoreData
  139. }
  140. let result: ParseResult
  141. // TODO: If compression is enabled and we store the buffer slices then we can feed the slices
  142. // into the decompressor. This should eliminate one buffer allocation (i.e. the buffer into
  143. // which we currently accumulate the slices before decompressing it into a new buffer).
  144. // If compression is set but the algorithm is 'identity' then we will not get a decompressor
  145. // here.
  146. if compressed, let decompressor = self.decompressor {
  147. var decompressed = ByteBufferAllocator().buffer(capacity: 0)
  148. try decompressor.inflate(&message, into: &decompressed)
  149. // Compression contexts should be reset between messages.
  150. decompressor.reset()
  151. result = .message(decompressed)
  152. } else {
  153. result = .message(message)
  154. }
  155. self.state = .expectingCompressedFlag
  156. return result
  157. }
  158. return .continue
  159. }
  160. }